{"text": "cache <- vector(\"integer\", 0)\ncache[1] <- 1\ncache[2] <- 1\n\nQ <- function(n) {\n if (is.na(cache[n])) {\n value <- Q(n-Q(n-1)) + Q(n-Q(n-2))\n cache[n] <<- value\n }\n cache[n]\n}\n\nfor (i in 1:1e5) {\n Q(i)\n}\n\nfor (i in 1:10) {\n cat(Q(i),\" \",sep = \"\")\n}\ncat(\"\\n\")\ncat(Q(1000),\"\\n\")\n\ncount <- 0\nfor (i in 2:1e5) {\n if (Q(i) < Q(i-1)) count <- count + 1\n}\ncat(count,\"terms is less than its preceding term\\n\")\n", "meta": {"hexsha": "5be2b708ac426d3bbd1791d947b17ff03aa2b117", "size": 411, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.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/Hofstadter-Q-sequence/R/hofstadter-q-sequence.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": 14.6785714286, "max_line_length": 52, "alphanum_fraction": 0.4939172749, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6495865742915208}} {"text": "# Ternary Diagram // треугольные диаграммы\n# ЧАСТЬ 1: вчитываем таблицу. делаем data.frame. удаляем NA\nMDF <- read.csv(\"Morphology.csv\", header=TRUE, sep = \",\")\nMDF <- na.omit(MDF) \nrow.has.na <- apply(MDF, 1, function(x){any(is.na(x))})\nsum(row.has.na) \nhead(MDF) \n\nMDTt = melt(setDT(MDF), measure = patterns(\"^plate\"), value.name = c(\"tectonics\"))\nhead(MDTt)\nlevels(MDTt$variable) = c(\"Philippine\" , \"Pacific\", \"Mariana\", \"Caroline\")\nPlates<- c(\"Philippine\" , \"Pacific\", \"Mariana\", \"Caroline\")\n\n\n# ЧАСТЬ 2: чертим треугольную диаграмму Марианского желоба пакетом ggtern\nlibrary(ggtern) \n \n# вариант-1. по тектонике (4 плиты)\nMDTer <- data.frame(\n\t\t\tx = MDTt$igneous_volc,\n\t\t\ty = MDTt$tectonics,\n\t\t\tz = MDTt$slope_angle,\n\t\t\tValue = MDTt$slope_angle,\n\t\t\tGroup = as.factor(MDTt$variable))\n\nMT1<- ggtern(data= MDTer,aes(x,y,z,color = Group)) + \n\ttheme_rgbw() +\n\tgeom_point() + \n#\tgeom_path() + \n\tscale_color_manual(values = c(\"green\" , \"red\", \"orange\", \"blue\")) + \n\tlabs(x=\"Igneous \\nVolcanos\",y=\"Tectonics\",z=\"Slope \\nAngle\",\n \t\ttitle=\"Mariana Trench\",\n \t\tsubtitle=\"Ternary Diagram: Tectonic Plates\") +\n geom_Tline(Tintercept=.5,arrow=arrow(), colour='red') +\n geom_Lline(Lintercept=.2, colour='magenta') +\n geom_Rline(Rintercept=.1, colour='blue') +\n geom_confidence_tern() \nMT1\n\n# вариант-2. по классам морфология\n\nlevels(MDTt$morph_class) = c(\"Strong Slope\", \"Very Strong Slope\", \"Steep Slope\", \"Extreme Slope\")\nMDTM <- data.frame(\n\t\t\tx = MDTt$Min,\n\t\t\ty = MDTt$aspect_degree,\n\t\t\tz = MDTt$slope_angle,\n\t\t\tValue = MDTt$slope_angle,\n\t\t\tGroup = as.factor(MDTt$morph_class))\n\nMT2<- ggtern(data= MDTM,aes(x,y,z,color=Group), show.legend=TRUE) + \n\ttheme_rgbw() +\n\tgeom_point() + \n\tgeom_path() + \n\tlabs(x=\"Max \\nDepth\",y=\"Aspect Degree\",z=\"Slope\\nAngle\",\n \t\ttitle=\"Mariana Trench\",\n \t\tsubtitle=\"Ternary Diagram: Slope Morphology Class\") +\n geom_Tline(Tintercept=.5,arrow=arrow(), colour='red') +\n geom_Lline(Lintercept=.2, colour='magenta') +\n geom_Rline(Rintercept=.1, colour='blue') +\n geom_confidence_tern() +\n geom_Tisoprop(value=0.5) +\n geom_Lisoprop(value=0.5) +\n geom_Risoprop(value=0.5)\nMT2\n\t\n# вариант-3 по аспекту - разворот угла\nMDTAs <- data.frame(\n\t\t\tx = MDTt$slope_angle,\n\t\t\ty = MDTt$aspect_degree,\n\t\t\tz = MDTt$Min,\n\t\t\tValue = MDTt$aspect_degree,\n\t\t\tGroup = as.factor(MDTt$aspect_class))\n\nMT3<- ggtern(data = MDTAs,aes(x,y,z,color = Group)) + \n\ttheme_rgbw() +\n\tgeom_point() + \n\tscale_color_manual(values = c(\"green\", \"red\", \"orange\", \"blue\", \"yellow\" , \"brown\", \"grey\", \"cyan\")) + \n\tlabs(x=\"Slope \\nAngle\", size = 1, y=\"Aspect \\nDegree\", z=\"Max \\nDepth\",\n \t\ttitle=\"Mariana Trench\",\n \t\tsubtitle=\"Ternary Diagram: Aspect Class\") +\n geom_Tline(Tintercept=.5,arrow=arrow(), colour='red') +\n geom_Lline(Lintercept=.2, colour='magenta') +\n geom_Rline(Rintercept=.1, colour='blue') +\n geom_confidence_tern() +\n geom_Tisoprop(value=0.5) +\n geom_Lisoprop(value=0.5) +\n geom_Risoprop(value=0.5) \nMT3\n\nplot<- grid.arrange(MT1, MT2, MT3, newpage = TRUE, nrow = 1, ncol = 3, top=\"Mariana Trench\")\n\n\n# вариант-4. по толщине мор. отложений / седиментология\nMD4 <- data.frame(\n\t\t\tx = MDTt$igneous_volc,\n\t\t\ty = MDTt$sedim_thick,\n\t\t\tz = MDTt$slope_angle,\n\t\t\tValue = MDTt$slope_angle)\n\nMT4<- ggtern(data = MD4,aes(x,y,z), show.legend=TRUE) + \n\ttheme_rgbw() +\n\tgeom_point() + \n#\tgeom_path(alpha = .5, lwd = 0.2) + \n\tlabs(x=\"Igneous \\nVolcanos\", size = 0.5,y=\"Sedimental \\nThickness\",z=\"Slope \\nAngle\",\n \t\ttitle=\"Mariana Trench\",\n \t\tsubtitle=\"Ternary Diagram: Sedimental Thickness\") +\n geom_Tline(Tintercept=.5,arrow=arrow(), colour='deeppink') +\n geom_Lline(Lintercept=.2, colour='magenta') +\n geom_Rline(Rintercept=.1, colour='springgreen') +\n geom_confidence_tern() + \n geom_smooth_tern(method = 'loess', size = .4, color = \"yellow1\") +\n geom_mean_ellipse (size = .5, color = \"cyan\")\nMT4\n\nfigure <-plot_grid(MT1, MT2, MT3, MT4, labels = c(\"1\", \"2\", \"3\", \"4\"), ncol = 2, nrow = 2)\n", "meta": {"hexsha": "3ae4d4ec6e1ca54e0994fed08102ae4035a3fcbe", "size": 3903, "ext": "r", "lang": "R", "max_stars_repo_path": "Ternary.r", "max_stars_repo_name": "paulinelemenkova/29-R-Ternary", "max_stars_repo_head_hexsha": "8edc8a9938e660476d8d3fafd8f546693db21ebc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ternary.r", "max_issues_repo_name": "paulinelemenkova/29-R-Ternary", "max_issues_repo_head_hexsha": "8edc8a9938e660476d8d3fafd8f546693db21ebc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ternary.r", "max_forks_repo_name": "paulinelemenkova/29-R-Ternary", "max_forks_repo_head_hexsha": "8edc8a9938e660476d8d3fafd8f546693db21ebc", "max_forks_repo_licenses": ["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.6465517241, "max_line_length": 104, "alphanum_fraction": 0.6692287984, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6494853961243069}} {"text": "## function to create titre and efficacy profiles\n\n\ndraw <- function(mu_ab_d1 = mu_ab_d1, mu_ab_d2 = mu_ab_d2, mu_ab_d3, std10 = std10, ab_50 = ab_50, ab_50_severe, \n dr_s = dr_s, dr_l = dr_l, period_s = period_s, t = t, t_d2 = t_d2, t_d3, k = k){\n \n # decay rates over time\n ## simple biphasic decay on natural log scale\n \n denom=log(exp(dr_l*period_s)+exp(dr_s*period_s))\n cum_dr_vec=log(exp(dr_s*t+dr_l*period_s)+exp(dr_l*t+dr_s*period_s))-denom\n dr_vec=c(0,diff(cum_dr_vec,1)) \n \n \n # dr_vec_sub <- c(rep(dr_s, round(period_s)-1),\n # seq(dr_s, dr_l, length.out = round(t_period_l)-round(period_s)+1),\n # rep(dr_l, length(t) - round(t_period_l)))\n \n # dr_vec <- rep(0, length(t))\n # dr_vec[2:t_d2] <- dr_vec_sub[1:(t_d2-1)]\n # dr_vec[(2+t_d2):(t_d3+t_d2)] <- dr_vec_sub[1:((t_d3+t_d2)-(t_d2+1))]\n # dr_vec[(2+t_d2+t_d3):length(t)] <- dr_vec_sub[1:(length(t) - (t_d2+t_d3+1)) ]\n \n # nab titre distribution for a given vaccine product: draw from a log-normal distribution\n # here the first titre is dependent on the second but I suppose could do it the other way around\n \n z2 <- rnorm(1, log10(mu_ab_d2), std10)\n z3 <- log10(10^z2 * (mu_ab_d3/mu_ab_d2))\n z1 <- log10(10^z2 * (mu_ab_d1/mu_ab_d2))\n \n # initiate titre vector\n nt <- rep(0, length(t))\n nt[1] <- log(10^z1)\n nt[t_d2+1] <- log(10^z2)\n nt[t_d2+t_d3+1] <- log(10^z3)\n \n # decay antibodies over time on natural log scale\n for (i in (2:t_d2)){\n nt[i] <- nt[i-1] + dr_vec[i]\n }\n for (i in ((t_d2+2):(t_d2+t_d3))){\n nt[i] <- nt[i-1] + dr_vec[i-t_d2-1]\n }\n for (i in ((t_d2+t_d3+2):length(t))){\n nt[i] <- nt[i-1] + dr_vec[i-t_d3-1]\n }\n \n nt <- exp(nt) # return to linear scale\n \n # relate titre to efficacy over time - using log-10 parameters\n ef_infection <- 1 / (1 + exp(-k * (log10(nt) - log10(ab_50))))\n ef_severe <- 1 / (1 + exp(-k * (log10(nt) - log10(ab_50_severe))))\n \n # output list containing titre and vaccine efficacy\n ret <- list(titre = nt, VE = ef_infection, VE_severe = ef_severe)\n return(ret)\n}", "meta": {"hexsha": "a7489f49e56047639712724ee99bd5c24616d3c3", "size": 2063, "ext": "r", "lang": "R", "max_stars_repo_path": "0_antibody_model_fitting/Plotting and Table Code/R/create_profile.r", "max_stars_repo_name": "mrc-ide/global_covid_vaccine_booster_paper", "max_stars_repo_head_hexsha": "fac5ddabb688cca4efa635b3c1be98262e29fcab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "0_antibody_model_fitting/Plotting and Table Code/R/create_profile.r", "max_issues_repo_name": "mrc-ide/global_covid_vaccine_booster_paper", "max_issues_repo_head_hexsha": "fac5ddabb688cca4efa635b3c1be98262e29fcab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "0_antibody_model_fitting/Plotting and Table Code/R/create_profile.r", "max_forks_repo_name": "mrc-ide/global_covid_vaccine_booster_paper", "max_forks_repo_head_hexsha": "fac5ddabb688cca4efa635b3c1be98262e29fcab", "max_forks_repo_licenses": ["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.1929824561, "max_line_length": 113, "alphanum_fraction": 0.622879302, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813513911654, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.6492821644658563}} {"text": "stdin <- file(\"stdin\")\nopen(stdin)\n\ninvisible(readLines(stdin, n = 1, warn = FALSE)) # Consumes line to ignore `n`\nv <- as.integer(strsplit(trimws(\n readLines(stdin, n = 1, warn = FALSE), which = \"both\"), \" \")[[1]])\nf <- as.integer(strsplit(trimws(\n readLines(stdin, n = 1, warn = FALSE), which = \"both\"), \" \")[[1]])\n\nclose(stdin)\n\nquartiles <- function(x) {\n y <- sort(x)\n if (length(y) %% 2 == 0) {\n return(c(\n median(y[1:(length(y) / 2)]),\n median(y),\n median(y[(length(y) / 2 + 1):length(y)])\n ))\n } else {\n return(c(\n median(y[1:(length(y) / 2)]),\n median(y),\n median(y[(length(y) / 2 + 1):length(y) + 1])\n ))\n }\n}\ninter_quartile <- function(v, f) {\n s <- c()\n for (i in seq_len(length(v))) {\n s <- c(s, rep(v[i], f[i]))\n }\n q <- quartiles(s)\n return(q[3] - q[1])\n}\ncat(sprintf(\"%.1f\", inter_quartile(v, f)), \"\\n\")\n", "meta": {"hexsha": "d22c7a81e8c88be0b2e6a6e9937e34b081f65c69", "size": 876, "ext": "r", "lang": "R", "max_stars_repo_path": "hr/ac/s10-interquartile-range.r", "max_stars_repo_name": "vitorgt/problem-solving", "max_stars_repo_head_hexsha": "11fa59de808f7a113c08454b4aca68b01410892e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hr/ac/s10-interquartile-range.r", "max_issues_repo_name": "vitorgt/problem-solving", "max_issues_repo_head_hexsha": "11fa59de808f7a113c08454b4aca68b01410892e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hr/ac/s10-interquartile-range.r", "max_forks_repo_name": "vitorgt/problem-solving", "max_forks_repo_head_hexsha": "11fa59de808f7a113c08454b4aca68b01410892e", "max_forks_repo_licenses": ["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.6756756757, "max_line_length": 78, "alphanum_fraction": 0.5228310502, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6492238766644356}} {"text": "# install.packages(\"vars\", repos = \"http://cran.us.r-project.org\")\nlibrary(vars)\n\ndata <- read.csv('data.csv', header = TRUE)\n\n# y1 and y5 are cointegrated\n\ny1 <- data$y1\ny5 <- data$y5\n\nv1 <- cbind(y1, y5)\ncolnames(v1) <- cbind('y1', 'y5')\n\nModel1 <- VAR(v1, p = 1, type = \"const\", season = NULL, exog = NULL) \nsummary(Model1)\n\n# y2 and y3 are cointegrated\n\ny2 <- data$y2\ny3 <- data$y3\n\nv2 <- cbind(y2, y3)\ncolnames(v2) <- cbind('y2', 'y3')\n\nModel2 <- VAR(v2, p = 1, type = \"const\", season = NULL, exog = NULL) \nsummary(Model2)\n\n# y4 and y10 are cointegrated\n\ny4 <- data$y4\ny10 <- data$y10\n\nv3 <- cbind(y4, y10)\ncolnames(v3) <- cbind('y4', 'y10')\n\nModel3 <- VAR(v3, p = 1, type = \"const\", season = NULL, exog = NULL) \nsummary(Model3)\n\n# y6 and y10 are cointegrated\n\ny6 <- data$y6\ny9 <- data$y9\n\nv4 <- cbind(y6, y9)\ncolnames(v4) <- cbind('y6', 'y9')\n\nModel4 <- VAR(v4, p = 1, type = \"const\", season = NULL, exog = NULL) \nsummary(Model4)\n\n\n# y1 = y1.l1 + y5.l1 + const \n# y1.l1 = -0.066, y5.l1 = 0.481, const = 0.476\n\n# y5 = y1.l1 + y5.l1 + const \n# y1.l1 = -0.058, y5.l1 = 0.473, const = 0.056\n\n# y1(t) = y1.l1 * y1(t-1) + y5.l1 * y2(t-1) + const\n# y2(t) = y1.l1 * y1(t-1) + y5.l1 * y2(t-1) + const\n\n#### HERE WE BUILD VAR MODEL FOR COINTEGRATED TIME SERIES Y1 and Y5\n\nminX <- 1\nmaxX <- 290\nxPointsForDates <- minX:maxX\nl11 <- -0.066\nl12 <- 0.481\nc1 <- 0.476\nl21 <- -0.058\nl22 <- 0.473\nc2 <- 0.056\n\ny1_var = c(y1[300])\ny5_var = c(y5[300])\n\nindex <- 2\n\nfor (i in (minX + 1):(maxX)) {\n y1_var[index] = l11 * y1_var[index - 1] + l12 * y5_var[index - 1] + c1\n y5_var[index] = l21 * y1_var[index - 1] + l22 * y5_var[index - 1] + c2\n index = index + 1\n}\n\npdfName <- 'y1_and_y5_var_model.pdf'\n# Open a pdf file\npdf(pdfName)\n# Create a plot\nplot(x = xPointsForDates, y = y1_var,\n type='l',\n pch = 16, frame = FALSE,\n xlab = '290 additional dates (after 300 previous ones)', ylab = 'y', col = '#2E9FDF')\nlines(x = xPointsForDates, y = y5_var, col = '#Df2E7E', pch = 16)\n# Close the pdf file\ndev.off() \n# Print that PDF is generated\nprint(sprintf('PDF %s with charts for VAR Model (y1 and y5) is generated', pdfName))\n\n\npngName <- 'y1_and_y5_var_model.png'\n# Open a pdf file\npng(pngName)\n# Create a plot\nplot(x = xPointsForDates, y = y1_var,\n type='l',\n pch = 16, frame = FALSE,\n xlab = '290 additional dates (after 300 previous ones)', ylab = 'y', col = '#2E9FDF')\nlines(x = xPointsForDates, y = y5_var, col = '#Df2E7E', pch = 16)\n# Close the pdf file\ndev.off() \n# Print that PDF is generated\nprint(sprintf('PNG %s with charts for VAR Model (y1 and y5) is generated', pdfName))\n\n#### HERE WE BUILD VAR MODEL FOR COINTEGRATED TIME SERIES Y2 and Y3\n\nminX <- 1\nmaxX <- 290\nxPointsForDates <- minX:maxX\nl11 <- -0.313\nl12 <- 3.503\nc1 <- 3.417\nl21 <- -0.272\nl22 <- 3.492\nc2 <- 0.229\n\ny2_var = c(y2[300])\ny3_var = c(y3[300])\n\nindex <- 2\n\nfor (i in (minX + 1):(maxX)) {\n y2_var[index] = l11 * y2_var[index - 1] + l12 * y3_var[index - 1] + c1\n y3_var[index] = l21 * y2_var[index - 1] + l22 * y3_var[index - 1] + c2\n index = index + 1\n}\n\npdfName <- 'y2_and_y3_var_model.pdf'\n# Open a pdf file\npdf(pdfName)\n# Create a plot\nplot(x = xPointsForDates, y = y2_var,\n type='l',\n pch = 16, frame = FALSE,\n xlab = '290 additional dates (after 300 previous ones)', ylab = 'y', col = '#2E9FDF')\nlines(x = xPointsForDates, y = y3_var, col = '#Df2E7E', pch = 16)\n# Close the pdf file\ndev.off() \n# Print that PDF is generated\nprint(sprintf('PDF %s with charts for VAR Model (y2 and y3) is generated', pdfName))\n\n#### LET'S COMPARE WITH NOT COINTEGRATED Y1 and Y6\n\nminX <- 1\nmaxX <- 290\nxPointsForDates <- minX:maxX\nl11 <- 157.317\nl12 <- -3.957\nc1 <- 3.452\nl21 <- 2.398\nl22 <- 161.639\nc2 <- 0.243\n\ny1_var = c(y1[300])\ny6_var = c(y6[300])\n\nindex <- 2\n\nfor (i in (minX + 1):(maxX)) {\n y1_var[index] = l11 * y1_var[index - 1] + l12 * y6_var[index - 1] + c1\n y6_var[index] = l21 * y1_var[index - 1] + l22 * y6_var[index - 1] + c2\n index = index + 1\n}\n\npdfName <- 'y1_and_y6_var_model.pdf'\n# Open a pdf file\npdf(pdfName)\n# Create a plot\nplot(x = xPointsForDates, y = y1_var,\n type='l',\n pch = 16, frame = FALSE,\n xlab = '290 additional dates (after 300 previous ones)', ylab = 'y', col = '#2E9FDF')\nlines(x = xPointsForDates, y = y6_var, col = '#Df2E7E', pch = 16)\n# Close the pdf file\ndev.off() \n# Print that PDF is generated\nprint(sprintf('PDF %s with charts for VAR Model (y1 and y6) is generated', pdfName))\n\n", "meta": {"hexsha": "d2389fbe93adeb80905a5caa3c6e7c2960beee10", "size": 4430, "ext": "r", "lang": "R", "max_stars_repo_path": "var.r", "max_stars_repo_name": "Guseyn/time-series-analysis", "max_stars_repo_head_hexsha": "b12139cc891b592f0d95dfeb886ed8a2e0d07638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "var.r", "max_issues_repo_name": "Guseyn/time-series-analysis", "max_issues_repo_head_hexsha": "b12139cc891b592f0d95dfeb886ed8a2e0d07638", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "var.r", "max_forks_repo_name": "Guseyn/time-series-analysis", "max_forks_repo_head_hexsha": "b12139cc891b592f0d95dfeb886ed8a2e0d07638", "max_forks_repo_licenses": ["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.8172043011, "max_line_length": 90, "alphanum_fraction": 0.6203160271, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6489905140472801}} {"text": "funkSVD <- function(R, k, lr = 0.01, reg = 0.5, miter = 2) {\n\tglobal_mean <- mean(as.matrix(R), na.rm = TRUE)\n\tbu <- rep(0, nrow(R))\n\tbi <- rep(0, ncol(R))\n\tP <- matrix(0.1, nrow = nrow(R), ncol = k)\n\tQ <- matrix(0.1, nrow = ncol(R), ncol = k)\n\tK <- which(!is.na(R), arr.ind = TRUE)\n\tfor(f in sample(k)) {\n\t\tfor(l in 1:miter) {\n\t\t\tfor(j in 1:nrow(K)){\n \t\t\tu <- K[j,1]\n \t\t\ti <- K[j,2]\n \t\t\tr_ui <- R[u,i]\n \t\t\tif(!is.na(r_ui)){\n \t\t\tpred <- global_mean + bu[u] + bi[i] + P[u, ] %*% Q[i, ]\n \t\t\te_ui <- r_ui - pred\n\t\t\t\t\tbu[u] <- bu[u] + lr * e_ui\n\t\t\t\t\tbi[i] <- bi[i] + lr * e_ui\n \t\t\ttemp_uf <- P[u,f]\n \t\t\tP[u,f] <- P[u,f] + lr * (e_ui * Q[i,f] - reg * P[u,f])\n\t\t\t \tQ[i,f] <- Q[i,f] + lr * (e_ui * temp_uf - reg * Q[i,f])\n \t\t\t}\n \t\t\t}\n\t\t}\n\t}\n\treturn(list(bu = bu, bi = bi, P = P, Q = Q))\n}\n\n", "meta": {"hexsha": "f97b22af39cf67fadbd765c0577776428c042310", "size": 848, "ext": "r", "lang": "R", "max_stars_repo_path": "class/class-3/funksvd.r", "max_stars_repo_name": "felipecustodio/recommender-systems", "max_stars_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "class/class-3/funksvd.r", "max_issues_repo_name": "felipecustodio/recommender-systems", "max_issues_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "class/class-3/funksvd.r", "max_forks_repo_name": "felipecustodio/recommender-systems", "max_forks_repo_head_hexsha": "902655d0c6b9a8058223b6e3d2db11589ad12ab8", "max_forks_repo_licenses": ["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.2413793103, "max_line_length": 67, "alphanum_fraction": 0.4186320755, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6489905133904639}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\n\r\nrm(list=ls(all=TRUE))\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\ncat(\"Stan version:\", stan_version(), \"\\n\")\r\nstanmodelcode <- \"\r\n\r\n\r\n#### define GP function\r\nfunctions {\r\n\r\nreal normal_generalized_poisson_log(int y, real theta, real lambda, real sigob) { \r\n return (log(theta) \r\n + (y - 1) * log(theta + y * lambda) \r\n - lgamma(y + 1) \r\n - y * lambda \r\n - theta)*(y<=200)\r\n +(normal_lpdf(y|theta,sigob))*(y>200);\r\n\t\t ## +log(1-normal_cdf(0.08*u,u,0.01))*(b0>0.08*u)\r\n\t\t ## +log(normal_cdf((0.515+0.125*u),u,0.01))*(b2>(0.515+0.125*u)); #### +log(b0>0.08*u); (b0>0.08*u)\r\n } \r\n\r\n}\r\n\r\n\r\n#### define our data, integer value\r\ndata {\r\nint N;\r\nint y[N];\r\nreal E[N];\r\n}\r\n\r\n\r\n#### define parameters \r\nparameters {\r\n\r\nreal lambda;\r\nreal u;\r\nreal b0;\r\nreal b1;\r\nreal b2;\r\nreal sig2;\r\nvector[N] e;\r\nreal sigob;\r\n}\r\n\r\n\r\n#### define some parameters which is the function of other parameters \r\ntransformed parameters {\r\nvector[N] mu;\r\n\r\n### define the mean function\r\n#mu[1] <- exp(u*exp(-b0)+e[1]);\r\n\r\nmu[1] <- y[1]; ## not tested\r\n\r\n for (n in 2:N) {\r\n\t\r\n mu[n] <- mu[n-1]*exp(u*exp(-b0*n)+b1*(mu[n-1]^b2)+e[n]); \r\n\t \r\n\t }\r\n\r\n}\r\n\r\n\r\n\r\n##### define piror and likelihood function\r\nmodel {\r\nlambda~uniform(-1,1);\r\nu ~ normal(0.13,0.1);\r\nb0 ~ normal(0.025,0.01);\r\nb1 ~ normal(-0.00000006,0.00000001);\r\nb2 ~ normal(0.1,0.1);\r\nsig2 ~ gamma(1,1); \r\ne~normal(0,sig2);\r\nsigob ~ uniform(100,1100);\r\n\r\nfor (j in 1:N) {\r\n\r\ny[j] ~ normal_generalized_poisson( mu[j]*E[j], lambda, sigob);\r\n}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n#### calculate DIC\r\ngenerated quantities {\r\nvector[N] log_lik;\r\nreal dev; // deviance\r\n\r\n\r\n for (n in 1:N){\r\n log_lik[n] <- normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n dev <- 0;\r\n for ( n in 1:N ) {\r\n dev <- dev + (-2) * normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\r\n\r\n\r\n###### \r\n\r\n\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covid19modelrisk/data/covid19_infected\")\r\n\r\n y=read.csv(\"COVID-19_confirmed__Germany.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Italy.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Japan.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Spain.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__US.csv\")\r\n## y=read.csv(\"COVID-19_confirmed_Australia.csv\")\r\n\r\ny=y[,2]\r\n\r\n\r\n\r\n\r\nE=rep(1,length(y))\r\n\r\nN=length(y)\r\ndat <- list(N = N, y = y,E=E)\r\n\r\n\r\n\r\n#### initial values\r\ninits =list(list(lambda=0,u=0.1,b0=0.025,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.2,b0=0.025,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.15,b0=0.025,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.25,b0=0.025,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.2,b0=0.05,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.2,b0=0.01,b1=-0.00000006, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.2,b0=0.01,b1=-0.0000001, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000),\r\nlist(lambda=0,u=0.2,b0=0.01,b1=-0.00000001, b2=0.1,sig2=0.0005,e=rep(0.01,N),sigob=1000))\r\n\r\n\r\nfit <- stan(model_code = stanmodelcode, model_name = \"example\",init =inits,\r\ndata = dat, warmup=10000,iter = 100000, chains = 8, seed=999,thin=1)\r\nprint(fit,digits = 4)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################### trace plot\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\nk=1\r\n\r\n\r\npdf(paste(\"M8_\",abn[k],\"_p1.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"u\",\"b0\",\"b1\",\"b2\"), inc_warmup = T, nrow = 4, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\npdf(paste(\"M8_\",abn[k],\"_p2.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"sigob\",\"sig2\",\"lambda\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\ndev.off()\r\n\r\n\r\n\r\n################## plot 30/45/60/ length(y)\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\npdf(paste(\"M8_\",abn[k],\"_30.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=30\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M8_\",abn[k],\"_45.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=45\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M8_\",abn[k],\"_60.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=60\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M8_\",abn[k],\"_all.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n######## log plot ####################################################\r\n\r\nk=1\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\ny=log(y)\r\nEpars_m=log(Epars_m)\r\nEpars_9=log(Epars_9)\r\nEpars_5=log(Epars_5)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/plot\")\r\n\r\npdf(paste(\"M8_\",abn[k],\"_log.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M8 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###########################################################################################################################\r\n\r\n\r\n\r\n\r\n\r\nmean(y)\r\nmedian(y)\r\n\r\nn=length(y)\r\n\r\n\r\n\r\nu=0.13\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\nx=c()\r\nx[1]=100\r\nfor (i in 1:(n-1) ){\r\n\r\nx[i+1]=x[i]*exp(u*exp(-b0*i)+b1*(x[i]^b2))\r\n}\r\nx=round(x)\r\nx\r\n\r\n\r\n\r\nplot(y,ylim=c(min(y,x),max(y,x)))\r\npar(new=TRUE)\r\nplot(x,col=\"red\",ylim=c(min(y,x),max(y,x)))\r\n\r\n\r\n\r\n\r\n\r\n\r\n#############################################################\r\n##### GM\r\n\r\n\r\nu=0.2\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n\r\n\r\n##### IT\r\n\r\nu=0.2\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n##### JP\r\n\r\n\r\nu=0.15\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n##### SP\r\n\r\nu=0.2\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n\r\n##### UK\r\n\r\nu=0.2\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n\r\n\r\n##### US\r\n\r\n\r\nu=0.27\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n##### AU\r\n\r\n\r\nu=0.13\r\nb0=0.025\r\nb1=-0.00000006\r\nb2=0.1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "8fa9fa192d06cb018f4ce1d5a43ca1fe9ed9a64c", "size": 11248, "ext": "r", "lang": "R", "max_stars_repo_path": "R/M8 run.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/M8 run.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/M8 run.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 22.406374502, "max_line_length": 178, "alphanum_fraction": 0.5574324324, "num_tokens": 4340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699433, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6489347456815211}} {"text": "#' Rotation of polygon\n#' @param mat Two-column numeric matrix. Coordinates of the polygon.\n#' @param origin Numeric vector of length two. Origin.\n#' @param alpha Numeric scalar. Rotation degree in radians.\n#' @export\nrotate <- function(mat, origin, alpha) {\n R <- matrix(\n c(cos(alpha), -sin(alpha), sin(alpha), cos(alpha)),\n nrow = 2, byrow = TRUE)\n\n origin <- matrix(c(origin[1], origin[2]), ncol=2, nrow = nrow(mat), byrow = TRUE)\n t(R %*% t(mat - origin)) + origin\n}\n", "meta": {"hexsha": "c55e0cb630a7fe8f8a0a2222c065678c3d657f59", "size": 481, "ext": "r", "lang": "R", "max_stars_repo_path": "R/misc.r", "max_stars_repo_name": "USCbiostats/polygons", "max_stars_repo_head_hexsha": "72249d5cc4a64193d7ead57fa11142868ca211cf", "max_stars_repo_licenses": ["MIT"], "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/misc.r", "max_issues_repo_name": "USCbiostats/polygons", "max_issues_repo_head_hexsha": "72249d5cc4a64193d7ead57fa11142868ca211cf", "max_issues_repo_licenses": ["MIT"], "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/misc.r", "max_forks_repo_name": "USCbiostats/polygons", "max_forks_repo_head_hexsha": "72249d5cc4a64193d7ead57fa11142868ca211cf", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 83, "alphanum_fraction": 0.6548856549, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6486822915238986}} {"text": " F02EKJ Example Program Results\n\nIteration Limit= 500\n Arnoldi basis vectors used: 20\n The following Ritz values (mu) are related to the\n true eigenvalues (lambda) by lambda = sigma + 1/mu\n\n Iteration number 1\n Ritz values converged so far ( 2) and their Ritz estimates:\n 1 ( 5.69917E-01, 8.80810E-01) 1.30081E-20\n 2 ( 5.69917E-01, -8.80810E-01) 1.30081E-20\n Next (unconverged) Ritz value:\n 3 ( 6.07774E-01, 0.00000E+00)\n\n The 5 Ritz values of closest to 5.50000E+00 are:\n 1 ( 6.01781E+00 , -8.00277E-01 )\n 2 ( 6.01781E+00 , 8.00277E-01 )\n 3 ( 4.34309E+00 , -1.94557E+00 )\n 4 ( 4.34309E+00 , 1.94557E+00 )\n 5 ( 7.14535E+00 , 0.00000E+00 )\n", "meta": {"hexsha": "925d7cb9d2518e17bd64a6a05aa67dcbb519f7c1", "size": 745, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/f02ekje.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/f02ekje.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/f02ekje.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": 35.4761904762, "max_line_length": 62, "alphanum_fraction": 0.5879194631, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6486062853801466}} {"text": "#' K-Means++ initialization to K-means\n#'\n#' INPUTS:\n#' x: The data formatted as a matrix.\n#' k: The number of clusters desired. \\code{k < nrows(x)}\n#' \n#'\n#' REFERENCE:\n#' Arthur, David and Vassilvitskii, Sergei k-means++: The Advantages of Careful Seeding\n#'\n\n\nkmpp <- function(x,k=2){\n\nla2 <- function(a,b){\n m1 <- matrix(as.numeric(a),nrow=dim(b)[1],ncol=dim(b)[2], byrow=TRUE)\n \n if(all(dim(m1) == dim(b))){\n dif <- apply((m1-b)^2,1,sum) \n return(dif)\n } else {\n stop(\"Wrong dimensions!\")}\n }\n\n### Step 1a\n#set.seed(2^13)\ns1 <- cp <- sample(nrow(x),1)\n\nind <- c(cp)\n\ncenters <- list()\n\ncenters[[1]] <- x[s1,]\n\np <- la2(x[s1,],x)\nP <- p/sum(p) ## P = D(x')^2/( ∑_x\\inX D(x)^2)\n\n### Step 1b-c\nfor( i in 2:k ) {\n #set.seed(2^13)\n cp <- sample(nrow(x),1,prob=P) ## c'\n centers[[i]] <-x[cp,]\n ind <- c(ind,cp)\n \n p <- apply(cbind(la2(x[cp,],x),p),1,min) #apply(cbind(p,ds[,cp]),1,min)\n P <- p/sum(p)\n }\n\nCtrs <- Reduce('rbind',centers)\n\nkObj <- kmeans(x, centers=Ctrs)\n\nreturn(kObj)\n} ### END FUNCTION\n\n\nbhkmpp <- function(x,blevels){\n require(data.table)\n\n k0 <- kmpp(x,2)\n L <- data.table(lv1=k0$cluster)\n\n for(y in 2:blevels){ L[[y]] <- 0L }\n colnames(L) <- paste0(\"lv\", 1:blevels)\n \n for(j in 1:(blevels-1)){\n for(i in sort(unique(L[[j]]))){\n ## Set seed to keep cluster labels somewhat consistant \n set.seed(13)\n kv <- kmpp(x[L[[j]] == i,], k = 2)\n if(i != 1){kv$cluster <- as.integer(kv$cluster + 2*(i-1))}\n L[L[[j]]==i,][[j+1]] <- kv$cluster\n }\n }\n return(L)\n}\n\n\n\n\n", "meta": {"hexsha": "86f18561a0179056a7f1026b9b9e31dd9da68406", "size": 1632, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/kmpp.r", "max_stars_repo_name": "neurodata-dev/synaptome-stats", "max_stars_repo_head_hexsha": "7637432355d4ccc169e5c3847dd123616f4594cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/kmpp.r", "max_issues_repo_name": "neurodata-dev/synaptome-stats", "max_issues_repo_head_hexsha": "7637432355d4ccc169e5c3847dd123616f4594cb", "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": "Code/kmpp.r", "max_forks_repo_name": "neurodata-dev/synaptome-stats", "max_forks_repo_head_hexsha": "7637432355d4ccc169e5c3847dd123616f4594cb", "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.1481481481, "max_line_length": 87, "alphanum_fraction": 0.5140931373, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6483006538293553}} {"text": "multiplier <- function(n1,n2) { (function(m){n1*n2*m}) }\nx = 2.0\nxi = 0.5\ny = 4.0\nyi = 0.25\nz = x + y\nzi = 1.0 / ( x + y )\nnum = c(x,y,z)\ninv = c(xi,yi,zi)\n\nmultiplier(num,inv)(0.5)\n\nOutput\n[1] 0.5 0.5 0.5\n", "meta": {"hexsha": "bbb0d6879b9077593d69b8d2c8c0c446038d6d07", "size": 209, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/First-class-functions-Use-numbers-analogously/R/first-class-functions-use-numbers-analogously-1.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/First-class-functions-Use-numbers-analogously/R/first-class-functions-use-numbers-analogously-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/First-class-functions-Use-numbers-analogously/R/first-class-functions-use-numbers-analogously-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": 13.9333333333, "max_line_length": 56, "alphanum_fraction": 0.5167464115, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6482655408450612}} {"text": "tb_lech_saiso <- function(x) {\n cat(\"tb: \", mean(x), \"\\n\")\n # tinh do lech tieu chuan\n cat(\"lech tieu chuan: \", sd(x), \"\\n\")\n # tinh\n cat(\"sai so chuan: \", sd(x)/sqrt(length(x)), \"\\n\")\n}\n\nfunc_6_1 <- function() {\n x <- c(1, 2, 5, 7, -3, 0, 5, 1, 5, 6)\n y <- c(2, 2, 0, -5, 7, 8, 11, 9, 3, 2)\n cat(\"x + y: \", x + y, \"\\n\")\n cat(\"x * y: \", x * y, \"\\n\")\n cat(\"x - y: \", x - y, \"\\n\")\n # z phan chan cua x\n z <- c()\n for (i in x) {\n if (i%%2 == 0) {\n z <- c(z, i)\n }\n }\n cat(\"z: \", z, \"\\n\")\n # t phan le cua y\n t <- c()\n for (i in y) {\n if (i%%2 == 0) {\n t <- c(t, i)\n }\n }\n cat(\"t: \", t, \"\\n\")\n # w lon hon 0\n w <- c()\n for (i in x) {\n if (i > 0) {\n w <- c(w, i)\n }\n }\n for (i in y) {\n if (i > 0) {\n w <- c(w, i)\n }\n }\n cat(\"w: \", w, \"\\n\")\n # tb, lech, sai so\n cat(\"x: \\n\")\n tb_lech_saiso(x)\n cat(\"min: \", min(x), \" max: \", max(x), \"\\n\")\n cat(\"tang dan: \", sort(x), \"\\n\")\n cat(\"y: \\n\")\n tb_lech_saiso(y)\n cat(\"min: \", min(y), \" max: \", max(y), \"\\n\")\n cat(\"giam dan\", sort(y, decreasing = T), \"\\n\")\n}\n", "meta": {"hexsha": "3e8753870c9b5db33da15f73ad7dc022f8eb4a4c", "size": 1203, "ext": "r", "lang": "R", "max_stars_repo_path": "src/week_6/prob-1.r", "max_stars_repo_name": "SummerSad/R-learn", "max_stars_repo_head_hexsha": "ea44c6f42980450dd3132dee19bbef2b10ee5d75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-25T14:56:24.000Z", "max_issues_repo_path": "src/week_6/prob-1.r", "max_issues_repo_name": "SummerSad/R-learn", "max_issues_repo_head_hexsha": "ea44c6f42980450dd3132dee19bbef2b10ee5d75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/week_6/prob-1.r", "max_forks_repo_name": "SummerSad/R-learn", "max_forks_repo_head_hexsha": "ea44c6f42980450dd3132dee19bbef2b10ee5d75", "max_forks_repo_licenses": ["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.2777777778, "max_line_length": 54, "alphanum_fraction": 0.3449709061, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7662936484231888, "lm_q1q2_score": 0.648240322593643}} {"text": "## Set up and plot hypothetical paths of productivity process\n\n## Set up scenarios\n# Each scenario has ID, theta, lambda, phi, gR, R0, A0\nscenario <- c('A','B','C','D','E')\ntheta <- c(.01,.01,.01,.01,.01)\nlambda <- c(1,1,1,1,.8)\nphi <- c(0,.8,-.8,0,0)\ngR <- c(.02,.02,.01,.04,.02)\nR0 <- c(1,1,2,1,1)\nA0 <- c(1,10,1,.9,10)\nlabel <- c('C','B','D','E','A') # allows different label for test purposes\n\n# Year vector gives total periods to run over\nyear <- c(0:400)\ns <- 0 # initializes vector\n\n# Merge year and scenario data to create scenario/year dataframe\nall_scenario <- data.frame(scenario,theta,lambda,phi,gR,R0,A0,label) # combine scenario parameters\nyear_scenario <- expand.grid(year,scenario) # create year/scenario combinations\nnames(year_scenario) <- c(\"year\",\"scenario\")\ns <- merge(year_scenario,all_scenario,by=\"scenario\") # add parameters to year/scenario combos\n\n# Make calculations of various values using theory\n# z is A^1-phi/R^lambda state variable, solved for first, then extract info\ns$conv <- 1-s$lambda*s$gR\ns$z <- (s$conv^s$year)*(s$A0^(1-s$phi))/(s$R0^(s$lambda)) + (1-s$conv^s$year)*(1-s$phi)*s$theta/(s$lambda*s$gR)\ns$RA <- 1/s$z # put this in R/A form\ns$gA <- s$theta/s$z # growth rate of A follows directly\ns$R <- s$R0*(1+s$gR)^(s$year) # constant growth of R\ns$lnA <- log(s$z)/(1-s$phi) + s$lambda*log(s$R)/(1-s$phi) # actual log of productivity\n\n# Plot figure of scenarios and their BGP's\nfig <- plot_ly(s, x = ~year, y = ~lnA, linetype = ~scenario, type = 'scatter', mode = 'lines')\n#fig <- add_trace(fig, x = ~year, y = ~lnystar, linetype = ~scenario, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'Log productivity', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Log of productivity (A)'),\n hovermode=\"x unified\")\n#api_create(fig, filename = \"sim-prod-lnA\")\n\nfig <- plot_ly(s, x = ~year, y = ~gA, linetype = ~scenario, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'Growth rate of productivity', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Growth rate of productivity'),\n hovermode=\"x unified\")\n#api_create(fig, filename = \"sim-prod-gA\")\n\nfig <- plot_ly(s, x = ~year, y = ~z, linetype = ~scenario, type = 'scatter', mode = 'lines')\nfig <- layout(fig, title = list(text = 'R/A ratio', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'R/A ratio'),\n hovermode=\"x unified\")\n#api_create(fig, filename = \"sim-prod-RA\")", "meta": {"hexsha": "cf68f9cb1bd57c29f99ef5ccd3027b7365fa6299", "size": 2557, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_Sim_Prod.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_Sim_Prod.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_Sim_Prod.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 47.3518518519, "max_line_length": 111, "alphanum_fraction": 0.6229956981, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6481151388034052}} {"text": "#number of trials\r\nn<-1000\r\n# the probability of success of single event is\r\nz<-0.001\r\nMean<-n*z\r\nprint(Mean)\r\n # Applying the Poisson probability distribution with U= 1\r\n\r\nU<-1\r\n# probability that none of a patients administered the drug experiences a particular side effect\r\n\r\ny<-0\r\nprobability_nopatientsideeffect<-((U^y)*(exp(1)^-U))/factorial(y)\r\nprint(probability_nopatientsideeffect)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "3caeab203e0d8ea1eea0ae20990b78c190f1a8ee", "size": 401, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.13/Ex4_13.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.13/Ex4_13.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.13/Ex4_13.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.2777777778, "max_line_length": 98, "alphanum_fraction": 0.7306733167, "num_tokens": 110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.648112333665361}} {"text": "x = (0:10)\n> x^2\n [1] 0 1 4 9 16 25 36 49 64 81 100\n> Reduce(function(y,z){return (y+z)},x)\n[1] 55\n> x[x[(0:length(x))] %% 2==0]\n[1] 0 2 4 6 8 10\n", "meta": {"hexsha": "764df9d327ebf2ebbb50952a32d55ae3148d82dc", "size": 165, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/List-comprehensions/R/list-comprehensions-1.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/List-comprehensions/R/list-comprehensions-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/List-comprehensions/R/list-comprehensions-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": 20.625, "max_line_length": 48, "alphanum_fraction": 0.4484848485, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6477430879504326}} {"text": "## See Paul T von Hippel, The American Statistician 58:160-164, 2004\n\nmvector <- c(0,0)\nmsigma <- matrix(c(1,0.5,0.5,1), nrow=2)\nlibrary(mvtnorm)\nlibrary(Hmisc)\n\n# XZ <- rmvnorm(1000, mvector, msigma)\nmvrnorm <- function(n, p = 1, u = rep(0, p), S = diag(p)) {\n Z <- matrix(rnorm(n * p), p, n)\n t(u + t(chol(S)) %*% Z)\n}\n\nXZ <- mvrnorm(1000, 2, mvector, msigma)\n \nU <- rnorm(1000)\nY <- XZ[,1]+XZ[,2]+U\nsummary(lm(Y ~ XZ))\nX <- XZ[,1]\nZ <- XZ[,2]\nZ.ni <- Z\n\ntype <- c('random','X<0','Y<0','Z<0')[3]\ni <- switch(type,\n random= runif(1000) < .5,\n 'X<0' = X<0,\n 'Y<0' = Y<0,\n 'Z<0' = Z<0)\n\nZna <- Z\nZna[i] <- NA\nsummary(lm(Y ~ X + Zna))\n\n#w <- aregImpute(~monotone(Y)+monotone(X)+monotone(Zna))\n#w <- aregImpute(~I(Y)+I(X)+I(Zna),fweight=.75)\nw <- aregImpute(~monotone(Y)+monotone(X)+monotone(Zna), n.impute=5,\n type='regression') \n\nplot(w)\nEcdf(Zna, add=T, col='red')\nEcdf(Z, add=T, col='green')\n# plot(w$imputed$Zna, Z[is.na(Zna)]) # use if n.impute=1\n# abline(a=0,b=1,lty=2)\n# lm(Z[is.na(Zna)] ~ w$imputed$Zna)\n\ncoef(fit.mult.impute(Y~X+Zna, lm, w, data=data.frame(X,Zna,Y),pr=F))\n\n#--------------------------------------------------------------------\n## From Ewout Steyerberg\n# Missing values: illustrate MCAR, MAR, MNAR mechanism\n# linear models\nlibrary(rms)\n\n## 1. x1 and x2 with y1 outcome\n## A) X only\n## B) X+Y\n\n#########################\n### Test Imputation ###\n### use aregImpute in default settings\n#########################\n\nn <- 20000 # arbitrary sample size\nx2 <- rnorm(n=n, mean=0, sd=1) # x2 standard normal\nx1 <- sqrt(.5) * x2 + rnorm(n=n, mean=0, sd=sqrt(1-.5)) # x2 correlated with x1\ny1 <- 1 * x1 + 1 * x2 + rnorm(n=n, mean=0, sd=sqrt(1-0)) # generate y\n# var of y1 larger with correlated x1 - x2\n\nx1MCAR <- ifelse(runif(n) < .5, x1, NA) # MCAR mechanism for 50% of x1\nx1MARx <- ifelse(rnorm(n=n,sd=.8) < x2, x1, NA) # MAR on x2, R2 50%, 50% missing (since mean x2==0)\nx1MARy <- ifelse(rnorm(n=n,sd=(sqrt(3)*.8)) >y1, x1, NA) # MAR on y, R2 50%, 50% missing (since mean y1==0)\n# x1MNAR <- ifelse(rnorm(n=n,sd=.8) < x1, x1, NA) # MNAR on x1, R2 50%, 50% missing (since mean x1==0)\nx1MNAR <- ifelse(rnorm(n=n,sd=.8) < x1, x1, NA) # MNAR on x1, R2 50%, 50% missing (since mean x1==0)\n\nplot(x2, x1MARx)\nplsmo(x2, is.na(x1MARx), datadensity=TRUE)\ndd <- datadist(x2,x1MARx)\noptions(datadist='dd')\nf <- lrm(is.na(x1MARx) ~ rcs(x2,4))\nplot(Predict(f, x2, fun=plogis))\n\nd <- data.frame(y1,x1,x2,x1MCAR, x1MARx,x1MARy,x1MNAR)\nols(y1~x1+x2)\nols(y1 ~ x1MARx + x2)\n\n# MAR on x: 3 approaches; CC, MI with X, MI with X+Y\n\ng <- aregImpute(~I(y1) + I(x1MARx) + I(x2), n.impute=5, data=d, pr=F, \n type=c('pmm','regression')[1], match='closest', plotTrans=TRUE)\nplot(g)\nEcdf(x1, add=TRUE, col='red',q=.5)\nEcdf(x1MARx, add=TRUE, col='blue',q=.5)\n\nf <- fit.mult.impute(y1 ~ x1MARx + x2, ols, xtrans=g, data=d, pr=F)\ng <- aregImpute(~y1 + x1MARx + x2, n.impute=5, data=d, pr=F, type='regression', plotTrans=TRUE)\nf <- fit.mult.impute(y1 ~ x1MARx + x2, ols, xtrans=g, data=d, pr=F)\n\n# MAR on y: 3 approaches; CC, MI with X, MI with X+Y\nf <- ols(y1~x1MARy+x2)\nif(FALSE) {\nMat.imputation[i,29:32] <- c(coef(f)[2:3], sqrt(diag(vcov(f)))[2:3])\ng <- aregImpute(~x1MARy + x2, n.impute=5, data=d, pr=F, type='regression')\nf <- fit.mult.impute(y1 ~ x1MARy + x2, ols, xtrans=g, data=d, pr=F)\nMat.imputation[i,33:36] <- c(coef(f)[2:3], sqrt(diag(vcov(f)))[2:3])\ng <- aregImpute(~y1 + x1MARy + x2, n.impute=5, data=d, pr=F, type='regression')\nf <- fit.mult.impute(y1 ~ x1MARy + x2, ols, xtrans=g, data=d, pr=F)\nMat.imputation[i,37:40] <- c(coef(f)[2:3], sqrt(diag(vcov(f)))[2:3])\n}\n", "meta": {"hexsha": "2e9e3151acd15713e3e4a27773dda71d802fced8", "size": 3726, "ext": "r", "lang": "R", "max_stars_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/aregImpute.r", "max_stars_repo_name": "klodzikowski/phongames", "max_stars_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-27T10:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T09:57:34.000Z", "max_issues_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/aregImpute.r", "max_issues_repo_name": "klodzikowski/phongames", "max_issues_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2019-12-28T07:09:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:33:50.000Z", "max_forks_repo_path": ".checkpoint/2018-05-06/lib/x86_64-apple-darwin15.6.0/3.5.1/Hmisc/tests/aregImpute.r", "max_forks_repo_name": "klodzikowski/phongames", "max_forks_repo_head_hexsha": "7dcc3cec90d44342653a53e8e3738b9ed3cb844a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-03-05T05:52:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T07:52:04.000Z", "avg_line_length": 34.1834862385, "max_line_length": 109, "alphanum_fraction": 0.5676328502, "num_tokens": 1549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6474096246658344}} {"text": "###############################################################\r\n#\r\n# WindPlume - an R script to conduct Monte Carlo analyses\r\n# with a simple atmospheric dispersion model\r\n#\r\n###############################################################\r\n\r\n### definitions ###\r\n\r\noptions(stringsAsFactors = FALSE)\r\n\r\nlibrary(reshape)\r\n\r\nrequire(compiler)\r\nenableJIT(3)\r\n\r\n#setwd(\"C:/Users/wmcnab/Desktop/fall 2016 projects/air dispersion R\")\r\nsetwd(\"D:/fall 2016 projects/air dispersion R\")\r\n\r\n\r\nWindVector <- function(intense_bin, orient_bin, orient, compass) {\r\n\r\n # posit wind velocity magnitude\r\n if (intense_bin == \"CALM\") {\r\n v_min <- 0.0\r\n v_max <- 0.5\r\n }\r\n else if (intense_bin == \">46\") {\r\n v_min <- 46.\r\n v_max <- 46.\r\n }\r\n else {\r\n bounds <- strsplit(intense_bin, \"-\")[[1]]\r\n v_min <- as.numeric(bounds[1]) - 0.5\r\n v_max <- as.numeric(bounds[2]) + 0.5\r\n }\r\n v <- runif(1, v_min, v_max) * 0.447 # convert MPH to m/sec\r\n \r\n # posit wind direction (origin)\r\n if (orient_bin != \"CALM\"){ \r\n delin <- match(orient_bin, orient)\r\n angle_center <- compass[delin]\r\n angle_min <- angle_center - 22.5/2.\r\n angle_max <- angle_center + 22.5/2.\r\n }\r\n else {\r\n angle_min <- 0.\r\n angle_max <- 360.\r\n }\r\n angle <- runif(1, angle_min, angle_max)\r\n if (angle < 0.) {angle <- 360. + angle}\r\n\r\n return (c(v, angle*pi/180.)) # convert angle to radians \r\n}\r\n\r\n\r\nStability <- function(v, day_f, stability){\r\n\r\n # assign atmospheric stability class\r\n\r\n if (v<2) {row <- 1} # wind velocity magnitude component\r\n else if (v>=2 & v<3) {row <- 2} \r\n else if (v>=3 & v<4) {row <- 3} \r\n else if (v>=4 & v<6) {row <- 4} \r\n else {row <- 5}\r\n\r\n if (day_f <= 0.5) {col <- 1} # solar irradiation component\r\n else {col <- 2}\r\n\r\n return (stability[row, col])\r\n}\r\n\r\n\r\nDispersion <- function(x, stable_class){\r\n \r\n # assign transverse and vertical dispersion coefficients (standard terrain)\r\n \r\n switch(stable_class,\r\n A = {\r\n sigma_y <- 0.22*x / sqrt(1.0 + 0.0001*x)\r\n sigma_z <- 0.2*x \r\n },\r\n B = {\r\n sigma_y <- 0.16*x / sqrt(1.0 + 0.0001*x)\r\n sigma_z <- 0.12*x \r\n }, \r\n C = {\r\n sigma_y <- 0.11*x / sqrt(1.0 + 0.0001*x)\r\n sigma_z <- 0.08*x / sqrt(1.0 + 0.0002*x) \r\n }, \r\n D = {\r\n sigma_y <- 0.08*x / sqrt(1.0 + 0.0001*x)\r\n sigma_z <- 0.06*x / sqrt(1.0 + 0.0015*x) \r\n }, \r\n E = {\r\n sigma_y <- 0.06*x / (1.0 + 0.0001*x)\r\n sigma_z <- 0.03*x / (1.0 + 0.0003*x) \r\n }, \r\n F_ = {\r\n sigma_y <- 0.04*x / (1.0 + 0.0001*x)\r\n sigma_z <- 0.016*x / (1.0 + 0.0003*x) \r\n } \r\n \r\n )\r\n \r\n return (c(sigma_y, sigma_z))\r\n \r\n}\r\n\r\n\r\nRotate <- function(x, y, theta) {\r\n \r\n # rotate coordinate system about theta\r\n x_prime <- x*cos(theta) - y*sin(theta)\r\n y_prime <- x*sin(theta) + y*cos(theta)\r\n\r\n return (c(x_prime, y_prime))\r\n \r\n }\r\n\r\n\r\nC <- function(x, y, z, u, H, flux, stable_class) {\r\n \r\n # calculate time-integrated concentration at x, y, z\r\n \r\n if (x > 0) {\r\n sigma <- Dispersion(x, stable_class)\r\n sigma_y = sigma[1]\r\n sigma_z = sigma[2] \r\n f <- exp(-(y**2./(2.*sigma_y**2)))\r\n g1 <- exp(-((z - H)**2./(2.*sigma_z**2)))\r\n g2 <- exp(-((z + H)**2./(2.*sigma_z**2)))\r\n conc <- flux/u * f/(sigma_y*sqrt(2.*pi)) * (g1 + g2)/(sigma_z*sqrt(2.*pi))\r\n }\r\n else\r\n {conc <- 0.}\r\n \r\n return (conc)\r\n \r\n }\r\n\r\n\r\nWindPlume <- function(){\r\n\r\n ### this is the main function of this script; specifies parameter sets, reads data, calls other functions, writes output\r\n\r\n # basic parameters\r\n num_trials <- 10000\r\n d_min <- 5.\r\n d_max <- 60.\r\n H <- 5. \r\n z <- 2.\r\n Q <- 2.\r\n log_avg_C0 <- 1.0\r\n log_stdev_C0 <- 0.3\r\n \r\n # define working parameter sets\r\n compass <- c(90., 67.5, 45., 22.5, 0., 337.5, 315., 292.5, 270., 247.5, 225., 202.5, 180., 157.5, 135., 112.5, 0.)\r\n stability_table <- matrix(c(\"A\", \"B\", \"F_\", \"A\", \"C\", \"E\", \"B\", \"C\", \"D\", \"C\", \"D\", \"D\", \"C\", \"D\", \"D\"),\r\n nrow=5, ncol=3, byrow = TRUE)\r\n\r\n # read in meteorology data\r\n wind_df <- read.csv(file=\"wind.txt\", sep=\"\\t\", header=TRUE)\t\r\n \r\n # record bin labels for velocity ranges and direction\r\n orient <- colnames(wind_df)[-1]\r\n intense <- wind_df[,1] \r\n\r\n # set up wind bins lookup table\r\n wind_bins_df <- melt(wind_df)\r\n colnames(wind_bins_df) <- c(\"intensity\", \"direction\", \"freq\")\r\n wind_bins_df$direction <- as.character(wind_bins_df$direction)\r\n wind_bins_df <- subset(wind_bins_df, freq > 0.)\r\n wind_bins_df$cumul <- cumsum(wind_bins_df$freq)\r\n rownames(wind_bins_df) <- NULL\r\n\r\n # posit source term vector\r\n log_C0 <- rnorm(num_trials, log_avg_C0, log_stdev_C0)\r\n C0 <- 10.**log_C0 \r\n flux <- Q * C0 \r\n\r\n # posit receptor location vectors\r\n d <- runif(num_trials, d_min, d_max)\r\n psi <- runif(num_trials, 0., 2.*pi)\r\n x <- d * cos(psi)\r\n y <- d * sin(psi)\r\n\r\n # create (empty) data frame to hold model results, one row per trial\r\n results_df <- data.frame(\"C0\" = double(num_trials),\r\n \"x\" = double(num_trials),\r\n \"y\" = double(num_trials),\r\n \"w_origin\" = character(num_trials),\r\n \"theta\" = double(num_trials),\r\n \"v\" = double(num_trials),\r\n \"s_class\" = character(num_trials),\r\n \"conc\" = double(num_trials),\r\n stringsAsFactors=FALSE)\r\n \r\n # generate trials \r\n\r\n for (i in 1:num_trials){\r\n \r\n # select random numbers to choose wind vector and solar irradiation conditions\r\n r <- runif(1, 0., 1.)\r\n day_f <- runif(1, 0., 1.) \r\n floor <- ifelse(r > wind_bins_df$cumul, 1, 0) \r\n bins_index <- sum(floor) + 1\r\n bins_index <- min(nrow(wind_bins_df), bins_index)\r\n\r\n # posit meteorology\r\n wvector <- WindVector(wind_bins_df$intensity[bins_index], wind_bins_df$direction[bins_index], orient, compass)\r\n v <- wvector[1]\r\n theta <- wvector[2]\r\n if (theta>pi) {theta_point <- theta - pi} # point theta 180 degrees away for orientation of local positive x-axis\r\n else {theta_point <- theta + pi}\r\n rot_pt <- Rotate(x[i], y[i], -theta_point)\r\n x_prime <- rot_pt[1]\r\n y_prime <- rot_pt[2] \r\n s <- Stability(v, day_f, stability_table) \r\n\r\n # run Gaussian plume model\r\n conc <- C(x_prime, y_prime, z, v, H, flux[i], s) \r\n \r\n # append results to data frame\r\n wind_dir <- wind_bins_df$direction[bins_index]\r\n results_df[i, ] <- c(C0[i], x[i], y[i], wind_dir, theta, v, s, conc)\r\n \r\n }\r\n\r\n write.csv(results_df, file = \"results.csv\") \r\n\r\n}\r\n\r\n# run the air dispersion script\r\n\r\nptm <- proc.time()\r\nWindPlume()\r\nprint (proc.time() - ptm)\r\n\r\n# process results ...\r\nnum_trials <- 10000\r\nd_min <- 5.\r\nd_max <- 60.\r\nH <- 5. \r\nz <- 2.\r\nQ <- 2.\r\nlog_avg_C0 <- 1.0\r\nlog_stdev_C0 <- 0.3\r\nmodel <- read.csv(file=\"results.csv\", sep=\",\", header=TRUE)\r\nC0 = 10.**log_avg_C0\r\ncount_steps <- c(0.01, 0.001, 0.0001, 1e-5, 1e-6)\r\nnum_bins = length(count_steps) + 1\r\n\r\n# pie graph to summarize exposure probability\r\ncount_bin <- double(num_bins)\r\ncount_bin[1] <- sum(ifelse(model$conc>=count_steps[1]*C0, 1, 0))\r\nfor (i in 2:(num_bins-1)) {\r\n count_bin[i] <- sum(ifelse(model$conc>=count_steps[i]*C0, 1, 0)) - count_bin[i-1]\r\n }\r\ncount_bin[num_bins] <- num_trials - count_bin[num_bins-1]\r\nlbls <- c(\">0.01\", \"0.001 - 0.01\", \"0.0001 - 0.001\", \"0.00001 - 0.0001\", \"0.000001 - 0.00001\", \"<0.000001\")\r\npct <- round(count_bin/num_trials*100)\r\nlbls <- paste(lbls, pct) # add percents to labels \r\nlbls <- paste(lbls,\"%\",sep=\"\") # ad % to labels \r\npie(count_bin,labels = lbls, col=rainbow(length(lbls)),\r\n main=\"Normalized Conc Exposures\")\r\n\r\n# augment model results data frame with concentration bin designation (for plotting)\r\nmodel$bin <- ifelse(model$conc>=count_steps[1]*C0, 1, 0)\r\nfor (i in 2:(num_bins-1)) {\r\n model$bin <- model$bin + ifelse((model$conc>=count_steps[i]*C0) & (model$conc 0.05, then use random effects\nphtest(fixed, random)\n\n################# Robusto\nsummary(random, robust = TRUE)\n\n# Test de normalidad de residuos\nresiduos=residuals(random)\nresiduos\n#jarqueberaTest(residuos)\njarque.bera.test(residuos)\n\n# stationarity residuals\n#Testing for unit roots/stationarity |||| If p-value < 0.05 then no unit roots present\nadf.test(residuos, k=2)\n\n### Testing for serial correlation |||| If p-value > 0.05, No serial correlation\npbgtest(random)\n\n### Testing for heteroskedasticity |||| If p-value > 0.05, No Presence of heteroskedasticity \n# If hetersokedaticity is detected you can use robust covariance matrix to account for it. See the following pages.\nlibrary(lmtest)\nbptest(IDHr ~ IGINICEPAL+INBpc+GasSocial+VOZYREND + factor(COD), data = datos, studentize=F)\n\n# Heteroskedasticity consistent coefficients (Arellano) Corrección\ncoeftest(fixed, vcovHC(fixed, method = \"arellano\")) \n\n\n\n", "meta": {"hexsha": "4262f19aeba5e6bde9a5146869e5e583f56a982e", "size": 2766, "ext": "r", "lang": "R", "max_stars_repo_path": "script.r", "max_stars_repo_name": "mogollonalex/Panel_Data_R", "max_stars_repo_head_hexsha": "d5027b12a5cadba35c59121eb8d41465a471cefa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script.r", "max_issues_repo_name": "mogollonalex/Panel_Data_R", "max_issues_repo_head_hexsha": "d5027b12a5cadba35c59121eb8d41465a471cefa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script.r", "max_forks_repo_name": "mogollonalex/Panel_Data_R", "max_forks_repo_head_hexsha": "d5027b12a5cadba35c59121eb8d41465a471cefa", "max_forks_repo_licenses": ["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.1627906977, "max_line_length": 166, "alphanum_fraction": 0.7133044107, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6470000333522986}} {"text": "model_netradiationequivalentevaporation <- function (lambdaV = 2.454,\n netRadiation = 1.566){\n #'- Name: NetRadiationEquivalentEvaporation -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: NetRadiationEquivalentEvaporation Model\n #' * Author: Pierre Martre\n #' * Reference: Modelling energy balance in the wheat crop model SiriusQuality2:\n #' Evapotranspiration and canopy and soil temperature calculations\n #' * Institution: INRA/LEPSE Montpellier\n #' * ExtendedDescription: It is given by dividing net radiation by latent heat of vaporization of water \n #' * ShortDescription: It is given by dividing net radiation by latent heat of vaporization of water\n #'- inputs:\n #' * name: lambdaV\n #' ** description : latent heat of vaporization of water\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 2.454\n #' ** min : 0\n #' ** max : 10\n #' ** unit : MJ kg-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: netRadiation\n #' ** description : net radiation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 1.566\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : MJ m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #'- outputs:\n #' * name: netRadiationEquivalentEvaporation\n #' ** variablecategory : auxiliary\n #' ** description : net Radiation in Equivalent Evaporation \n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n netRadiationEquivalentEvaporation <- netRadiation / lambdaV * 1000.0\n return (list('netRadiationEquivalentEvaporation' = netRadiationEquivalentEvaporation))\n}", "meta": {"hexsha": "cf23d3d558e0ce6e14f260abf43cbc7cbe0510f6", "size": 2623, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Energy_Balance/Netradiationequivalentevaporation.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_stars_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/SQ_Energy_Balance/Netradiationequivalentevaporation.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_issues_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "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": "src/r/SQ_Energy_Balance/Netradiationequivalentevaporation.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_forks_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "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": 59.6136363636, "max_line_length": 120, "alphanum_fraction": 0.4613038506, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.646934702888535}} {"text": "# ************************************************\n### simon munzert\n### panel data II\n# ************************************************\n\nsource(\"packages.r\")\nsource(\"functions.r\")\n\n\n## CRAN Task View on econometrics (including panel data models)\nbrowseURL(\"https://cran.r-project.org/web/views/Econometrics.html\")\n\n\n# ************************************************\n# Example: Comparative Political Dataset ---------\n\ndat <- read_dta(\"../data/CPDS-1960-2015.dta\")\ndat <- dplyr::select(dat, year, country, iso, gov_left2, socexp_t_pmp, instcons, unemp, eu)\nhead(dat)\n\n\n\n# ************************************************\n# Panel data econometrics with R: the plm package\n\nlibrary(plm)\n\n# inspect dimensionality\npdim(dat, index = c(\"iso\", \"year\"))\n\n# panel data estimators\nplm() # plm can do (amongst others):\n # pooling: --> model = \"pooling\" (same as lm())\n # fixed effects: --> model = \"within\"\n # random effects: --> model = \"random\"\n # first differences: --> model = \"fd\"\n\n# various tests\nmtest() # Arellano-Bond test of serial correlation\npbgtest() # Breusch-Godfrey test\npdwtest () # Durbin-Watson test\nphtest() # Hausman test\nplmtest() # Lagrange multiplier tests\npurtest() # Unit root tests\n\n# extract fixed effects\nfixef()\n\n# make data balanced\nmake.pbalanced()\n\n# extract indices of panel data\nindices <- index(model_fe)\ntable(indices$iso, indices$year)\n\n# for more information, see\nbrowseURL(\"https://cran.r-project.org/web/packages/plm/vignettes/plm.pdf\")\n\n\n\n# ************************************************\n# Implementing the Fixed-Effects estimator -------\n\n# pooled OLS\nsummary(model_pooled <- lm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat))\nhist(dat$gov_left2)\n# interplot(model_pooled, var1 = \"gov_left2\", var2 = \"instcons\")\n# interplot(model_pooled, var1 = \"gov_left2\", var2 = \"unemp\")\n\n# pooled OLS with plm\nsummary(model_pooled_plm <- plm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat, index = c(\"iso\", \"year\"), model = \"pooling\"))\n\n# fixed-effects estimator, manually\nsummary(model_fe <- lm(socexp_t_pmp ~ gov_left2 + instcons + unemp + iso, data = dat))\n\n# fixed-effects estimator with plm\nsummary(model_fe_plm <- plm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat, index = c(\"iso\", \"year\"), model = \"within\"))\n\n# F test for fixed effects\npFtest(model_fe_plm, model_pooled_plm) # F test FE vs pooling model\n\n\n\n\n# ************************************************\n# How do fixed effects look like? ----------------\n\n# visualize fixed effects\nfixed_effects <- c(coef(model_fe)[1], \n coef(model_fe)[1] + coef(model_fe)[5:(length(coef(model_fe)))])\nfe_dat <- data.frame(iso = unique(model_fe$model$iso),\n fixed_effect = fixed_effects)\n\n# we could've had this easier...\nfixef(model_fe_plm)\n\n# plot fixed effects\nggplot(fe_dat, aes(x = reorder(iso, fixed_effect), y = fixed_effect)) + geom_bar(stat = \"identity\") + labs(x = \"\")\n\n# compute raw means\ndat_sum <- group_by(dat, iso) %>% summarize(n_obs = n(), \n mean_socexp = mean(socexp_t_pmp, na.rm = T))\n\n# merge model fixed effects with raw means: don't confuse fixed effects with \"normal levels\" or something - they simply account for unobserved constant effects, i.e. the portion of y in i that is not explained by the other, time-varying covariates and that is unit-constant across time\nfe_dat <- merge(fe_dat, dat_sum, by = \"iso\", all.x = TRUE)\nplot(fe_dat$fixed_effect, fe_dat$mean_socexp)\ntext(fe_dat$fixed_effect, fe_dat$mean_socexp, fe_dat$iso)\n\n\n\n# ******************************************************\n# LSDV/FE estimation: Is demeaning and introducing \n# unit dummies really equivalent?\n\nset.seed(1)\nx = rnorm(100)\nfe = rep(rnorm(10), each = 10)\nid = rep(1:10,each = 10)\nti = rep(1:10, 10)\ne = rnorm(100)\ny = x + fe + e\ndat_sim = data.frame(y, x, id, ti)\n\n# standard FE model\nreg_fe = plm(y ~ x, model = \"within\", index = c(\"id\", \"ti\"), data = dat_sim)\nsummary(reg_fe)\n\n# FE model using demeaning\ny_dem = y - tapply(y, id, mean)[id]\nx_dem = x - tapply(x, id, mean)[id]\n\nreg_dem = lm(y_dem ~ -1 + x_dem) # note that we do not estimate the intercept because we have demeaned the data\nsummary(reg_dem) # note that the standard error is wrong. We would need to account for that we are losing degrees of freedom by taking out the fixed effects.\n\n\n# ******************************************************\n# What about time-fixed effects?\n\n # would pick up variation in the outcome that occurs over time and is not attributed to other explanatory variables\n # --> capture the influence of aggregate (time-series) trends\n # could help you deal with heteroskedasticity \n\n# fixed-effects estimator with plm\nsummary(model_fe_time <- plm(socexp_t_pmp ~ gov_left2 + instcons + gov_left2 + unemp + as.factor(year), data = dat, index = c(\"iso\", \"year\"), model = \"within\"))\n\n# test for the need of time-fixed effects\npFtest(model_fe_time, model_fe_plm)\n\n# Breusch-Pagan test for heteroskedasticity across time\nplmtest(model_fe_plm, effect = c(\"time\"), type = (\"bp\"))\n\n\n\n\n\n# ************************************************\n# Implementing the Random-Effects estimator ------\n\nsummary(model_re_plm <- plm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat, index = c(\"iso\", \"year\"), model = \"random\"))\n\nformat(coef(model_fe_plm), scientific = FALSE)\nformat(coef(model_re_plm), scientific = FALSE)\n\n# Hausman test\nphtest(model_fe_plm, model_re_plm)\n\n\n\n# ************************************************\n# Using Panel-Corrected Standard Errors (PCSEs) --\n\n\n# Beck and Katz 1995: \n # TSCS data, such as country panels, often tackled with models that do not account properly for complex error structures (autocorrelation, heteroskedasticity - it's a mess!)\n # finding: frequently applied FGLS produces dramatically inaccurate coefficient standard errors\n # PCSE estimator suggested \n\n\n# pooled OLS\n\n\n# extract complete cases\ndat_sub <- dplyr::select(dat, socexp_t_pmp, gov_left2, instcons, unemp, iso, year)\ndat_sub <- dat_sub[complete.cases(dat_sub),]\n\n# run OLS\nsummary(model_pooled <- lm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat_sub))\n\n# panel-corrected standard errors\nmodel_pcse <- pcse(model_pooled, groupN = dat_sub$iso, groupT = dat_sub$year)\nsummary(model_pcse)\n\n# pcse() cannot be applied on plm objects - there is another solution:\nsummary(model_pooled <- plm(socexp_t_pmp ~ gov_left2 + instcons + unemp, data = dat_sub, index = c(\"iso\", \"year\"), model = \"pooling\"))\nplm2 <- coeftest(model_pooled, vcov=function(x) vcovBK(x, type = \"HC1\", cluster = \"time\"))\nplm2\n\n\n", "meta": {"hexsha": "a37456f6732bc94f511501c3c31abb83086a7d9f", "size": 6598, "ext": "r", "lang": "R", "max_stars_repo_path": "code/06-panel-data-2.r", "max_stars_repo_name": "simonmunzert/stats-II-hertie-2017", "max_stars_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_stars_repo_licenses": ["MIT"], "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/06-panel-data-2.r", "max_issues_repo_name": "simonmunzert/stats-II-hertie-2017", "max_issues_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_issues_repo_licenses": ["MIT"], "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/06-panel-data-2.r", "max_forks_repo_name": "simonmunzert/stats-II-hertie-2017", "max_forks_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-18T08:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-22T08:28:12.000Z", "avg_line_length": 33.1557788945, "max_line_length": 285, "alphanum_fraction": 0.6489845408, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6468391666187141}} {"text": "# split plot ANOVA \r\n\r\nclass <- read.table('class.txt',header=T,as.is=T)\r\n\r\n# convert group variables to factors\r\nclass$class.f <- as.factor(class$class)\r\nclass$method.f <- as.factor(class$method)\r\nclass$tutor.f <- as.factor(class$tutor)\r\n\r\n# aov has more helper functions, but it only works correctly for\r\n# balanced data\r\n\r\n\r\nclass.aov <- aov(score~method.f*tutor.f+Error(method.f:class.f),data=class)\r\n\r\n# aov complains that error is singular, \r\n# but results seem to be correct\r\n\r\n# the * generates main effects and all interactions (SAS's |)\r\n# the : generates interaction (SAS's *)\r\n\r\n# fixed effects go in the usual place\r\n# random effects go in the Error() function.\r\n# need to specifically indicate that class and method are related\r\n# 'all combinations of method and class', i.e. method.f:class.f does this\r\n\r\n# if you replace Error(method.f:class.f) with Error(class.f)\r\n# Method is tested against the error MS, not the class MS\r\n\r\n# helper functions include:\r\n\r\nmodel.tables(class.aov,type='means')\r\n# marginal means and cell means\r\n\r\nmodel.tables(class.aov,type='means',se=T)\r\n# if you try to get s.e's, you get told 'not yet implemented'\r\n# for a multiple e.u. model\r\n\r\nsummary(class.aov)\r\n# gives you the anova table given separately for each\r\n# error term\r\n\r\n# the residual standard error is the sqrt(MSE) for each stratum\r\n\r\n\r\n# the alternative is to use the mixed model workhorse: \r\n# lmer in the lme4 package\r\n\r\nlibrary(lme4)\r\n\r\nclass.lmer <- lmer(score~method.f*tutor.f+(1|method.f:class.f),data=class)\r\n\r\n# fixed effects in the usual place\r\n# random effects are indicated inside ()\r\n# by the parameter that varies (here, the intercept)\r\n# and the group that it varies by \r\n# (here, all comb. of method and class)\r\n\r\n# again, if you use class instead of class:method, method\r\n# gets tested against the MSerror\r\n\r\nprint(class.lmer) # or summary(class.lmer)\r\n# gives you estimates of the variance components\r\n# the fixed effect estimates are the regression coefficients for\r\n# the columns of X variables used by R\r\n\r\nanova(class.lmer)\r\n# gives you an anova table, but it doesn't indicate\r\n# error df or give you p-values.\r\n\r\n# if there is an option to do this, please let me know and\r\n# I will update this information\r\n\r\n# if there is an easy way to get marginal means (especially for\r\n# unbalanced data), please let me know.\r\n\r\n# for unbalanced data, my understanding is that the R tests \r\n# are sequential (Type I), not type III. The usual way to get\r\n# type III tests, using drop1(XXX, .~.) does not appear to work\r\n# with lmer objects.\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "24aac38ee60af6c5c127ae63af49fa3b3f54fee0", "size": 2595, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/splitteach.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/splitteach.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/splitteach.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5294117647, "max_line_length": 76, "alphanum_fraction": 0.7071290944, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6466714465192988}} {"text": "# Barometric formula: altitude analysis\n# https://en.wikipedia.org/wiki/Barometric_formula\n# Ideal law: P = rho * R/M * T\n\nround_timestamp <- function(ts, scalefactor.sec = 3600*12) {\n as.POSIXct(round(as.numeric(ts)/scalefactor.sec) * scalefactor.sec, origin = '1970-01-01', tz = 'UTC')\n}\n\nlogger.names <- grep('barometer/', gwloggeR.data::enumerate(), value = TRUE)\n\nlogger.names <- setdiff(logger.names, 'barometer/BAOL016X_W1666.csv')\nlogger.names <- setdiff(logger.names, 'barometer/BAOL050X_56819.csv') # high freq manu in range of 80 cmH2O\n\ndf.list <- sapply(logger.names, function(name) {\n df <- gwloggeR.data::read(name)$df\n\n # Filter\n df <- df[!duplicated(TIMESTAMP_UTC), ]\n df <- df[!is.na(PRESSURE_VALUE), ]\n df <- df[!is.na(TIMESTAMP_UTC), ]\n\n # Aggregate\n df <- df[, .('PRESSURE_VALUE' = mean(PRESSURE_VALUE)),\n by = .('TIMESTAMP_UTC' = round_timestamp(TIMESTAMP_UTC))]\n\n # Filter\n df <- df[PRESSURE_VALUE < 1100,]\n df <- df[PRESSURE_VALUE > 975,]\n\n # Meta data\n df[, FILE := basename(name)]\n df[, N := .N]\n\n data.table::setkey(df, TIMESTAMP_UTC)\n\n df\n}, simplify = FALSE, USE.NAMES = TRUE)\n\ndf <- data.table::rbindlist(df.list, use.names = TRUE)\n\nmedians <- sapply(df.list, function(df) {\n median(df$PRESSURE_VALUE, na.rm = TRUE)\n}, simplify = TRUE, USE.NAMES = TRUE)\n\n# Load functions from analysis 07.\nsys.source('./drifts/analysis_07.r', envir = (bf <- new.env()))\n\n# This function computes the altitude in function of pressure.\n# LR stands for lapse rate: the drop in temperature in function of altitude is\n# here taken into consideration. For altitude between 0 and 11 km, the drop\n# in temperature is taken as a linear function: T = T_b + L_b*h.\n# See: https://en.wikipedia.org/wiki/Barometric_formula#Derivation\n# Other assumption here is that the air pressure is hydrostatic (i.e. \"fluid\" is not moving).\nbf$h.lr <- function(P.Pa) {\n A <- g0 * M / (R * L_b)\n B <- log(P_b / P.Pa)/A + log(T_b)\n (exp(B) - T_b)/L_b + h_b\n}\nenvironment(bf$h.lr) <- bf\n\nbf$h.lr(bf$P_b)\nbf$h.lr(bf$P.lr(50)) # Test, should be the same as input: 50\n\nmedians.Pa <- sapply(medians, bf$P.cmH2O_to_Pa, simplify = TRUE, USE.NAMES = TRUE)\n\naltitude.m.bf <- sapply(medians.Pa, bf$h.lr, simplify = TRUE, USE.NAMES = TRUE)\n\nhist(altitude.m.bf, breaks = 50, main = 'Altitudes (m) based on barometric formula', xlab = 'Altitude (m)')\n\ndf <- merge(x = df,\n y = data.frame(FILE = basename(names(altitude.m.bf)), ALTITUDE = as.vector(altitude.m.bf)),\n all.x = TRUE, by = 'FILE')\n\ndata.table::setkey(df, FILE, TIMESTAMP_UTC)\n\nggplot2::ggplot(data = df, mapping = ggplot2::aes(y = PRESSURE_VALUE, x = sprintf('%s (#%i)', FILE, N))) +\n ggplot2::geom_boxplot() +\n ggplot2::coord_flip() +\n ggplot2::ggtitle(label = 'Barometer boxplots (2 obs/day)') +\n ggplot2::xlab(NULL) +\n ggplot2::theme_light()\n\nggplot2::ggsave('./drifts/analysis_08/baro_hist_uhd-1.png', width = 2160/96, height = 3840/96, dpi = 96)\n\nggplot2::ggplot(data = df, mapping = ggplot2::aes(y = PRESSURE_VALUE, x = sprintf('%s (#%i) [%.2fm]', FILE, N, ALTITUDE))) +\n ggplot2::geom_boxplot() +\n ggplot2::geom_hline(yintercept = bf$P.Pa_to_cmH2O(bf$P.lr(0)), size = 1.5, col = 'darkblue') +\n ggplot2::geom_hline(yintercept = bf$P.Pa_to_cmH2O(bf$P.lr(50*c(-1,1))), size = 1.5, col = 'green') +\n ggplot2::geom_hline(yintercept = bf$P.Pa_to_cmH2O(bf$P.lr(100*c(-1,1))), size = 1.5, col = 'red') +\n ggplot2::coord_flip() +\n ggplot2::ggtitle(label = 'Barometer boxplots (2 obs/day) with altitudes (barometric formula) based on medians',\n subtitle = 'Blue: 0m, green: ±50m and red: ±100m') +\n ggplot2::xlab(NULL) +\n ggplot2::theme_light()\n\nggplot2::ggsave('./drifts/analysis_08/baro_hist_altitudes_uhd-1.png', width = 2160/96, height = 3840/96, dpi = 96)\n\nwrite.csv(as.data.frame(altitude.m.bf), file = './drifts/analysis_08/baro_barometric_formula_altitudes.csv')\n", "meta": {"hexsha": "7b6b83cba09d9bf526c87df5ec0eab5ecbaf89e7", "size": 3885, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/drifts/analysis_08.r", "max_stars_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_stars_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-16T10:47:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T10:47:56.000Z", "max_issues_repo_path": "src/r/drifts/analysis_08.r", "max_issues_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_issues_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2019-05-17T21:14:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T13:47:40.000Z", "max_forks_repo_path": "src/r/drifts/analysis_08.r", "max_forks_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_forks_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-30T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T10:48:04.000Z", "avg_line_length": 39.2424242424, "max_line_length": 124, "alphanum_fraction": 0.67001287, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.64653113991418}} {"text": "prData <- 0.0081\ndomanda1 <- 5\ndomanda2_1 <- 9;\ndomanda2_2 <- 5;\n\np <- 1;\n\npr <- function(p){\n\n somma <- 0;\n for( i in 1:(domanda1-1) ){\n\n somma <- somma + p*(1-p)^(i-1);\n\n }\n return(somma);\n\n}\n\nf <- function(x){\n\n 1 - prData - (pr(x));\n\n}\n\nprX <- function(x){\n\n p*(1-p)^(x-1);\n\n}\n\np <- round(uniroot(f, c(0,1), extendInt=\"yes\")$root, digits = 3);\n\nprint(p);\n\nsomma <- 0;\n\nfor( i in domanda2_2:domanda2_1 ){\n\n somma <- somma + prX(i);\n\n}\n\nprCondizionante <- 1;\n\nfor( i in 1:(domanda2_2-1) ){\n\n prCondizionante <- prCondizionante - prX(i);\n\n}\n\nrisposta2 <- somma/prCondizionante;\nrisposta2_1 <- somma/prData;\n\nprint(risposta2)\nprint(risposta2_1)\n", "meta": {"hexsha": "25d7e2824f7dce38ef731361cb5985e18a1bfdb5", "size": 660, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 39.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 39.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 39.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.5789473684, "max_line_length": 65, "alphanum_fraction": 0.5772727273, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6462102678111294}} {"text": "mylist <- c(1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1)\ndata <- matrix(mylist, nrow=4, ncol=3)\nprint(data)\ntarget <- matrix(c(1, 0, 1, 0), nrow=4)\nprint(target)\n\nsigmoid <- function(x, deriv) {\n if (deriv == TRUE) {\n return (x*(1-x))\n }\n return (1/(1+exp(-x)))\n }\nw0 = matrix(c(0.1, -0.1, 0.01), nrow=3)\nlearning_rate <- 1\nfor (i in 1:10000) {\n layer0 <- data\n layer1 <- sigmoid(layer0%*%w0, FALSE)\n error <- layer1-target\n delta <- error*sigmoid(layer1, TRUE)\n w0 <- w0 - learning_rate*t(layer0)%*%delta\n}\nprint(layer1)", "meta": {"hexsha": "0565cd1f3a985ccb580f289b1344f27d4ca1700a", "size": 550, "ext": "r", "lang": "R", "max_stars_repo_path": "ann-2l.r", "max_stars_repo_name": "Xiaoyu-Xing/learning-machine-learning", "max_stars_repo_head_hexsha": "92fc86a3b18b34d7d91e24d3e1693f27611cb08e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-02-16T21:41:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-17T17:43:42.000Z", "max_issues_repo_path": "ann-2l.r", "max_issues_repo_name": "Xiaoyu-Xing/learning-machine-learning", "max_issues_repo_head_hexsha": "92fc86a3b18b34d7d91e24d3e1693f27611cb08e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ann-2l.r", "max_forks_repo_name": "Xiaoyu-Xing/learning-machine-learning", "max_forks_repo_head_hexsha": "92fc86a3b18b34d7d91e24d3e1693f27611cb08e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 47, "alphanum_fraction": 0.5581818182, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966717067252, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6461220313014764}} {"text": "#' Simple method to calculate paleoslope from preserved sediments\n#'\n#' \\code{lynds_one} calculates the slope of an ancient river, provided you know the flow depth, the grain size of the bed material, and make some assumptions about shear stress in the river. Implemented from Lynds et al. (2014) \n#' @param tau_mode Denotes whether to use a fixed value for the shields number of the flow, or to use a logarithmically-spaced range going from one to ten. \n#' @param D The median grain size of bedload sediments.\n#' @param rhos The density of the sediment in kg/m^3\n#' @param rhof The density of the fluid in kg/m^3\n#' @return Returns a single dimensionless number giving the slope. \n#' @export\n\n#\tFirst method to reconstruct paleoslope from Lynds et al 2014\n#\tEric Barefoot\n#\tNov 2017\n\n#\tdefine needed variables and data types\n\nlynds_one = function(D, H, tau_mode = 'fixed', rhos = 2650, rhof = 1000) {\n\t\n\t#\tD is the D50b or median bedload grainsize\n\t#\tH is Hbf or the bankfull flow depth\n\t\n\trhos = rhos\n\trhof = rhof\n\t\n\t#\tkey assumption is that shields number is equal to one. But paper varies it by up to ten. Provide here a choice for selecting either the recommended value of 1 or a range of estimates from one to ten spaced evenly in log space. \n\t\n\ttau_bf_50 = switch(tau_mode, fixed = 1, range = round(log10(seq(1.258935,10,length = 10)) * 10, 4))\n\t\n\t#\tR is assumed in the paper, but we will calculate it here, and provide defaults above.\n\t\n\tR = rhos/rhof - 1\n\t\n\t#\tnow we calculate the slope based on equation (3) in Lynds et al 2014\n\t\n\tS = (tau_bf_50 * R * D)\t/ H\n\t\n\treturn(S)\n\t\n}", "meta": {"hexsha": "a470045ff6acf0a8e3a557dd4cfec6de417c2f80", "size": 1586, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lynds_slope_method_1.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/lynds_slope_method_1.r", "max_issues_repo_name": "ericbarefoot/barefootr", "max_issues_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-17T16:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-17T16:32:53.000Z", "max_forks_repo_path": "R/lynds_slope_method_1.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": 40.6666666667, "max_line_length": 230, "alphanum_fraction": 0.7282471627, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6461035927263712}} {"text": "# Binomial logistic regression with mediation simulation code\n# NOTE: The assumption is that the mediator is a continuous variable\n\n# Raymond Viviano\n# rayviviano@gmail.com\n# March 25, 2020\n\n# TODO: Implement checks to make sure that all models converged\n\n\n#' Inverse Logit Function\ninv.logit <- function(p){\n return(exp(p)/(1+exp(p)))\n}\n\n\n#' Sobel indirect effect standard error approximation\nsobel.std.err <- function(a, b, se.a, se.b){\n return((b^2 * se.a^2) + (a^2 + se.b^2))\n}\n\n\n#' Coverage Probability, i.e., the probability that the confidence interval (ci)\n#' for a parameter will contain the true value\n#' Inputs:\n#' b - Estimate\n#' se - Standard Error of the Estimate\n#' true - True value of parameter for data-generating process\n#' cl - Confidence level\n#' dof - Degrees of Freedom\n#' Output:\n#' List containing coverage probability, vect\ncoverage.prob <- function(b, se, true, cl=.95, dof=Inf){\n # Compute quantile based on confidence level\n coverage.quantile <- cl + (1-cl)/2\n\n # Compute confidence interval upper and lower bounds\n ci.lower <- b - qt(coverage.quantile, df=dof)*se\n ci.upper <- b + qt(coverage.quantile, df=dof)*se\n\n # For each ci generated for each b/se pair, eval if true param is in ci\n ci.contain.true <- ifelse(true>=ci.lower & true<=ci.upper, 1, 0)\n\n # Calculate coverage probability\n cp <- mean(ci.contain.true)\n\n # Calculate Monte Carlo Error\n mc.err.lower <- cp - 1.96*sqrt((cp*(1-cp))/length(b))\n mc.err.upper <- cp + 1.96*sqrt((cp*(1-cp))/length(b))\n\n # Return coverage probability and error\n return(list(cp=cp, ci=cbind(mc.err.lower, mc.err.upper)))\n}\n\n\n#' Power to detect any effect at various alpha levels\n#' Takes a vector of p-values and calculates the proportion of modell where the \n#' p-val for the effect of interest was < .5, .01, and .001.\npower.detect.effect <- function(p.val.vec){\n less.than.05 <- ifelse(p.val.vec < .05, 1, 0)\n prop.05 <- sum(less.than.05)/length(less.than.05)\n\n less.than.01 <- ifelse(p.val.vec < .01, 1, 0)\n prop.01 <- sum(less.than.01)/length(less.than.01)\n\n less.than.001 <- ifelse(p.val.vec < .001, 1, 0)\n prop.001 <- sum(less.than.001)/length(less.than.001)\n\n cat(paste0('Power to detect effect at .05: ', prop.05, '\\n'))\n cat(paste0('Power to detect effect at .01: ', prop.01, '\\n'))\n cat(paste0('Power to detect effect at .001: ', prop.001, '\\n'))\n}\n\n# Some equations to keep in mind for logistic regression with mediation:\n#\n# EQ1. Y = B0_1 + Tau*X + e1\n# EQ2. Y = B0_2 + Tau_Prime*X + Beta*M + e2\n# EQ3. M = B0_3 + alpha*X + e3\n# EQ4. Tau = alpha*beta + Tau_Prime || (c = ab + c') (approx for logistic)\n#\n# Tau = total effect, tau_prime = direct effect of X on Y accounting for\n# mediating relationship, alpha = effect of X on M, beta = effect of M on Y\n# B0_1,2,&3 are intercept terms for their respective equations. \n#\n# Assuming zero error, the mean, or expected value, for the intercept term for \n# EQ1 can be defined by the other variables.\n#\n# EQ5. E[B0_1] = E[B0_2] + Tau_Prime*E[X] + Beta*(E[B0_3] + Alpha*E[X]) - Tau*[X]\n#\n# If we force the mean of X to 1, then we get equation 6:\n#\n# EQ6. E[B0_1] = E[B0_2] + Tau_Prime + Beta*E[B0_3] + Alpha*Beta - Tau\n#\n# As Tau_Prime - Tau = -1 * Alpha*Beta, we get equation 7:\n#\n# EQ7. E[B0_1] = E[B0_2] + Beta*E[B0_3]\n#\n# We also get equation 7 if we force the mean of x to 0...and the derivation is easier...\n#\n# Define B0_1, B0_2, B0_3, alpha, beta, tau, and tau_prime for the data\n# generation process.\n#\n# Use Eq3 to generate M, then use Eq2 to generate Y\n# Test that you recover the expected values for alpha, beta, tau, tau_prime,\n# B0_1, B02, and B03\n\n# Specify indirect and direct effect terms\nalpha = .2\nbeta = .2\ntau_prime = .1\n\n# Specify total effect (note that for logit this is actually approximate)\ntau = alpha*beta + tau_prime\n\n# Intercept terms for EQ2 and EQ3 (Means or expected values) \nB0_2 <- .2 \nB0_3 <- .4 \n\n# Calculate intercept term for EQ1 based on the other specified values\nB0_1 <- B0_2 + beta*B0_3\n\n# Ensure reproducible results\nset.seed(10000)\n\n# Define sample size\nn <- 16000\n\n# Define number of simulations\nnsims <- 50\n\n# Define matrix to hold simulation data (estimates, std.errors, and pvals)\nsim.prms <- matrix(NA, nrow=nsims, ncol=20)\n\n# Loop through simulations\nfor(i in 1:nsims){\n # Generate independant variable data, uniform random between -1 and 1\n # The expected value, or expected mean of this vector should be 0\n x <- runif(n, -1, 1)\n\n # Generate data for the mediating variable, the mean or expected value \n # should equal B03. But, we'll add some noise\n m <- alpha*x + B0_3 \n # Add noise\n m <- m + rnorm(length(m), 0, .2)\n\n # True data-generation-process for Bernoulli trials\n y <- rbinom(n, 1, inv.logit(B0_2 + tau_prime*x + beta*m))\n\n # Estimate logit model\n model1 <- glm(y ~ x, family=binomial(link=logit))\n model2 <- glm(y ~ x + m, family=binomial(link=logit))\n model3 <- lm(m ~ x)\n\n # TODO: Implement checks to make sure that all models converged\n\n # Put model paramters in simulation matrix\n sim.prms[i, 1] <- model1$coef[1] # Estimate for B0_1\n sim.prms[i, 2] <- model2$coef[1] # Estimate for B0_2\n sim.prms[i, 3] <- model3$coef[1] # Estimate for B0_3\n sim.prms[i, 4] <- model3$coef[2] # Estimate for Alpha\n sim.prms[i, 5] <- model2$coef[3] # Estimate for Beta\n sim.prms[i, 6] <- sim.prms[i, 4] * sim.prms[i, 5] # Estimate for Indirect \n sim.prms[i, 7] <- model1$coef[2] # Estimate for Tau\n sim.prms[i, 8] <- model2$coef[2] # Estimate for Tau_Prime\n sim.prms[i, 9] <- summary(model3)$coefficients[,2][2] # Alpha Std.Err\n sim.prms[i,10] <- summary(model2)$coefficients[,2][3] # Beta Std.Err\n sim.prms[i,11] <- sobel.std.err(sim.prms[i,4], sim.prms[i,5], \n sim.prms[i,9], sim.prms[i,10]) # Indirect Std.Err\n sim.prms[i,12] <- summary(model1)$coefficients[,2][2] # Tau Std.Err\n sim.prms[i,13] <- summary(model2)$coefficients[,2][2] # Tau_Prime Std.Err\n sim.prms[i,14] <- summary(model1)$coefficients[,4][1] # P-Value for B0_1\n sim.prms[i,15] <- summary(model2)$coefficients[,4][1] # P-Value for B0_2\n sim.prms[i,16] <- summary(model3)$coefficients[,4][1] # P-Value for B0_3\n sim.prms[i,17] <- summary(model3)$coefficients[,4][2] # P-Value for Alpha\n sim.prms[i,18] <- summary(model2)$coefficients[,4][3] # P-Value for Beta\n sim.prms[i,19] <- summary(model1)$coefficients[,4][2] # P-Value for Tau\n sim.prms[i,20] <- summary(model2)$coefficients[,4][2] # P-Value for Tau'\n\n}\n\n# Note: The assumption for this simulation is that the mediator is continuous\ncat(\"Note: This simulation assumes that the mediator is continous...\\n\\n\")\n\n# Get Covarage probabilities for the parameters\n# B0_1.coverage <- coverage.prob(sim.prms[,1], sim.prms[,], B0_1, .95, n-model1$rank) TODO: Add these std.errs to sim.prms\n# B0_2.coverage <- coverage.prob(sim.prms[,2], sim.prms[,], B0_2, .95, n-model2$rank) TODO: Add these std.errs to sim.prms\n# B0_3.coverage <- coverage.prob(sim.prms[,3], sim.prms[,], B0_3, .95, n-model3$rank) TODO: Add these std.errs to sim.prms\nalpha.coverage <- coverage.prob(sim.prms[,4], sim.prms[, 9], alpha, .95, n-model3$rank)\nbeta.coverage <- coverage.prob(sim.prms[,5], sim.prms[,10], beta, .95, n-model2$rank)\nindirect.coverage <- coverage.prob(sim.prms[,6], sim.prms[,11], alpha*beta, .95, n-model2$rank) # TODO: Figure out confidence interval for sobel std.err\ntau.coverage <- coverage.prob(sim.prms[,7], sim.prms[,12], tau, .95, n-model3$rank)\ntau.prime.coverage <- coverage.prob(sim.prms[,8], sim.prms[,13], tau_prime, .95, n-model2$rank)\n\n# # Intercept coverage probabilities -- TODO\n# print(\"Coverage Probability for B0_1\")\n# print(B0_1.coverage)\n# print(\"Coverage Probability for B0_2\")\n# print(B0_2.coverage)\n# print(\"Coverage Probability for B0_3\")\n# print(B0_3.coverage)\n\nprint(\"alpha.coverage\")\nprint(alpha.coverage)\nprint(\"beta.coverage\") \nprint(beta.coverage) \nprint(\"indirect.coverage\") \nprint(indirect.coverage) \nprint(\"tau.coverage\")\nprint(tau.coverage) \nprint(\"tau.prime.coverage\")\nprint(tau.prime.coverage) \n\n\n# TODO: Update/Fix Proportion Code\n# power.detect.effect(sim.prms[,5])\n# power.detect.effect(sim.prms[,6])", "meta": {"hexsha": "3d02894504e7d23834a9b649509472827e25dde2", "size": 8545, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/mediated-logistic-regress-simulations.r", "max_stars_repo_name": "rviviano/data-tools", "max_stars_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/mediated-logistic-regress-simulations.r", "max_issues_repo_name": "rviviano/data-tools", "max_issues_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/mediated-logistic-regress-simulations.r", "max_forks_repo_name": "rviviano/data-tools", "max_forks_repo_head_hexsha": "97ab15584d01ac81ffe4349e337ed2d76a042ece", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5601851852, "max_line_length": 153, "alphanum_fraction": 0.6488004681, "num_tokens": 2673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.646094847103081}} {"text": "library(tmvtnorm)\n\n# t-Stutdet parameters\nMu = c(9, 8, 7, 6)\nSigma = matrix(c(16, -2, -1, -3,\n -2, 9, -4, -1,\n -1, -4, 4, 1,\n -3, -1, 1, 1),\n nrow=4, ncol=4)\nlower_bound = 5\nupper_bound = 12\n\n# Generate scenarios\ndata <- rtmvt(n=10000, mean=mu, sigma=sigma, df=5, lower=rep(lower_bound, 4), upper=rep(upper_bound, 4))\nwrite.table(format(data, digits=15, drop0trailing=F), \"data10000.txt\", quote=F, sep=\"\\t\", eol=\"\\n\\t\", col.names = F, row.names = T)\nmean <- colMeans(data)\n\nE <- function(idx, Mu, Sigma, v, alfa, beta) {\n mu = Mu[idx]\n sigma = Sigma[idx, idx]\n a = (alfa - mu)/sigma\n b = (beta - mu)/sigma\n nom = gamma((v-1)/2) *\n ((v+a^2)^(-1*(v-1)/2) - \n (v+b^2)^(-1*(v-1)/2)) *\n v^(v/2)\n den = 2 * (pt(b, v) - pt(a, v)) * gamma(v/2) * gamma(1/2)\n return (mu + sigma*(nom/den))\n}\n\nER1 <- E(1, Mu, Sigma, 5, 5, 12)\nER2 <- E(2, Mu, Sigma, 5, 5, 12)\nER3 <- E(3, Mu, Sigma, 5, 5, 12)\nER4 <- E(4, Mu, Sigma, 5, 5, 12)\nER <- c(ER1, ER2, ER3, ER4)\nwrite.table(ER, \"ER.txt\", sep=\"\\t\", col.names=F, row.names=F)", "meta": {"hexsha": "abce8f97e6d8bd31e51354f57bf15109c2e80405", "size": 1100, "ext": "r", "lang": "R", "max_stars_repo_path": "WDWR.r", "max_stars_repo_name": "elohhim/WDWR-projekt", "max_stars_repo_head_hexsha": "05d3acd36c5347664049299a8f96e92fb43663a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WDWR.r", "max_issues_repo_name": "elohhim/WDWR-projekt", "max_issues_repo_head_hexsha": "05d3acd36c5347664049299a8f96e92fb43663a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WDWR.r", "max_forks_repo_name": "elohhim/WDWR-projekt", "max_forks_repo_head_hexsha": "05d3acd36c5347664049299a8f96e92fb43663a6", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 131, "alphanum_fraction": 0.5127272727, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.64592715856178}} {"text": "#' Generate data\n#'\n#'@description{\n#' The generated responses are discretized and truncated from a latent exponential\n#' generalized linear model with natural parameter exp(X b)\n#' }\n#'\n#' @param X An n x p design matrix\n#' @param b A vector of p regression coefficients\n#' @param d A scalar controlling the coarseness of the support, where d = 1\n#' means integer support (see details)\n#' @param ymax An upper bound on the observable response (see details)\n#'\n#' @return A matrix with n rows and 2 columns; the first is the lower endpoint\n#' of the observed interval and the second the upper endpoint (see details)\n#'\n#' @details{\n#' Data are generated by (i) draw y ~ Exp(exp(X b)), (ii) replace y by floor(y\n#' / d) * d, and (iii) replace every element of y greater than ymax by ymax;\n#' this gives the lower endpoint of the interval. Observe that the operation\n#' floor(y / d) * d sets y to the nearest smaller multiple of d.\n#'\n#' The upper endpoint of the observed interval is yupp = y + d, unless y =\n#' ymax in which case yupp = Inf.\n#' }\n#'\n#' @export\ngenerate_ee <- function(X, b, d = 1, ymax = 10){\n # Do argument checking\n stopifnot(is.matrix(X))\n p <- ncol(X)\n n <- nrow(X)\n stopifnot(is.numeric(b), length(b) == p)\n stopifnot(is.numeric(d), length(d) == 1, d > 0)\n stopifnot(is.numeric(ymax), length(ymax) == 1, ymax >= 0)\n\n eta <- X %*% b\n y <- stats::rexp(n = nrow(X), rate = exp(X %*% b))\n y <- floor(y / d) * d\n y <- pmin(y, ymax)\n yupp <- y + d\n yupp[y == ymax] <- Inf\n return(cbind(y, yupp))\n}\n\n#' Evaluate objective function and its derivatives\n#'\n#' @description{The objective function is that of an elastic net-penalized negative\n#' log-likelihood corresponding to a latent exponential generalized linear model\n#' with natural parameter exp(X b).\n#' }\n#'\n#' @param y A vector of n observed responses (see details in fit_ee)\n#' @param X An n x p matrix of predictors\n#' @param b A vector of p regression coefficients\n#' @param yupp A vector of n upper endpoints of intervals corresponding to y\n#' (see details in fit_ee)\n#' @param lam A scalar penalty parameter\n#' @param alpha A scalar weight for elastic net (1 = lasso, 0 = ridge)\n#' @param pen_factor A vector of coefficient-specific penalty weights; defaults\n#' to 0 for first element of b and 1 for the remaining.\n#' @param order An integer where 0 means only value is computed; 1 means both value\n#' and sub-gradient; and 2 means value, sub-gradient, and Hessian (see details)\n#' @return A list with elements \"obj\", \"grad\", and \"hessian\" (see details)\n#'\n#' @details{\n#' When order = 0, the gradient and Hessian elements of the return list are set\n#' to all zeros, and similarly for the Hessian when order = 1.\n#'\n#' The sub-gradient returned is that obtained by taking the sub-gradient of the\n#' absolute value to equal zero at zero. When no element of b is zero, this is\n#' the usual gradient. The Hessian returns is that of the smooth part of the\n#' objective function that is, the average negative log-likelihood plus the L2\n#' penalty only. When no element of b is zero, this is the Hessian of the\n#' objective function\n#' }\n#' @export\nobj_diff <- function(y, X, b, yupp, lam = 0, alpha = 1, pen_factor = c(0, rep(1,\n ncol(X) - 1)), order){\n # Do argument checking\n stopifnot(is.matrix(X))\n p <- ncol(X)\n n <- nrow(X)\n stopifnot(is.numeric(b), length(b) == p)\n stopifnot(is.numeric(y), is.null(dim(y)), length(y) == n)\n stopifnot(is.numeric(yupp), is.null(dim(yupp)), length(yupp) == n)\n stopifnot(is.numeric(lam), length(lam) == 1)\n stopifnot(is.numeric(alpha), length(alpha) == 1,\n alpha >= 0, alpha <= 1)\n stopifnot(is.numeric(pen_factor), is.null(dim(pen_factor)),\n length(pen_factor) == p)\n stopifnot(is.numeric(order), length(order) == 1, order %in% 0:2)\n\n obj_diff_cpp(y, X, b, yupp, lam1 = alpha * lam * pen_factor, lam2 = (1 -\n alpha) * lam * pen_factor, order)\n}\n", "meta": {"hexsha": "feea03428249a14aea6ac2f755d63749ff52dae8", "size": 3936, "ext": "r", "lang": "R", "max_stars_repo_path": "R/misc.r", "max_stars_repo_name": "jonatanrg/fglm", "max_stars_repo_head_hexsha": "e99767b8003ce12a4b3bab15ce0a56991df8b166", "max_stars_repo_licenses": ["MIT"], "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/misc.r", "max_issues_repo_name": "jonatanrg/fglm", "max_issues_repo_head_hexsha": "e99767b8003ce12a4b3bab15ce0a56991df8b166", "max_issues_repo_licenses": ["MIT"], "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/misc.r", "max_forks_repo_name": "jonatanrg/fglm", "max_forks_repo_head_hexsha": "e99767b8003ce12a4b3bab15ce0a56991df8b166", "max_forks_repo_licenses": ["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.5773195876, "max_line_length": 83, "alphanum_fraction": 0.6768292683, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6458633007508895}} {"text": "#' Takes a power spectrum and makes it noisy, by adding white noise to\n#' its amplitude, and introducing random, uniformly distributed\n#' phases.\n#'\n#' \\deqn{A(f) \\sim \\mathcal{N}(PSD(f), \\sigma^2)}\n#' \\deqn{\\phi(f) \\sim \\mathcal{U}(0, 2\\pi)}\n#' \\deqn{z(f) = A(f) \\exp(i \\phi(f))}\n#'\n#' @param power Power spectral density.\n#' @param sd Standard deviation of white noise.\n#'\n#' @return Power with noise added.\n#'\n#' @export\nnoisy.power.spectrum <- function(power, sd = 1.0) {\n A <- rnorm(power, mean = power, sd = sd)\n phi <- runif(power, min = 0, max = 2*pi)\n\n A * exp(1i * phi)\n}\n", "meta": {"hexsha": "e699ea7b80e0a07920114f44a1854911193d7a41", "size": 593, "ext": "r", "lang": "R", "max_stars_repo_path": "R/noisy.power.spectrum.r", "max_stars_repo_name": "dwysocki/random-noise-generation", "max_stars_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-02-24T05:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-24T05:46:19.000Z", "max_issues_repo_path": "R/noisy.power.spectrum.r", "max_issues_repo_name": "dwysocki/random-noise-generation", "max_issues_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_issues_repo_licenses": ["MIT"], "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/noisy.power.spectrum.r", "max_forks_repo_name": "dwysocki/random-noise-generation", "max_forks_repo_head_hexsha": "97bb8392faa4c25399b44b52bc471a95cb44ec7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2380952381, "max_line_length": 70, "alphanum_fraction": 0.6172006745, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6458563123453466}} {"text": "ISLMPlot <- function(input,output,values){\n prod = seq(0,input$ymax,length.out = 1000)\n to_plot = data.frame(revenu = prod)\n fig = plot_ly(to_plot, x = ~revenu)\n \n fig = fig %>% add_trace(y = ((1-input$alpha-input$iy)*prod+input$alpha*input$t-input$cpi-input$id*input$D/values$p-input$bari-input$g)/input$ir, \n type = \"scatter\", mode = \"lines\", name = \"$$IS_1$$\", line = list(color = \"#ff0000\"),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n fig = fig %>% add_trace(y = lm_curve(input$lr, input$Ms, values$p, input$ly, prod, input$rmin), \n type = \"scatter\", mode = \"lines\", name = \"$$LM_1$$\", line = list(color = \"#007bff\"),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n \n fig = fig %>% add_segments(0,values$eq$r,values$eq$y,values$eq$r,\n line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")) \n fig = fig %>% add_segments(values$eq$y,0,values$eq$y,values$eq$r, \n line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n \n if(values$shock){\n for(i in 1:2){\n if(!is.na(input[[paste0(\"new_value_\",i)]])){\n if(input[[paste0(\"shocked_var_\",i)]] %in% choicesIS){\n fig = with(values[[paste0(\"shocked_params_\",i)]], \n add_trace(fig, y = ((1-alpha-iy)*prod+alpha*t-cpi-id*input$D/p-bari-g)/ir,\n type = \"scatter\", mode = \"lines\",\n name = paste0(\"$$IS_2^\",i,\"$$\"), line = list(color = paste0(\"#\",i+7,\"a0000\")),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")))\n } else if(input[[paste0(\"shocked_var_\",i)]] %in% choicesLM){\n fig = with(values[[paste0(\"shocked_params_\",i)]], \n add_trace(fig, y = lm_curve(lr,Ms,p,ly,prod,input$rmin), \n type = \"scatter\", mode = \"lines\", \n name = paste0(\"$$LM_2^\",i,\"$$\"), line = list(color = paste0(\"#0234\",3+i^2,\"b\")),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")))\n } else if(input[[paste0(\"shocked_var_\",i)]] == \"p\"){\n fig = with(values[[paste0(\"shocked_params_\",i)]], \n add_trace(fig, y = ((1-alpha-iy)*prod+alpha*t-cpi-id*input$D/p-bari-g)/ir,\n type = \"scatter\", mode = \"lines\",\n name = paste0(\"$$IS_2^\",i,\"$$\"), line = list(color = paste0(\"#\",i+7,\"a0000\")),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")))\n fig = with(values[[paste0(\"shocked_params_\",i)]], \n add_trace(fig, y = lm_curve(lr,Ms,p,ly,prod,input$rmin), \n type = \"scatter\", mode = \"lines\", \n name = paste0(\"$$LM_2^\",i,\"$$\"), line = list(color = paste0(\"#0234\",3+i^2,\"b\")),\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")))\n }\n \n fig = fig %>% add_segments(0,values[[paste0(\"new_eq_\",i)]]$r,values[[paste0(\"new_eq_\",i)]]$y,values[[paste0(\"new_eq_\",i)]]$r, \n line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\")) \n fig = fig %>% add_segments(values[[paste0(\"new_eq_\",i)]]$y,0,values[[paste0(\"new_eq_\",i)]]$y,values[[paste0(\"new_eq_\",i)]]$r, \n line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"y=%{x:.0f}\",\"
r=%{y:.2f}\",\"\"))\n \n islm_new_eq = list(\n x = values[[paste0(\"new_eq_\",i)]]$y,\n y = values[[paste0(\"new_eq_\",i)]]$r,\n text = paste0(\"y*=\",round(values[[paste0(\"new_eq_\",i)]]$y), \", r*=\",round(values[[paste0(\"new_eq_\",i)]]$r,4))\n )\n fig = fig %>% layout(annotations = islm_new_eq)\n }\n }\n } else{\n islm_eq = list(\n x = values$eq$y,\n y = values$eq$r,\n text = paste0(\"y*=\",round(values$eq$y), \", r*=\",round(values$eq$r,4))\n )\n fig = fig %>% layout(annotations = islm_eq)\n }\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n revenu <- list(\n title = \"Revenu, y\",\n titlefont = f\n )\n interest <- list(\n title = \"Taux d'intérêt, r\",\n titlefont = f,\n range = c(0,10)\n )\n fig = fig %>% layout(xaxis = revenu, yaxis = interest)\n return(fig)\n}", "meta": {"hexsha": "059ed183de502659ca1ea32f885fc3f377cefc63", "size": 5018, "ext": "r", "lang": "R", "max_stars_repo_path": "src/ISLM_functions.r", "max_stars_repo_name": "placardo/macro_monetaire", "max_stars_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ISLM_functions.r", "max_issues_repo_name": "placardo/macro_monetaire", "max_issues_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ISLM_functions.r", "max_forks_repo_name": "placardo/macro_monetaire", "max_forks_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.0227272727, "max_line_length": 147, "alphanum_fraction": 0.4732961339, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912849, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6458082141762778}} {"text": "is.perf <- function(n){\n\tif (n==0|n==1) return(FALSE)\n\ts <- seq (1,n-1)\n\tx <- n %% s\n\tm <- data.frame(s,x)\n\tout <- with(m, s[x==0])\n\treturn(sum(out)==n)\t\n}\n# Usage - Warning High Memory Usage\nis.perf(28)\nsapply(c(6,28,496,8128,33550336),is.perf)\n", "meta": {"hexsha": "f4ad1103e9b460d57a89385adb46971d2f5b36dd", "size": 246, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Perfect-numbers/R/perfect-numbers.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/Perfect-numbers/R/perfect-numbers.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/Perfect-numbers/R/perfect-numbers.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.5, "max_line_length": 41, "alphanum_fraction": 0.5853658537, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6456891640722643}} {"text": "N <- 10000 # Games per run\nM <- 10 # Runs\n\nrewards <- matrix(nrow=M, ncol=N)\nfracs1 <- matrix(nrow=M, ncol=N)\nfracs2 <- matrix(nrow=M, ncol=N)\nfor (j in 1:M) {\n for (i in 1:N) {\n coin <- 1\n coins <- vector()\n \n # Play the St. Petersburg game\n while(coin) {\n coin <- sample(c(0, 1), 1)\n coins <- c(coins, coin)\n }\n \n rewards[j,i] <- 2**(sum(coins)+1)\n if (i == 1) {\n fracs1[j,i] = 0\n fracs2[j,i] = 0\n } else {\n fracs1[j,i] =\n sum(rewards[j,1:i])/(i*log2(i))\n fracs2[j,i] =\n sum(rewards[j,1:i])/(i*log2(i*log2(i)))\n }\n }\n}\n\n# Plot the results\nsvg(filename=\"Figures/petersburgslow.svg\")\nplot(1:N, fracs1[1,1:N], type='l',\n ylim=c(min(fracs1[,1000:N]), max(fracs1[,1000:N])),\n xlab='Trials (n)', ylab='S_n/(n*log_2(n))')\nfor (j in 2:M) {\n lines(1:N, fracs1[j,1:N])\n}\nlines(1:N, rep(1,N), col='red')\ndev.off()\nsvg(filename=\"Figures/petersburgfast.svg\")\nplot(1:N, fracs2[1,1:N], type='l',\n ylim=c(min(fracs1[,1000:N]), max(fracs1[,1000:N])),\n xlab='Trials (n)', ylab='S_n/(n*log_2(n*log_2(n)))')\nfor (j in 2:M) {\n lines(1:N, fracs2[j,1:N])\n}\nlines(1:N, rep(1,N), col='red')\ndev.off()", "meta": {"hexsha": "6547128ee8d1fe32832480b00c864140556acd93", "size": 1177, "ext": "r", "lang": "R", "max_stars_repo_path": "Conditional Expectation/Code/petersburg.r", "max_stars_repo_name": "mathysie/master-thesis", "max_stars_repo_head_hexsha": "6f57889625b2044454889008720484e36b8fb46c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Conditional Expectation/Code/petersburg.r", "max_issues_repo_name": "mathysie/master-thesis", "max_issues_repo_head_hexsha": "6f57889625b2044454889008720484e36b8fb46c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Conditional Expectation/Code/petersburg.r", "max_forks_repo_name": "mathysie/master-thesis", "max_forks_repo_head_hexsha": "6f57889625b2044454889008720484e36b8fb46c", "max_forks_repo_licenses": ["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.0204081633, "max_line_length": 57, "alphanum_fraction": 0.5352591334, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6456050218690533}} {"text": "=begin\n # sample-algebraic-root01.rb\n\n require \"algebra\"\r\n \r\n R2, r2, r2_ = Root(Rational, 2) # r2 = sqrt(2), -sqrt(2)\r\n p r2 #=> sqrt(2)\r\n R3, r3, r3_ = Root(R2, 3) # r3 = sqrt(3), -sqrt(3)\r\n p r3 #=> sqrt(3)\r\n R6, r6, r6_ = Root(R3, 6) # R6 = R3, r6 = sqrt(6), -sqrt(6)\r\n p r6 #=> -r2r3\r\n p( (r6 + r2)*(r6 - r2) ) #=> 4\r\n \r\n F, a, b = QuadraticExtensionField(Rational){|x| x**2 - x - 1}\r\n # fibonacci numbers\r\n (0..100).each do |n|\r\n puts( (a**n - b**n)/(a - b) )\r\n end\r\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "ac52bc444b5f55d509798afefe29613021b1c8d7", "size": 526, "ext": "rd", "lang": "R", "max_stars_repo_path": "work/consider/algebra-0.72/doc/sample-algebraic-root01.rb.v.rd", "max_stars_repo_name": "rubyworks/stick", "max_stars_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-04-24T05:51:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-24T05:51:21.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-algebraic-root01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "work/consider/algebra-0.72/doc/sample-algebraic-root01.rb.v.rd", "max_forks_repo_name": "rubyworks/stick", "max_forks_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0476190476, "max_line_length": 68, "alphanum_fraction": 0.4828897338, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692236, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.645406204279084}} {"text": "=begin\n # sample-geometry07.rb\n\n require \"algebra\"\n R = MPolynomial(Rational)\n m, b, a = R.vars(\"mba\")\n K = LocalizedRing(R)\n a0, b0, m0 = K[a], K[b], K[m]\n \n M = SquareMatrix(K, 3)\n l0, l1, l2 = M[[0, 1, 0], [1, 1, -1], [1, 0, 0]]\n m4 = M[[a0, 1, -a0], [1, b0, -b0], [m0, -1, 0]]\n m40 = m4.dup; m40.set_row(0, l0)\n m41 = m4.dup; m41.set_row(1, l1)\n m42 = m4.dup; m42.set_row(2, l2)\n \n def mdet(m, i)\n i = i % 3\n m.minor(i, 2).determinant * (-1) ** i\n end\n \n def tris(m, i)\n pts = [0, 1, 2] - [i]\n (m.determinant)**2 / mdet(m, pts[0]) / mdet(m, pts[1])\n end\n \n u0 = (tris(m4, 0) - tris(m40, 0)).numerator\n u1 = (tris(m4, 1) - tris(m41, 1)).numerator\n u2 = (tris(m4, 2) - tris(m42, 2)).numerator\n \n puts [u0, u1, u2]\n puts\n \n [u0, u1, u2].each do |um|\n p um.factorize\n end\n puts\n \n x = u0 / a / (m*b+1)\n y = u1 / (m+a) / (b-1)\n z = u2 / (-b*a+1)\n \n p x\n p y\n p z\n puts\n \n gb = Groebner.basis([x, y, z])\n puts gb\n puts\n \n gb.each do |v|\n p v.factorize\n end\n #(-1)(-mb + m + ba^3 + ba^2 - ba - a^2)\n #(-1)(-ma + m + ba^2 - a^2)\n #(-1)(b + a - 1)(-ba + 1)(a)\n #(-1)(-ba + 1)(a)(a^2 + a - 1)\n \n # => a = -1/2 + \\sqrt{5}/2\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "2ffdf023be7a4acc8ef1013677abbde5a9e86653", "size": 1209, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-geometry07.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc/sample-geometry07.rb.v.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-geometry07.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1904761905, "max_line_length": 58, "alphanum_fraction": 0.4623655914, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.645347815237839}} {"text": "creatingBuckets <- function(arr) {\n o <- list(c(), c(), c(), c(), c(), c(), c(), c(), c(), c())\n for (i in 1:length(arr)) {\n n <- as.integer(floor(10 * arr[i]))\n o[[n]] <- c(o[[n]], arr[i])\n }\n for (i in 1:length(o)) {\n if(length(o[[i]])>1){\n o[[i]] <- insertionSort(o[[i]])\n }\n }\n mergeList(o)\n}\ninsertionSort <- function(a) {\n for (c in 2:(length(a))) {\n d = c\n while (d > 1 && (a[d] < a[d-1])) {\n t = a[d]\n a[d] = a[d - 1]\n a[d - 1] = t\n d = d - 1\n }\n }\n a\n}\nmergeList <- function(q) {\n res <- as.vector(c())\n for (k in 1:length(q)) {\n if (!is.null(q[[k]]))\n res <- c(res, q[[k]])\n }\n print(\"Vector after BucketSort\")\n print(res)\n}\narr <- c(0.78, 0.17, 0.39, 0.26)\ncreatingBuckets(arr)\n", "meta": {"hexsha": "37391ad2447669b9a0794d5eb302cbcf62de40c4", "size": 757, "ext": "r", "lang": "R", "max_stars_repo_path": "sort/bucket_sort/r/bucket_sort.r", "max_stars_repo_name": "CarbonDDR/al-go-rithms", "max_stars_repo_head_hexsha": "8e65affbe812931b7dde0e2933eb06c0f44b4130", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1253, "max_stars_repo_stars_event_min_datetime": "2017-06-06T07:19:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:07:58.000Z", "max_issues_repo_path": "sort/bucket_sort/r/bucket_sort.r", "max_issues_repo_name": "rishabh99-rc/al-go-rithms", "max_issues_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 554, "max_issues_repo_issues_event_min_datetime": "2017-09-29T18:56:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:48:13.000Z", "max_forks_repo_path": "sort/bucket_sort/r/bucket_sort.r", "max_forks_repo_name": "rishabh99-rc/al-go-rithms", "max_forks_repo_head_hexsha": "4df20d7ef7598fda4bc89101f9a99aac94cdd794", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2226, "max_forks_repo_forks_event_min_datetime": "2017-09-29T19:59:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:59:55.000Z", "avg_line_length": 20.4594594595, "max_line_length": 61, "alphanum_fraction": 0.4438573316, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.645275419279755}} {"text": "library(Matrix)\nA <- matrix(c(1, 3, 5, 2, 4, 7, 1, 1, 0), 3, 3, byrow=T)\ndim(A) <- c(3, 3)\nexpand(lu(A))\n", "meta": {"hexsha": "6793dbc0552eb57fe688918190bbd2845252c697", "size": 105, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/LU-decomposition/R/lu-decomposition.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/LU-decomposition/R/lu-decomposition.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/LU-decomposition/R/lu-decomposition.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 56, "alphanum_fraction": 0.5142857143, "num_tokens": 60, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6451414591281032}} {"text": "#### 일원 분산분석(One-way ANOVA) #####\n\n# 01.데이터 불러오기 \nowa.df <- read.csv(\"Ch0901.OWA.csv\", \n header=TRUE, \n na.strings = \".\")\n\nowa.df$group <- factor(owa.df$group,\n levels = c(1:4),\n labels = c(\"강남\",\"강서\",\"강동\",\"강북\"))\n\nstr(owa.df)\nhead(owa.df)\n\n# 02.기본통계치 확인\nlibrary(psych)\ndescribeBy(owa.df$score, \n owa.df$group, \n mat=T) # 합쳐서 하나의 표로 보여줄지, 따로 그룹별로 보여줄지 나타내는 옵션 \n\n\n# 03.그래프 그리기(박스그래프,히스토그램)\n# install.packages(\"ggplot2\")\n\nlibrary(ggplot2)\n\nggplot(owa.df, aes(x = group, y = score)) + #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=score)) + \n geom_histogram(binwidth=10) + \n facet_grid(.~ group) +\n ggtitle(\"매장별 만족도\") + \n theme_classic()\n\n# 04.통계분석\n# 등분산 검증\n# 이분산일때는 하단의 부록(Welch's ANOVA test) 참조\nbartlett.test(score ~ group, data=owa.df)\n\n# barlett test는 정규분포에 민감하기 때문에 leveneTest 많이 사용\n# install.packages(\"car\")\nlibrary(car)\nleveneTest(score ~ group, data=owa.df) # 레벤의 검증은 library(car)에 있다. \n\n# 등분산일때 ANOVA분석\nowa.result <- aov(score ~ group, data=owa.df) \n\nowa.result\n\nsummary(owa.result)\n\n# 부록: 이분산일때 Welch's ANOVA test\noneway.test(owa.df$score ~ owa.df$group, data=owa.df, \n var.equal = FALSE)\n\n\n# 사후검정(Multicamparison test )\n# Fisher LSD\npairwise.t.test(owa.df$score, \n owa.df$group, \n data=owa.df, \n p.adj=\"non\") # 많이 않쓰임. 오차가 크기 때문에 \n\n# Bonferroni, Tukey HSD, Duncan LSR\npairwise.t.test(owa.df$score, \n owa.df$group, \n data=owa.df, \n p.adj=\"bonf\") # 여기서비교하는 방법을 알려줌. 이것은 유의확률을 보여줌. 강남-강동 차이 있음 \n\n# Tukey HSD, Duncan LSR\nTukeyHSD(owa.result) # 결과값으로 바로 보여줌 (분산분석 결과치를 데이타프레임으로 저장하고 입력)\n\n\n\n\n# group으로 표현\n# install.packages(\"agricolae\")\nlibrary(agricolae)\n\n# console=TRUE: 결과를 화면에 표시\n# group=TRUE: 그룹으로 묶어서 표시, FALSE: 1:1로 비교하여 다 보여줌, 다른 것끼리 구분되는 것 \nLSD.test(owa.result, \n \"group\", \n console = T, \n p.adj=\"bonf\")\nduncan.test(owa.result, \n \"group\", \n group=T, \n console = T)\nscheffe.test(owa.result, \n \"group\", \n group=F, \n console = T)\n\n\n\n\n\n\n\n# 05.통계결과 그래프\ntukeyPlot <- TukeyHSD(owa.result) # 그룹간 차이 비교\nplot(tukeyPlot) # 0을 거치고 있다는 것은 차이가 없다는 뜻임\n\n\n\n\n\n\n\n# 정규분포로 표시(강남)\nx=88.87 \nse=1.34\ndata <-rnorm(1000, x, se)\ndata <- sort(data)\nplot(data, \n dnorm(data, x, se), \n col=\"blue\",\n type='l', \n main=\"매장별 고객만족도\", \n xlim=c(75, 95), \n ylim=c(0,0.3))\nabline(v=x, col=\"blue\", lty=3)\n\n\n# 그래프를 겹쳐서 표현하기 \npar(new=T) \n\n\n# 정규분포로 표시(강서)\nx=88.19 \nse=1.33\ndata <-rnorm(1000, x, se)\ndata <- sort(data)\nplot(data, \n dnorm(data, x, se), \n type='l', \n col=\"red\",\n xlim=c(75, 95), \n ylim=c(0,0.3))\nabline(v=x, col=\"red\", lty=3)\n\n\npar(new=T)\n\n# 정규분포로 표시(강북)\nx=86.05 \nse=1.58\ndata <-rnorm(1000, x, se)\ndata <- sort(data)\nplot(data, \n dnorm(data, x, se), \n type='l', \n col=\"black\",\n xlim=c(75, 95), \n ylim=c(0,0.3))\nabline(v=x, col=\"black\", lty=3)\n\n\npar(new=T)\n\n\n# 정규분포로 표시(강동)\nx=82 \nse=2.05\ndata <-rnorm(1000, x, se)\ndata <- sort(data)\nplot(data, \n dnorm(data, x, se), \n type='l', \n col=\"green\",\n xlim=c(75, 95), \n ylim=c(0,0.3))\nabline(v=x, col=\"green\", lty=3)\n\n\n\n# 부록: 비모수통계분석 Kruskal Wallis H test \nkruskal.test(owa.df$score ~ owa.df$group, \n data=owa.df)\n# install.packages(\"userfriendlyscience\")\nlibrary(userfriendlyscience)\nposthocTGH(owa.df$score, \n owa.df$group)\n\n\n# install.packages(\"nparcomp\") # 비모수 검정에서 다중 비교 방식 \nlibrary(nparcomp)\nresult = mctp(owa.df$score ~ owa.df$group, \n data=owa.df)\nsummary(result)\n", "meta": {"hexsha": "7284917aeedc46eb990dce232d6deadd1d4f3a1f", "size": 3836, "ext": "r", "lang": "R", "max_stars_repo_path": "ch09 - 분산분석 1/01.일원 분산분석(One-way 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/01.일원 분산분석(One-way 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/01.일원 분산분석(One-way 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.18, "max_line_length": 76, "alphanum_fraction": 0.57455683, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6450856315007639}} {"text": "### Nicholas Spyrison 08 March 2021\n### Recreate figure 3 from spinifex paper. Silo'd, with minimal dependencies.\n\nrequire(\"spinifex\")\nrequire(\"tourr\")\nrequire(\"ggplot2\")\nrequire(\"magrittr\")\nmy_theme <- list(scale_color_brewer(palette = \"Dark2\"),\n theme_void(), \n theme(legend.position =\"none\"))\n\n### Create the \nmake_radial_tour_fig <- function(){\n dat <- scale_sd(flea[, 1:6])\n clas <- factor(flea$species)\n bas <- MASS::lda(dat, grouping = clas)$scaling %>% tourr::orthonormalise()\n mvar <- 4 ## aede1, primary disting of 1 cluster.\n \n if(F) ## Manual check the starting LDA basis\n view_frame(bas, dat, mvar,\n aes_args = list(color = clas, shape = clas),\n ggproto = my_theme)\n \n ang <- .29\n mtour <- manual_tour(bas, manip_var = mvar, angle = ang)\n if(F){ ## Manually check for frames to use\n play_manual_tour(bas, dat, mvar, angle = ang)\n for(i in 1:dim(mtour)[3]){\n mvr <- mtour[mvar,, i]\n msg <- paste0(\"i=\",i,\". norm(mv)=\", sqrt(mvr[1]^2 + mvr[2]^2))\n print(msg)\n }\n }\n ## Show frames: 1, 4, 10, 15\n \n p1 <- view_frame(mtour[,, 1], dat, mvar,\n aes_args = list(color = clas, shape = clas)) + my_theme\n p2 <- view_frame(mtour[,, 4], dat, mvar,\n aes_args = list(color = clas, shape = clas)) + my_theme\n p3 <- view_frame(mtour[,, 10], dat, mvar,\n aes_args = list(color = clas, shape = clas)) + my_theme\n p4 <- view_frame(mtour[,, 15], dat, mvar,\n aes_args = list(color = clas, shape = clas)) + my_theme\n \n ## Return ggplot figure.\n # gridExtra::grid.arrange(p1, p2, p3, p4, ncol = 4)\n cowplot::plot_grid(p1, p2, p3, p4, ncol = 4,\n scale = c(1, 1, .75, 1), hjust = -.1,\n label_fontface = \"plain\",\n labels = c(\"1) norm = 0.86\", \"2) norm = 1\", \"3) norm = 0\", \"4) norm = 0.86\")\n )\n}\n\nfig <- make_radial_tour_fig()\nggsave(filename = \"fig_radial_manual_tour.png\",\n plot = fig,\n device = \"png\", path = \"./figures\", \n dpi = 300,\n width = 6, height = 1.5, units = \"in\"\n)\n", "meta": {"hexsha": "b9869f7dee75f7861c83fbeed4fb0f48f3e981fc", "size": 2132, "ext": "r", "lang": "R", "max_stars_repo_path": "R/make_radial_tour_fig.r", "max_stars_repo_name": "dicook/wiley-isghdd", "max_stars_repo_head_hexsha": "fb04a3b48a1d614b21ffd0679fe4884dc77390b7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-23T13:57:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T13:57:31.000Z", "max_issues_repo_path": "R/make_radial_tour_fig.r", "max_issues_repo_name": "dicook/wiley-isghdd", "max_issues_repo_head_hexsha": "fb04a3b48a1d614b21ffd0679fe4884dc77390b7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-02-17T02:42:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T05:36:50.000Z", "max_forks_repo_path": "R/make_radial_tour_fig.r", "max_forks_repo_name": "dicook/wiley-isghdd", "max_forks_repo_head_hexsha": "fb04a3b48a1d614b21ffd0679fe4884dc77390b7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9508196721, "max_line_length": 97, "alphanum_fraction": 0.5581613508, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6450788070791807}} {"text": "=begin\n # sample-quotientfield03.rb\n\n require \"algebra\"\n \n F13 = ResidueClassRing(Integer, 13)\n F = AlgebraicExtensionField(F13, \"a\") {|a| a**2 - 2}\n a = F.var\n RF = RationalFunctionField(F, \"x\")\n x = RF.var\n \n p( (a/4*x + RF.unity/2)/(x**2 + a*x + 1) +\n (-a/4*x + RF.unity/2)/(x**2 - a*x + 1) )\n #=> 1/(x**4 + 1)\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "b229c4b7041c8bae94dec8d903e52e0162565fbb", "size": 350, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-quotientfield03.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-quotientfield03.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-quotientfield03.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5882352941, "max_line_length": 54, "alphanum_fraction": 0.5342857143, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947132556618, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6450285704268205}} {"text": "# The sequence of the epsilons in a random walk\n# A vector of size n, the elements are generated\n# at random : +1 with probability 0.5 and -1 with\n# probability 0.5\n# 23-04-2015\n# Killian Martin--Horgassan\n\nEpsilon_is = function(n) {\n\t\n\t# The vector of the Epsilon_is, they are uniformly distributed on {-1,+1}\n\tvect <- sample(x = c(-1,1), size = n, replace = TRUE, prob = c(0.5,0.5))\n\t\n\treturn(vect)\n}\n", "meta": {"hexsha": "1584e067a83a603f1609b1c780b5f6e1efac9a93", "size": 403, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_buildingBM/Epsilon_is.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_files_buildingBM/Epsilon_is.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_files_buildingBM/Epsilon_is.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8666666667, "max_line_length": 74, "alphanum_fraction": 0.6799007444, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6448625230179048}} {"text": "#' @title calcAt\n#'\n#' @description Estimate transom area (\\code{At}) (m^2) using method in Rakke\n#' (2016).\n#'\n#' @param Cm Midship area coefficient (vector of numericals, dimensionless) \n#' (see \\code{\\link{calcCm}})\n#' @param breadth Moulded breadth (vector of numericals, m)\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#'\n#' @return \\code{At}\n#'\n#' @references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'\\href{http://hdl.handle.net/11250/2410741}{Rakke, S. G. 2016. \"Ship Emissions\n#'Calculation from AIS.\" NTNU}\n#'\n#' @seealso \\code{\\link{calcCm}}\n#'\n#' @examples\n#'calcAt(0.98, 32, 10)\n#'calcAt(c(0.98,0.99), c(32,45.5), c(10,15.5))\n#'\n#' @export\n\ncalcAt <-function(Cm, breadth, maxDraft){\n\n At<- 0.051*Cm*breadth*maxDraft\n\n return(At)\n}\n", "meta": {"hexsha": "a3b77c48cbca6903a9363aa7acaa677e58ba8439", "size": 865, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcAt.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/calcAt.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/calcAt.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": 25.4411764706, "max_line_length": 79, "alphanum_fraction": 0.6693641618, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6448592121705735}} {"text": "#' @title calcHMCa\n#'\n#'@description Calculate incremental hull (roughness) resistance coefficient\n#'(\\code{Ca}) (dimensionless), which describes the effect of hull roughness and\n#' still-air resistance, using the Holtrop & Mennen method.\n#'\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#' @param lwl Waterline length (vector of numericals, m) (see \\code{\\link{calclwl}})\n#' @param Cbw Waterline block coefficient (vector of numericals, dimensionless) \n#' (see \\code{\\link{calcCbw}})\n#' @param breadth Moulded breadth (vector of numericals, m)\n#' @param forwardDraft Forward draft (deviation from actual draft indicates trim)\n#' (vector of numericals, m)\n#' @param Abt Traverse bulb area (vector of numericals, m^2) (see \n#' \\code{\\link{calcAbt}})\n#' @param hb Center of bulb area above keel line (vector of numericals, m) (see \n#' \\code{\\link{calchb}})\n#'\n#' @return \\code{Ca} (vector of numericals, dimensionless)\n#'\n#' @references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCbw}}\n#'\\item \\code{\\link{calcAbt}}\n#'\\item \\code{\\link{calchb}}\n#'}\n#'\n#' @family Holtrop-Mennen Calculations\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcHMCa(c(13.57,11.49),c(218.7500,209.2518),c(0.81,0.65),c(32.25,32.20),c(13.57,11.49),\n#' c(25.09,55.86),c(5.43,4.6))\n#'\n#'calcHMCa(13.57,218.7500,0.81,32.25,13.57,25.0880,5.428)\n#'\n#' @export\n\ncalcHMCa<-function(maxDraft,lwl,Cbw,breadth,forwardDraft,Abt,hb){\n\nCa<-\n ifelse(forwardDraft/lwl<=0.04,#case 1\n 0.006*((lwl+100)^-0.16)-0.00205+0.003*sqrt(lwl/7.5)*Cbw^4*\n (#c2\n exp(-1.89*sqrt(\n #c3\n 0.56*Abt^1.5/(breadth*maxDraft*(\n 0.31*sqrt(Abt)+forwardDraft-hb\n ))\n ))\n )*\n (0.04-\n (#c4\n forwardDraft/lwl\n ))\n ,#case 2\n 0.006*((lwl+100)^-0.16)-0.00205+0.003*sqrt(lwl/7.5)*Cbw^4*\n (#c2\n exp(-1.89*sqrt(\n #c3\n 0.56*Abt^1.5/(breadth*maxDraft*(\n 0.31*sqrt(Abt)+forwardDraft-hb\n ))\n ))\n )*\n (0.04-\n (#c4\n 0.04\n ))\n )\n\nreturn(Ca)\n}\n", "meta": {"hexsha": "0eb3b00d80f4172ad0b913e325b03bf73f857390", "size": 2196, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMCa.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/calcHMCa.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/calcHMCa.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 28.1538461538, "max_line_length": 91, "alphanum_fraction": 0.6316029144, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6448591998802985}} {"text": "esbi <- function(i, a){(1-exp(-a))/(1-exp(-a/i))}\nesbia <- function(i, a){(1-exp(-a))/(i*(1-exp(-a/i)))}\nesbib <- function(i, a){1-esbia(i, a)}\n\nn <- 1000\na <- 1\n\nx <- seq(0, n, by=1)\nplot(x, x, type=\"l\", ylim=c(0, n))\nlines(x, log(x), col=\"green\")\nlines(x, esbi(x, 1), col=\"red\")\nlines(x, esbi(x, 10), col=\"blue\")\n\nx <- seq(0, n, by=1)\nplot(x, x*x, type=\"l\", ylim=c(0, n*n))\nlines(x, x*log(x), col=\"green\")\nlines(x, x*esbi(x, 1), col=\"red\")\nlines(x, x*esbi(x, 10), col=\"blue\")\n\nx <- seq(0, n, by=1)\nplot(x, x*x, type=\"l\", ylim=c(0, n*n))\nlines(x, x*log(x), col=\"green\")\nlines(x, x^2*esbia(x, 1), col=\"red\")\nlines(x, x^2*esbia(x, 10), col=\"blue\")\n\nx <- seq(0, n, by=1)\nplot(x, log(x)*x, type=\"l\", ylim=c(0, log(n)*(n-log(n))))\nlines(x, rep(0, length(x)), col=\"green\")\nlines(x, x*log(x)*esbib(x, 1), col=\"red\")\nlines(x, x*log(x)*esbib(x, 10), col=\"blue\")\n\nx <- seq(0, n, by=1)\nplot(x, x*x+log(x)*x, type=\"l\", ylim=c(0, n*n+log(n)*(n-log(n))))\nlines(x, x*log(x)+log(x)*log(x), col=\"green\")\nlines(x, x^2*esbia(x, 1)+x*log(x)*esbib(x, 1), col=\"red\")\nlines(x, x^2*esbia(x, 10)+x*log(x)*esbib(x, 10), col=\"blue\")\n\nx <- seq(0, n, by=1)\nplot(x, esbi(x, a)/x, type=\"l\")\n\nx <- seq(0, n, by=1)\nplot(x, exp(-1*x/n), type=\"l\", ylim=c(0, 1))\nlines(x, exp(-10*x/n), type=\"l\", col=\"red\")\nlines(x, exp(-15*x/n), type=\"l\", col=\"green\")\n", "meta": {"hexsha": "159d8da1504fbcdd0416e971bcf563afb55bab6f", "size": 1318, "ext": "r", "lang": "R", "max_stars_repo_path": "doc/average_complexity_big_oh.r", "max_stars_repo_name": "scidom/PGUManifoldMC.jl", "max_stars_repo_head_hexsha": "766cf983b122678d47524c566ebd6fffa7f804d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-08-08T12:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-08T12:59:00.000Z", "max_issues_repo_path": "doc/average_complexity_big_oh.r", "max_issues_repo_name": "eford/PGUManifoldMC.jl", "max_issues_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-04-13T03:04:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-13T03:05:48.000Z", "max_forks_repo_path": "doc/average_complexity_big_oh.r", "max_forks_repo_name": "eford/PGUManifoldMC.jl", "max_forks_repo_head_hexsha": "0a75d899f580a79282eb742f17a207b14963ea79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-08-21T18:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-21T18:03:01.000Z", "avg_line_length": 29.2888888889, "max_line_length": 65, "alphanum_fraction": 0.535660091, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6447399941380036}} {"text": "##CTE534_Clasificación_No_Superisada=group\n##Imagen=raster\n##Banda=number 1\n##Centros=number 10\n##Iteracciones=number 500\n##Inicio=number 5\n##Cluster= output raster\n##Algortimo=selection HartiganWong;Lloyd;Forgy;MacQueen\n##showplots\n\nnr <- getValues(Imagen[[Banda]])\nset.seed(99)\n\n\nif (Algortimo == 0) {\ncluster <- kmeans(na.omit(nr), \n centers = Centros, \n iter.max = Iteracciones, \n nstart = Inicio, \n algorithm=\"Hartigan-Wong\")\n} else if (Algortimo == 1) {\ncluster <- kmeans(na.omit(nr), \n centers = Centros, \n iter.max = Iteracciones, \n nstart = Inicio, \n algorithm=\"Lloyd\")\n} else if (Algortimo == 2) {\ncluster <- kmeans(na.omit(nr), \n centers = Centros, \n iter.max = Iteracciones, \n nstart = Inicio, \n algorithm=\"Forgy\")\n} else if (Algortimo == 3) {\ncluster <- kmeans(na.omit(nr), \n centers = Centros, \n iter.max = Iteracciones, \n nstart = Inicio, \n algorithm=\"MacQueen\")\n}\n\nCluster <- setValues(Imagen[[Banda]], cluster$cluster)\n\npar(mfrow =c(1,2))\nplot(Imagen[[Banda]], \n col =rev(terrain.colors(Centros)), \n main = names(Imagen[[Banda]]))\nplot(Cluster, main = 'Clasificación No Supervisada \\n (Kmeans)')\n", "meta": {"hexsha": "a17d1f383675d55222446c7d0c601169a9c1b445", "size": 1393, "ext": "rsx", "lang": "R", "max_stars_repo_path": "Rscripts/Kmeans.rsx", "max_stars_repo_name": "klauswiese/QGIS-R", "max_stars_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rscripts/Kmeans.rsx", "max_issues_repo_name": "klauswiese/QGIS-R", "max_issues_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rscripts/Kmeans.rsx", "max_forks_repo_name": "klauswiese/QGIS-R", "max_forks_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_forks_repo_licenses": ["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.0208333333, "max_line_length": 64, "alphanum_fraction": 0.5527638191, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505204, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6447396138135387}} {"text": "subroutine triar(x0,y0,x1,y1,x2,y2,area)\n\n# Calculate the area of a triangle with given\n# vertices, in anti clockwise direction.\n# Called by delout.\n\nimplicit double precision(a-h,o-z)\nhalf = 0.5d0\n\narea = half*((x1-x0)*(y2-y0)-(x2-x0)*(y1-y0))\nreturn\nend\n", "meta": {"hexsha": "13f932238879bea2bd48eb64d4ee8b6d199311be", "size": 256, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/triar.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/triar.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/triar.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 19.6923076923, "max_line_length": 45, "alphanum_fraction": 0.70703125, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6447179749447624}} {"text": "# Goodness of fit (r2), predicción.\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n#################################################################\n# Motivacion\n#################################################################\n\n# Sabemos interpretar los coeficientes, sabemos cuando los coeficientes\n# son significativos (estadisticamente hablando). Lo que no hemos \n# hablado hasta el momento, es como evaluamos distintos modelos: como podemos\n# saber que modelo interpreta mejor la realidad?\n\n# Matematicamente, queremos saber cuan bien nuestra linea se acerca/aleja\n# de nuestros datos. Mientras nuestra linea de regresion se acerque mas,\n# mejor nuestro modelo. \n\n# DEMOSTRAR EN LA PIZARRA.\n\n# El estadistico que ocupamos para tener una idea de cuan bien nuestro\n# modelo interpreta la realidad, es el r-cuadrado, o r2.\n\n\n#################################################################\n# r2: Definicion y Significado\n#################################################################\n\n# El r-cuadrado es un porcentaje, que obviamente va de 0 a 1. Mientras \n# mas cercano a 1, nuestro modelo mejora. \n\n# Usualmente, se interpreta como el % de la varianza que es explicada\n# por nuestro modelo. Por ej., un \"r2 = 0.3\" significa que nuestras variables\n# explican el 30% de nuestros datos. \n\n# (1) Es eso \"suficientemente bueno\"? \n# (2) Que % nos da la \"tranquilidad\" de que tenemos un buen modelo?\n\n\n# Por que es importante el r2? Bueno, asi podemos comparar que modelo\n# explica mas la realidad. Imaginate que tenemos dos modelos, m1 y m2.\n# Si r2(m1) > r2(m2), debieramos quedarnos con el m1. Por que?\n# Porque el set de variables de m1 explica mas varianza (mas datos)\n# al compararlo con el m2.\n\n#################################################################\n# r2: Viendo el r2\n#################################################################\n\n# Cargar paquete para cargar bases que no son de R.\n# install.packages(\"foreign\")\nlibrary(foreign) # significa \"foraneo\"\noptions(scipen = 1000000) # apagar notacion cientifica.\ndat = read.dta(\"https://github.com/hbahamonde/OLS/raw/master/Datasets/obama.dta\")\n\n# Base\nhead(dat) # Base sobre preferencias politicas: Obama.\n\n# \ndat$Obamafav <- as.numeric(jitter(dat$Obamafav, factor=2, amount = 1))\ndat$ideology <- as.numeric(jitter(dat$ideology, factor=2, amount = 1))\n\n\n# Modelo 1\noptions(scipen = 1000000) # apagar notacion cientifica.\nmodelo.entero = lm(Obamafav ~ income + education + age + sex + ideology, dat)\nsummary(modelo.entero)\n\n# obtener el r2 de \"modelo.entero\"\nsummary(modelo.entero)$r.squared # Atencion: al summary le podemos pedir una parte especifica usando \"$\".\n\n# Modelo 2\nmodelo.parcial = lm(Obamafav ~ ideology, dat)\nsummary(modelo.parcial)\n\n# obtener el r2 de \"modelo.parcial\"\nsummary(modelo.parcial)$r.squared\n\n\n\n# Modelo 3: este es un \"mal\" modelo\nmodelo.mediocre = lm(Obamafav ~ age, dat)\nsummary(modelo.mediocre)\nsummary(modelo.mediocre)$r.squared # Pesimo...\n\n# (1) Que podemos concluir de los r2 respectivos de \"modelo.entero\" y \"modelo.parcial\"?\n# (2) Con que modelo nos quedamos? Costo-beneficio, teniendo en cuenta la parsimonia.\n# (*) Este es el tipo de decisiones que podemos tomar usando el estadiatico r2.\n\n\n\n# Graficos\n## Grafiquemos nuestro \"fit\", es decir, cuan \"en forma\" esta nuestro modelo.\n\nlayout(matrix(1:3, nrow = 1)) # modifiquemos el plano donde graficamos.\n# Aqui le decimos a R que \"haga espacio\" para 3 graficos, y que los ordene \n# en una sola fila. Asi podremos poner tres graficos, uno por cada modelo.\n\n# Los siguientes graficos, pondran en el eje-X el \"fitted\" es decir, el predicho.\n# El eje-y tendra el observado.\n\nplot(dat$Obamafav, fitted(modelo.entero), col = \"gray\", main = \"Modelo Entero\"); curve((x), col = \"blue\", add = TRUE)\nplot(dat$Obamafav, fitted(modelo.parcial), col = \"gray\", main = \"Modelo Parcial\"); curve((x), col = \"blue\", add = TRUE)\nplot(dat$Obamafav, fitted(modelo.mediocre), col = \"gray\", main = \"Modelo Mediocre\"); curve((x), col = \"blue\", add = TRUE)\n\n# (1) Notar que puse \";\" en la misma linea.\n# (2) Que podemos concluir de esto?\n\n\n#################################################################\n# r2: Formula Estadistica\n#################################################################\n\n# Hablemos de la formula del r2. \n# r2 = 1- (Errores Cuadrados del Residuo / Errores Cuadrados Totales)\n\n# Errores Cuadrados del Residuo: Por cada fila, tomamos la diferencia entre\n# predicho y observado. Eso al cuadrado, y despues sumamos todo. Despues, eso \n# lo dividimos por los errores (o variabilidad) de la variable dependiente. \n# Piensa que el valor esperado de \"y\" es su promedio. Entonces, el \"error\" en \n# este caso es cuanto se aleja cada fila (observacion) del promedio de \"y\". Y \n# finalmente, restamos 1 a ese numero final.\n\n\n#################################################################\n# r2: Matrices\n#################################################################\noptions(scipen = 1000000) # apagar notacion cientifica.\n\n# Saquemos el r2 del modelo.entero.\n\n# Recuerda, este era nuestro modelo\n#modelo.entero = lm(Obamafav ~ income + education + age + sex + ideology, dat)\nsummary(modelo.entero) # resumen\nsummary(modelo.entero)$r.squared # r2\n\n# Formula del r2 en Matrices\n\n## 1. Calcular los errores del modelo\n\n## (a) Extraer \"y\" observado.\ny.observado = dat$Obamafav\n\n## (b) Extraer \"y\" predicho.\ny.predicho = modelo.entero$fitted.values\n\n## Calcular los errores del modelo\ne.m = y.observado - y.predicho\n\n### BONUS: Comparalo con el que esta dentro del objeto del modelo.\ntable(round(as.numeric(modelo.entero$residuals),8) == round(as.numeric(e.m), 8))\n\n\n## 2. Calcular los errores de la variable dependiente (Errores del vector y)\ny.m = y.observado - mean(y.observado) # round(mean(y, trim = 0.5), 3)\n\n## Calcular r2\n### 1- e'e/y'y\n1 - t(e.m) %*% e.m / t(y.m) %*% y.m # Vemos que es igual a la tabla\n\n# Ahora hagamos lo mismo, pero usando algebra \"normal\", no de matrices.\n\n# Formula Estadistica\ny_fit <- modelo.entero$fitted.values # Fitted es lo que predecimos\n\n# Sum Square Error\nSSE <- sum((y_fit - y.observado)^2) # Aqui restamos lo que predecimos (\"y_fit\") menos lo que observamos (\"y), y despues sacamos el cuadrado de esos numeros, y despues sumamos todas esas diferencias cuadradas. Esta cantidad se llama \"Sum Square Error\", y es eso: la suma de todos los errores cuadrados. \n\n# Sum Square Total\nSST <- sum((y.observado - mean(y.observado))^2) # Despues calculamos el \"Sum Square Total\". Estos son los \"errores\" o desviaciones que tiene nuestra matriz \"y\", y tiene que ver con cuanto cada elemento en \"y\" se desvia del promedio de \"y\".\n\n# r2\n1-SSE/SST # R^2, que es 1 menos SSE/SST \nsummary(modelo.entero)$r.squared # r2// Y que es esto mismo.\n\n\n#################################################################\n# r2: \"Ajustado\"\n#################################################################\n\n# Como dice King, el r2 es una funcion de los parametros (variables independientes).\n# Mientras mas variables (o x's), mejor nuestro r2. Es por esto que \n# es muy comun \"mentir\" en estadisticas: pones un monton de x's, y mejoras\n# tu r2. Esto se ha llamado \"kitchen-sink regression\".\n\n# Una manera de \"arreglar\" esto, es no mirar el r2, si no que el r2-ajustado.\n# Este estadistico nos dice lo mismo que el r2, pero \"ajusta\" por el numero\n# de x's que calculamos. En otras palabras, por cada parametro que calculamos,\n# existe un \"castigo\".\n\n# Recordemos nuestros r2's\nsummary(modelo.entero)$r.squared\nsummary(modelo.parcial)$r.squared\nsummary(modelo.mediocre)$r.squared\n\n# Ahora calculemos el r(2)-ajustado\nsummary(modelo.entero)$adj.r.squared\nsummary(modelo.parcial)$adj.r.squared\nsummary(modelo.mediocre)$adj.r.squared\n\n# Como ven, dice casi lo mismo, y el penalty es muy pequeno.\n\n\n#################################################################\n# Criticas al r2\n#################################################################\n\n# Sin embargo, pensemos por un momento en el r2 perfecto, y lo que \n# tendriamos que hacer para lograrlo.\n\n# (1) Que tendriamos que hacer para lograr un r2 = 1?\n# (2) Es realmente bueno/posible?\n# (3) Si no es el r2, que otra alternativa tenemos (paper de King)?\n\n\n\n\n", "meta": {"hexsha": "f56f13d93804d97bfc2323f566038a07622cafd3", "size": 8230, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase16/Clase16.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Clase16/Clase16.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Clase16/Clase16.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5799086758, "max_line_length": 302, "alphanum_fraction": 0.639854192, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6446315299721813}} {"text": "library(markovchain)\n\nage<-seq(from = 30, to = 50, by=1)\nProbA2U<-seq(0.0006,0.0060,length.out = 21)\nProbA2D<-seq(0.0005,0.0020,length.out = 21)\nProbA2A<-1-(ProbA2U+ProbA2D)\nProbU2A<-seq(0,0,length.out = 21)\nProbU2D<-seq(0.1219,0.1879,length.out = 21)\nProbU2U<-1-(ProbU2A+ProbU2D)\nProbD2A<-seq(0,0,length.out = 21)\nProbD2U<-seq(0,0,length.out = 21)\nProbD2D<-1-(ProbD2A+ProbD2U)\nDecrementsTable<- data.frame(age,ProbA2A,ProbA2U,ProbA2D,ProbU2A,ProbU2U,ProbU2D,ProbD2A,ProbD2U,ProbD2D)\n\nstr(DecrementsTable)\nsummary(DecrementsTable)\nhead(DecrementsTable)\n\nWorkesStates<-c(\"Active\",\"Unable\",\"Dead\")\n\nTransMatrix35<-matrix(as.numeric(DecrementsTable[DecrementsTable$age==35,2:10]),nrow = 3,ncol = 3, byrow = TRUE,\n dimnames = list(WorkesStates, WorkesStates))\n\nMCModel35<-new(\"markovchain\", transitionMatrix = TransMatrix35, states = WorkesStates, name=\"MCModel35\")\n\nMCModel35\n\nstates(MCModel35)\ndim(MCModel35)\nstr(MCModel35)\nMCModel35@transitionMatrix\nabsorbingStates(MCModel35)\n\nset.seed(5)\n\nWorkerStatePred35<- rmarkovchain(n = 1000, object = MCModel35, t0 =\"Active\")\ntable(WorkerStatePred35)\n\nTransMatrix50<-matrix(as.numeric(DecrementsTable[DecrementsTable$age==50,2:10]),nrow = 3,ncol = 3, byrow = TRUE,\n dimnames = list(WorkesStates, WorkesStates))\nMCModel50<-new(\"markovchain\", transitionMatrix = TransMatrix50, states = WorkesStates, name=\"MCModel50\")\n\nWorkerStatePred50<- rmarkovchain(n = 1000, object = MCModel50, t0 =\"Active\")\ntable(WorkerStatePred50)\n\nMCModelsList=list()\nj=1\nfor(i in 30:50){\n TransMatrix<-matrix(as.numeric(DecrementsTable[DecrementsTable$age==i,2:10]),nrow = 3,ncol = 3, byrow = TRUE,\n dimnames = list(WorkesStates, WorkesStates))\n \n MCModelsList[[j]]<-new(\"markovchain\", transitionMatrix = TransMatrix, states = WorkesStates)\n j=j+1\n}\n\nMCList30to50<-new(\"markovchainList\", markovchains = MCModelsList,name=\"MCList30to50\")\n \nStatesSequence<-rmarkovchain(n=10000, object=MCList30to50,t0=\"Active\")\nstr(StatesSequence)\nStatesOccurences<-table(StatesSequence$value)\nExpectedUnableOccurence<-StatesOccurences[3]/nrow(StatesSequence)\nExpectedUnableOccurence\n\n\n", "meta": {"hexsha": "2f508bd8e70bd26fd35ff6f0bad0b5498ed24de6", "size": 2156, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter10/HealthInsurance.r", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_stars_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-19T06:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T06:37:07.000Z", "max_issues_repo_path": "Chapter10/HealthInsurance.r", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_issues_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter10/HealthInsurance.r", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_forks_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-25T17:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:19:18.000Z", "avg_line_length": 33.1692307692, "max_line_length": 112, "alphanum_fraction": 0.7425788497, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6443937876774918}} {"text": "library(nloptr)\n\nfit = function(cases, window=7, lags=7, omega) {\n #Contructs de R with thompson method... (Cori et al)\n priorRate=2\n priorShape=1\n initialVector=cases[1:lags]\n \n omega_matrix=matrix(0,length(cases)-lags,lags)\n for(i in 1:length(cases)-lags){\n for(j in 1:lags){\n omega_matrix[i,j] = omega(i, j)\n }\n }\n \n infectPotential_T=matrix(0,length(cases)-lags,1)\n for(i in 1:dim(infectPotential_T)[1]){\n infectPotential_T[i]=sum(cases[i:(i+lags-1)]*rev(omega_matrix[i,]))\n }\n #Seriel interval times observed cases, there are lags values\n # computing denominatortofequation 4?\n casesMatrix=matrix(0,length(infectPotential_T)-(window-1),window)\n for(i in 1:dim(casesMatrix)[1]){\n casesMatrix[i,]=infectPotential_T[i:(i+window-1)]\n }\n #doble suma ecuacion 7\n infectPotential=casesMatrix%*%matrix(1,window,1)\n \n #Generate observation Matrix\n postcasesMatrix=matrix(0,length(cases)-(window-1),window)\n for(i in 1:dim(postcasesMatrix)[1]){\n postcasesMatrix[i,]=cases[i:(i+window-1)]\n }\n \n #suma iw(t) se supone esto es Poisson\n infectObservados=postcasesMatrix%*%matrix(1,window,1)\n \n betaParameteres=cbind(priorShape, priorRate)\n \n for(i in 1:dim(casesMatrix)[1]){\n shape1=priorShape+infectObservados[i]\n rate1=priorRate+infectPotential[i]\n betaParameteres=rbind(betaParameteres,cbind(shape1, rate1))\n }\n shape1=betaParameteres[-1,1]\n rate1=betaParameteres[-1,2]\n \n lb=qgamma(0.05, shape=shape1, rate=rate1)\n ub=qgamma(0.95, shape=shape1, rate=rate1)\n beta=((shape1-1)/rate1)\n for(i in 1:window){\n lb=c(lb[1],lb)\n ub=c(ub[1],ub)\n beta=c(beta[1],beta)\n }\n \n data=cbind(lb, beta,ub)\n data=as.data.frame(data)\n data$day=1:length(lb)\n print(data$beta)\n data$R=data$beta*sum(omega_matrix[1,])\n data$Rlb=data$lb*sum(omega_matrix[1,])\n data$Rub=data$ub*sum(omega_matrix[1,]) \n \n #R_Caso\n lb=data$lb\n ub=data$ub\n beta=data$beta\n longCaseslb=c(rep(lb[1], length=lags-1),lb)\n longCasesub=c(rep(ub[1], length=lags-1),ub)\n longCasesbeta=c(rep(beta[1], length=lags-1),beta)\n \n data$R_c=data$beta*sum(omega_matrix[1,])\n data$R_clb=data$lb*sum(omega_matrix[1,])\n data$R_cub=data$ub*sum(omega_matrix[1,]) \n \n for(i in 1:length(lb)){\n data$R_c[i]=sum(longCasesbeta[i:(i+lags-1)]*omega_matrix[1,])\n data$R_clb[i]=sum(longCaseslb[i:(i+lags-1)]*omega_matrix[1,]) \n data$R_cub[i]=sum(longCasesub[i:(i+lags-1)]*omega_matrix[1,])\n }\n return(data)\n}\n\nfit2 = function(I, window=7, prior_shape, prior_rate, omega) {\n \"\n Unvectorized model fitting.\n \"\n steps = length(I)\n mode = rep(NaN, window + 1)\n lb = rep(NaN, window + 1)\n ub = rep(NaN, window + 1)\n for (t in (window + 1):steps) {\n shape = prior_shape + sum(I[(t - window):t])\n # solve rate iteratively\n rate = prior_rate\n for (t_prime in (t - window):t) {\n for (tau in 1:(t_prime - 1)) {\n rate = rate + (omega[tau] * I[t_prime - tau])\n }\n }\n mode = c(mode, (shape - 1)/rate)\n lb = c(lb, qgamma(0.05, shape=shape, rate=rate))\n ub = c(ub, qgamma(0.95, shape=shape, rate=rate))\n }\n R = list(\"mode\"=mode, \"lb\"=lb, \"ub\"=ub)\n return(R)\n}\n\nfit3 = function(I, window=7, prior_shape, prior_rate, omega) {\n \"\n Like fit2, but omega is a function of (t, tau).\n \"\n steps = length(I)\n mode = rep(NaN, window)\n for (t in window:steps) {\n shape = prior_shape + sum(I[(t - window):t])\n # solve rate iteratively\n rate = prior_rate\n for (t_prime in (t - window):t) {\n for (tau in 1:(t_prime - 1)) {\n rate = rate + (omega(t, tau) * I[t_prime - tau])\n }\n }\n mode = c(mode, (shape - 1)/rate)\n }\n R = list(\"mode\"=mode)\n return(R)\n}", "meta": {"hexsha": "59ff1c4762273031fd9a0fddf05d5830ae48bee7", "size": 3654, "ext": "r", "lang": "R", "max_stars_repo_path": "bayesian/model_fitting.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bayesian/model_fitting.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesian/model_fitting.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3255813953, "max_line_length": 71, "alphanum_fraction": 0.6406677614, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6443937876774917}} {"text": "#' Calculates the match value of an input to a category.\n#' \n#' This function returns a value which represents the amount of match\n#' between the given input and the given category.\n#' @title ART_Calculate_Match\n#' @param input Vector of size NumFeatures that contains the input signal into the network\n#' @param weightVector Matrix of size NumFeatures which holds the weights of the network for a given category\n#' @return Measure of the degree of match between the input and the current category\n#' @details The length of the INPUT vector must equal the length of the WEIGHTVECTOR.\n#' \nART_Calculate_Match = function(input, weightVector)\n{\n # Initialize the local variables.\n match = 0;\n numFeatures = length(input);\n \n # Make sure the weight vector is appropriate for the input.\n if(numFeatures != length(weightVector))\n {\n stop('The input and weight vector lengths do not match.');\n }\n \n # Calculate the match between the given input and weight vector.\n # This is done according to the following equation:\n # Match = |Input^WeightVector| / |Input|\n matchVector = pmin(input, weightVector);\n inputLength = sum(input);\n if(inputLength == 0)\n {\n match = 0;\n }\n else\n {\n match = sum(matchVector) / inputLength;\n }\n return (match);\n}", "meta": {"hexsha": "b9d801ecbf98170af6aa84ad4b0a77075a3cefc4", "size": 1268, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ART_Calculate_Match.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ART_Calculate_Match.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ART_Calculate_Match.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2702702703, "max_line_length": 109, "alphanum_fraction": 0.7216088328, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6443532439399907}} {"text": "#' Yang's network tomography data \r\n#'\r\n#' Simulated traffic counts on Yang's (1995) network. The aim is to sample the corresponding origin-destination traffic volumes that are consistent with those counts.\r\n#' The dataset appears as a list prepared for that purpose. \r\n#' Components of the list are A (the configuration matrix, which in this case is the link-path incidence matrix); y (observed traffic counts); lambda (assumed mean origin-destination traffic volumes); \r\n#' and MarkovBasis (a matrix with columns corresponding to the vectors in full Markov basis for the resampling problem).\r\n#'\r\n#' @references Yang, H. (1995). Heuristic algorithms for the bilevel origin-destination matrix estimation problem. Transportation Research Part B: Methodological, 29(4), 231-242.\r\n#'\r\n#' @docType data\r\n#'\r\n#' @usage data(YangNetwork) \r\n#' @export\r\n#' @examples\r\n#' data(YangNetwork)\r\n#' Xsampler(A=YangNetwork$A,y=YangNetwork$y,lambda=YangNetwork$lambda,Model=\"Poisson\",Method=\"Gibbs\",tune.par=0.5,combine=TRUE)\r\n\"YangNetwork\"", "meta": {"hexsha": "83ef2a1f4360cca917376f10b825e14f959318d7", "size": 1025, "ext": "r", "lang": "R", "max_stars_repo_path": "R/yang-network.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/yang-network.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/yang-network.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": 60.2941176471, "max_line_length": 202, "alphanum_fraction": 0.7551219512, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6443340117676697}} {"text": "#RESUMEN R\r\n\r\n#CLASE 9\r\n#EJEMPLO DISEÑO WEB\r\n\r\ndiseweb <- read.csv(\"C:/Users/Milagros/Desktop/exp numerica/datos_ejemplo_disenoweb.csv\")\r\nhead(diseweb)\r\n# ANOVA es para comparar igualdad de medias para 2 o mas grupos\r\n# antes que nada se realiza barlett para comparar la igualdad de varianzas\r\n# porque ANOVA necesita igualdad de varianzas\r\n# Cuando las varianzas son distintas se utiliza Kruskal para comparar medianas\r\n# Sin embargo como son muestras relacionadas kruskal no nos da buenos resultados para poder\r\n# concluir diferencia en las medianas, Kruskal sirve para muestras independientes.\r\nkruskal.test(puntuacion~tipodiseno,diseweb)\r\n# entonces utilizamos friedman \r\nfriedman.test(puntuacion~tipodiseno|jurado,diseweb)\r\n\r\n\r\n\r\n#EJERCICIO CAFE\r\n\r\nf <- read.csv(choose.files())\r\nf\r\nhead(f)\r\n#hipotesis\r\n\r\n# h0= las medianas de los distintos tipos de cafe son iguales\r\n# h1= al menos una de las medianas es diferente\r\n# quito la columna de expertos que solo es numeros\r\nf<-f[,-1]\r\nf \r\n#creo una columna de expertos con etiquetas mas entendibles\r\npaste0(\"Experto_\", rownames(f));\r\n#transformo el set de datos para que sea una matriz que pueda recibir el test\r\nf2 <-reshape(f,ids=rownames(f),times=(names(f)),timevar=\"tipocafe\",varying=list(names(f)),direction=\"long\") \r\nhead(f2)\r\nnames(f2)<-c(\"tipocafe\",\"puntuacion\",\"experto\")\r\n#realizamos el test\r\nfriedman.test(puntuacion~tipocafe|experto,f2)\r\n# conclusion:\r\n# Como el p value es menor que el nivel de significancia (alpha)\r\n# se rechaza la hipotesis nula\r\n# podemos concluir que a un nivel de confianza de 0.95 se puede afirmar que al menos uno de los \r\n# tipos de cafe tiene una puntuacion mediana diferente\r\n\r\n\r\n#CAPITULO 11\r\n\r\n# ejercicio Relajacion muscular\r\n\r\n# diseño experimental: completamente al azar (DCA)\r\n# unidad Experimental: Un paciente\r\n# variable respuesta: tiempo de la duracion de la relajacion muscular\r\n# factor en estudio: las distintas drogas\r\n# niveles del factor: sin droga, innovar, droperidol, fentayl\r\n# tratamientos:sin droga, innovar, droperidol, fentayl\r\n# Factores: de bloqueo\r\n# Covariable: No existe\r\n\r\n# EJERCICIO DIETAS ANIMALES coagulacion\r\nA <- c(62,60,63,59)\r\nB <- c(63,67,71,64,65,66)\r\nC <- c(68,66,71,67,68,68)\r\nD <- c(56,62,60,61,63,64,63,59)\r\n\r\nresultado <- c(A,B,C,D)\r\ndietas <- c(rep(\"A\",length(A)),\r\n rep(\"B\",length(B)),\r\n rep(\"C\",length(C)),\r\n rep(\"D\",length(D)))\r\n\r\nmisdatos <- data.frame(dietas,resultado)\r\n# un pequeño grafico\r\nboxplot(resultado~dietas,misdatos, main=\"Tiempo de coagulación de la sangre segun dieta\", ylab=\"Tiempo (segundos)\")\r\n\r\n# ANOVA Siempre se usa \r\nanova1 <- aov(resultado~dietas,misdatos)\r\nsummary(anova1)\r\n# se rechaza la hipotesis nula y acepto h1, entonces concluimos que almenos una tiene media diferente\r\n# media general\r\nmu.est <- mean(misdatos$resultado)\r\n#aplicar media por grupos\r\nmean_treatment <- aggregate(resultado~dietas,misdatos,mean)\r\n#diferencia media por grupos y media global\r\neffect_treatment <- aggregate(resultado~dietas,misdatos,function(x){mean(x)-mu.est})\r\nmu.est\r\neffect_treatment\r\n\r\n# Treatment Effect with a reference Level\r\n# mide los efectos respecto a un nivel, en este caso el nivel A\r\nround(coefficients(anova1),2)\r\n\r\n# Changing Reference Level\r\n# en este caso el nivel B\r\nmisdatos$dietas <- relevel(misdatos$dietas,ref=\"B\")\r\nanova1 <- aov(resultado~dietas,misdatos)\r\nsummary(anova1)\r\nround(coefficients(anova1),2)\r\n# como se puede ver la media de tiempos del nivel a respecto al B es 5 minutos menos\r\n# la media del nivel C es 2 minutos mas y la media del nivel D es 5 minutos menos\r\n\r\n#EJERCICIO BACTERIA\r\nres <- c(13,16,5,22,24,4,18,17,1,39,44,22)\r\nfactor <- c(1,2,3,1,2,3,1,2,3,1,2,3)\r\nbloque <- c(1,1,1,2,2,2,3,3,3,4,4,4)\r\n\r\nmidata <- data.frame(factor,bloque,res)\r\n\r\n#graficos\r\nboxplot(res~factor,midata, main=\"Retardo en el crecimiento de bacterias\",\r\n ylab=\"Tiempo (segundos)\",\r\n xlab=\"Factor: Soluciones de lavado\")\r\nboxplot(res~bloque,midata, main=\"Retardo en el crecimiento de bacterias\",\r\n ylab=\"Tiempo (segundos)\",\r\n xlab=\"Bloques: Dias\")\r\n\r\n#graficos\r\ninteraction.plot(midata$factor,midata$bloque,midata$res,\r\n xlab=\"Factor: Soluciones de lavado\",\r\n ylab=\"Tiempo (segundos)\",\r\n leg.legend=\"Bloque\")\r\n\r\n#Annova\r\nanova3 <- aov(res~as.factor(factor)+as.factor(bloque),midata)\r\nsummary(anova3)\r\n\r\n#reformulo la data con dos factores\r\nmidata <- data.frame(factor=as.factor(factor),bloque=as.factor(bloque),res)\r\nanova1 <- aov(res~factor+bloque,midata)\r\nsummary(anova1)\r\n\r\n# global Effect and Treatment Effect\r\n#Ver diferencia de medias entre cada factor\r\nmu.est <- mean(midata$res)\r\nmean_treatment <- aggregate(res~factor,midata,mean)\r\neffect_treatment <- aggregate(res~factor,midata,function(x){mean(x)-mu.est})\r\neffect_block <- aggregate(res~bloque,midata,function(x){mean(x)-mu.est})\r\nmu.est\r\neffect_treatment\r\neffect_block\r\n\r\n#Effects with control treatment\r\n#Ver diferencias de medias respecto un nivel\r\nround(coefficients(anova1),4)\r\n\r\n\r\n#EJERCICIO GASOLINA\r\n# h0 : T1=t2=T3=t4=t5=0\r\n# h1 : al menos un Ti <>0\r\n \r\ndata5 <- read.csv(choose.files())\r\ndata5\r\n\r\nanova4 <- aov(res~as.factor(factor)+as.factor(bloque),data5)\r\nsummary(anova4)\r\n\r\n#Con un nivel de confianza del 95% se puede concluir que al menos\r\n#un tipo de gasolina tienen un efecto distinto en el rendimiento del carro\r\n\r\n\r\n#CAPITULO 12\r\n\r\n#Ejercicio Voltaje\r\n\r\nmidata <- read.csv(\"C:/Users/Milagros/Desktop/exp numerica/datos_voltaje.csv\")\r\nmidata$Temperatura <- as.factor(midata$Temperatura)\r\nmidata$material <- as.factor(midata$material)\r\nanova <- aov(voltaje~Temperatura+material+Temperatura*material,midata)\r\nsummary(anova)\r\n\r\ninteraction.plot(midata$Temperatura,midata$material,midata$voltaje,\r\n xlab=\"Factor: Temperatura\",\r\n ylab=\"Voltaje\",\r\n leg.legend=\"Material\")\r\n\r\n\r\n# Medias\r\ntapply(midata$voltaje,midata$Temperatura, mean)\r\ntapply(midata$voltaje,midata$material, mean)\r\n\r\n#Estimacion\r\nmean(midata$voltaje)\r\ntapply(midata$voltaje,midata$Temperatura, mean) - mean(midata$voltaje)\r\ntapply(midata$voltaje,midata$material, mean) - mean(midata$voltaje)\r\n\r\n#combino medias--> las medias de la combinacion material temperatura\r\ncombinacion<-aggregate(voltaje~Temperatura+material,midata,mean)\r\n\r\n\r\nunique(midata$Temperatura)\r\nunique(midata$material)\r\n\r\ndataframe <-data.frame()\r\nfor(i in unique(midata$Temperatura)){\r\n for(j in unique(midata$material)){ \r\n media_ij <- mean(midata$voltaje[midata$Temperatura%in%c(i) & midata$material%in%c(j)])\r\n media_i <- mean(midata$voltaje[midata$Temperatura%in%c(i)])\r\n media_j <- mean(midata$voltaje[midata$material%in%c(j)])\r\n media_global <- mean(midata$voltaje)\r\n \r\n eff_ij <- media_ij - media_i - media_j + media_global\r\n \r\n dataframe <- rbind(dataframe,data.frame(i,j,eff_ij))\r\n \r\n }\r\n}\r\n", "meta": {"hexsha": "a6a85a2591ddd0b776845d3965210bddc837cb6e", "size": 6879, "ext": "r", "lang": "R", "max_stars_repo_path": "Final/Clases/RESUMEN_R.r", "max_stars_repo_name": "jchudb93/Exp-Numerica", "max_stars_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Final/Clases/RESUMEN_R.r", "max_issues_repo_name": "jchudb93/Exp-Numerica", "max_issues_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Final/Clases/RESUMEN_R.r", "max_forks_repo_name": "jchudb93/Exp-Numerica", "max_forks_repo_head_hexsha": "c288c9e73d9770fd49fd6646984a1c2ea6c893c0", "max_forks_repo_licenses": ["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.231884058, "max_line_length": 117, "alphanum_fraction": 0.7158017154, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6443331688808511}} {"text": "##' Estimate parameters of a circle using Hough Circle Transform\n##' \n##' Uses a portion of the canny algorithm to find candidate edge points\n##' and the direction of the gradient at those points, then uses\n##' Hough Circle Transform to estimate circle parameters.\n##' \n##' @param im The image to find a circle in (a modulation estimate is best)\n##' @param fw Size of Gaussian blur to smooth image\n##' @param qt Threshold to accept strong edge candidate\n##' @param excl Number of pixels to exclude around edge of frame as candidates\n##' @param rmin Minimum circle radius\n##' @param rmax Maximum circle radius\n##' @param rstep step size in constructing lookup table\n##' @param dtheta_max maximum assumed error in gradient direction\n##' @param dtheta_step increment for dtheta\n##' @param number of nearest neighbors for alternate calculation\n##' @param plots plot?\n##' @param details Return extra details?\n##' \n##' @details\n##' The Hough transform section first creates a lookup table of candidate\n##' radii and center points, then for each candidate edge point calculates\n##' potential centers along a fan of rays near the gradient direction.\n##' An inner join then finds matches in the lookup table and increments\n##' an accumulator vector. Highest vote at the end wins.\n##' \n##' @return If details is FALSE a named list with the circle parameters\n##' \n##' @note\n##' This is experimental and can be very slow. A good guess for the radius is very helpful.\n##' Experimental feature: find the nn nearest neighbors of the selected trio of parameters\n##' and calculate a vote weighted mean. This is returned as \\code{rxy_alt} if details is TRUE.\n##' \n##' @seealso [circle.pars()], [pupil.pars()]\n##' \n##' @examples\n##' example(\"psifit\", package=\"zernike\", ask=FALSE)\n##' X11()\n##' cp2 <- circle.hough(tfit$mod, rmin=round(tfit$cp$rx)-10, rmax=round(tfit$cp$rx)+10)\ncircle.hough <- function(im, fw=2, qt=0.995, excl=5,\n rmin=min(dim(im))/4, rmax=min(dim(im))/2, rstep=1,\n dtheta_max = 0.5, dtheta_step=0.05,\n nn=7, plots=TRUE, details=FALSE) {\n require(data.table)\n nr <- nrow(im)\n nc <- ncol(im)\n if (fw > 0) {\n im <- gblur(im, fw)\n }\n if (excl < 1) {\n excl <- 1\n }\n kern.sobel <- rbind(c(-1,-2,-1),c(0,0,0),c(1,2,1))\n gx <- convolve2d(im, kern.sobel)\n gy <- convolve2d(im, t(kern.sobel))\n modg <- sqrt(gx^2+gy^2)\n modg <- modg/max(modg)\n dirg <- atan2(gy, gx)\n \n # round off directions to 45 degrees\n \n dir <- dirg\n dir[abs(dirg) < 7*pi/8] <- (round(dirg[abs(dirg) < 7*pi/8]*4/pi))\n dir[abs(dirg) >= 7*pi/8] <- 0\n dir[dir < 0] <- 4+dir[dir<0]\n \n # find local maxima\n \n maxima <- NULL\n \n for (i in 0:3) {\n ptsi <- which(dir==i, arr.ind=TRUE)\n ed <- which(ptsi[,1] <= excl)\n ed <- c(ed, which(ptsi[,1] >= nr-excl+1))\n ed <- c(ed, which(ptsi[,2] <= excl))\n ed <- c(ed, which(ptsi[,2] >= nc-excl+1))\n if (length(ed) > 0) {\n ptsi <- ptsi[-ed,]\n }\n nb <- switch(i+1, c(1,0), c(1,1), c(0,1), c(1, -1))\n ptsp <- t(t(ptsi)+nb)\n ptsm <- t(t(ptsi)-nb)\n lm <- which((modg[ptsi] > modg[ptsp]) & (modg[ptsi] > modg[ptsm]))\n maxima <- rbind(maxima, ptsi[lm,])\n }\n \n # the thinned edges consist of the local maxima in the direction of gradient\n \n thin <- matrix(0, nr, nc)\n thin[maxima] <- modg[maxima]\n ec <- which(modg[maxima] >= quantile(modg[maxima], probs=qt))\n maxima <- maxima[ec,]\n dir_edges <- dirg[maxima]\n\n if (plots) {\n image(1:nr, 1:nc, thin, col=grey256, asp=1, xlab=\"X\", ylab=\"Y\", useRaster=TRUE)\n points(maxima[,1], maxima[,2], pch=20, col='green')\n }\n \n # Hough circle transform\n \n xc_min <- rmin\n xc_max <- nr-rmin\n yc_min <- rmin\n yc_max <- nc-rmin\n \n r_cand <- seq(rmin, rmax, by=rstep)\n xc_cand <- seq(xc_min, xc_max, by=rstep)\n yc_cand <- seq(yc_min, yc_max, by=rstep)\n rxy <- data.table(expand.grid(r_cand, xc_cand, yc_cand))\n rxy <- cbind(index=1:nrow(rxy), rxy)\n names(rxy) <- c(\"index\", \"r\", \"xc\", \"yc\")\n dtheta <- seq(-dtheta_max, dtheta_max, by=dtheta_step)\n lt <- length(dtheta)\n acc <- numeric(nrow(rxy))\n \n for (i in 1:nrow(maxima)) {\n xc <- maxima[i,1] - as.vector(outer(r_cand, dir_edges[i]+dtheta, function(X,Y) X * cos(Y)))\n xc <- rstep * round(xc/rstep)\n yc <- maxima[i,2] - as.vector(outer(r_cand, dir_edges[i]+dtheta, function(X,Y) X * sin(Y)))\n yc <- rstep * round(yc/rstep)\n circles <- data.table(r=rep(r_cand, lt), xc=xc, yc=yc)\n matches <- dplyr::inner_join(rxy, circles, by=c(\"r\", \"xc\", \"yc\"))\n acc[matches$index] = acc[matches$index] + 1\n }\n rxy_best <- rxy[which.max(acc),]\n cp <- list(xc = rxy_best$xc, yc=rxy_best$yc, rx=rxy_best$r, ry=rxy_best$r, obstruct=0)\n \n wtmean <- function(x, wt) sum(wt*x)/sum(wt)\n \n gets_vote <- as.vector(nabor::knn(rxy[,-1],rxy_best[,-1], k=nn)$nn.idx)\n rxy_alt <- list(r=wtmean(rxy$r[gets_vote],acc[gets_vote]), xc=wtmean(rxy$xc[gets_vote],acc[gets_vote]), \n yc=wtmean(rxy$yc[gets_vote],acc[gets_vote]))\n \n if (plots) {\n points(rxy_best$xc, rxy_best$yc, col=\"red\", pch=20)\n symbols(rxy_best$xc, rxy_best$yc, circles=rxy_best$r, inches=FALSE, add=TRUE, fg=\"red\")\n }\n if (details) {\n list(cp=cp, thin=thin, maxima=maxima, dir_edges=dir_edges, \n rxy=rxy, acc=acc, rxy_best=rxy_best, rxy_alt=rxy_alt)\n } else {\n cp\n }\n}\n \n \n", "meta": {"hexsha": "8d7bfa320e8c980b2842d21a031416bf5842d5b6", "size": 5376, "ext": "r", "lang": "R", "max_stars_repo_path": "R/circle.hough.r", "max_stars_repo_name": "gmke/zernike", "max_stars_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/circle.hough.r", "max_issues_repo_name": "gmke/zernike", "max_issues_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_issues_repo_licenses": ["MIT"], "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/circle.hough.r", "max_forks_repo_name": "gmke/zernike", "max_forks_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 36.3243243243, "max_line_length": 106, "alphanum_fraction": 0.6236979167, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6443331585751869}} {"text": "###################################\n########## 군 집 분 석 ############\n###################################\n# install.packages(\"caret\")\n# install.packages(\"fastcluster\")\nlibrary(caret)\nlibrary(fastcluster)\n\n# 표준화\ntraining_data <- scale(iris[ ,-5]) #Species 데이터 제거(숫자형변수x)\nsummary(training_data)\n\n\n# 군집수 결정 \n## 패키지 사용 (최적의 combination을 통해 선택)\n# install.packages(\"NbClust\")\n# library(NbClust)\n# \n# nc <- NbClust(training_data, min.nc=2, max.nc=15, method=\"kmeans\")\n# barplot(table(nc$Best.n[1,]), xlab=\"Numer of Clusters\", ylab=\"Number of Criteria\", main=\"Number of Clusters Chosen\")\n\n## sum of squares 제일 작아 지는 지점 탐색\n# wss <- NULL\n# for(i in 1:7){\n# wss[i] = kmeans(training_data, centers=i)$tot.withinss\n# }\n# i=1:7\n# plot(i,wss);lines(i,wss);\n\n\nset.seed(100)\n##### k-means (비계층적) 군집분석 ######\n# 모델링 (군집개수-3개분류)\niris_kmeans <- kmeans(training_data, centers=3, iter.max=10000)\niris_kmeans$cluster <- as.factor(iris_kmeans$cluster) #Rownumber별 군집 매핑 값\n\ntable(iris_kmeans$cluster)\ntable(iris$Species, iris_kmeans$cluster) #virginica는 잘 분류해 내지만, 그 외는 변별력 약함.\n\nplot(iris[c(\"Sepal.Length\", \"Sepal.Width\")], col=iris_kmeans$cluster)\n\n\nset.seed(0)\n##### Hierarchical - hcluster (계층적) 군집분석 ######\n# 모델링\nhc <- hclust(dist(training_data), method=\"ave\") #Row간 거리 계산\n\n# plot(hc, hang=-1, labels=iris$Species)\n# rect.hclust(hc, k=3) #3개의 클러스터 표현\n\ngroups <- cutree(hc, k=3) #3개의 클러스터로 표현\ntable(groups)\n\ntable(iris$Species, groups) #setosa는 잘 분류해 내지만, 그 외는 변별력 약함.\n\n\n\n###################################\n########## D-TREE 분 석 ###########\n###################################\n# install.packages(\"party\")\nlibrary(party)\n\nset.seed(2)\n# train / test 분할\nind <- sample(2, nrow(iris), replace=TRUE, prob=c(0.7,0.3))\ntrainData <- iris[ind==1, ]\ntestData <- iris[ind==2, ]\n\n# 모델링\nformula <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width\niris_ctree <- ctree(formula, data=trainData)\n\nplot(iris_ctree)\n\n# test 예측\nctreepred <- predict(iris_ctree, newdata=testData)\ntable(testData$Species, ctreepred)\n\n\n\n###################################\n##### 로 지 스 틱 회 귀 분 석 #####\n###################################\n# install.packages(\"glm2\")\nlibrary(glm2)\n\n# target 변수 2개 범주로만 선택 (범주형변수로변환)\nadj_iris <- iris\nadj_iris$Species <- as.character(adj_iris$Species)\nadj_iris <- subset(adj_iris, Species %in% c('versicolor', 'virginica'))\nadj_iris$Species <- as.factor(adj_iris$Species)\n\nset.seed(10)\n# train / test 분할\nind <- sample(2, nrow(adj_iris), replace=TRUE, prob=c(0.7,0.3))\ntrainData <- adj_iris[ind==1, ]\ntestData <- adj_iris[ind==2, ]\n\n# 모델링\nformula <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width\niris_logit <- glm(formula, data=trainData, family=binomial()) \n#일반선형모형(GLM)이 아닌 로지스틱 회귀를 실행하기 위해, R 프로그램에 family=binomial 이란 옵션을 설정해야 하는 것\n\n# test 예측\n#data.frame(adj_iris$Species, as.numeric(adj_iris$Species)-1) #versicolor=0, virginica=1\n\nlogitpred_a <- predict(iris_logit, newdata=testData, type=\"response\")\nlogitpred <- ifelse(logitpred_a>=0.5, \"virginica\", \"versicolor\")\n\ntable(testData$Species , logitpred)\n\n\n\n###################################\n##### H2O Deeplearning 분 석 ######\n###################################\n# install.packages(\"h2o\")\nlibrary(h2o)\n\nh2o.init()\n\nset.seed(4)\niris.hex <- as.h2o(iris)\n\n# 모델링\niris_dl <- h2o.deeplearning(x = 1:4, y = 5, training_frame = iris.hex, activation = \"Tanh\", hidden = c(10, 10)) #x:인풋변수, y:타겟변수\n\n# 예측\npredictions <- h2o.predict(iris_dl, iris.hex)\npredictions <- as.data.frame(predictions)\n\ntable(iris$Species, predictions$predict)\n\n\n\n\n\n\n\n# ###################################\n# ##### ANN (인공신경망) 분 석 ######\n# ###################################\n# # install.packages(\"nnet\")\n# library(nnet)\n# \n# set.seed(3)\n# # train / test 분할\n# ind <- sample(2, nrow(iris), replace=TRUE, prob=c(0.7,0.3))\n# trainData <- iris[ind==1, ]\n# testData <- iris[ind==2, ]\n# \n# # 모델링\n# formula <- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width\n# iris_nnet <- nnet(formula, data=trainData, size=3) #size : hidden layer\n# \n# # test 예측\n# nnetpred <- predict(iris_nnet, newdata=testData, type=\"class\")\n", "meta": {"hexsha": "11382c2b487db6892461ed7af5d1b6bc7fd1db27", "size": 4043, "ext": "r", "lang": "R", "max_stars_repo_path": "r-script.r", "max_stars_repo_name": "m-duel-project/in-game-rl", "max_stars_repo_head_hexsha": "de2786005b9383939680c929dc9eb5600c808656", "max_stars_repo_licenses": ["MIT"], "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-script.r", "max_issues_repo_name": "m-duel-project/in-game-rl", "max_issues_repo_head_hexsha": "de2786005b9383939680c929dc9eb5600c808656", "max_issues_repo_licenses": ["MIT"], "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-script.r", "max_forks_repo_name": "m-duel-project/in-game-rl", "max_forks_repo_head_hexsha": "de2786005b9383939680c929dc9eb5600c808656", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.427672956, "max_line_length": 127, "alphanum_fraction": 0.6136532278, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6443212118743971}} {"text": "## Created on Wednesday, October 6, 2021 at 9:52pm EDT by Weekend Editor on WeekendEditorMachine.\n## Copyright (c) 2021, SomeWeekendReading.blog. All rights reserved. As if you care.\n\ntoolsDir <- \"../../tools\" # Various tools available from author\nsource(file.path(toolsDir, \"graphics-tools.r\")) # Various graphics hacks\n\nlibrary(\"hypergeo\") # For hypergeo() and genhypergeo()\n\n##\n## Compare with the example Julian Saffer plots on his GitHub repository:\n## https://github.com/jsaffer/beta_quotient_distribution\n## - Numerator beta distribution: alpha1 = 3, beta1 = 6\n## - Denominator beta distribution: alpha2 = 12, beta2 = 7\n##\n## This comparison is \"naive\" in the sense that I'm just using the hypergeo library functions\n## without any caution for large values of the hypergeometric function's parameters. E.g., for\n## the Moderna/Pfizer COVID-19 vaccine clinical trials, those could be O(10k-20k). We almost\n## certainly need some recurrence relation or other to help out with that.\n##\n## But Saffer's example is doable with naive numerics.\n##\n## IWBNI we also did the Monte Carlo version for comparison: take pairs of random draws from the\n## numerator and denominator distributions, calculate a ratio, and histogram the probability\n## density of the ratio. Compare with theoretical distribution by something like a\n## Kolmogorov-Smirnov test?\n##\n\ndoit <- function(alpha1 = 3, beta1 = 6, # Numerator beta distribution\n alpha2 = 12, beta2 = 7, # Denominator beta distribution\n nPoints = 1000, # Number of points on each curve\n xmax = 2.0, # Limit on horizontal axis from Saffer\n ymax = 3.75, # Limit on vertical axis from Saffer\n alpha = 0.40, # Transparency level of fill colors (0 to 1)\n cols = c(numerator = \"blue\", # Colors for various curves\n denominator = \"orange\", # and the fill for them inside\n ratio = \"green\", # their 90% credible intervals\n ratioCDF = \"red\"), # Finally, destination for plot\n plotFile = \"2021-09-13-beta-ratios-naive-comparison-vs-saffer.png\") {\n\n dBetaRatio <- function(alpha1, beta1, alpha2, beta2, R) {\n ## Beta ratio PDF\n ## NB: this WILL NOT WORK when alpha, beta ~ O(10^4), as for Pfizer & Moderna clinical trial!\n stopifnot(is.numeric(R) && R >= 0) # Don't be ridiculous\n if (R <= 1) # Small values of R\n beta(alpha1 + alpha2, beta2) / (beta(alpha1, beta1) * beta(alpha2, beta2)) *\n R^(alpha1 - 1) * #\n hypergeo(alpha1 + alpha2, 1 - beta1, alpha1 + alpha2 + beta2, R)\n else # Large values of R\n beta(alpha1 + alpha2, beta1) / (beta(alpha1, beta1) * beta(alpha2, beta2)) *\n R^(-(alpha2+1)) * #\n hypergeo(alpha1 + alpha2, 1 - beta2, alpha1 + alpha2 + beta1, 1 / R)\n } #\n\n pBetaRatio <- function(alpha1, beta1, alpha2, beta2, R) {\n ## Beta ratio CDF\n ## NB: this WILL NOT WORK when alpha, beta ~ O(10^4), as for Pfizer & Moderna clinical trial!\n stopifnot(is.numeric(R) && R >= 0) # Don't be ridiculous\n if (R <= 1) # Small values of R\n beta(alpha1 + alpha2, beta2) / (beta(alpha1, beta1) * beta(alpha2, beta2)) *\n R^alpha1 / alpha1 * #\n genhypergeo(c(alpha1, alpha1 + alpha2, 1 - beta1), c(alpha1 + 1, alpha1 + alpha2 + beta2),\n R) #\n else # Large values of R\n 1 - beta(alpha1 + alpha2, beta1) / (beta(alpha1, beta1) * beta(alpha2, beta2)) *\n 1 / (alpha2 * R^alpha2) * #\n genhypergeo(c(alpha2, alpha1 + alpha2, 1 - beta2), c(alpha2 + 1, alpha1 + alpha2 + beta1),\n 1 / R) #\n } #\n\n qBetaRatio <- function(alpha1, beta1, alpha2, beta2, q, minR = 0, maxR = 10) {\n ## Beta ratio quantile (numeric solution via CDF)\n ## NB: this WILL NOT WORK when alpha, beta ~ O(10^4), as for Pfizer & Moderna clinical trial!\n stopifnot(is.numeric(q) && is.numeric(minR) && is.numeric(maxR))\n stopifnot(0 <= q && q <= 1.0) # Don't be ridiculous\n stopifnot(0 <= minR && 0 <= maxR && minR < maxR) # Really: don't be ridiculous\n uniroot(function(R) {q - pBetaRatio(alpha1, beta1, alpha2, beta2, R)}, c(minR, maxR))$\"root\"\n } #\n\n medianBetaRatio <- function(alpha1, beta1, alpha2, beta2, minR = 0, maxR = 10) {\n ## NB: this WILL NOT WORK when alpha, beta ~ O(10^4), as for Pfizer & Moderna clinical trial!\n qBetaRatio(alpha1, beta1, alpha2, beta2, 0.50, minR, maxR)\n } # Analytic version uses incomplete Beta func\n\n meanBetaRatio <- function(alpha1, beta1, alpha2, beta2) {\n alpha1 * (alpha2 + beta2 - 1) / ((alpha1 + beta1) * (alpha2 - 1))\n } # Mean has simple closed form\n\n meanBeta <- function(alpha, beta) { alpha / (alpha + beta) }\n\n colorCI <- function(col, alpha, xvals, yvals, x05, x95) {\n col <- col2rgb(col) # Base color to make transparent\n col <- rgb(col[[1]], col[[2]], col[[3]], max = 255, alpha = alpha * 255)\n foo <- subset(data.frame(x = xvals, pdf = yvals), subset = x05 <= x & x <= x95)\n polygon(x = c(rev(foo$\"x\"), foo$\"x\"),\n y = c(rep(0, length.out = nrow(foo)), foo$\"pdf\"),\n border = NA, col = col) # Filled in 90% credible interval\n } #\n\n ## Values where we numerically evaluate the distributions\n xvals <- seq(from = 0, to = xmax, length.out = nPoints)\n\n ## Numerator beta distribution\n numPDF <- dbeta(x = xvals, shape1 = alpha1, shape2 = beta1)\n numMean <- meanBeta(alpha1, beta1) # Mean of numerator beta distribution\n num05 <- qbeta(p = 0.05, shape1 = alpha1, shape2 = beta1)\n num95 <- qbeta(p = 0.95, shape1 = alpha1, shape2 = beta1)\n\n ## Denominator bea distribution\n denomPDF <- dbeta(x = xvals, shape1 = alpha2, shape2 = beta2)\n denomMean <- meanBeta(alpha2, beta2) # Mean of denominator beta distribution\n denom05 <- qbeta(p = 0.05, shape1 = alpha2, shape2 = beta2)\n denom95 <- qbeta(p = 0.95, shape1 = alpha2, shape2 = beta2)\n\n ## Ratiodistribution\n ratioPDF <- sapply(xvals, function(R) { dBetaRatio(alpha1, beta1, alpha2, beta2, R) })\n ratioCDF <- sapply(xvals, function(R) { pBetaRatio(alpha1, beta1, alpha2, beta2, R) })\n ratioMean <- meanBetaRatio(alpha1, beta1, alpha2, beta2)\n ratio05 <- qBetaRatio(alpha1, beta1, alpha2, beta2, 0.05)\n ratio95 <- qBetaRatio(alpha1, beta1, alpha2, beta2, 0.95)\n\n ## Saffer: 1152 x 648 --> us: 400 x 225\n withPNG(file.path(\".\", plotFile), 400, 225, FALSE, function() {\n withPars(function() { # Save/restore graphics parameters\n\n matplot(x = xvals, # Plot PDFs and ratio CDF\n y = matrix(data = c(numPDF, denomPDF, ratioPDF, ratioCDF), nrow = nPoints),\n lty = c(\"solid\", \"solid\", \"solid\", \"dotted\"),\n col = c(cols[[\"numerator\"]], cols[[\"denominator\"]],\n cols[[\"ratio\"]], cols[[\"ratioCDF\"]]),\n type = \"l\", lwd = 2, #\n xlim = c(0, xmax), ylim = c(0, ymax), #\n xlab = \"X\", ylab = \"Pr(X) or Pr(> X)\", #\n main = \"Saffer's Example Beta Ratio\") #\n\n colorCI(cols[[\"numerator\"]], alpha, xvals, numPDF, num05, num95)\n colorCI(cols[[\"denominator\"]], alpha, xvals, denomPDF, denom05, denom95)\n colorCI(cols[[\"ratio\"]], alpha, xvals, ratioPDF, ratio05, ratio95)\n\n abline(v = c(numMean, denomMean, ratioMean), # Vertical dashed lines at means\n col = c(cols[[\"numerator\"]], cols[[\"denominator\"]], cols[[\"ratio\"]]),\n lty = \"dashed\", lwd = 2) #\n\n ## Grid lines\n abline(h = seq(from = 0, to = 3.5, by = 0.5), col = \"gray\")\n abline(v = seq(from = 0, to = 2.0, by = 0.5), col = \"gray\")\n\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # White background\n mar = c(3, 3, 2, 1), # Pull in on margins a bit\n mgp = c(1.7, 0.5, 0), # Axis title, labels, ticks\n las = 1, # Always horizontal axis labels\n ps = 16) # Larger type size for file capture\n }) #\n\n invisible(NA) # Return nothing of interest, invisibly\n} #\n", "meta": {"hexsha": "48e678eef2381caea6fd9276975843049cbd089e", "size": 9452, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2021-09-13-beta-ratios-naive-comparison-vs-saffer.r", "max_stars_repo_name": "SomeWeekendReading/someweekendreading.github.io", "max_stars_repo_head_hexsha": "3b781a1b9bafff8f970fe7692c4384cb328c32f7", "max_stars_repo_licenses": ["MIT"], "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-09-13-beta-ratios-naive-comparison-vs-saffer.r", "max_issues_repo_name": "SomeWeekendReading/someweekendreading.github.io", "max_issues_repo_head_hexsha": "3b781a1b9bafff8f970fe7692c4384cb328c32f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-10-14T16:09:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T21:01:06.000Z", "max_forks_repo_path": "assets/2021-09-13-beta-ratios-naive-comparison-vs-saffer.r", "max_forks_repo_name": "SomeWeekendReading/someweekendreading.github.io", "max_forks_repo_head_hexsha": "3b781a1b9bafff8f970fe7692c4384cb328c32f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.2038216561, "max_line_length": 99, "alphanum_fraction": 0.5163986458, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6442101565763801}} {"text": "##################################### FUNCOES PARA INTERPOLACAO ####################################\n\n#' Modelo Para Interpolacao De Curva Colina\n#' \n#' Funcao para estimacao de diferentes interpoladores de curva colina\n#' \n#' \\code{interpolador} serve como uma interface comum para estimacao de diversas formas atraves das\n#' quais interpolar a colina original. Atualmente ha tres abordagens implementadas:\n#' \n#' \\itemize{\n#' \\item{\\code{\\link{triangulacao}}}\n#' \\item{\\code{\\link{thinplate}}}\n#' \\item{\\code{\\link{tensorprod}}}\n#' }\n#' \n#' Se \\code{metodo = \"triangulacao\"}, a colina fornecida e projetada no plano hl x pot e entao \n#' tesselada atraves da triangulacao de Delaunay. Interpolacao de um ponto em objetos de \n#' triangulacao se da atraves de transformacao para coordenadas baricentricas e subsequente media\n#' ponderada dos rendimentos nos vertices do triangulo que o contem.\n#' \n#' Quando \\code{metodo = \"thinplate\"} ou \\code{metodo = \"tensorprod\"}, a colina e suavizada atraves \n#' de splines, cujo tipo depende do \\code{metodo} passado: \\code{\"thinplate\"} corresponde a \n#' suavizacao por splines homonimas e \\code{\"tensorprod\"} ao produto tensor de splines. A\n#' interpolacao nesse caso consiste simplesmente da consulta a curva suavizada em pontos \n#' selecionados.\n#' \n#' O argumento \\code{...} permite passar os argumentos opcionais aos metodos especificos. As paginas\n#' de ajuda dos interpoladores proveem mais informacao a respeito destes argumentos extras.\n#' \n#' \\bold{Interpoladores Multiplos}:\n#' \n#' Existe a possibilidade de estimar um interpolador combinando mais de um metodo. Isto pode ser\n#' feito passando um vetor de duas posicoes em \\code{metodo} indicando os dois metodos a serem\n#' usados conjuntamente com o argumento \\code{quebra}, um numero indicando o rendimento da curva\n#' a partir da qual o segundo metodo deve ser utilizado.\n#' \n#' Nestes casos, o objeto retornado tera classe \\code{\"interpolador\"} e subclasse \n#' \\code{\"interpoladorM\"}, com todos os mesmos metodos disponivies.\n#' \n#' @param colina objeto da classe \\code{curvacolina} (retornado pelas funcoes de leitura)\n#' @param metodo um ou dois de \\code{c(\"triangulacao\", \"thinplate\", \"tensorpro\")}. Ver Detalhes\n#' @param quebra opcional, numerico indicando o rendimento da curva a partir da qual chavear\n#' metodos. Ver Detalhes\n#' @param ... demais parametros que possam ser passados as funcoes de ajuste de cada \\code{metodo}.\n#' Ver Detalhes\n#' \n#' @examples\n#' \n#' # usando dado dummy contido no pacote\n#' interp_tri <- interpolador(colinadummy, \"triangulacao\")\n#' \n#' # interpolando uma grade 20x20 no dominio da colina\n#' pontos <- coordgrade(colinadummy, 20, 20)\n#' grade <- predict(interp_tri, pontos)\n#' \n#' \\dontrun{\n#' # visualizacao 3d e 2d do resultado\n#' plot(grade)\n#' plot(grade, \"2d\")\n#' }\n#' \n#' # INTERPOLADOR MULTIPLO\n#' interp_mult <- interpolador(colinadummy[rend > 92], c(\"thinplate\", \"triangulacao\"), 95.5)\n#' \n#' # interpolando uma grade 20x20 no dominio da colina\n#' pontos <- coordgrade(colinadummy, 20, 20)\n#' grade <- predict(interp_mult, pontos)\n#' \n#' \\dontrun{\n#' # visualizacao 3d e 2d do resultado\n#' plot(grade)\n#' plot(grade, \"2d\")\n#' }\n#' \n#' @return objeto da classe \\code{interpolador} e subclasse \\code{metodo}, isto e, um modelo com o \n#' qual se realizar previsoes e, assim, interpolar o dado original\n#' \n#' @family interpolador\n#' \n#' @export\n\ninterpolador <- function(colina, metodo, quebra, ...) {\n\n rend <- NULL\n\n if(missing(quebra)) {\n interp_func <- match.call()\n interp_func[[1]] <- as.name(metodo)\n interp_func$metodo <- NULL\n\n interp <- eval(interp_func, envir = parent.frame())\n\n return(interp)\n } else {\n\n if(length(metodo) != 2) stop(\"Quando 'quebra' e fornecido, 'metodos' deve ter tamanho 2\")\n\n colinas <- list(colina[rend <= quebra], colina[rend >= quebra])\n\n interp_func <- match.call()\n interp <- mapply(metodo, colinas, FUN = function(m, c) {\n interp_func[[1]] <- as.name(m)\n interp_func$colina <- c\n interp_func$metodo <- NULL\n\n eval(interp_func, envir = parent.frame())\n }, SIMPLIFY = FALSE)\n\n new_interpoladorM(interp, quebra)\n }\n}\n\n# METODOS ------------------------------------------------------------------------------------------\n\n#' @rdname getcolina\n\ngetcolina.interpolador <- function(object) stop(paste0(\"Implemente metodo 'getcolina' do modelo: \", class(object)[1]))\n\n#' Previsao Com Modelos Interpoladores\n#' \n#' Metodo para interpolar curva colina a partir de um objeto gerado por \\code{interpolador}\n#' \n#' O argumento \\code{as.gradecolina} permite alterar a saida da interpolacao. Se \n#' \\code{as.gradecolina = FALSE}, o padrao, apenas o vetor de rendimentos interpolados sera\n#' retornado. Caso \\code{as.gradecolina = TRUE}, a saida sera um objeto \\code{\\link{gradecolina}}.\n#' \n#' @param object objeto da classe \\code{interpolador} retornado pela funcao homonima\n#' @param pontos data.frame ou matriz contendo pontos nos quais amostrar o rendimento\n#' @param as.gradecolina booleano indicando o nivel de detalhe na saida da funcao. Ver Detalhes\n#' @param ... demais parametros que possam ser passados aos metodos de \\code{predict} especificos\n#' \n#' @return vetor de rendimentos nas coordenadas especificadas em \\code{pontos}\n#' \n#' @family interpolador\n#' \n#' @export\n\npredict.interpolador <- function(object, pontos, as.gradecolina, ...) {\n stop(paste0(\"Implemente metodo 'predict' do modelo: \", class(object)[1]))\n}\n", "meta": {"hexsha": "603406b8e621494007899048595893a7f6b77e47", "size": 5555, "ext": "r", "lang": "R", "max_stars_repo_path": "R/interpolacao.r", "max_stars_repo_name": "lkhenayfis/gtdp-curvacolina", "max_stars_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/interpolacao.r", "max_issues_repo_name": "lkhenayfis/gtdp-curvacolina", "max_issues_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-01-29T15:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T16:13:23.000Z", "max_forks_repo_path": "R/interpolacao.r", "max_forks_repo_name": "lkhenayfis/gtdp-curvacolina", "max_forks_repo_head_hexsha": "a3583255f8dfeb9ef14a6195055deac2b8938ba4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3971631206, "max_line_length": 118, "alphanum_fraction": 0.6838883888, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6442101438342968}} {"text": "############################################################\n# For owl monkey project, last revised 04.18\n# Plots and statistical tests for Figure 1 and Figure S2\n# in owl monkey paper.\n#\n# Gregg Thomas\n############################################################\n\nlibrary(ggplot2)\nthis.dir <- dirname(parent.frame(2)$ofile)\nsetwd(this.dir)\ncat(\"----------\\n\")\n\nfigs2_opt = T\n# CHANGE TO TRUE TO GENERATE FIG. S2\n\n####################\n## Estimating model parameters using Kong (2012) data\nhuman_dm0 = 34; human_df = 31; human_num_f = 14.2; human_haploid = 2630000000; human_diploid = human_haploid * 2;\n# Parameters observed from Drost & Lee (1995) and Kong (2012)\n\nhuman_mu_c = (human_num_f / human_df)\ncat(\"mu_c estimated from Kong params: \", human_mu_c, \"\\n\")\nhuman_mu_c = human_mu_c / human_haploid\ncat(\"mu_c per site estimated from Kong params: \", human_mu_c, \"\\n\")\n# Estimating mu_c\n\n# Calculate spermatogenic proportion and expected number of spermatogenic divisions\n# per year using human (Kong) observations.\nhuman_sc = 16\nhuman_dy1 = ((2.01 / human_haploid) / human_mu_c)\nhuman_sp = human_dy1 / (365/16)\ncat(\"Human expected # of spermatogenic cycles/year: \", human_dy1, \"\\n\")\ncat(\"Human spermatogenic cell proportion given a cycle length of 16 days: \", human_sp, \"\\n\")\ncat(\"----------\\n\")\n# Estimating the expected number of spermatogenic cycles per year\n\n# 2.01 is the slope of the Kong line -- mutations per year in males after puberty.\n# We can calculate the expected number of spermatogenic cycles per year (human_dy1) based on mu_c.\n# Then, we can estimate the proportion of cells undergoing spermatogenesis at any given time (human_sp)\n####################\n\n####################\n## Owl monkey prediction (purple dashed) using Kong parameters\nom_puberty = 1; om_sc = 10.2;\nom_dy1 = (365/om_sc) * human_sp\ncat(\"Owl monkey expected # of spermatogenic cycles/year: \", om_dy1, \"\\n\")\n# Estimate the expected number of spermatogenic cycles per year in owl monkeys using the human proportion\n# of cells actively dividing (human_sp).\n\nage_range = seq(om_puberty, 15, by=0.1)\nrep_long = age_range - om_puberty\n# The owl monkey age of puberty set at 1 year and a range of paternal ages\n\nom_mu_g = ((human_df * human_mu_c) + ((human_dm0 * human_mu_c) + (om_dy1 * rep_long * human_mu_c))) / 2\n# Calculating the mutation rate (Equation 9 in paper)\n\nom_pred = data.frame(om_mu_g, age_range)\nnames(om_pred) = c(\"Mutation.rate\", \"Parental.age\")\nom_pred_reg = lm(om_mu_g ~ age_range)\ncat(\"----------\\n\")\n####################\n\n####################\n## Owl monkey observed data (purple solid)\nin_data = read.csv(\"data/owl-monkey-filters.csv\", header=TRUE)\n\nif(figs2_opt) {\n cur_filter = subset(in_data, Min.DP==20 & Max.DP==60 & Min.AB==0.3 & Max.AB==0.7)\n}else{\n cur_filter = subset(in_data, Min.DP==20 & Max.DP==60 & Min.AB==0.4 & Max.AB==0.6)\n}\nom_obs = cur_filter$MVs.corrected.for.FN\nom_gt = cur_filter$Paternal.GT\nom_callable = (cur_filter$Sites - cur_filter$Uncallable.SNP.sites) * 2\nom_mu = om_obs / om_callable\ncur_filter$CpG.rate = cur_filter$CpG.MVs / om_callable\nom_obs_reg = lm(om_mu ~ om_gt)\n# Read data and define current filter\n\ncat(\"PREDICTED SLOPE (d_ym1)\\n\")\ncat(coef(om_pred_reg)[2], \" mutations per site per year\\n\")\ncat(coef(om_pred_reg)[2] * human_haploid * 2, \" mutations per year\\n\")\ncat(\"OBSERVED SLOPE (dy_m1)\\n\")\ncat(coef(om_obs_reg)[2], \" mutations per site per year\\n\")\ncat(coef(om_obs_reg)[2] * (mean(om_callable)), \" mutations per year\\n\")\ncat(\"----------\\n\")\n# Predicted vs observed slopes (d_ym1)\n####################\n\n####################\n## The plot for Fig. 1\nfig1 = ggplot(cur_filter, aes(x=Paternal.GT, y=Mutation.rate.corrected.for.FN)) + \n geom_smooth(method='glm', color='#b66dff', fill=\"#f2e6ff\", fullrange=T) +\n geom_point(color='#b66dff', size=3) +\n geom_smooth(aes(x=Paternal.GT, y=CpG.rate), method='glm', color=\"#6db6ff\", fill=NA, fullrange=T) +\n geom_point(aes(x=Paternal.GT, y=CpG.rate), color=\"#6db6ff\", size=3) +\n scale_x_continuous(breaks = seq(1, 60, by=2)) + \n scale_y_continuous(breaks = seq(0, 1.8e-8, by=0.4e-8)) + \n geom_line(data=om_pred, aes(x=Parental.age, y=Mutation.rate), linetype=2, size=0.75, color=\"purple\") +\n geom_vline(xintercept=1, linetype=3, color=\"grey\", size=0.75) + \n labs(x=\"Age of father at conception (y)\",y=\"Mutation rate per site\\nper generation\") +\n theme_classic() +\n theme(axis.text=element_text(size=14), \n axis.title=element_text(size=20), \n axis.title.y=element_text(margin=margin(t=0,r=20,b=0,l=0),color=\"black\"), \n axis.title.x=element_text(margin=margin(t=20,r=0,b=0,l=0),color=\"black\"),\n axis.line=element_line(colour='#595959',size=0.75),\n axis.ticks=element_line(colour=\"#595959\",size = 1),\n axis.ticks.length=unit(0.2,\"cm\")\n )\nprint(fig1)\nif(figs2_opt) {\n ggsave(filename=\"figS1C.pdf\", fig1, width=6, height=5, units=\"in\")\n}else{\n ggsave(filename=\"fig1.pdf\", fig1, width=6, height=5, units=\"in\")\n}\ncat(\"--Regression summary for observed points--\\n\")\nprint(summary(om_obs_reg))\ncat(\"----------\\n\")\n####################\n\n####################\n## The F test for Fig. 1\npred_actual = coef(om_pred_reg)[1] + om_gt * coef(om_pred_reg)[2]\npred_resids = om_mu - pred_actual\n#plot(age_range,om_mu_g, type='l',ylim=c(min(om_mu),max(om_mu)))\n#points(om_gt, om_mu)\n#segments(x0=om_gt,y0=om_mu,x1=om_gt,y1=om_mu-pred_resids)\n#abline(om_obs_reg, lty=2)\n#segments(x0=om_gt,y0=om_mu,x1=om_gt,y1=om_mu-resid(om_obs_reg),lty=2)\ncat(\"--F test for differences between residuals of the predicted and observed lines--\")\nprint(var.test(resid(om_obs_reg), pred_resids, alternative=\"two.sided\"))\ncat(\"----------\\n\")\n####################\nstop()\n####################\n## Paternal (orange) vs. Maternal (teal) mutations\npat_df = data.frame(cur_filter$Paternal.MVs[cur_filter$Paternal.MVs!=0], cur_filter$Paternal.GT[cur_filter$Paternal.MVs!=0])\nnames(pat_df) = c(\"Paternal.MVs\", \"Paternal.GT\")\nmat_df = data.frame(cur_filter$Maternal.MVs[cur_filter$Maternal.MVs!=0], cur_filter$Maternal.GT[cur_filter$Maternal.MVs!=0])\nnames(mat_df) = c(\"Maternal.MVs\", \"Maternal.GT\")\n\np = ggplot(pat_df, aes(x=Paternal.GT, y=Paternal.MVs)) +\n geom_smooth(method='glm', color='#db6d00', fill='#ffe6cc', fullrange=T) +\n geom_point(color='#db6d00', size=3) +\n geom_vline(xintercept=1, linetype=3, color=\"grey\", size=0.75) + \n geom_smooth(data=mat_df, aes(x=Maternal.GT, y=Maternal.MVs), method='glm', color='#009292', fill='#ccffff', fullrange=T) +\n geom_point(data=mat_df, aes(x=Maternal.GT, y=Maternal.MVs), color='#009292', size=3) +\n #scale_y_continuous(limits=c(0,16)) + \n labs(x=\"Age of parent at conception (y)\",y=\"Mutation rate per site\") +\n theme_classic() +\n theme(axis.text=element_text(size=14), \n axis.title=element_text(size=20), \n axis.title.y=element_text(margin=margin(t=0,r=20,b=0,l=0),color=\"black\"), \n axis.title.x=element_text(margin=margin(t=20,r=0,b=0,l=0),color=\"black\"),\n axis.line=element_line(colour='#595959',size=0.75),\n axis.ticks=element_line(colour=\"#595959\",size = 1),\n axis.ticks.length=unit(0.2,\"cm\")\n )\n#print(p)\npat_reg = lm(pat_df$Paternal.MVs ~ pat_df$Paternal.GT)\ncat(\"--Regression summary for paternal mutations--\\n\")\nprint(summary(pat_reg))\ncat(\"--Regression summary for maternal mutations--\\n\")\nmat_reg = lm(mat_df$Maternal.MVs ~ mat_df$Maternal.GT)\nprint(summary(mat_reg))\n####################\n", "meta": {"hexsha": "7d5776df4e519db22720aa8d0b1f8dc5c5fd1cca", "size": 7395, "ext": "r", "lang": "R", "max_stars_repo_path": "fig1.r", "max_stars_repo_name": "gwct/owl-monkey", "max_stars_repo_head_hexsha": "cceff1499b54d83949103f98a1da29e5cfc6179b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fig1.r", "max_issues_repo_name": "gwct/owl-monkey", "max_issues_repo_head_hexsha": "cceff1499b54d83949103f98a1da29e5cfc6179b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fig1.r", "max_forks_repo_name": "gwct/owl-monkey", "max_forks_repo_head_hexsha": "cceff1499b54d83949103f98a1da29e5cfc6179b", "max_forks_repo_licenses": ["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.7573964497, "max_line_length": 124, "alphanum_fraction": 0.6707234618, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6441728515485758}} {"text": "#' Mixing Layer Depth\r\n#'\r\n#' Identification of the mixing layer depth (e.g. thermocline, pycnocline) \r\n#' using a modified version of the Maximum Angle Method.\r\n#'\r\n#' @param z Vector of depths, or 2-column dataframe containing depths in first \r\n#' column and variable of interest (e.g. temperature, salinity) in second\r\n#' column.\r\n#' @param x Vector containing variable of interest (e.g. temperature, salinity)\r\n#' of same length as \\code{z}.\r\n#' @param np Number of points to use in linear regressions (see 'details'). \r\n#' @param min.range The minimum range in the value of \\code{x} in order\r\n#' for a mixing layer to be detectable.\r\n#' @param max.z Maximum value of \\code{z} to use when searching for mixing \r\n#' layer depth.\r\n#' @param return.index If TRUE, return the index of \\code{z} corresponding to\r\n#' the mixing layer depth. Otherwise, return the depth.\r\n#' @return either the mixing layer depth or the element index of z associated \r\n#' with said depth, depending on the value of \\code{return.type}.\r\n#'\r\n#' @details The Maximum Angle Method is modified to better handle the\r\n#' identification of the mixing layer depth when the surface layer is \r\n#' poorly-mixed and to provide some flexibility in the linear regression, but\r\n#' may be less stable as a result. The modifications force the dual linear \r\n#' regressions to share the last/first data point and allow the user to \r\n#' specify the number of points used in the regressions.\r\n#'\r\n#' @references Chu, Peter C., and Chenwu Fan. \"Maximum angle method for \r\n#' determining mixed layer depth from seaglider data.\" Journal of \r\n#' oceanography 67.2 (2011): 219-230.\r\n#'\r\n#' @examples\r\n#' data(ctd)\r\n#' zt = subset(ctd, date == date[1] & dist == dist[1])[c(\"depth\", \"ta\")] \r\n#' mld(zt)\r\n#' mld(zt, return.index = TRUE)\r\n#' \r\n#' #' @seealso \\code{\\link{blt}}\r\n#' @export\r\nmld = function(z, x = NULL, np = 2, min.range = 0, max.z = NULL, \r\n return.index = FALSE){\r\n if(is.null(x)){\r\n x = z[, 2]\r\n z = z[, 1]\r\n }\r\n if(!is.null(max.z)){\r\n x = x[z <= max.z]\r\n z = z[z <= max.z]\r\n }\r\n if(np > floor(0.5*length(z)))\r\n stop(\"Argument 'np' is too large.\")\r\n minx = min(x)\r\n maxx = max(x)\r\n rangex = maxx - minx\r\n # return NA if range of variable is too small\r\n if(rangex < min.range)\r\n return(NA)\r\n minz = z[min(which(x == min(x)))]\r\n maxz = z[max(which(x == max(x)))]\r\n rangez = maxz - minz\r\n if(minz != min(z) | maxz != max(z))\r\n warning(\"Data is noisy\")\r\n m = np - 1\r\n j = np - 1\r\n K = length(z)\r\n tantheta = 0\r\n clinek = 1\r\n for(k in seq(j + 1, K - m)){\r\n# Gtop = lm(x ~ z, data.frame(z = z[seq(k - j, k)], \r\n# x = x[seq(k - j, k)]))$coefficients[[2]]\r\n# Gbot = lm(x ~ z, data.frame(z = z[seq(k, k + m)], \r\n# x = x[seq(k, k + m)]))$coefficients[[2]]\r\n # slope of line z ~ x is defined as cor(x, z)*sd(x)/sd(z)\r\n topmask = seq(k - j, k)\r\n botmask = seq(k, k + m)\r\n Gtop = cor(z[topmask], x[topmask])*sd(x[topmask])/sd(z[topmask])\r\n Gbot = cor(z[botmask], x[botmask])*sd(x[botmask])/sd(z[botmask])\r\n newtantheta = abs((Gbot - Gtop)/(1 + Gbot*Gtop))\r\n if(!is.na(newtantheta) & newtantheta > tantheta){\r\n clinek = k\r\n tantheta = newtantheta\r\n } \r\n }\r\n if(return.index)\r\n clinek\r\n else\r\n z[clinek]\r\n}\r\n\r\n#' Barrier Layer Thickness\r\n#'\r\n#' Calculate the thickness of the barrier layer.\r\n#'\r\n#' @param z Vector of depths, or 3-column dataframe containing depths in first \r\n#' column, temperatures in the second column and salinities in the third \r\n#' column.\r\n#' @param t Vector of temperatures of same length as \\code{z}.\r\n#' @param s Vector of salinities of same length as \\code{z}.\r\n#' @param ... Other arguments passed to \\code{mld}. Note that \r\n#' \\code{return.index = FALSE} is fixed.\r\n#' @return The thickness of the barrier layer.\r\n##'\r\n#' @details The 'Barrier Layer' is the region between the pycnocline and \r\n#' thermocline. This function identifies the thermocline and pycnocline \r\n#' depths using \\code{mld} and calculates the thickness of the barrier as the \r\n#' difference the two depths.\r\n#'\r\n#' @references Chu, Peter C., and Chenwu Fan. \"Maximum angle method for \r\n#' determining mixed layer depth from seaglider data.\" Journal of \r\n#' oceanography 67.2 (2011): 219-230.\r\n#'\r\n#' @seealso \\code{\\link{mld}} \r\n#' @export\r\nblt = function(z, t, s, ...){\r\n if(is.missing(t) | is.missing(s)){\r\n s = z[, 3]\r\n t = z[, 2]\r\n z = z[,1]\r\n }\r\n thermocline = mld(z, t, return.index = FALSE, ...)\r\n pycnocline = mld(z, s, return.index = FALSE, ...)\r\n abs(thermocline - pycnocline)\r\n}\r\n\r\n#' Stratify by a Variable\r\n#'\r\n#' Stratify data into zones using specified midpoints.\r\n#'\r\n#' @param x Vector of values.\r\n#' @param midpoints Vector of midpoints or cut points to stratify \\code{x} by.\r\n#' \\code{min(x)} and \\code{max(x)} are automatically included.\r\n#' @param ... Other arguments to pass to \\code{cut()}.\r\n#'\r\n#' @details This function is basically a wrapper for \\code{cut()}, but requires\r\n#' the cuts be directly specified and that \\code{include.lowest = TRUE}.\r\n#' Every element of \\code{x} is therefore guaranteed to be included in one\r\n#' interval.\r\nstratify = function(x, midpoints, ...){\r\n minx = min(x)\r\n maxx = max(x)\r\n if(any(midpoints >= maxx) | any(midpoints <= minx))\r\n stop(\"Midpoints must be within range (min(x), max(x))\")\r\n cut(x, unique(c(minx, sort(midpoints), maxx)), include.lowest = TRUE, ...) \r\n}\r\n", "meta": {"hexsha": "fdc9c4b5eabb285e48cdfcc45535dc8d792280d1", "size": 5459, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rrexplore.r", "max_stars_repo_name": "mkoohafkan/rremat", "max_stars_repo_head_hexsha": "5ee5737372287ac84c9dfe5635b428ab91766184", "max_stars_repo_licenses": ["MIT"], "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/rrexplore.r", "max_issues_repo_name": "mkoohafkan/rremat", "max_issues_repo_head_hexsha": "5ee5737372287ac84c9dfe5635b428ab91766184", "max_issues_repo_licenses": ["MIT"], "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/rrexplore.r", "max_forks_repo_name": "mkoohafkan/rremat", "max_forks_repo_head_hexsha": "5ee5737372287ac84c9dfe5635b428ab91766184", "max_forks_repo_licenses": ["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.6482758621, "max_line_length": 81, "alphanum_fraction": 0.6281370214, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6441728491963941}} {"text": "iterate.until.escape <- function(z, c, trans, cond, max=50, response=dwell) {\n #we iterate all active points in the same array operation,\n #and keeping track of which points are still iterating.\n active <- seq_along(z)\n dwell <- z\n dwell[] <- 0\n for (i in 1:max) {\n z[active] <- trans(z[active], c[active]);\n survived <- cond(z[active])\n dwell[active[!survived]] <- i\n active <- active[survived]\n if (length(active) == 0) break\n }\n eval(substitute(response))\n}\n\nre = seq(-2, 1, len=500)\nim = seq(-1.5, 1.5, len=500)\nc <- outer(re, im, function(x,y) complex(real=x, imaginary=y))\nx <- iterate.until.escape(array(0, dim(c)), c,\n function(z,c)z^2+c, function(z)abs(z) <= 2,\n max=100)\nimage(x)\n", "meta": {"hexsha": "d2710d85c761a121f24f923046fd7b240c0edff7", "size": 763, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Mandelbrot-set/R/mandelbrot-set.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Mandelbrot-set/R/mandelbrot-set.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/Mandelbrot-set/R/mandelbrot-set.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": 31.7916666667, "max_line_length": 77, "alphanum_fraction": 0.5910878113, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6441235666124716}} {"text": "# V and beta supplied via graph.py script\n\nV <- structure(c(3.19826308e-06, -1.28332733e-02, 1.28734322e+01, -1.28332733e-02, 5.14946331e+01, -5.16559253e+04, 1.28734322e+01, -5.16559253e+04, 5.18178740e+07\n), .Dim = c(3L, 3L), .Dimnames = list(c(\"a0\", \"a1\", \"a2\"), c(\"a0\",\n\"a1\", \"a2\")))\n\nbeta <- c(1.93057366e+05, -1.95738445e+02, 4.96009134e-02)\nx <- seq(1993, 2100, by = 1)\nX <- cbind(1, x, x ^ 2)\nmu <- X %*% beta\n# e <- sqrt( rowSums(X * (X %*% V)) )\n# n <- 978\n# lo <- mu + e * qt(0.025, n - 3)\n# up <- mu - e * qt(0.025, n - 3)\n# print(qnorm(.99999))\n\n# e <- 1.644*(mu/sqrt(978))\n# e <- qnorm(.95) *(mu/sqrt(978))\ne <- 10 *(mu/sqrt(978))\n\nlo <- mu + e\nup <- mu - e\n\nprint(e)\nprint(n - 3)\nprint(mu)\nprint(lo)\nprint(up)\nmatplot(x, cbind(mu, lo, up), type = \"l\", col = 1, lty = c(1,2,2))\n# matplot(x, cbind(mu), type = \"l\", col = 1, lty = c(1,2,2))\n", "meta": {"hexsha": "a3d41246334f0976f03f413e3dbe644898a1c3ba", "size": 858, "ext": "r", "lang": "R", "max_stars_repo_path": "data/confidence-bands.r", "max_stars_repo_name": "Kashiblood/fathom", "max_stars_repo_head_hexsha": "b79b6d099cc04637a65e80a46535889c2242a1c1", "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": "data/confidence-bands.r", "max_issues_repo_name": "Kashiblood/fathom", "max_issues_repo_head_hexsha": "b79b6d099cc04637a65e80a46535889c2242a1c1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2021-03-09T21:17:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T13:05:18.000Z", "max_forks_repo_path": "data/confidence-bands.r", "max_forks_repo_name": "Kashiblood/fathom", "max_forks_repo_head_hexsha": "b79b6d099cc04637a65e80a46535889c2242a1c1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6774193548, "max_line_length": 166, "alphanum_fraction": 0.548951049, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6438662490009941}} {"text": "addfit <- function(xx, yy, col='black', interval='conf', alpha=0.05, sided=2, pch=1, vlines=NULL) {\n ## plot points\n points(xx, yy, pch=pch, col=col)\n\n ## put points in dataframe and remove any pairs that do not have values\n df <- na.omit( data.frame(xx,yy) )\n\n ## write points back out to xx and yy\n xx <- df$xx\n yy <- df$yy\n\n ## perform fit\n fit <- lm(yy~xx)\n intercept <- fit$coefficients[[1]]\n slope <- fit$coefficients[[2]]\n\n ## add vertical lines to plot\n if ( !is.null(vlines[1]) & !is.na(vlines[1]) ) abline(v=vlines, lty=3, col=col)\n\n ## add prediction to plot\n if ( !is.null(vlines[1]) & !is.na(vlines[1]) ) {\n ## restrict fit to within vlines\n new.xx <- seq(min(vlines, na.rm=TRUE), max(vlines, na.rm=TRUE), len=100)\n } else {\n ## extend data to range of data\n new.xx <- seq(min(xx, na.rm=TRUE), max(xx, na.rm=TRUE), len=100)\n }\n if (interval == 'mean') {\n lines(new.xx, slope * new.xx + intercept, lwd=2, col=col)\n } else if (interval == 'line') {\n newdf <- data.frame(xx,yy)\n newdf <- newdf[order(newdf$xx),]\n xx <- newdf$xx\n yy <- newdf$yy\n lines(xx, yy, lwd=2, col=col) \n } else {\n pred <- predict(fit, new=data.frame(xx=new.xx), interval=interval, level=1-alpha/sided)\n lines(new.xx, pred[,\"fit\"], lwd=2, col=col)\n lines(new.xx, pred[,\"lwr\"], lty=3, col=col)\n lines(new.xx, pred[,\"upr\"], lty=3, col=col)\n }\n \n ## print results of fit\n ## estbound(fit)\n\n ## calculate rise of fit over range bounds if supplied,\n ## otherwise calculate rise over range of data\n if ( !is.null(vlines[1]) & !is.na(vlines[1]) ) {\n rise <- (vlines[2] - vlines[1]) * slope\n } else {\n rise <- (max(xx) - min(xx)) * slope\n } \n equation = paste0(\"y = \", signif(intercept,4), \" + \", signif(slope,4), \" * x; \",\n expression(Delta), \" = \", signif(rise,4))\n return(list(equation=equation, slope=slope, intercept=intercept, rise=rise))\n\n}\n", "meta": {"hexsha": "6d8fe5f64963daee479ebbff33f75592f0a34bc8", "size": 2071, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/addfit.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/addfit.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/addfit.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": 35.7068965517, "max_line_length": 99, "alphanum_fraction": 0.5528730082, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6437895925806602}} {"text": "#ANALIZA\n\n\n#MODEL LOESS ZA NAPOVED EARNINGOV\n\nmorningstar_izbran<- filter(morningstar,Podatki==\"Earnings Per Share USD\")%>%\n select(Leto,Vrednost)\nmodel_earning <-loess(dat=morningstar_izbran,\n Vrednost~Leto,control=loess.control(surface=\"direct\"))\n\nloe_ear <- function(zeljena_leta){\n prihodnost_dobicek_na_delnico <- data.frame(Leto=c(zeljena_leta))\n napoved_dobicek_na_delnico <- prihodnost_dobicek_na_delnico %>%\n mutate(Vrednost=predict(model_earning,.))\n \n dobicek_na_delnico_graf <- ggplot(data=morningstar_izbran,\n aes(x=Leto,y=Vrednost,color=\"Dobiček na delnico\"))+\n geom_smooth(method = \"loess\",formula = y~x,se=F) +\n geom_point(aes(color=\"Točne vrdednosti\"))+\n geom_point(data=napoved_dobicek_na_delnico,\n aes(x=Leto,y=Vrednost,color=\"Napoved dobička za naprej\"),size=3)+\n scale_colour_manual(name=\"LEGENDA\",values=c(\"red\",\"green\",\"black\"))+\n labs(title=\"Graf dobička na delnico po metodi loess\")+\n scale_x_continuous(name = \"Leto\", breaks = seq(2011,2025,1))+\n scale_y_continuous(name = \"Dobiček na delnico (USD)\", breaks = seq(0,5,0.2))+\n theme(legend.position = c(0.3, 0.8),\n panel.grid.minor = element_blank(),\n plot.title = element_text(hjust = 0.5))\n return(dobicek_na_delnico_graf)}\n\n\n#MODEL NAPOVEDI EARNINGOV REGRESIJA\n\nmodel_dobicek <- lm(data=morningstar_izbran,Vrednost ~ Leto) #ce klices ta model na fukcijo reg_pov ali opt_pov moras leta vnesti kot data frame\n\nreg_ear<- function(zeljena_leta){\n prihodnost_dobicek <- data.frame(Leto=c(zeljena_leta))\n napoved_dobicek <- prihodnost_dobicek%>%\n mutate(Vrednost=predict(model_dobicek, .))\n \n premica_dobicek<-ggplot(morningstar_izbran,aes(x=Leto,y=Vrednost,\n color=\"Dobiček na delnico\"))+\n geom_point(aes(color=\"Točne vrdednosti\"))+\n geom_smooth(method = lm,formula = y~x,se=F,fullrange=TRUE)+\n geom_point(data = napoved_dobicek,aes(x=Leto,y=Vrednost,\n color=\"Napoved dobička za naprej\"),size=3)+\n scale_colour_manual(name=\"LEGENDA\",values=c(\"red\",\"green\",\"black\"))+\n labs(title=\"Graf dobička na delnico s pomočjo linearne regresije\")+\n scale_x_continuous(name = \"Leto\", breaks = seq(2011,2025,1))+\n scale_y_continuous(name = \"Dobiček na delnico (USD)\", breaks = seq(0,5,0.2))+\n theme(legend.position = c(0.3, 0.8),\n panel.grid.minor = element_blank(),\n plot.title = element_text(hjust = 0.5))\n return(premica_dobicek)}\n\n\n#REGRESIJA ZA POVEZAVO MED EARNINGI IN CENO\n\nyah.mor <- right_join(morningstar_izbran,yahoo)\nreg_pov <- function(prihodnost_dobicek_na_delnico,vrsta_modela){\n model_odvisnost1 <- lm(data=yah.mor,Najvisja_cena~Vrednost)\n prihodnost_povezava1 <- data.frame(Vrednost=c(predict(vrsta_modela,prihodnost_dobicek_na_delnico)))\n napoved_povezava1 <- prihodnost_povezava1%>%\n mutate(Najvisja_cena=predict(model_odvisnost1, .))\n \n premica_odvisnost<-ggplot(yah.mor,aes(x=Vrednost,y=Najvisja_cena,\n color=\"Približek za naše podatke\"))+\n geom_point(aes(color=\"Točne vrednosti\"))+\n geom_smooth(method = lm,formula = y~x,se=F,fullrange=TRUE)+\n geom_point(data = napoved_povezava1,\n aes(x=Vrednost,y=Najvisja_cena,\n color=\"Napoved cene preko dobička\"),size=3)+\n scale_colour_manual(name=\"LEGENDA\",values=c(\"green\",\"red\",\"black\"))+\n labs(title=\"Napoved cene preko dobička s pomočjo linearne regresije\")+\n scale_x_continuous(name = \"Dobiček na delnico (USD)\", breaks = seq(0,5,0.2))+\n scale_y_continuous(name = \"Cena (USD)\", breaks = seq(0,140,10))+\n theme(legend.position = c(0.3, 0.8),\n panel.grid.minor = element_blank(),\n plot.title = element_text(hjust = 0.5))\n return(premica_odvisnost)}\n\n\n#SKUPINE\n\ncena.earning <- select(yah.mor,Vrednost,Najvisja_cena)\nstandardizacija <-as.matrix(cena.earning)%>%scale()\nD <- dist(standardizacija)\nmodel22 <- hclust(D)\ncena.earning<-mutate(cena.earning,skupina=cutree(model22,k=2))\n\n\n#OPT\n\nopt_pov <- function(prihodnost_dobicek_na_delnico,vrsta_modela){\n model_opt <- lm(data=filter(cena.earning,skupina==1),\n Najvisja_cena~Vrednost) \n prihodnost_opt <- data.frame(Vrednost=c(predict(vrsta_modela,prihodnost_dobicek_na_delnico)))\n napoved_opt<- prihodnost_opt%>%mutate(Najvisja_cena=predict(model_opt,.))\n \n premica_odvisnost_opt <- ggplot(filter(cena.earning,skupina==1),\n aes(x=Vrednost,y=Najvisja_cena,\n color=\"Izboljšan približek\"))+\n geom_smooth(method = lm,formula = y~x,se=F,fullrange=TRUE)+\n geom_point(aes(color=\"Točne vrdednosti\"))+\n geom_point(data = napoved_opt,\n aes(x=Vrednost,y=Najvisja_cena,\n color=\"Izboljšana napoved cene\"),size=3)+\n scale_colour_manual(name=\"LEGENDA\",values=c(\"red\",\"green\",\"black\"))+\n labs(title=\"Izboljšana napoved cene preko dobička s pomočjo linearne regresije\")+\n scale_x_continuous(name = \"Dobiček na delnico (USD)\", breaks = seq(0,5,0.2))+\n scale_y_continuous(name = \"Cena delnice (USD)\", breaks = seq(0,110,5))+\n theme(legend.position = c(0.3, 0.8),\n panel.grid.minor = element_blank(),\n plot.title = element_text(hjust = 0.5))\n return(premica_odvisnost_opt)}\n", "meta": {"hexsha": "885d699d9e8e28dc9316d5b16382adc2ba64f879", "size": 5367, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "ian-spiller/APPR-2020-21", "max_stars_repo_head_hexsha": "96ad0ff92f9acdae02c0c0ce32bc79aa8601263f", "max_stars_repo_licenses": ["MIT"], "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": "ian-spiller/APPR-2020-21", "max_issues_repo_head_hexsha": "96ad0ff92f9acdae02c0c0ce32bc79aa8601263f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-28T17:03:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-02T18:05:44.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "ian-spiller/APPR-2020-21", "max_forks_repo_head_hexsha": "96ad0ff92f9acdae02c0c0ce32bc79aa8601263f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2672413793, "max_line_length": 144, "alphanum_fraction": 0.6804546301, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6436108265510564}} {"text": "### fimd2.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\n### Tested with Mac OS X 10.7.3, R2.14-2, mice 2.11\n\n### Chapter 2 Multiple imputation\n\nlibrary(\"mice\")\nlibrary(\"lattice\")\nlibrary(\"MASS\")\n\n### Section 2.1.3 The expanding literature on multiple imputation\n### Figure 2.1\n\ncit <- c( 2010, 37, 182, NA,\n 2009, 36, 129, NA,\n 2008, 27, 111, NA,\n 2007, 35, 136, NA,\n 2006, 18, 80, NA,\n 2005, 20, 76, NA,\n 2004, 6, 56, NA,\n 2003, 17, 42, NA,\n 2002, 14, 40, NA,\n 2001, 13, 36, 57,\n 2000, 8, 21, 33,\n 1999, 6, 25, 47,\n 1998, 6, 13, 22,\n 1997, 6, 18, 29,\n 1996, 4, 12, 28,\n 1995, 3, 5, 20,\n 1994, 2, 5, 34,\n 1993, 2, 6, 15,\n 1991, 2, 4, 19,\n 1990, 1, 2, 15,\n 1989, NA, NA, 11,\n 1988, 1, NA, 13,\n 1987, NA, NA, 10,\n 1986, NA, NA, 5,\n 1985, NA, NA, 1,\n 1984, NA, NA, 2,\n 1983, NA, NA, 5,\n 1982, NA, NA, 2,\n 1981, NA, NA, 1,\n 1980, NA, NA, 5,\n 1979, NA, NA, 2,\n 1978, NA, NA, 1,\n 1977, NA, NA, 2)\ncit <- matrix(cit, nr=2010-1977, nc=4, byrow=TRUE)\ncit <- as.data.frame(cit)\nnames(cit) <- c(\"Year\",\"Title\",\"Abstract\",\"All\")\npar(mfrow=c(1,1))\npar(cex=0.7, lwd=0.5)\nplot(x=cit$Year, y=cit$Abstract, type=\"o\",log=\"y\",\n xlim=c(1975,2010),ylim=c(1,200),\n ylab=\"Number of publications (log)\", xlab=\"Year\", pch=2, \n axes=FALSE)\naxis(1, lwd=par(\"lwd\"))\naxis(2, lwd=par(\"lwd\"), las=1)\n# box(lwd=0.5)\nlines(x=cit$Year, y=cit$Title, pch=15, type=\"o\")\nlines(x=cit$Year, y=cit$All, pch=16, type=\"o\")\nlegend(x=1975,y=200,legend=c(\"early publications\",\n \"'multiple imputation' in abstract\",\n \"'multiple imputation' in title\"),\n pch=c(16,2,15), bty=\"n\")\n\n### Section 2.2.4 MCAR, MAR and MNAR again\n\nlogistic <- function(x) exp(x)/(1+exp(x))\nset.seed(80122)\nn <- 300\ny <- mvrnorm(n=n,mu=c(0,0),Sigma=matrix(c(1,0.5,0.5,1),nrow=2))\ny1 <- y[,1]\ny2 <- y[,2]\nr2.mcar <- 1-rbinom(n, 1, 0.5)\nr2.mar <- 1-rbinom(n, 1, logistic(y1))\nr2.mnar <- 1-rbinom(n, 1, logistic(y2))\n\n### Figure 2.2\n\ny3 <- rbind(y,y,y)\nr2 <- c(r2.mcar,r2.mar,r2.mnar)\nr2 <- factor(r2, labels=c(\"Ymis\",\"Yobs\"))\ntyp <- factor(rep(3:1,each=n),labels=c(\"MNAR\",\"MAR\",\"MCAR\"))\nd <- data.frame(y1=y3[,1],y2=y3[,2],r2=r2,typ=typ)\ntrellis.par.set(box.rectangle=list(col=c(mdc(2),mdc(1)),lwd=1.2))\ntrellis.par.set(box.umbrella=list(col=c(mdc(2),mdc(1)),lwd=1.2))\ntrellis.par.set(plot.symbol=list(col=mdc(3),lwd=1))\ntp <- bwplot(r2~y2|typ, data=d,\n horizontal=TRUE, layout=c(1,3),\n xlab=expression(Y^2),\n col=c(mdc(2),mdc(1)),strip=FALSE, xlim=c(-3,3),\n strip.left = strip.custom(bg=\"grey95\"))\nprint(tp)\n\n### Section 2.3.7 Numerical example\noptions(digits=3)\nimp <- mice(nhanes, print=FALSE, m=10, seed=24415)\nfit <- with(imp, lm(bmi~age))\nest <- pool(fit)\nnames(est)\nattach(est)\n(r+2/(df+3))/(r+1)\n(df+1)/(df+3)*lambda+2/(df+3)\ndetach(est)\n", "meta": {"hexsha": "541f9ad10160baeb7d81259dfc90538ac31d1a30", "size": 3434, "ext": "r", "lang": "R", "max_stars_repo_path": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd2.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/fimd2.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/fimd2.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.2181818182, "max_line_length": 65, "alphanum_fraction": 0.5110658125, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6430948426757781}} {"text": "\r\n\r\n# Assignment 4 - PCA \r\n\r\nThis document does a PCA (Principal component analysis) on the Heart Failure Prediction dataset\r\n\r\n# Let us load libraries and data\r\n\r\n```{r results='hide', message=FALSE, warning=FALSE}\r\n# clear environment\r\nrm(list = ls())\r\n\r\n# defining libraries\r\n\r\nlibrary(ggplot2)\r\nlibrary(dplyr)\r\nlibrary(PerformanceAnalytics)\r\nlibrary(data.table)\r\nlibrary(sqldf)\r\nlibrary(nortest)\r\nlibrary(tidyverse)\r\nlibrary(MASS)\r\nlibrary(rpart)\r\nlibrary(class)\r\nlibrary(ISLR)\r\nlibrary(scales)\r\nlibrary(ClustOfVar)\r\nlibrary(GGally)\r\nlibrary(reticulate)\r\nlibrary(ggthemes)\r\nlibrary(RColorBrewer) \r\nlibrary(gridExtra)\r\nlibrary(kableExtra)\r\nlibrary(Hmisc) \r\nlibrary(corrplot)\r\nlibrary(energy)\r\nlibrary(nnet)\r\nlibrary(Hotelling)\r\nlibrary(car)\r\nlibrary(devtools)\r\nlibrary(ggbiplot)\r\nlibrary(factoextra)\r\nlibrary(rgl)\r\nlibrary(FactoMineR)\r\n\r\n```\r\n\r\n```{r}\r\n# reading data\r\ndata <- read.csv('/Users/mac/Downloads/heart_failure_clinical_records_dataset.csv')\r\nstr(data)\r\n```\r\n\r\n\\\r\nWe check to see if we have categorical variables \\\r\nHowever we see all our variables are numeric \\\r\nEven the categorical ones are binary and already have 1/0 as values \\\r\n\r\n# Let's quickly revise our correlation plot\r\n```{r}\r\n# Correlation plot\r\nM<-cor(data)\r\nhead(round(M,2))\r\ncorrplot(M, method=\"color\")\r\n```\r\n\\\r\nSince most of the correlations are low (Pearson's r < 0.25) ), \r\nwe don't particularly see a need for PCA \\\r\n We use PCA to reduce the dimensionality of the dataset as \r\n PCA accomplishes this by capturing the variance in the dataset. \r\n It get the components such that the are in the direction of the highest variance. \\\r\n We also saw from EDA in last exercise that our VIF was quite low\r\n indicating absence of multi-collinearity. \\\r\n So, reducing dimensionality may lead to loss of variance for our project.\r\n However, for exposition, we will try PCA and analyse results \\\r\n \r\n # Let us perform PCA on our dataset\r\n \r\n ```{r}\r\n pca <- prcomp(data[,1:12],scale=TRUE)\r\n summary(pca)\r\n ```\r\n \\\r\n Here, we see that we need 8 components to get cumulative proportion of \r\n variance equivalent to 0.78. \\\r\n For convention, we would consider as many components as required\r\n to get in the range of 0.75-0.95 \\\r\n Let us then consider 10 components (Cum prop. ~90%) instead of 12 reducing our dimensions\r\n from 12 to 10 \\\r\n \r\n # Let's plot the Scree diagrams\r\n ```{r}\r\n plot(pca, type=\"lines\", main = \"Scree diagram\")\r\n fviz_eig(pca)\r\n ```\r\n \r\n # We can also see a cumulative plot\r\n ```{r}\r\n std_dev <- pca$sdev\r\n pr_var <- std_dev^2\r\n prop_varex <- pr_var/sum(pr_var)\r\n plot(cumsum(prop_varex), xlab = \"Principal Component\",\r\n ylab = \"Cumulative Proportion of Variance Explained\",\r\n type = \"b\")\r\n ```\r\n \\\r\n Both of the above plots (variance and cum. variance) show that we need atleast 10 components for 90% variance\r\n and since we don't see a taper down in graph of cum. variance or a steep decline in scree diagram, we can note that this isnt ideal. \\\r\n\r\n# Plotting PCA\r\n\r\n```{r}\r\n# bi-plot which will use PC1 and PC2\r\nggbiplot(pca)\r\n```\r\n\\\r\nHere, we can tell that ejection_fraction, diabetes, platelets all\r\ncontribute to PC1 with higher values in these features moving the samples\r\nto the right \\\r\nSimilarly we can tell that age, serum_creatinine contributes more towards PC2 \\\r\nIn PC1, we can see sex, smoking towards negative side of PC1 \\\r\nIn PC2, we can time towards negative side of PC2 \\\r\n\r\n```{r}\r\n# We can also tell which patients are similar to one other\r\n# by adding rownames\r\n# Let's use each row as a patient identifier, then,\r\n \r\n ggbiplot(pca, labels=rownames(data))\r\n ```\r\n \\\r\n This tells us that patient IDs-16,32,56 are similar as they cluster together\r\n This would ideally be helpful with more meaningful identifiers \\\r\n \r\n # Let's also look at contribution by variables\r\n ```{r}\r\n fviz_pca_var(pca,\r\n col.var = \"contrib\", # Color by contributions to the PC\r\n gradient.cols = c(\"#00AFBB\", \"#E7B800\", \"#FC4E07\"),\r\n repel = TRUE # Avoid text overlapping\r\n )\r\n ```\r\n \\\r\n We see that age, sex, smoking contribute more to PC1 and PC2 \r\n so we can try and visualize this in more detail by bi-plots with these groups. \\\r\n \r\n # Let's plot the bi-plot with gender\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE, labels=rownames(data), groups=data$sex)\r\n ```\r\n \\\r\n A clear indicator that males indicated by 1 have more breadth\r\n in PC1 as opposed to Females indicated by 0 which are more\r\n narrow along with that we see +ve indication for females\r\n along PC1 and negative for males \\\r\n \r\n # Let's plot the bi-plot with smoking\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE, labels=rownames(data), groups=data$smoking)\r\n ```\r\n \\\r\n A clear indicator that smokers indicated by 1 have less breadth\r\n in PC1 as opposed to non-smokers indicated by 0 which are more\r\n wider and to the positive side along with that we see +ve\r\n indication for non-smokers for PC1 and negative for smokers \\\r\n \r\n # We will create an age range variable and do the same as well\r\n ```{r}\r\n data$age_tr[data$age < 50 & data$age >= 40]=\"40-50\"\r\n data$age_tr[data$age < 60 & data$age >= 50]=\"50-60\" \r\n data$age_tr[data$age < 70 & data$age >= 60]=\"60-70\"\r\n data$age_tr[data$age < 80 & data$age >= 70]=\"70-80\"\r\n data$age_tr[data$age < 90 & data$age >= 80]=\"80-90\"\r\n data$age_tr[data$age < 100 & data$age >= 90]=\"90-100\"\r\n ```\r\n \r\n # And then plot the same result with \r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE, labels=rownames(data), groups=data$age_tr)\r\n ```\r\n \\\r\n Not much indication here other than higher age groups\r\n tend to be more spread out in PC2 \\\r\n \r\n # We can also look at PC3 and PC4\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE,choices=c(3,4), labels=rownames(data))\r\n ```\r\n \\\r\n serum_creatinine, diabetes more towards PC3 \\\r\n Platelets, creatinine_phosphokinase, and high bp more towards PC4 \\\r\n \r\n # By gender\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE,choices=c(3,4), labels=rownames(data), groups=data$sex)\r\n ```\r\n \\\r\n We note even spread in PC3, PC4 for gender \\ \r\n \r\n # By smoking\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE,choices=c(3,4), labels=rownames(data), groups=data$sex)\r\n ```\r\n \\\r\n We note even spread in PC3, PC4 for smoking \\\r\n \r\n # By age groups\r\n ```{r}\r\n ggbiplot(pca,ellipse=TRUE, var.axes=FALSE, choices=c(3,4), labels=rownames(data), groups=data$age_tr)\r\n \r\n ```\r\n \\\r\n We note age group 40-50 with most spread in PC4 \\\r\n \r\n \\newpage\r\n \r\n # Let us do a visualizations to see how much of each variable is present in each component \r\n ### We use factoextra and factominer for this ###\r\n \r\n ```{r}\r\n pca_viz <- PCA(data[,1:12], graph = FALSE,ncp =12)\r\n var <- get_pca_var(pca_viz)\r\n \r\n # We can now use the contrib function to get contribution of each variable\r\n # to the PCs\r\n var$contrib\r\n \r\n ```\r\n \r\n # Let's plot this -\r\n ```{r}\r\n corrplot(var$contrib, is.corr=FALSE, method=\"pie\") \r\n ```\r\n \r\n ### Key Observations ### \r\n \r\n 1. Sex and Smoking are dominant in PC1 \\\r\n 2. Age and time are dominant in PC2 \\\r\n 3. Serum_Sodium is dominant in PC3 \\\r\n 4. Platelets and creatinine_phosphokinase are dominant in PC4 \\\r\n 5. creatinine_phosphokinase is dominant in PC5 \\\r\n 6. Platelets and ejection_fraction are dominant in PC6 \\\r\n 7. Anaemia is dominant in PC7 \\\r\n 8. Diabetes is dominant in PC8 \\\r\n 9. Age is dominant in PC9 \\\r\n 10. Serum_Sodium, Serum_creatinine is dominant in PC10 \\\r\n 11. Time, anaemia is dominant in PC11 \\\r\n 12. Sex and smoking are dominant in PC12 \\\r\n \r\n ### Note ###\r\n \\\r\n We don't see a good combination of variables in any component and \r\nPC12 is redundant as PC1 and gives same information \\\r\n\r\n# Let us now combine the pca with dataset\r\n```{r}\r\ndata_pca <- cbind(data,pca$x)\r\n```\r\n\\\r\nThe new dataset now has 26 variables with PC1-PC12 added \\\r\n\r\n# Now Let us check the means by death events\r\n```{r}\r\nmeansPC <- aggregate(data_pca[,15:26],by=list(DEATH_EVENT=data$DEATH_EVENT),mean)\r\nmeansPC\r\n```\r\n# Let us check stddev by death events\r\n```{r}\r\nsdsPC <- aggregate(data_pca[,15:26],by=list(DEATH_EVENT=data$DEATH_EVENT),sd)\r\nsdsPC\r\n```\r\n\\\r\nWe notice a clear difference in means (note the different signs) however not much in std. deviation \\\r\nThis may indicate that PCs aren't doing a good job in\r\n segregating the death events from non-death events \\\r\n \r\n # Let us perform t-tests\r\n ```{r}\r\n t.test(PC1~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC2~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC3~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC4~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC5~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC6~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC7~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC8~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC9~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC10~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC11~data_pca$DEATH_EVENT,data=data_pca)\r\n t.test(PC12~data_pca$DEATH_EVENT,data=data_pca)\r\n ```\r\n \\\r\n We notice signifcant results in PC2, PC3, PC4, and PC11 at alpha=0.5 \\\r\n \r\n # Let us also perform F-ratio tests\r\n ```{r}\r\n var.test(PC1~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC2~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC3~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC4~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC5~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC6~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC7~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC8~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC9~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC10~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC11~data_pca$DEATH_EVENT,data=data_pca)\r\n var.test(PC12~data_pca$DEATH_EVENT,data=data_pca)\r\n ```\r\n \\\r\n We notice signifcant results in PC2, PC4, PC5, PC6, PC8, PC9, and PC10 \\\r\n \r\n # Plotting the scores for the first and second components\r\n ```{r}\r\n plot(data_pca$PC1, data_pca$PC2,\r\n pch=ifelse(data_pca$DEATH_EVENT == \"1\",1,16),xlab=\"PC1\", ylab=\"PC2\",col=\"dark blue\",\r\n main=\"Heart disease patient against values for PC1 & PC2\")\r\n abline(h=0)\r\n abline(v=0)\r\n legend(\"bottomleft\", legend=c(\"Death_Event=1\",\"Death_Event=0\") ,col=\"dark blue\", pch=c(1,16))\r\n \r\n ```\r\n \\\r\n We do note that survivors seem to be closer to average than those who died \\\r\n Also recall the definition of PC1 and PC2 - \\\r\n PC1 was sex, smoking dominant \\\r\n PC2 was age, time dominant \\\r\n This also tells us that non-survivors were on the extremes of ages and follow-up\r\n period\\\r\n \r\n # PCA - prediction \r\n \r\n # We can try a prediction with pca by splitting our data into train and test and finding the PCs on train and validating on test data\r\n \r\n ```{r}\r\n data <- read.csv('/Users/mac/Downloads/heart_failure_clinical_records_dataset.csv')\r\n # Split data into 2 parts for pca training (75%) and prediction (25%)\r\n set.seed(1)\r\n samp <- sample(nrow(data), nrow(data)*0.75)\r\n data.train <- data[samp,]\r\n data.valid <- data[-samp,]\r\n dim(data.train)\r\n dim(data.valid)\r\n ```\r\n \\\r\n We split our data into 224 rows, and 75 rows into sets of train and valid.\\\r\n \r\n # conduct PCA on training dataset\r\n ```{r}\r\n pca <- prcomp(data.train[,1:12], retx=TRUE, center=TRUE, scale=TRUE)\r\n expl.var <- round(pca$sdev^2/sum(pca$sdev^2)*100) # percent explained variance\r\n expl.var\r\n ```\r\n \\\r\n The explained variance in components is same as before \\\r\n \r\n # prediction of PCs for validation dataset\r\n ```{r}\r\n pred <- predict(pca, newdata=data.valid[,1:12])\r\n head(pred,5)\r\n ```\r\n \\\r\n We print the first 5 rows to see the predicted values in our validation set. \\\r\n \r\n # Let us take first 10 components that explain 90% variance in data and do the same\r\n \r\n ```{r}\r\n train.data <- data.frame(DEATH_EVENT=data.train$DEATH_EVENT, pca$x)\r\n train.data <- train.data[,1:11]\r\n \r\n test.data <- predict(pca, newdata = data.valid)\r\n test.data <- as.data.frame(test.data)\r\n test.data <- test.data[,1:10]\r\n head(test.data,5)\r\n ```\r\n \\\r\n This finally gives us the test data with PC1-10 \\\r\n Our final conclusion however remains the same that PCA isn't ideal\r\nfor modeling purpose in our project \\\r\n\r\n\r\n### This concludes our analysis of PCA in our dataset\r\n\r\n", "meta": {"hexsha": "38c857e8a6e832b68c14d0fafa78caa55970ded7", "size": 22557, "ext": "r", "lang": "R", "max_stars_repo_path": "Assignment 4.r", "max_stars_repo_name": "Tanvi445/Heart-failure-Prediction", "max_stars_repo_head_hexsha": "43e9e6f5b675e745985981c093d3fd1ee22abaaa", "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": "Assignment 4.r", "max_issues_repo_name": "Tanvi445/Heart-failure-Prediction", "max_issues_repo_head_hexsha": "43e9e6f5b675e745985981c093d3fd1ee22abaaa", "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": "Assignment 4.r", "max_forks_repo_name": "Tanvi445/Heart-failure-Prediction", "max_forks_repo_head_hexsha": "43e9e6f5b675e745985981c093d3fd1ee22abaaa", "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": 58.7421875, "max_line_length": 175, "alphanum_fraction": 0.3731879239, "num_tokens": 3607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6430744406706277}} {"text": "##Umbrales=group\n##Imagen=raster\n##Banda=number 1\n##Mascara= output raster\n##ImagenUmbral= output raster\n##showplots\nrango <- range(na.omit(c(Imagen[[Banda]][]))) #Encontrar el rango de los datos\n#levels <- 100 #Definir el número de niveles posibles\nbreaks <- seq(rango[1], rango[2], length.out = 100 + 1) #Número de \"breaks\" basado en niveles y rangos\nh <- hist.default(na.omit(c(Imagen[[Banda]][])), breaks = breaks, plot = FALSE) #Crear histograma de datos\ncounts <- as.double(h$counts) #Observaciones por nivel\nmids <- as.double(h$mids) #Media por break\nlen <- length(counts) #Número total de observaciones\nw1 <- cumsum(counts) #Suma acumulada\nw2 <- w1[len] + counts - w1 #\ncm <- counts * mids\nm1 <- cumsum(cm)\nm2 <- m1[len] + cm - m1\nvar <- w1 * w2 * (m2/w2 - m1/w1)^2\nmaxi <- which(var == max(var, na.rm = TRUE))\notsu <- (mids[maxi[1]] + mids[maxi[length(maxi)]])/2\n\nprint(otsu)\n\nhist(as.matrix(na.omit(Imagen[[Banda]])),\n xlab=names(Imagen[[Banda]]),\n ylab=\"Frecuencia\", \n col=\"red\", \nmain=paste(\"Distribución \", \n names(Imagen[[Banda]]), \n sep=\"\"))\nabline(v=otsu, \n col=\"black\", \n lwd=1, lty=2)\nbox()\ngrid(lwd=1)\n\nMascara <- Imagen[[Banda]] >= otsu\nImagenUmbral <- Mascara * Imagen[[Banda]]\n", "meta": {"hexsha": "6bb23928b22ad058e8fad506bc1e085f3cb610f7", "size": 1243, "ext": "rsx", "lang": "R", "max_stars_repo_path": "Rscripts/OTSU.rsx", "max_stars_repo_name": "klauswiese/QGIS-R", "max_stars_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rscripts/OTSU.rsx", "max_issues_repo_name": "klauswiese/QGIS-R", "max_issues_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rscripts/OTSU.rsx", "max_forks_repo_name": "klauswiese/QGIS-R", "max_forks_repo_head_hexsha": "d4da3aa782427c082c82299b7374dfc79843f019", "max_forks_repo_licenses": ["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.075, "max_line_length": 106, "alphanum_fraction": 0.6411906677, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6430641187872339}} {"text": "library(MASS)\n#num_states <- 4\n\nerror_bound <- 0.001\n\nstate_log_lik <- function(dat, mu, cov_mat, cov_mat_inv,cov_mat_det, N, num_var){\n #dat is a matrix of dimension num_var X N\n #mu is a vector with num_var elements\n #cov_mat is the covanriance matrix with dim num_var X num_var, its determinant is cov_mat_det,\n #its inverse is cov_mat_inv\n # returns a vector 1 x N of log-likelihoods\n diff <- dat - matrix(rep(mu, N), nrow = num_var, ncol = N)\n return (diag(-0.5 * t(diff) %*% cov_mat_inv %*% diff) - 0.5 * num_var * log(2 * pi) - 0.5 *log(abs(cov_mat_det)))\n}\n\nEM <- function (test_data, num_states){\n #format of test_data: dim X T X N matrix, N = number of days in training data,\n # T = number of steps in a day, dim = number of parameters to consider for each state\n #format of prob matrix for each time: m x T x N matrix, m is the number of possible states\n #Prob. matrix initialized so that each state has equal prob.\n N = dim(test_data)[3]\n Tnum = dim(test_data)[2]\n num_var = dim(test_data)[1]\n P = array(rep(1 / num_states, num_states * N * Tnum), c(num_states, Tnum, N))\n \n #transition prob. matrix is m x m matrix, initialized such that each state goes to itself with prob ~1.\n # A = matrix(0, num_states, num_states)\n # for (i in 1: num_states){\n # for (j in 1 : num_states){\n # if (i == j) A[i,j] = 0.9\n # else A[i,j] = (1 - 0.9)/(num_states - 1)\n # }\n # }\n A = matrix(1/num_states, nrow = num_states, ncol = num_states)\n \n #mu is initialized to the mid points of test_data, all var initialized to std of test_data\n #covariance initialized to 0\n qt0 <- seq(0, 1, length.out = num_states + 1)\n qt <- (qt0[1:num_states] + qt0[2:(num_states+1)]) / 2\n \n mu <- matrix(0, nrow = num_var, ncol = num_states)\n cov_mat <- array(0, c(num_var, num_var, num_states))\n for (i in 1:num_var){\n mu[i,] = quantile(as.vector(test_data[i,,]), qt)\n cov_mat[i,i,] = rep(var(as.vector(test_data[i,,])), num_states)\n }\n \n max_iter_num = 500\n for (i in 1:max_iter_num){\n old_mu <- mu\n old_cov_mat <- cov_mat\n old_A <- A\n \n log_alpha = calc_forward(num_states, N, Tnum, num_var, A, mu, cov_mat, test_data)\n log_beta = calc_backward(num_states, N, Tnum, num_var, A, mu, cov_mat, test_data)\n P <- calc_P(num_states, N, Tnum, log_alpha, log_beta)\n mu = update_mu(num_states, num_var, P, test_data)\n cov_mat = update_cov_mat(num_states, num_var, N, Tnum, P, test_data, mu)\n A = update_A(num_states, N, Tnum, num_var, P, log_alpha, log_beta, A, mu, cov_mat, test_data)\n \n diff_mu <- sum(abs(old_mu - mu)) / sum(abs(old_mu))\n diff_cov_mat <- sum(abs(old_cov_mat - cov_mat)) / sum(abs(old_cov_mat))\n diff_A <- sum(abs(old_A - A)) / sum(abs(old_A))\n if (diff_mu < error_bound && diff_cov_mat < error_bound && diff_A < error_bound){\n break\n }\n }\n data_A <- data.frame(A)\n data_mu <- data.frame(mu)\n data_cov_mat <- data.frame(cov_mat)\n \n params <- list(data_A, data_mu, data_cov_mat)\n names(params) <- c('A', 'mu', 'covariance matrix')\n \n return(params)\n}\n\ncalc_forward <- function(num_states, N, Tnum, num_var, A, mu, cov_mat, test_data){\n\n log_alpha <- array(0, c(num_states, Tnum, N))\n #get the initial prob\n for (s in 1:num_states){\n cov_mat_inv <- solve(cov_mat[,,s])\n cov_mat_det <- det(cov_mat[,,s])\n log_alpha[s, 1, ] = state_log_lik(test_data[,1,], mu[,s], cov_mat[,,s], cov_mat_inv,cov_mat_det, N, num_var)\n }\n \n if (Tnum > 1){\n for (t in 2:Tnum){\n temp1 <- matrix(0, nrow = num_states, ncol = N)\n for (s in 1:num_states){\n cov_mat_inv <- solve(cov_mat[,,s])\n cov_mat_det <- det(cov_mat[,,s])\n temp1[s,] <- state_log_lik(test_data[,t,], mu[,s], cov_mat[,,s], cov_mat_inv,cov_mat_det, N, num_var)\n }\n log_diff <- exp(log_alpha[, t-1, ] - matrix(apply(matrix(log_alpha[, t-1, ], nrow = num_states, ncol = N), 2, max), nrow = num_states, ncol = N, byrow = TRUE))\n log_alpha[, t, ] <- t(log(t(log_diff) %*% A)) + \n matrix(apply(matrix(log_alpha[, t-1, ], nrow = num_states, ncol = N), 2, max), nrow = num_states, ncol = N, byrow = TRUE) + \n temp1\n \n }\n }\n \n return (log_alpha)\n}\n\ncalc_backward <- function(num_states, N, Tnum, num_var, A, mu, cov_mat, test_data){\n log_beta <- array(0, c(num_states, Tnum, N))\n log_beta[, Tnum, ] <- 0\n for (t in (Tnum - 1) : 1){\n log_diff <- exp(log_beta[, t+1, ] - matrix(apply(log_beta[, t+1, ], 2, max), nrow = num_states, ncol = N, byrow = TRUE))\n temp1 <- matrix(0, nrow = num_states, ncol = N)\n for (s in 1:num_states){\n cov_mat_inv <- solve(cov_mat[,,s])\n cov_mat_det <- det(cov_mat[,,s])\n temp1[s,] <- state_log_lik(test_data[,t+1,], mu[,s], cov_mat[,,s], cov_mat_inv,cov_mat_det, N, num_var)\n }\n\n log_beta[, t, ] <- log(A %*% exp(log_diff * temp1)) + \n matrix(apply(log_beta[, t+1, ], 2, max), nrow = num_states, ncol = N, byrow = TRUE)\n }\n return (log_beta[,1:Tnum,])\n}\n\ncalc_P <- function(num_states, N, Tnum, log_alpha, log_beta){\n temp <- log_alpha + log_beta\n temp2 <- array(0, c(num_states, Tnum, N))\n P <- array(0, c(num_states, Tnum, N))\n for (t in 1: Tnum){\n temp2[,t,] = exp(temp[,t,] - matrix(apply(temp[,t,], 2, max), nrow = num_states, ncol = N, byrow = TRUE))\n P[,t,] <- temp2[,t,] / matrix(colSums(temp2[,t,]), nrow = num_states,ncol = N, byrow = TRUE)\n }\n return (P)\n}\n\nupdate_A <- function(num_states, N, Tnum, num_var, P, log_alpha, log_beta, A, mu, cov_mat, test_data){\n conditional_tp <- array(0, c(N, (Tnum - 1), num_states, num_states))\n for (n in 1:N){\n for(t in 1:(Tnum - 1)){\n temp_a <- matrix(rep(log_alpha[, t, n], num_states), ncol = num_states, nrow = num_states)\n temp_log_lik <- matrix(0, nrow = num_states, ncol = 1)\n for (s in 1:num_states){\n cov_mat_inv <- solve(cov_mat[,,s])\n cov_mat_det <- det(cov_mat[,,s])\n temp_log_lik[s,] <- state_log_lik(test_data[,t+1,n], mu[,s], cov_mat[,,s], cov_mat_inv,cov_mat_det, 1, num_var)\n }\n temp_b <- log_beta[,t+1,n] + temp_log_lik\n temp_bb <- matrix(t(temp_b), nrow = num_states, ncol = num_states, byrow = TRUE)\n temp_c <- temp_a + temp_bb + log(A)\n temp_c = exp(temp_c - temp_c[which.max(temp_c)])\n conditional_tp[n,t,,] <- temp_c / sum(temp_c)\n }\n }\n new_A <- matrix(0, nrow = num_states, ncol = num_states)\n for (i in 1:num_states){\n for (j in 1:num_states){\n new_A[i,j] <- sum(conditional_tp[,,i,j])/sum(conditional_tp[,,i,])\n }\n }\n return (new_A)\n}\n\nupdate_mu <- function(num_states, num_var, P, test_data){\n new_mu <- matrix(0, nrow = num_var, ncol = num_states)\n for (v in 1: num_var){\n for (i in 1: num_states){\n new_mu[v,i] <- sum(P[i,,] * test_data[v,,]) / sum(P[i,,])\n }\n }\n return(new_mu)\n}\n\nupdate_cov_mat <- function(num_states, num_var, N, Tnum, P, test_data, mu){\n new_cov_mat <- array(0, c(num_var, num_var, num_states))\n for(s in 1: num_states){\n for (i in 1:num_var){\n for (j in 1:num_var){\n new_cov_mat[i,j,s] <- sum((test_data[i,,] - mu[i,s]) * (test_data[j,,] - mu[j,s]) * P[s,,]) * N * Tnum / ((Tnum * N - 1) * sum(P[s,,]))\n }\n }\n }\n return(new_cov_mat)\n}\n\n", "meta": {"hexsha": "bede926df1531319922824b75c838e6fd3f6d570", "size": 7196, "ext": "r", "lang": "R", "max_stars_repo_path": "hmm_v2.r", "max_stars_repo_name": "yuwu10112358/APS490RBCCM", "max_stars_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmm_v2.r", "max_issues_repo_name": "yuwu10112358/APS490RBCCM", "max_issues_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmm_v2.r", "max_forks_repo_name": "yuwu10112358/APS490RBCCM", "max_forks_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_forks_repo_licenses": ["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.8972972973, "max_line_length": 165, "alphanum_fraction": 0.6165925514, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6430549100324435}} {"text": "# Sub-pixel confusion–uncertainty matrix\n# Implementation following https://doi.org/10.1016/j.rse.2007.07.017\n\n# Comparator function\nComparator = function(s_k, r_l, A=MIN, D=PROD_D, scale=FALSE)\n{\n # If we have a data.frame, convert into a matrix\n if (is.data.frame(s_k))\n s_k = as.matrix(s_k)\n if (is.data.frame(r_l))\n r_l = as.matrix(r_l)\n\n stopifnot(is.numeric(s_k))\n stopifnot(is.numeric(r_l))\n stopifnot(!is.null(A) || !is.null(D))\n \n if (!is.null(A))\n A = match.fun(A)\n if (!is.null(D))\n D = match.fun(D)\n \n # If s_k and r_l are matrices/data.frames, we sum them all\n # If not, make it a matrix anyway to make the same code handle it\n if (is.vector(s_k))\n s_k = t(as.matrix(s_k))\n if (is.vector(r_l))\n r_l = t(as.matrix(r_l))\n \n stopifnot(all(dim(s_k) == dim(r_l)))\n \n CumulativeResult = matrix(0, ncol(s_k), ncol(r_l))\n for (n in 1:nrow(s_k))\n {\n s_nk = s_k[n,]\n r_nl = r_l[n,]\n \n K = length(s_nk)\n \n # Overestimation and underestimation\n sp_nk = s_nk - r_nl; sp_nk[sp_nk<0] = 0\n rp_nl = r_nl - s_nk; rp_nl[rp_nl<0] = 0\n\n Result = matrix(NA, K, K) #p_nkl\n for (k in 1:K)\n {\n for (l in 1:K)\n {\n if (k == l) { # Diagonal\n if (!is.null(A))\n Result[k,l] = A(s_nk[k], r_nl[l])\n else\n Result[k,l] = D(sp_nk, rp_nl, k, l)\n } else {\n if (!is.null(D))\n Result[k,l] = D(sp_nk, rp_nl, k, l)\n else\n Result[k,l] = A(s_nk[k], r_nl[l])\n }\n }\n }\n CumulativeResult = CumulativeResult + Result\n }\n rownames(CumulativeResult) = colnames(s_k)\n colnames(CumulativeResult) = colnames(r_l)\n if (scale)\n CumulativeResult = CumulativeResult / nrow(s_k)\n \n return(CumulativeResult)\n}\n\n# Agreement operators\n# MIN is literally the function min\n# PROD is literally the function \"*\"\n\nSI = function(s_nk, r_nl)\n{\n 1 - abs(s_nk - r_nl)/(s_nk + r_nl)\n}\n\nLEAST = function(s_nk, r_nl)\n{\n max(s_nk + r_nl - 1, 0)\n}\n\n# l is \"should be attributed to...\", k is \"but was guessed as\"\nPROD_D = function(sp_nk, rp_nl, k, l)\n{\n sp_nk[k] * rp_nl[l] / sum(rp_nl)\n}\n\nMIN_D = function(sp_nk, rp_nl, k, l)\n{\n min(sp_nk[k], rp_nl[l])\n}\n\nLEAST_D = function(sp_nk, rp_nl, k, l)\n{\n max(sp_nk[k]+rp_nl[l]-sum(rp_nl), 0)\n}\n\n# Function for calculating a confusion matrix\nSCM = function(predicted, observed, agreement=min, disagreement=\"SCM\", scale=FALSE, accuracy=FALSE, totals=FALSE, plot=FALSE)\n{\n # Aliases; TODO: remove/rename\n s_nk = predicted\n r_nl = observed\n \n # Sanity checks: the input must be 0-1 range and add up to 100%\n stopifnot(all(r_nl >= 0-options()$ts.eps))\n stopifnot(all(r_nl <= 1+options()$ts.eps))\n stopifnot(all(s_nk >= 0-options()$ts.eps))\n stopifnot(all(s_nk <= 1+options()$ts.eps))\n if (is.vector(s_nk))\n stopifnot(all(round(sum(s_nk), 6) == 1))\n else\n stopifnot(all(round(rowSums(s_nk), 6) == 1))\n if (is.vector(r_nl))\n stopifnot(all(round(sum(r_nl), 6) == 1))\n else\n stopifnot(all(round(rowSums(r_nl), 6) == 1))\n \n if (is.character(disagreement) && disagreement == \"SCM\") # Mean of MIN_D and LEAST_D + confusion\n {\n p_min = Comparator(s_nk, r_nl, A=agreement, D=MIN_D, scale=scale)\n p_least = Comparator(s_nk, r_nl, A=agreement, D=LEAST_D, scale=scale)\n P_kl = (p_min + p_least)/2\n U_kl = (p_min - p_least)/2\n } else {\n P_kl = Comparator(s_nk, r_nl, A=agreement, D=disagreement, scale=scale)\n U_kl = matrix(0, nrow=nrow(P_kl), ncol=ncol(P_kl), dimnames=dimnames(P_kl)) # No uncertainties for other types; U is a zero matrix\n }\n\n scm = structure(list(P=P_kl, U=U_kl, agreement=as.character(substitute(agreement)), disagreement=as.character(substitute(disagreement))), class=\"scm\")\n \n if (plot)\n plot(scm)\n \n if (accuracy || totals)\n scm = accuracy.scm(scm)\n \n if (totals)\n scm = totals.scm(scm)\n\n return(scm)\n}\n\nplot.scm = function(scm, ...)\n{\n if (requireNamespace(\"lattice\", quietly = TRUE) && requireNamespace(\"gridExtra\", quietly = TRUE))\n {\n P_plot = lattice::levelplot(t(scm$P), xlab=\"Observed\", ylab=\"Predicted\", sub=\"Centre values\", ...)\n U_plot = lattice::levelplot(t(scm$U), xlab=\"Observed\", ylab=\"Predicted\", sub=\"Uncertainty\", ...)\n gridExtra::grid.arrange(P_plot, U_plot, ncol=2)\n } else {\n stop(\"Unable to plot due to missing lattice or gridExtra packages\")\n }\n}\n\n# Function for adding \"total\" columns/rows to the SCM\ntotals.scm = function(scm)\n{\n stopifnot(class(scm) == \"scm\")\n\n if (is.null(scm[[\"P_row_totals\"]]))\n {\n warning(\"Passed an SCM without calculating accuracy metrics. This will be done for you.\")\n scm = accuracy.scm(scm)\n }\n \n P_kp = rowSums(scm$P)\n P_pl = colSums(scm$P)\n P_pp = sum(scm$P)\n\n U_kp = rowSums(scm$U)\n U_pl = colSums(scm$U)\n U_pp = sum(scm$U)\n\n # Add total rows/columns: with uncertainty\n P_FullMatrix = cbind(scm$P, total=scm$P_row_totals)\n P_FullMatrix = rbind(P_FullMatrix, total=c(scm$P_col_totals, scm$P_total))\n\n U_FullMatrix = cbind(scm$U, total=scm$U_row_totals)\n U_FullMatrix = rbind(U_FullMatrix, total=c(scm$U_col_totals, scm$U_total))\n \n # Add user/producer accuracy\n P_FullMatrix = cbind(P_FullMatrix, user.acc=c(scm$P_user_accuracy, NA))\n P_FullMatrix = rbind(P_FullMatrix, prod.acc=c(scm$P_producer_accuracy, NA, scm$P_overall_accuracy))\n\n U_FullMatrix = cbind(U_FullMatrix, user.acc=c(scm$U_user_accuracy, NA))\n U_FullMatrix = rbind(U_FullMatrix, prod.acc=c(scm$U_producer_accuracy, NA, scm$U_overall_accuracy))\n \n scm$P = P_FullMatrix\n scm$U = U_FullMatrix\n return(scm)\n}\n\n# Add accuracy metrics to an scm object\naccuracy.scm = function(scm)\n{\n stopifnot(class(scm) == \"scm\")\n \n P_kp = rowSums(scm$P)\n P_pl = colSums(scm$P)\n P_pp = sum(scm$P)\n\n U_kp = rowSums(scm$U)\n U_pl = colSums(scm$U)\n U_pp = sum(scm$U)\n\n P_OA_s = (P_pp*sum(diag(scm$P))) / (P_pp^2 - U_pp^2)\n U_OA_s = (U_pp*sum(diag(scm$P))) / (P_pp^2 - U_pp^2)\n\n P_UA_s = (diag(scm$P)*P_kp) / (P_kp^2 - U_kp^2) # Problems when we have uncertainty == prediction, division by 0\n U_UA_s = (diag(scm$P)*U_kp) / (P_kp^2 - U_kp^2) # In which case the diagonals are 0, so it's 0 by definition\n P_UA_s[is.nan(P_UA_s)] = 0\n U_UA_s[is.nan(U_UA_s)] = 0\n\n P_PA_s = (diag(scm$P)*P_pl) / (P_pl^2 - U_pl^2)\n U_PA_s = (diag(scm$P)*U_pl) / (P_pl^2 - U_pl^2)\n P_PA_s[is.nan(P_PA_s)] = 0\n U_PA_s[is.nan(U_PA_s)] = 0\n\n # Kappa coefficient\n # Expected proportion of agreement (i.e. when using the monkey method)\n P_e = sum(((P_pp^2 + U_pp^2)*(P_pl*P_kp + U_pl*U_kp) - 2 * P_pp*U_pp*(U_pl*P_kp + P_pl*U_kp)) / (P_pp^2-U_pp^2)^2)\n U_e = sum((2 * P_pp*U_pp*(P_pl*P_kp + U_pl*U_kp) - (P_pp^2 + U_pp^2)*(U_pl*P_kp + P_pl*U_kp)) / (P_pp^2-U_pp^2)^2)\n\n Sign = (1-P_OA_s-U_OA_s)*(1-P_e-U_e)\n P_Kappa_s = ((P_OA_s-P_e) * (1-P_e) - (sign(Sign)*U_OA_s+U_e) * U_e)/((1-P_e)^2-U_e^2)\n U_Kappa_s = ((sign(Sign)*(1-P_OA_s)*U_e + (1-P_e)*U_OA_s)/((1-P_e)^2-U_e^2))\n \n scm[[\"P_row_totals\"]] = P_kp\n scm[[\"P_col_totals\"]] = P_pl\n scm[[\"P_total\"]] = P_pp\n scm[[\"U_row_totals\"]] = U_kp\n scm[[\"U_col_totals\"]] = U_pl\n scm[[\"U_total\"]] = U_pp\n scm[[\"P_overall_accuracy\"]] = P_OA_s\n scm[[\"U_overall_accuracy\"]] = U_OA_s\n scm[[\"P_user_accuracy\"]] = P_UA_s\n scm[[\"U_user_accuracy\"]] = U_UA_s\n scm[[\"P_producer_accuracy\"]] = P_PA_s\n scm[[\"U_producer_accuracy\"]] = U_PA_s\n scm[[\"P_user_accuracy\"]] = P_UA_s\n scm[[\"P_kappa\"]] = P_Kappa_s\n scm[[\"U_kappa\"]] = U_Kappa_s\n \n return(scm)\n}\n\n# Examples moved to:\n#' @example subpixel-confusion-matrix-examples.r\n# Note that they will need to be split per function\n", "meta": {"hexsha": "992e993192ff5dd64651ce9483282020beb44433", "size": 8065, "ext": "r", "lang": "R", "max_stars_repo_path": "src/pixel-based/utils/subpixel-confusion-matrix.r", "max_stars_repo_name": "GreatEmerald/master-classification", "max_stars_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-07-18T07:28:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T07:28:55.000Z", "max_issues_repo_path": "src/pixel-based/utils/subpixel-confusion-matrix.r", "max_issues_repo_name": "GreatEmerald/master-classification", "max_issues_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pixel-based/utils/subpixel-confusion-matrix.r", "max_forks_repo_name": "GreatEmerald/master-classification", "max_forks_repo_head_hexsha": "2f8d22bbcaf431f19d121b242f840f78a329d124", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-07T08:58:22.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-02T14:07:32.000Z", "avg_line_length": 31.7519685039, "max_line_length": 154, "alphanum_fraction": 0.5966522009, "num_tokens": 2763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6430449664822878}} {"text": "#' punto medio\n#' Calcula el punto que se encuentra entre 2 puntos\n#'\n#' @param a vector\n#' @param b vector\n#'\n#' @return vector\n#'\n#' @export\n#'\n#' @examples\n#' puntoMedio(c(1,1),c(2,2))\npuntoMedio <- function(a,b){\n x <- vector(\"numeric\",2)\n x[1] <- (a[1]+b[1])/2\n x[2] <- (a[2]+b[2])/2\n x\n}\n", "meta": {"hexsha": "c5392c05fd317540a2d3de1ae057ec3e8cc50fd6", "size": 298, "ext": "r", "lang": "R", "max_stars_repo_path": "R/puntoMedio.r", "max_stars_repo_name": "frandepy2/geoanaliticaP", "max_stars_repo_head_hexsha": "ea8e7b4d7bace3e23c93ac565b829164aaa2a7f7", "max_stars_repo_licenses": ["MIT"], "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/puntoMedio.r", "max_issues_repo_name": "frandepy2/geoanaliticaP", "max_issues_repo_head_hexsha": "ea8e7b4d7bace3e23c93ac565b829164aaa2a7f7", "max_issues_repo_licenses": ["MIT"], "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/puntoMedio.r", "max_forks_repo_name": "frandepy2/geoanaliticaP", "max_forks_repo_head_hexsha": "ea8e7b4d7bace3e23c93ac565b829164aaa2a7f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.6842105263, "max_line_length": 51, "alphanum_fraction": 0.5570469799, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6430068708784591}} {"text": "multiplyUncertainties <- function(opinions,l){\n pd = NULL\n for(j in setdiff(opinions$Label,l)){\n if(is.null(pd))\n pd = opinions[opinions$Label==j,]$Uncertainty\n else\n pd = pd * opinions[opinions$Label==j,]$Uncertainty\n }\n return(pd)\n}\n\nmultiSourceWeightedFusion <- function(opinions){\n if(nrow(opinions)==1)\n return(data.frame(Label=\"fused\",Belief = opinions$Belief, Disbelief = opinions$Disbelief, Uncertainty=opinions$Uncertainty, Apriori = opinions$Apriori))\n sm <- 0\n for(l in opinions$Label){\n el = opinions[opinions$Label==l,]$Belief * (1-opinions[opinions$Label==l,]$Uncertainty)\n pd = multiplyUncertainties(opinions,l)\n sm = sm + (el * pd)\n }\n dsm <- 0\n \n for(l in opinions$Label){\n pd = multiplyUncertainties(opinions,l)\n dsm = dsm + pd\n }\n pd = NULL\n for(l in opinions$Label){\n if(is.null(pd))\n pd = opinions[opinions$Label==l,]$Uncertainty\n else\n pd = pd * opinions[opinions$Label==l,]$Uncertainty\n }\n \n apriori = NULL\n nominator = 0\n for(l in opinions$Label){\n nominator = nominator + (opinions[opinions$Label==l,]$Apriori * (1-opinions[opinions$Label==l,]$Uncertainty))\n }\n denominator = nrow(opinions) - sum(opinions$Uncertainty )\n apriori = nominator / denominator\n \n belief = (sm / (dsm - nrow(opinions) * pd))\n \n uncertainty = ((nrow(opinions)-sum(opinions$Uncertainty))*pd)/(dsm- nrow(opinions) * pd)\n disbelief= 1-(belief + uncertainty)\n return(data.frame(Label=\"fused\",Belief = belief, Disbelief = disbelief, Uncertainty=uncertainty, Apriori = apriori))\n}\n\n\n#Subtraction - compute the difference between two subjective opinions\n\nsubtract <- function(opinionA, opinionB){\n aprioriA = 0.5\n aprioriB = 0.5\n if(!is.null(opinionA$Apriori))\n aprioriA = opinionA$Apriori\n if(!is.null(opinionB$Apriori))\n aprioriB = opinionB$Apriori\n belief = max((opinionA$Belief - opinionB$Belief),0)\n disbelief = (aprioriA * (opinionA$Disbelief + opinionB$Belief) - aprioriB * (1 + opinionB$Belief - opinionA$Belief - opinionB$Uncertainty))/(aprioriA-aprioriB)\n uncertainty = ((aprioriA*opinionA$Uncertainty)-(aprioriB*opinionB$Uncertainty))/(aprioriA-aprioriB)\n apriori = aprioriA - aprioriB\n return(data.frame(Belief = belief, Disbelief = disbelief, Uncertainty = uncertainty, Apriori = apriori))\n}\n\n#Compute the projected probability from a Subjective Opinion.\n\nprojectedProbability <- function(apriori, belief, uncertainty){\n probability = belief + (apriori * uncertainty)\n return(probability)\n}\n\n\n\n#Computes the beta-distribution that corresponds to a given subjective opinion [@josang2016subjective,@duan2016representation].\n\ncomputeBeta <- function(opinion){\n if(opinion$Disbelief == 0){\n opinion$Uncertainty = opinion$Uncertainty - 0.00001\n opinion$Disbelief = 1 - (opinion$Uncertainty + opinion$Belief)\n }\n r = ((opinion$Belief * 2) / opinion$Uncertainty) + 1\n s = ((opinion$Disbelief * 2) / opinion$Uncertainty) + 1\n \n distribution = dbeta(x=seq(0,1,length=100),shape1=r, shape2=s)\n bDist <- data.frame(x=seq(0,1,length=100),y=distribution)\n bDist$Label=rep(opinion$Label,100)\n return(bDist)\n}\n\n#Plot the barycentric triangle for a given opinion [@josang2016subjective].\n\nplotTriangle <- function(opinion, withLines){\n triangle <- data.frame(x=c(0,1,0.5,0),y=c(0,0,0.5,0))\n coords <- data.frame(x=c(0,0.25,1,0.75,0,0.5,0.5),y=c(0,0.25,0,0.25,0,0,0.5))\n apriori <- data.frame(x=c(0.5,opinion$Apriori),y=c(0.5,0)) \n \n aX = 0\n aY = 0\n bX = 1 * opinion$Belief\n bY = 0\n cX = 0.5 * opinion$Uncertainty\n cY = cX\n pX = aX + bX + cX\n pY = aY + bY + cY\n \n proj <- projectedProbability(opinion$Apriori, opinion$Belief, opinion$Uncertainty) \n \n projected <- data.frame(x=c(pX,proj),y=c(pY,0))\n \n p <- ggplot(triangle,aes(x=x,y=y, size=1))+geom_path(aes(size=0.5))\n if(withLines){\n p <- p + geom_path(data=coords,size=0.25,linetype = \"dashed\") + geom_path(data=apriori,size=0.25,colour='red') + #geom_text(aes(size=0.8),x=opinion$Apriori,y=-.015,label=\"Apriori\", colour='red') + #geom_text(aes(size=0.8), x=opinion$Apriori,y=0.015,label=round(opinion$Apriori,2),colour='red') + \n geom_path(data=projected,size=0.25, colour=\"blue\")\n #+ geom_text(aes(size=0.8),x=proj,y=-.015,label=\"Projected\", colour='blue') + geom_text(aes(size=0.8), x=proj,y=0.015,label=round(proj,2),colour='blue')\n }\n p <- p + geom_point(aes(size=1, x=pX,y=pY), shape=8,colour=\"blue\")+ geom_text(aes(size=0.8),label=opinion$Label,x=0,y=0.5,colour=\"blue\", fontface = \"bold\",hjust=0,vjust=1) + theme(legend.position = \"none\",axis.title.x=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank(),axis.text.x=element_blank()) + geom_text(aes(size=0.8),label=\"Disbelief\",x=0,y=-0.015, fontface = \"bold\",hjust=0) + geom_text(aes(size=0.8),label=\"Belief\",x=1,y=-0.015, fontface = \"bold\",hjust=1) + geom_text(aes(size=0.8),label=\"Uncertainty\",x=0.5,y=0.502, fontface = \"bold\",hjust=0) #+ geom_text(aes(size=0.5),label=paste0(\"(\",round(opinion$Belief,2),\",\",round(opinion$Disbelief,2),\",\",round(opinion$Uncertainty,2),\")\"),x=pX,y=pY+0.02, colour='blue') \n return(p)\n}\n\n\n#Plot a time-line - changes in opinion as a series of arrows in a barycentric triangle.\n\ngetCoord <- function(opinion){\n aX = 0\n aY = 0\n bX = 1 * opinion$Belief\n bY = 0\n cX = 0.5 * opinion$Uncertainty\n cY = cX\n pX = aX + bX + cX\n pY = aY + bY + cY\n return(data.frame(x=pX, y=pY))\n}\n\n\nplotTimeTriangle <- function(opinions){\n triangle <- data.frame(x=c(0,1,0.5,0),y=c(0,0,0.5,0))\n coords <- data.frame(x=c(0,0.25,1,0.75,0,0.5,0.5),y=c(0,0.25,0,0.25,0,0,0.5))\n \n xv <- c()\n yv <- c()\n \n for(i in 1:nrow(opinions)){\n o <- getCoord(opinions[i,])\n xv <- c(xv,o$x)\n yv <- c(yv,o$y)\n }\n \n route <- data.frame(x=xv,y=yv)\n \n colours <- seq(1,nrow(opinions))\n \n p <- ggplot(triangle,aes(x=x,y=y, size=1))+geom_path(aes(size=0.5)) + geom_path(data=coords,size=0.25,linetype = \"dashed\") + theme(legend.position = \"none\",axis.title.x=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank(),axis.text.x=element_blank()) + geom_text(aes(size=0.8),label=\"Disbelief\",x=0,y=-0.015, fontface = \"bold\",hjust=0) + geom_text(aes(size=0.8),label=\"Belief\",x=1,y=-0.015, fontface = \"bold\",hjust=1) + geom_text(aes(size=0.8),label=\"Uncertainty\",x=0.5,y=0.502, fontface = \"bold\",hjust=0) + geom_path(data=route,aes(colour=colours), size=0.25)\n return(p)\n}\n\ncomputeTriangles <- function(beliefs){\n triangles <- list()\n local({\n for(i in 1:(nrow(beliefs))){\n triangles[[i]] <<- plotTriangle(beliefs[i,], FALSE)\n }\n return(triangles)\n })\n}\n\ncomputeDistributions <- function(beliefs){\n betas <- data.frame()\n local({\n for(i in 1:(nrow(beliefs))){\n if(nrow(betas)==0){\n betas <- computeBeta(beliefs[i,])\n }\n else{\n betas <- rbind(betas,computeBeta(beliefs[i,]))\n }\n }\n return(betas)\n })\n}\n\n\n#For a given set of beliefs, plot a row of barycentric triangles, coupled with a set of distributions\n#If rows is 1, everything should be laid out horizontally. If it's 2, everything should be vertical.\n\nsoPlot <- function(beliefs, rows, min, max){\n betas <- computeDistributions(beliefs)\n triangles <- computeTriangles(beliefs)\n \n axisSequence <- round(seq(min,max,length.out=7),2)\n \n separateDistributions <- ggplot(betas) + geom_line(aes(x=x,y=y,colour=Label))+ ylab(\"Probability Mass\")+\n theme(axis.text.x = element_text(size=8,angle = 315),axis.title.x = element_text(size=8),\n axis.text.y = element_text(size=8),axis.title.y = element_text(size=8),legend.text = element_text(size=8),legend.title = element_blank())+ \n xlab(\"Effect size\") + scale_x_continuous(breaks=seq(0,1,length.out=7),labels=c(paste(\"\\u2264\",min),axisSequence[2:6],paste(\"\\u2265\",max)))\n \n separateTriangles <- ggarrange(plotlist=triangles, ncol=length(triangles))\n final <- NULL\n if(rows == 1){\n final <- ggarrange(separateTriangles,separateDistributions,ncol=2, nrow=1, widths=c(2,4))\n }\n else{\n final <- ggarrange(separateDistributions,separateTriangles,ncol=1, nrow=2,heights=c(2,1))\n }\n return(final)\n}\n\n#Assumes a dataframe with a \"Group\" column, separating out the different groups of beliefs\ngroupedBeliefPlot <- function(beliefs, min, max){\n local({\n lowerPlots = list()\n fused = data.frame()\n lengths <- c()\n labels <- c()\n counter <- 1\n if(is.null(beliefs$Group)){\n beliefs$Group <- rep(\"All\", nrow(beliefs))\n }\n for(g in unique(beliefs$Group)){\n subset <- beliefs[beliefs$Group==g,]\n lowerPlots[[counter]] <- soPlot(subset,2,min,max)+theme(panel.border = element_rect(colour = \"black\", fill=NA, size=1))\n f <- multiSourceWeightedFusion(subset)\n lengths <- c(lengths,nrow(subset))\n labels <- c(labels,g)\n f$Label <- paste(\"Fused\\n\",g)\n if(nrow(fused)==0){\n fused <- f\n }\n else{\n fused <- rbind(fused,f)\n }\n counter = counter + 1\n }\n print(fused)\n upperPlot <- soPlot(fused,1,min,max) + border()\n lowerPlot <- ggarrange(plotlist=lowerPlots,nrow=1,ncol=length(lowerPlots),widths=lengths,labels=labels) \n finalPlot <- ggarrange(upperPlot,lowerPlot,ncol=1,nrow=2, heights=c(1,2))\n return(finalPlot)\n })\n}\n\n", "meta": {"hexsha": "44a697c3e9fca1cdbdd8f1d3dd25416f1a1cd9ac", "size": 9209, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SLUtilityFunctions.r", "max_stars_repo_name": "CITCOM-project/subjectiveLogic", "max_stars_repo_head_hexsha": "5dc6e71d037baf0346c40fd3474668bc6504ce25", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/SLUtilityFunctions.r", "max_issues_repo_name": "CITCOM-project/subjectiveLogic", "max_issues_repo_head_hexsha": "5dc6e71d037baf0346c40fd3474668bc6504ce25", "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": "src/r/SLUtilityFunctions.r", "max_forks_repo_name": "CITCOM-project/subjectiveLogic", "max_forks_repo_head_hexsha": "5dc6e71d037baf0346c40fd3474668bc6504ce25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7418032787, "max_line_length": 745, "alphanum_fraction": 0.6667390596, "num_tokens": 3113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6429452238587187}} {"text": "# take input from the user\nnum = as.integer(7)\nfactorial = 1\n# check is the number is negative, positive or zero\nif(num < 0) {\nprint(\"Sorry, factorial does not exist for negative numbers\")\n} else if(num == 0) {\nprint(\"The factorial of 0 is 1\")\n} else {\nfor(i in 1:num) {\nfactorial = factorial * i\n}\nprint(paste(\"The factorial of\", num ,\"is\",factorial))\n}", "meta": {"hexsha": "1d5b4d45406408f5bf1c91a85c049ada2bc0cbea", "size": 354, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/factorial.r", "max_stars_repo_name": "lresende/elyra-sample", "max_stars_repo_head_hexsha": "6447e7affd9dd9338206e76551ce377046770a3a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/factorial.r", "max_issues_repo_name": "lresende/elyra-sample", "max_issues_repo_head_hexsha": "6447e7affd9dd9338206e76551ce377046770a3a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/factorial.r", "max_forks_repo_name": "lresende/elyra-sample", "max_forks_repo_head_hexsha": "6447e7affd9dd9338206e76551ce377046770a3a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-08T18:23:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T18:23:51.000Z", "avg_line_length": 25.2857142857, "max_line_length": 61, "alphanum_fraction": 0.6836158192, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6427956378487797}} {"text": "\r\nybar = 105.75 # sample mean \r\nmu0 = 75 # hypothesized value \r\nsigma = 82.429 # population standard deviation \r\nn = 20 # sample size \r\n# test statistic\r\nt = abs((ybar- mu0)/(sigma/sqrt(n)))\r\n print(t)\r\n\r\n# formula based on level of significance\r\n m=33\r\n B=1000\r\np_value= m/B\r\n print(p_value)\r\nalpha=0.05\r\n# our p value< alpha , therfore\r\nprint(\"we conclude that there is sufficient evidence that the mean cotanine level exceeds 75 in the population of children under CPS supervision\")\r\n \r\n", "meta": {"hexsha": "9109299f6b809d2c424dbd31ab1bdcf913110bb8", "size": 526, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.19/Ex5_19.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.19/Ex5_19.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH5/EX5.19/Ex5_19.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 27.6842105263, "max_line_length": 147, "alphanum_fraction": 0.6539923954, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813501370537, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6427365592448531}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\n\r\n#dados\r\nprint(sunspots)\r\n#classe\r\nclass(sunspots)\r\n#informacoes\r\nhelp(sunspots)\r\n#maior e menor valor\r\nmax(sunspots)\r\nmin(sunspots)\r\n#media, mediana, sumario, comprimento\r\nmean(sunspots)\r\nmedian(sunspots)\r\nsummary(sunspots)\r\nlength(sunspots)\r\n\r\n#inicio, fim\r\nstart(sunspots)\r\nend(sunspots)\r\n\r\n#frequencia\r\nfrequency(sunspots)\r\n\r\n#ciclo\r\ncycle(AirPassengers)\r\n\r\n#sub conjunto\r\nsun2 = window(sunspots,1749,c(1763,12))\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "c0a2bada2ca0cd88874680d53530d504acdb555c", "size": 488, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/3.1.Estatisticas media, mediana, maximo, minimo, sumarios.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/3.1.Estatisticas media, mediana, maximo, minimo, sumarios.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/3.1.Estatisticas media, mediana, maximo, minimo, sumarios.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9428571429, "max_line_length": 58, "alphanum_fraction": 0.7254098361, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6425962546445589}} {"text": "\nqmix <- function (p, params, pro = c(.5, .5), expand=.1, dist = \"binorm\") {\n nr <- 1000000\n XX <- rbinom(n=nr, size=1, prob=pro)\n if(dist == \"binorm\") {\n sd.s <- 1\n x = rnorm(n=nr, params[1], sd.s)*XX + rnorm(n=nr, params[2], sd.s)*(1-XX)\n } else if(dist == \"bibeta\") {\n x = rbeta(n=nr, params[[1]][1], params[[1]][2])*XX + rbeta(n=nr, params[[2]][1], params[[2]][2])*(1-XX)\n } \n span <- seq(min(x) - expand * diff(range(x)), max(x) + expand * diff(range(x)), length = nr)\n cdf <- vector(mode = \"numeric\", length = nr)\n if(dist == \"binorm\") {\n sd.s <- 1\n cdf = pnorm(span, params[1], sd.s)*pro[1] + pnorm(span, params[2], sd.s)*(1-pro[1])\n } else if(dist == \"bibeta\") {\n cdf = pbeta(span, params[[1]][1], params[[1]][2])*pro[1] + pbeta(span, params[[2]][1], params[[2]][2])*(1-pro[1])\n } \n quants <- stats::spline(cdf, span, method = \"hyman\", xout = p)$y\n quants[which(p < 0L | p > 1L)] <- NaN\n quants[which(p == 0L)] <- -Inf\n quants[which(p == 1L)] <- Inf\n if (any(is.nan(quants)))\n warning(\"Some quantile values could not be calculated. If all 'p's are within [0,1], try reducing the value of 'expand' and try again.\")\n return(as.vector(quants))\n}\n\n# # # Simulate Case 1 scores from paper\n# r.vec <- c(2^seq(1, 13), 3^seq(1, 8), 10, 105, 300, 1500, 15000)\n# r.vec <- r.vec[order(r.vec)]/150000\n# \n# m <- 150000\n# pi.0.true <- 1/501\n# set.seed(111)\n# X <- rbinom(n=m, size=1, prob=pi.0.true)\n# mu.mix <- c(1.4, 0)\n# sd.mix <- 1\n# S <- rnorm(n=m, mu.mix[1], sd.mix)*X + rnorm(n=m, mu.mix[2], sd.mix)*(1-X)\n# \n# metric = \"k\"; type = \"band\"; method = \"sup-t\"; correction = \"JZ\";\n# conf.level = .95; boot.rep = 100; myseed = 111; mc.rep = 100000;\n# simreps = 10; pi.0.true = 1/501;dist = \"binorm\"; plus2 = T\n# \n# params <- c(1.4, 0)\n\n\n# params= params.ls[[i]]; dist = dist.v[i]; pi.0.true = 1/501;\n# myseed=567; method = \"JZ\"; plus2 = correction.v[j];\n# simreps = simreps; m = 150000; B = 1000; mc.rep = mc.rep;\n# r.vec = r.vec; metric = \"k\"\n\n# Compare to simulated interval\ncov.prob.tab = function(params, pi.0.true, myseed=567, dist = \"binorm\",\n simreps = 100, r.vec = c(.01, .1, .5), metric = \"k\",\n m = 100, plus = F, method = \"JZ\", B = 100, mc.rep = 1000000){\n r <- (1:m)/m\n idx <- which(r %in% r.vec)\n r <- r[idx]\n set.seed(myseed)\n \n if(dist == \"binorm\" | dist == \"bibeta\") {\n suppressWarnings(c <- qmix(1-r, params, c(pi.0.true, 1-pi.0.true), expand=.1, dist = dist))\n } else if(dist == \"unif\") {\n p <- 1-r\n # mixture weights\n w1 <- (1-pi.0.true)\n w2 <- (pi.0.true)\n # knots\n t1 <- w1*(.25/.75)\n t2 <- w1 + w2*((.75-.25)/.75)\n # p <- runif(1000000)\n c <- vector(length = length(p))\n for(j in seq_along(p)) {\n if(p[j] <= 0) {\n c[j] <- 0\n } else if(p[j] > 0 & p[j] <= t1) {\n c[j] <- .75*p[j]/w1\n } else if(p[j] > t1 & p[j] <= t2) {\n c[j] <- .75*p[j] + w2*.25\n } else if(p[j] > t2 & p[j] <= 1) {\n c[j] <- .75*(p[j]-w1)/w2 + .25\n } else if(p[j] == 1) {\n c[j] <- 1L\n }\n }\n }\n\n if (dist == \"binorm\") {\n sd.s = 1\n F.plus <- pnorm(c, mean = params[1], sd.s)\n } else if (dist == \"bibeta\") {\n F.plus <- pbeta(c, params[[1]][1], params[[1]][2])\n } else if (dist == \"unif\") {\n F.plus <- punif(c, params[[1]][1], params[[1]][2])\n }\n \n k.true <- vector(length = length(F.plus))\n pi.true <- vector(length = length(F.plus))\n \n # if k or pi is above 1, then they should actually be slightly below 1\n k.true <- ifelse(k.true > 1, 1 - 1E-10, k.true)\n pi.true <- ifelse(pi.true > 1, 1 - 1E-10, pi.true)\n\n for (i in 1:length(k.true)) {\n # Account for the case when you have non-overlapping uniforms and you \n # know that pi should be 1\n if (dist == \"unif\" & c[i] > params[[2]][2]) {\n pi.true[i] <- 1L\n k.true[i] <- r[i]/pi.0.true\n } else {\n k.true[i] <- 1 - F.plus[i]\n pi.true[i] <- k.true[i]*pi.0.true/r[i]\n }\n }\n eff_seeds <- sample(1:2^15, simreps)\n results <- foreach(z = 1:simreps, .export=c(\"mvrnorm\", \"PerfCurveBands\", \"EstLambda\")) %dopar% {\n set.seed(eff_seeds[z])\n X = rbinom(n=m, size=1, prob=pi.0.true)\n if(dist == \"binorm\") {\n S = rnorm(n=m, params[1], sd.s)*X + rnorm(n=m, params[2], sd.s)*(1-X)\n } else if(dist == \"bibeta\") {\n S = rbeta(n=m, params[[1]][1], params[[1]][2])*X + rbeta(n=m, params[[2]][1], params[[2]][2])*(1-X)\n } else if(dist == \"unif\") {\n S = runif(n=m, params[[1]][1], params[[1]][2])*X + runif(n=m, params[[2]][1], params[[2]][2])*(1-X)\n } \n \n PerfCurveBands(S, X, r, metric = \"rec\", type = ifelse(method == \"JZ\", \"pointwise\", \"band\"), method = method, plus = plus, conf.level = .95,\n mc.rep = mc.rep, myseed = eff_seeds[z])\n }\n \n covout <- matrix(NA, nrow=1, ncol=simreps)\n widthout <- matrix(NA, nrow=length(r), ncol=simreps)\n interval.ls <- list()\n params <- matrix(NA, nrow=length(r), ncol=simreps)\n rec.mat <- matrix(NA, nrow=length(r), ncol=simreps)\n \n for (i in 1:simreps) {\n ind <- vector(length = length(k.true))\n for(j in seq_along(k.true)) {\n ind[j] <- (round(results[[i]]$CI[j, 1], 10) <= k.true[j]) & (round(results[[i]]$CI[j, 2], 10) >= k.true[j])\n }\n covout[i] <- all(ind)\n widthout[, i] <- results[[i]]$CI[, 2] - results[[i]]$CI[, 1] \n interval.ls[[i]] <- results[[i]]$CI\n params[, i] <- k.true\n rec.mat[, i] <- results[[i]]$rec\n }\n \n return(list(r = r, covout = covout, widthout = widthout, interval.ls = interval.ls, params = params, rec.mat = rec.mat))\n}\n\n", "meta": {"hexsha": "14aeb7bbb7a0bd500429296349a4cf28943bb2e3", "size": 5540, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation_files/confidence_bands/coverage_probabilities_bands.r", "max_stars_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_stars_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation_files/confidence_bands/coverage_probabilities_bands.r", "max_issues_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_issues_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_files/confidence_bands/coverage_probabilities_bands.r", "max_forks_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_forks_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4473684211, "max_line_length": 143, "alphanum_fraction": 0.5254512635, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.642553878663029}} {"text": "# -----------------------\n# App Title: t-test\n# Author: Jimmy Wong\n# -----------------------\n\nif (!require(\"ggplot2\"))\n install.packages(\"ggplot2\")\n\nif (!require(\"shinyBS\"))\n install.packages(\"shinyBS\")\n\nshinyUI(fluidPage(\n tags$head(tags$link(rel = \"icon\", type = \"image/x-icon\", \n href = \"https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico\")),\n \n navbarPage(title=\"t-test\",\n \n tabPanel(\"Information of t-test\",\n \n column(1),\n column(5,br(),br(),br(),\n withMathJax(p(\"This application allows users to perform either a\", code(\"one-sample t-test\",style=\"color:navy\"), \n \"or a\", code(\"two-sample t-test\",style=\"color:navy\"),\". A one-sample t-test focuses on comparing the average of a \n single quantitative variable to a hypothesized value, while a two-sample t-test\n focuses on comparing the difference in averages of a quantitative variable between two groups to a hypothesized value. In\n both scenarios, the purpose of the hypothesis test is to determine how likely are the observed results or any more extreme results, \n under the assumption that the null hypothesis is true. This is known as a\", strong(\"p-value.\")),\n p(\"In most data analyses, the population mean(s) along with the population standard deviation(s) are unknown. \n Therefore, the\", strong(\"t-test\"), \"is used instead of a z-test. The\", strong(\"t-statistic\"), \"can be calculated to determine the p-value,\nby comparing it to the\", strong(\"t-distribution\"), \"with a\", strong(\"specified degrees of freedom.\"), \"In this scenario, the sample standard deviation(s) replaces the population standard deviation(s) to yield\n the\", strong(\"standard error\"), \"(an estimate of the true standard deviation) of the\", strong(\"sampling distribution.\")))),\n \n column(5,br(),br(),br(),\n wellPanel(\n code(\"One-sample t-test:\",style=\"color:navy\"),\n p(HTML(\"
  • the parameter of interest is the population mean, μ
  • \"),p(),\n p(\"t-statistic = \\\\(\\\\frac{\\\\bar x -\\\\mu_0}{s_{x}/\\\\sqrt{n}}\\\\)\"), HTML(\"
\")),br(),\n code(\"Two-sample t-test:\",style=\"color:navy\"),\n p(HTML(\"
  • the parameter of interest is the difference between the two population means, μ12
  • \"),p(),\n p(\"t-statistic = \\\\(\\\\frac{(\\\\bar x_1 - \\\\bar x_2) -(\\\\mu_1-\\\\mu_2)}{\\\\sqrt{\\\\frac{s_{1}^2}{n_1} + \\\\frac{s_{2}^2}{n_2}}}\\\\)\"), HTML(\"
\")))),\n \n column(1)),\n \n tabPanel(\"Data Exploration\",\n tabsetPanel(\n tabPanel(\"Sample Data\",\n fluidRow(\n column(3,\n wellPanel(\n selectInput(\"sampdat\", \"Choose a data set:\", choices=list(\"One-sample\"=1,\"Two-sample\"=2), selected=1),\n bsPopover(id=\"sampdat\", title=\"Data set information\", content=\"The one-sample data set is collected from the Old Faithful geyser in Yellowstone National Park, Wyoming, USA. The variable of interest is the duration of each eruption in minutes. The two-sample data set is associated with the 1974 Motor Trend US magazine. The explanatory variable is the type of transmission and the response variable is horsepower.\",\n trigger=\"hover\",placement=\"right\"),\n checkboxInput(\"usedata\", \"Use sample data\", TRUE),\n bsTooltip(\"usedata\",\"Remember to uncheck this when not using sample data!\",\"right\"),\n br(),br(),br(),\n div(\"Shiny app by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Base R code by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Shiny source files:\",\n a(href=\"https://gist.github.com/calpolystat/48dc47f3ff436aba4b19\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\", \n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\"))),\n column(9,\n conditionalPanel(\n condition=\"input.usedata\",\n dataTableOutput(\"data.tab1\"))))),\n \n tabPanel(\"Upload Data\",\n fluidRow(\n column(3,\n wellPanel(\n fileInput(\"file\", \"\",accept=c(\"text/csv\", \"text/comma-separated-values,text/plain\", \".csv\")),\n bsPopover(\"file\",\"Note\", \"Remember to select the correct data format after uploading file! Hover over the Select data format panel for more information.\",\n trigger=\"hover\",placement=\"right\"),\n tags$hr(),\n radioButtons(\"datformat\", strong(\"Select data format:\"), choices=c(\"1-sample\"=1,Stacked=2,Unstacked=3), selected=1),\n bsPopover(\"datformat\",\"Data format\", \"Select Stacked for 2-sample with explanatory and response variables in two columns. Select Unstacked with explanatory variable as column names and response variable in two columns\",\n trigger=\"hover\",placement=\"right\"),\n tags$hr(),\n strong(\"Customize file format:\"),\n checkboxInput(\"header\", \"Header\", TRUE),\n radioButtons(\"sep\", \"Separator:\", choices=c(Comma=\",\",Semicolon=\";\",Tab=\"\\t\"), selected=\",\"),\n radioButtons(\"quote\", \"Quote\", choices=c(None=\"\",\"Double Quote\"='\"',\"Single Quote\"=\"'\"),selected=\"\"),\n br(),br(),br(),\n div(\"Shiny app by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Base R code by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Shiny source files:\",\n a(href=\"https://gist.github.com/calpolystat/48dc47f3ff436aba4b19\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\", \n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\"))),\n column(9,\n conditionalPanel(\n condition=\"input.file!='NULL'\",\n dataTableOutput(\"data.tab\"))))),\n \n tabPanel(\"Visualize Data\",\n fluidRow(\n column(6,\n plotOutput(\"datagraph\")),\n column(6,br(),br(),\n checkboxInput(\"displaystats\", \"Summary statistics\", FALSE),\n tableOutput(\"summarystats\")))))),\n \n tabPanel(\"Hypothesis Test\",\n fluidRow(\n column(3,\n wellPanel(\n conditionalPanel(\n condition=\"input.datformat==1 && input.sampdat==1\",\n h4(\"Hypotheses:\"),\n uiOutput(\"hypo1\"),\n tags$hr(),\n numericInput(\"null1\", label=\"Hypothesized value:\", value=0),\n selectInput(\"alt1\", \"Select a direction for Ha:\", choices=list(\"two-sided\",\"less than\",\"greater than\"),selected=\"two-sided\")),\n conditionalPanel(\n condition=\"input.datformat!=1 || input.sampdat==2\",\n h4(\"Hypotheses:\"),\n uiOutput(\"hypo2\"),\n tags$hr(),\n numericInput(\"null2\", label=\"Hypothesized value:\", value=0),\n selectInput(\"alt2\", label=\"Select a direction for Ha:\", choices=list(\"two-sided\",\"less than\",\"greater than\"),selected=\"two-sided\")),\n sliderInput(\"alpha\", label=HTML(\"Significance level α:\"), value=.05, max=1, min=0, step=.01),\n tags$hr(),\n actionButton(\"teststart\", strong(\"Perform t-test\")),\n bsPopover(\"teststart\",\"Note\",\"Remember to check the normality condition before performing t-test.\",trigger=\"hover\",placement=\"right\"),\n br(),br(),br(),\n div(\"Shiny app by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Base R code by\", \n a(href=\"http://www.linkedin.com/in/jimmywong46/\",target=\"_blank\",\"Jimmy Wong\"),align=\"right\", style = \"font-size: 8pt\"),\n div(\"Shiny source files:\",\n a(href=\"https://gist.github.com/calpolystat/48dc47f3ff436aba4b19\",\n target=\"_blank\",\"GitHub Gist\"),align=\"right\", style = \"font-size: 8pt\"),\n div(a(href=\"http://www.statistics.calpoly.edu/shiny\",target=\"_blank\", \n \"Cal Poly Statistics Dept Shiny Series\"),align=\"right\", style = \"font-size: 8pt\"))),\n \n column(9,\n br(),br(),\n conditionalPanel(\n condition=\"input.teststart>0\",\n column(7,\n plotOutput(\"tdist\"),\n bsPopover(\"tdist\",\"p-value\",\"The p-value is the shaded region. A large p-value indicates to fail to reject Ho and no evidence for Ha. A small p-value indicates to reject the Ho and evidence for Ha.\",\n trigger=\"hover\",placement=\"left\"),br()),\n column(5,br(),\n strong(\"Test output:\"),\n tableOutput(\"test\"),br(),\n checkboxInput(\"showpoint\",\"Point estimate(s):\",FALSE),\n uiOutput(\"est\"),\n checkboxInput(\"ci\",\"Confidence interval:\", FALSE),\n tableOutput(\"citab\"),\n bsPopover(\"citab\",\"Confidence interval sample interpretation\",\"We are 95% confident that the true parameter is anywhere between the lower bound to the upper bound.\",\n trigger=\"hover\",placement=\"bottom\")))))),\n \n tabPanel(\"Normality Condition\",\n column(1),\n column(4,br(),\n p(strong(\"Normality test:\"),\"The sampling distribution of the sample means or differences in the sample means is 1) Normal if the population(s) is Normal or 2) approximately Normal if the \n sample size(s) is large enough (at least 30). In situations with small sample size(s), the approach to access \n whether the sample data could have came from a Normal distribution is either through a Q-Q plot or a Normality test.\"),\n actionButton(\"normstart\", label=strong(\"Perform normality test\")),br(),br(),\n conditionalPanel(\n condition=\"input.normstart>0\",\n wellPanel(\n strong(\"Ho: data is from a Normal distribution\"),br(),\n strong(\"Ha: data is not from a Normal distribution\"),br(),br(),\n em(\"Shapiro-Wilk Normality Test:\"),\n tableOutput(\"sw\"),\n bsPopover(\"sw\",\"Normality test\",\"In a normality test, a large p-value does not provide evidence that the sample data is not from a Normal distribution.\",\n trigger=\"hover\",placement=\"bottom\")))),\n column(6,\n conditionalPanel(\n condition=\"input.normstart>0\",br(),br(),\n plotOutput(\"qqplot\"),\n bsPopover(\"qqplot\",\"Q-Q plot\",\"In a Q-Q plot, points that resemble a diagonal line with no curvature implies that the sample data could have came from a Normal distribution.\",\n trigger=\"hover\",placement=\"left\"))),\n column(1))\n \n)))\n\n", "meta": {"hexsha": "6d9fa5c5dcb6e6416cb773ff6efc42a0b8671619", "size": 15165, "ext": "r", "lang": "R", "max_stars_repo_path": "t_Test/ui.r", "max_stars_repo_name": "townsenddw/shiny1", "max_stars_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "t_Test/ui.r", "max_issues_repo_name": "townsenddw/shiny1", "max_issues_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t_Test/ui.r", "max_forks_repo_name": "townsenddw/shiny1", "max_forks_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T12:48:05.000Z", "avg_line_length": 81.5322580645, "max_line_length": 462, "alphanum_fraction": 0.4471480382, "num_tokens": 2686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6425538742410083}} {"text": "# MIT License\n# Copyright (c) 2020 Abhinav Prakash, Vijay Panchang, Yu Ding, and Lewis Ntaimo\n \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\npar2015 = c(55,0.3,15,0.2027349)\nquantile = seq(0,230,1) \nmu2015 = par2015[1]\nsigma = par2015[3]\nepsilon = par2015[4]\nmu1965 = mu2015 - 50*par2015[2]\nt2015 = (1+epsilon*((quantile-mu2015)/sigma))^(-1/epsilon)\npdf2015 = (t2015^(epsilon+1))*exp(-t2015)/sigma\nt1965 = (1+epsilon*((quantile-mu1965)/sigma))^(-1/epsilon)\npdf1965 = (t1965^(epsilon+1))*exp(-t1965)/sigma\npdf = data.frame(pdf1965,pdf2015)\npdf(file = \"Results/distplot.pdf\")\nmatplot(quantile,pdf,type='l',lwd=2,main= 'Nonstationary GEV distribution', xlab = NA, ylab = 'Density', cex.main = 1.33, cex.lab = 1.33, cex.axis = 1.33)\nlegend('topright', legend = c('Year 1965', 'Year 2015'),lty = c(1,2), col = c(1,2), cex = 1.33)\ndev.off()", "meta": {"hexsha": "794d6184f9cabeec6adb057a0779b313b5d94407", "size": 1847, "ext": "r", "lang": "R", "max_stars_repo_path": "distplot.r", "max_stars_repo_name": "abhinavprakash2006/SCBM-R", "max_stars_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-07T13:24:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-07T13:24:28.000Z", "max_issues_repo_path": "distplot.r", "max_issues_repo_name": "abhinavprakash2006/SCBM-R", "max_issues_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distplot.r", "max_forks_repo_name": "abhinavprakash2006/SCBM-R", "max_forks_repo_head_hexsha": "959d1a420c1a29b38c8dd630c9d3300c745f8fa2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3055555556, "max_line_length": 154, "alphanum_fraction": 0.7374120195, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6425431234280585}} {"text": "\nlibrary(\"shiny\")\nlibrary(\"ggplot2\")\npersons <- seq(-3, 3, by = .1)\nb <- -3:3\nrasch <- function(person, item) {\n exp(person - item)/(1 + exp(person - item))\n}\ndata_r <- matrix(nrow = length(persons), ncol = length(b))\nfor(i in 1:length(b)){\n data_r[,i] <- rasch(persons, b[i])\n}\ndata_r <- as.data.frame(data_r)\ncolnames(data_r) <- b\n\nshinyServer(\n function(input, output){\n output$one <- renderPlot({\n qplot(y = data_r[,input$idiff], x = persons, geom = \"line\") + ylab(\"Probability of Getting Item Correct\") + xlab(\"Person Ability\") + coord_cartesian(ylim = c(0, 1), xlim = c(-3, 3)) + geom_vline(xintercept = as.numeric(input$idiff), colour = \"red\", linetype = \"longdash\")\n })\n }\n)\n\n", "meta": {"hexsha": "91a9b4cd5992f7c1fe1e687caeeea3514e2816cb", "size": 699, "ext": "r", "lang": "R", "max_stars_repo_path": "talks/akureyri_irt/unak_shiny/rasch/server.r", "max_stars_repo_name": "cddesja/Presentations", "max_stars_repo_head_hexsha": "d877bd30406f10532f9b1da79200fdddea0eb40d", "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": "talks/akureyri_irt/unak_shiny/rasch/server.r", "max_issues_repo_name": "cddesja/Presentations", "max_issues_repo_head_hexsha": "d877bd30406f10532f9b1da79200fdddea0eb40d", "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": "talks/akureyri_irt/unak_shiny/rasch/server.r", "max_forks_repo_name": "cddesja/Presentations", "max_forks_repo_head_hexsha": "d877bd30406f10532f9b1da79200fdddea0eb40d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.125, "max_line_length": 277, "alphanum_fraction": 0.6280400572, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6423967994241585}} {"text": "> solve24()\n8 * (4 - 2 + 1)\n> solve24(c(6,7,9,5))\n6 + (7 - 5) * 9\n> solve24(c(8,8,8,8))\n[1] NA\n> solve24(goal=49) #different goal value\n8 * (4 + 2) + 1\n> solve24(goal=52) #no solution\n[1] NA\n> solve24(ops=c('-', '/')) #restricted set of operators\n(8 - 2)/(1/4)\n", "meta": {"hexsha": "5e3d4e96c8e255b5c4d7b15ab08c53b5beba25bf", "size": 261, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/24-game-Solve/R/24-game-solve-2.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/24-game-Solve/R/24-game-solve-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/24-game-Solve/R/24-game-solve-2.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.0769230769, "max_line_length": 55, "alphanum_fraction": 0.5440613027, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6423769409655521}} {"text": "evec = matrix(\n c(\t\t\t -0.5, 0.6906786606674509, 0.15153543380548623, 0.5,\n\t\t\t 0.5, -0.15153543380548576, 0.6906786606674498, 0.5,\n\t\t\t -0.5, -0.6906786606674498, -0.15153543380548617, 0.5,\n\t\t\t 0.5, 0.15153543380548554, -0.6906786606674503, 0.5),\n nrow=4,ncol=4,byrow=T)\n\nievc = matrix(\n c(\t\t\t -0.5, 0.5, -0.5, 0.5,\n\t\t\t 0.6906786606674505, -0.15153543380548617, -0.6906786606674507, 0.15153543380548645,\n\t\t\t 0.15153543380548568, 0.6906786606674509, -0.15153543380548584, -0.6906786606674509,\n\t\t\t 0.5, 0.5, 0.5, 0.5),\n nrow=4,ncol=4,byrow=T)\n\nmake.expDt = function(t) {\n matrix(\n c(exp(-2*t), 0, 0, 0,\n 0, exp(-1*t)*cos(1*t), exp(-1*t)*sin(1*t), 0,\n 0, -exp(-1*t)*sin(1*t), exp(-1*t)*cos(1*t), 0,\n 0, 0, 0, 1),\n nrow=4,ncol=4,byrow=T)\n}\n\nq.circulant = matrix(\n c(-1, 1, 0, 0,\n 0, -1, 1, 0,\n 0, 0, -1, 1,\n 1, 0, 0, -1),\n nrow=4,ncol=4,byrow=T)\n\ntest.1 = evec %*% make.expDt(0.1) %*% ievc # Schur decomposition (method used in BEAGLE)\n\nEvec = eigen(q.circulant)$vectors # Complex eigendecomposition\nIevc = solve(Evec)\nmake2.expDt = function(t) {\n diag(exp(eigen(q.circulant)$values * t))\n}\n\ntest.2 = Evec %*% make2.expDt(0.1) %*% Ievc # Should (and does) equal test.1\n\nout.1 = t(make.expDt(0.1)) %*% t(evec) # Should be intermediate result\n\nout.2 = t(ievc) %*% out.1 # Should (and does) equal t(test.1)\n\n\n\n\n", "meta": {"hexsha": "10249393c57001c880450a80590f77567db54703", "size": 1467, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/complextest/compareValues.r", "max_stars_repo_name": "ayresdl/beagle-lib", "max_stars_repo_head_hexsha": "1d4b21d062999c303d0d8b3e1e306c3d5e81d708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 110, "max_stars_repo_stars_event_min_datetime": "2015-04-16T02:06:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T20:35:32.000Z", "max_issues_repo_path": "examples/complextest/compareValues.r", "max_issues_repo_name": "ayresdl/beagle-lib", "max_issues_repo_head_hexsha": "1d4b21d062999c303d0d8b3e1e306c3d5e81d708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 92, "max_issues_repo_issues_event_min_datetime": "2015-04-16T12:06:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T16:10:22.000Z", "max_forks_repo_path": "examples/complextest/compareValues.r", "max_forks_repo_name": "ayresdl/beagle-lib", "max_forks_repo_head_hexsha": "1d4b21d062999c303d0d8b3e1e306c3d5e81d708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49, "max_forks_repo_forks_event_min_datetime": "2015-04-16T02:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T14:03:05.000Z", "avg_line_length": 30.5625, "max_line_length": 90, "alphanum_fraction": 0.5562372188, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6422327676852652}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\nrm(list=ls(all=TRUE))\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\ncat(\"Stan version:\", stan_version(), \"\\n\")\r\nstanmodelcode <- \"\r\n\r\n\r\n\r\n#### define GP function\r\nfunctions {\r\n\r\nreal normal_generalized_poisson_log(int y, real theta, real lambda, real sigob) { \r\n return (log(theta) \r\n + (y - 1) * log(theta + y * lambda) \r\n - lgamma(y + 1) \r\n - y * lambda \r\n - theta)*(y<=200)\r\n +(normal_lpdf(y|theta,sigob))*(y>200);\r\n\t\t \r\n } \r\n\r\n}\r\n\r\n\r\n#### define our data, integer value\r\ndata {\r\nint N;\r\nint y[N];\r\nreal E[N];\r\n}\r\n\r\n\r\n#### define parameters \r\nparameters {\r\n\r\nreal lambda;\r\nreal u;\r\nreal b5;\r\nreal b6;\r\nreal sig2;\r\nvector[N] e;\r\nreal sigob;\r\n}\r\n\r\n\r\n#### define some parameters which is the function of other parameters \r\ntransformed parameters {\r\nvector[N] mu;\r\n\r\n### define the mean function\r\n\r\n\r\nmu[1] <- y[1]; ## not tested\r\n\r\n for (n in 2:N) {\r\n\t\r\n\t \r\n\t mu[n] <- mu[n-1]*exp(u*(b6^2/((mu[n-1]-b5)^2+b6^2))+e[n]); \r\n\t \r\n\t }\r\n\r\n}\r\n\r\n\r\n\r\n##### define piror and likelihood function\r\nmodel {\r\nlambda~uniform(-1,1);\r\nu ~ normal(0.07,0.1);\r\nb5 ~ normal(3000,100000);\r\nb6 ~ normal(3000,100000);\r\nsig2 ~ gamma(1,1); \r\ne~normal(0,sig2);\r\nsigob ~ uniform(100,1100);\r\n\r\nfor (j in 1:N) {\r\n\r\ny[j] ~ normal_generalized_poisson( mu[j]*E[j], lambda, sigob);\r\n}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n#### calculate DIC\r\ngenerated quantities {\r\nvector[N] log_lik;\r\nreal dev; // deviance\r\n\r\n\r\n for (n in 1:N){\r\n log_lik[n] <- normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n dev <- 0;\r\n for ( n in 1:N ) {\r\n dev <- dev + (-2) * normal_generalized_poisson_log (y[n],mu[n]*E[n], lambda, sigob);\r\n }\r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\"\r\n\r\n\r\n###### \r\n\r\n\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covdi19modelrisk/output/forecast\")\r\n\r\n## y=read.csv(\"COVID-19_confirmed__Germany.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Italy.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Japan.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__Spain.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")\r\n## y=read.csv(\"COVID-19_confirmed__US.csv\")\r\n y=read.csv(\"COVID-19_confirmed_Australia.csv\")\r\n\r\ny=y[,2]\r\n\r\n\r\n\r\n\r\nE=rep(1,length(y))\r\n\r\nN=length(y)\r\ndat <- list(N = N, y = y,E=E)\r\n\r\n\r\n#### initial values\r\ninits =list(list(lambda=0,u=0.07,b5=3000, b6=3000, sig2=0.01,e=rep(0.01,N),sigob=1000)) ### 134\r\n\r\n\r\nfit <- stan(model_code = stanmodelcode, model_name = \"example\",init =inits,\r\ndata = dat, warmup=10000,iter = 100000, chains = 1, seed=999,thin=1)\r\nprint(fit,digits = 4)\r\n\r\n\r\n\r\n\r\n\r\n#################### trace plot\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\n\r\n##k=1\r\n\r\n\r\npdf(paste(\"M12_\",abn[k],\"_p1.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"u\",\"b5\",\"b6\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\n\r\ndev.off()\r\n\r\npdf(paste(\"M12_\",abn[k],\"_p2.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\ntraceplot(fit, pars=c(\"sigob\",\"sig2\",\"lambda\"), inc_warmup = T, nrow = 3, ncol = 1, window = NULL, include = TRUE)\r\ndev.off()\r\n\r\n\r\n\r\n################## plot 30/45/60/ length(y)\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M12_\",abn[k],\"_30.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=30\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M12_\",abn[k],\"_45.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=45\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M12_\",abn[k],\"_60.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=60\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\npdf(paste(\"M12_\",abn[k],\"_all.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n######## log plot ####################################################\r\n\r\nk=1\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , mean )\r\n\r\nEpars_5 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , quantile, probs=0.05 )\r\n\r\nEpars_9 <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\n\r\ny=log(y)\r\nEpars_m=log(Epars_m)\r\nEpars_9=log(Epars_9)\r\nEpars_5=log(Epars_5)\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/plot\")\r\n\r\npdf(paste(\"M12_\",abn[k],\"_log.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nm=length(y)\r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\n\r\npolygon(c(rev(newx), newx), c(rev(Epars_9[1:m]), Epars_5[1:m]), col = \"grey80\", border = NA)\r\n\r\nlines(newx,Epars_9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Epars_5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(y[1:m],ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),pch=19)\r\npar(new=TRUE)\r\nplot.ts(Epars_m[1:m],col=\"red\",ylim=c(min(y[1:m]),max(y[1:m],Epars_9[1:m])),ylab=\"Count\",xlab=\"Time\",main=paste(\"In-sample fit results of M12 model for \",name[k],sep=\"\"),lwd = 2)\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#####################################################################################################################################################\r\n###################################### forecast ###################################\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n################################################\r\n\r\nP=20\r\nMu=matrix(,nrow=90000,ncol=P)\r\nX=matrix(,nrow=90000,ncol=P)\r\n\r\n\r\nlambda_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,1]\r\nu_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,2]\r\nb5_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,3]\r\nb6_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,4]\r\nsig2_p=as.data.frame(fit@sim[[1]][[1]])[10001:100000,5]\r\n\r\n\r\nset.seed(999)\r\n\r\nfor (r in 1:90000){\r\n\r\n\r\n\r\nMu[r,1]=y[length(y)]\r\nfor (s in 1:(P-1) ){\r\n\r\ne=rnorm(1,0,sig2_p[r])\r\n\r\nMu[r,s+1]=Mu[r,s]*exp(u_p[r]*(b6_p[r]^2/((Mu[r,s]-b5_p[r])^2+b6_p[r]^2))+e)\r\n\r\n}}\r\n\t \r\n\r\nsigob=1000\r\nfor (r in 1:90000){\r\nfor (s in 1:P ){\r\n\r\nX[r,s]=rnorm(1,Mu[r,s], sigob)\r\n\r\n\r\n}}\r\n\r\n\r\n\r\nXm=apply(X,2,mean)\r\n\r\nX5 <- apply( X , 2 , quantile, probs=0.05 )\r\n\r\nX9 <- apply( X , 2 , quantile, probs=0.95 )\r\n\r\n\r\n\r\nZm=c(y,Xm)\r\nZ5=c(y,X5)\r\nZ9=c(y,X9)\r\n\r\n\r\n\r\n##### read forecast\r\nsetwd(\"./covid19modelrisk/data/covid19_infected\")\r\n\r\n## FT=read.csv(\"COVID-19_confirmed__Germany_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Italy_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Japan_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__Spain_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__United Kingdom_FT.csv\")[,2]\r\n## FT=read.csv(\"COVID-19_confirmed__US_FT.csv\")[,2]\r\nFT=read.csv(\"COVID-19_confirmed_Australia_FT.csv\")[,2]\r\n\r\n\r\n\r\n\r\n\r\nZ_FT=c(y,FT)\r\n\r\n\r\n#####\r\n#######\r\n############\r\n\r\nk=7\r\n\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\nm=length(Zm)\r\n\r\n\r\n\r\nsetwd(\"./covid19modelrisk/output/forecast\")\r\npdf(paste(\"M12_\",abn[k],\"_F.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nnewx=c(1:m)\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m],Z_FT)),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M12 model for \",name[k],sep=\"\"),pch=19,col=\"red\",xaxt = 'n')\r\npolygon(c(rev(newx), newx), c(rev(Z9[1:m]), Z5[1:m]), col = \"grey80\", border = NA)\r\n\r\npar(new=TRUE)\r\nplot(Zm[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m],Z_FT)),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M12 model for \",name[k],sep=\"\"),pch=19,col=\"red\",xaxt = 'n')\r\nlines(newx,Z9[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\nlines(newx, Z5[1:m], lty = 'dashed', col = 'red',lwd = 2)\r\npar(new=TRUE)\r\nplot(Z_FT[1:m],ylim=c(min(Zm[1:m]),max(Zm[1:m],Z9[1:m],Z_FT)),ylab=\"Count\",xlab=\"Time\",main=paste(\"Out-sample forecast results of M12 model for \",name[k],sep=\"\"),pch=19,xaxt = 'n')\r\nlegend(\"topleft\", legend=c(\"Observed data\", \"Forecasted data\"), col=c(\"black\", \"red\"), lty=c(1,1), lwd = 3,cex=2)\r\n\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/27\",\"Mar/17\",\"May/05\",\"Jun/25\",\"Aug/06\")) ### GM\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/31\",\"Mar/13\",\"May/09\",\"Jun/29\",\"Aug/06\")) ### IT\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/22\",\"Mar/12\",\"Apr/30\",\"Jun/19\",\"Aug/06\")) ### JP\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Feb/01\",\"Mar/20\",\"May/10\",\"Jun/30\",\"Aug/06\")) ### SP\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/31\",\"Mar/21\",\"May/09\",\"Jun/29\",\"Aug/06\")) ### UK\r\n# axis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/22\",\"Mar/12\",\"Apr/30\",\"Jun/19\",\"Aug/06\")) ### US\r\naxis(1, at=c(0,50,100,150,length(y)), labels=c(\"Jan/26\",\"Mar/16\",\"May/04\",\"Jun/24\",\"Aug/06\")) ### AU\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\nM=length(FT)\r\n\r\ne=FT-Xm\r\nmae=mean(abs(e))\r\nrmse=sqrt(mean(e^2))\r\n############ PR\r\n p=e/FT\r\n# p1=e1/mean(mo1)\r\nmape=mean(abs(p))\r\n########## QR\r\nmd=sum(abs(FT[2:M]-FT[1:(M-1)]))/(M-1)\r\nqj=e/md\r\nmase=mean(abs(qj))\r\n\r\n\r\nlist(mae,rmse,mape,mase)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###### RMSE results ###############################################################\r\n\r\n### Germany\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 509.454\r\n\r\n[[2]]\r\n[1] 621.1698\r\n\r\n[[3]]\r\n[1] 0.002233969\r\n\r\n[[4]]\r\n[1] 0.4242845\r\n\r\n\r\n## Italy\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 9250.797\r\n\r\n[[2]]\r\n[1] 10628.97\r\n\r\n[[3]]\r\n[1] 0.03603019\r\n\r\n[[4]]\r\n[1] 13.74884\r\n\r\n\r\n## Japan\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 10380.91\r\n\r\n[[2]]\r\n[1] 11466.17\r\n\r\n[[3]]\r\n[1] 0.1780064\r\n\r\n[[4]]\r\n[1] 10.37272\r\n\r\n\r\n\r\n## Spain\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 38964.49\r\n\r\n[[2]]\r\n[1] 47789.93\r\n\r\n[[3]]\r\n[1] 0.1027847\r\n\r\n[[4]]\r\n[1] 7.018166\r\n\r\n\r\n\r\n## UK\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 4733.137\r\n\r\n[[2]]\r\n[1] 5370.857\r\n\r\n[[3]]\r\n[1] 0.01470337\r\n\r\n[[4]]\r\n[1] 4.532514\r\n\r\n\r\n\r\n## US\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 290955.2\r\n\r\n[[2]]\r\n[1] 318595.1\r\n\r\n[[3]]\r\n[1] 0.0527834\r\n\r\n[[4]]\r\n[1] 6.268938\r\n\r\n\r\n## AU\r\n> list(mae,rmse,mape,mase)\r\n[[1]]\r\n[1] 2835.194\r\n\r\n[[2]]\r\n[1] 3092.975\r\n\r\n[[3]]\r\n[1] 0.1182316\r\n\r\n[[4]]\r\n[1] 11.6498\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n###########################################################################################################################\r\n###########################################################################################################################\r\n###########################################################################################################################\r\n\r\n\r\nmean(y)\r\nmedian(y)\r\n\r\nn=length(y)\r\n\r\n\r\n#################\r\n### remove one b6\r\n\r\nu=0.07\r\nb5=3000\r\nb6=3000\r\n\r\n\r\nx=c()\r\nx[1]=100\r\nfor (i in 1:(n-1) ){\r\n\r\nx[i+1]=x[i]*exp(u*(b6^2/((b5-x[i])^2+b6^2)))\r\n\r\n\r\n}\r\nx=round(x)\r\nx\r\nplot(x,col=\"red\",ylim=c(min(x),max(x)))\r\n\r\n\r\n\r\nplot(y,ylim=c(min(y,x),max(y,x)))\r\npar(new=TRUE)\r\nplot(x,col=\"red\",ylim=c(min(y,x),max(y,x)))\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f27c67db93663d0fba729cc9e1f927dcb3241d71", "size": 15161, "ext": "r", "lang": "R", "max_stars_repo_path": "R/M12 run.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/M12 run.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/M12 run.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 22.628358209, "max_line_length": 189, "alphanum_fraction": 0.535123013, "num_tokens": 5577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6422327493867728}} {"text": "simpson1<-function(data,type=\"complement\"){\n simpson.diversity<-numeric(ncol(data))\n for(j in 1:ncol(data)){\n soma<-sum(data[,j])\n prop<-data[,j]/soma\n prop2<-prop^2\n D<-sum(prop2)\n if(type==\"inverse\") (simp<-1/D)\n if(type==\"complement\") (simp<-1-D)\n simpson.diversity[j]<-simp\n }\n plot.number<-1:ncol(data)\n return(rbind(plot.number,simpson.diversity))\n}\n\n\n###this is a simple example of function in R\n\n\n\n\n\n\n\n\n####\n\nsimpson2<-function(data,type=\"complement\"){\n simpson.diversity<-numeric(ncol(data))\n for(j in 1:ncol(data)){\n soma<-sum(data[,j])\n prop<-data[,j]*(data[,j]-1)\n prop2<-sum(prop)\n D<-prop2/(soma*(soma-1))\n if(type==\"inverse\") (simp<-1/D)\n if(type==\"complement\") (simp<-1-D)\n simpson.diversity[j]<-simp\n }\n plot.number<-1:ncol(data)\n return(rbind(plot.number,simpson.diversity))\n}\n", "meta": {"hexsha": "1089d06f6dfcaff4dd65af373462b9a4f050709c", "size": 847, "ext": "r", "lang": "R", "max_stars_repo_path": "notes/week6-examples/simpson-f.r", "max_stars_repo_name": "namkyodai/2022-UrbanComputation-SUTD", "max_stars_repo_head_hexsha": "fc3921ec4ea8719ebfb04f2646f00c90d886721f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2022-03-16T10:46:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:48:39.000Z", "max_issues_repo_path": "notes/week6-examples/simpson-f.r", "max_issues_repo_name": "namkyodai/2022-UrbanComputation-SUTD", "max_issues_repo_head_hexsha": "fc3921ec4ea8719ebfb04f2646f00c90d886721f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2022-03-16T06:48:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T16:39:15.000Z", "max_forks_repo_path": "notes/week6-examples/simpson-f.r", "max_forks_repo_name": "namkyodai/2022-UrbanComputation-SUTD", "max_forks_repo_head_hexsha": "fc3921ec4ea8719ebfb04f2646f00c90d886721f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2022-03-16T10:35:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:12:09.000Z", "avg_line_length": 20.1666666667, "max_line_length": 46, "alphanum_fraction": 0.6221959858, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.642153127113525}} {"text": "# via Houstonwp\nq <- c(0.001,0.002,0.003,0.003,0.004,0.004,0.005,0.007,0.009,0.011)\nw <- c(0.05,0.07,0.08,0.10,0.14,0.20,0.20,0.20,0.10,0.04)\nP <- 100\nS <- 25000\nr <- 0.02\n\nbase_r_npv <- function(q,w,P,S,r) {\n inforce <- c(1,head(cumprod(1-q-w), -1))\n ncf <- inforce * P - inforce * q * S\n d <- (1/(1+r)) ^ seq_along(ncf)\n sum(ncf * d)\n}\n\nbase_r_npv(q,w,P,S,r)\n#> [1] 50.32483\nmicrobenchmark::microbenchmark(base_r_npv(q,w,P,S,r))\n\nnpv_loop <- function(q,w,P,S,r) {\n inforce = 1.0\n result = 0.0\n v = 1 / (1 + r)\n v_t = v\n for (t in 1:length(q)) {\n result <- result + inforce * (P-S*q[t-1]) * v_t\n inforce <- inforce * (1 - (q[t-1] + w[t-1]))\n v_t = v_t * v\n }\n result\n}\nmicrobenchmark::microbenchmark(npv_loop(q,w,P,S,r))", "meta": {"hexsha": "2efd3c555b7ffbdaf0d647689e64ed28f730b5d4", "size": 783, "ext": "r", "lang": "R", "max_stars_repo_path": "Benchmarks/LifeModelingProblem/r/base.r", "max_stars_repo_name": "JeannotJeannot/Learn", "max_stars_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-10-03T02:20:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:50:17.000Z", "max_issues_repo_path": "Benchmarks/LifeModelingProblem/r/base.r", "max_issues_repo_name": "JeannotJeannot/Learn", "max_issues_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7, "max_issues_repo_issues_event_min_datetime": "2020-10-02T00:16:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T19:34:34.000Z", "max_forks_repo_path": "Benchmarks/LifeModelingProblem/r/base.r", "max_forks_repo_name": "JeannotJeannot/Learn", "max_forks_repo_head_hexsha": "b6a40a12772de06655e1c7ae4d7c1791a01e0c48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-03-13T19:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T13:49:42.000Z", "avg_line_length": 25.2580645161, "max_line_length": 67, "alphanum_fraction": 0.533844189, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6421531206763532}} {"text": "# # This script was written by nicolas m. roberts, primarily using the geologyGeometry library of functions, written by Joshua R. Davis. \n# # if you incounter bugs in the code, please inform nick at nmroberts@wisc.edu\n\n### PRELIMINARY WORK ####\n\n# FOR MAC: Set the working directory.\nsetwd(\"~/Desktop/20170620geologyGeometry\")\n\n# [!!!] FOR WINDOWS: Set the working directory.\n# setwd(\"C:/users/[Insert user name]/Desktop/20170620geologyGeometry\")\n\n# Load the necessary R libraries.\nsource(\"library/all.R\")\n\n# Load some custom functions.\nsource(\"JSG_statsFunctions.r\")\n\n# [!!!] Markov chain Monte Carlo and Kamb contouring in equal volume plots require C compiler. Skip MCMC and equal volume Kamb lines if you do not wish to install C. Load the necessary library\n# source(\"libraryC/all.R\")\n\n#==========================LOAD THE DATA========================================\n\n# 1) Foliation only\nFols <- geoDataFromFile(\"data/Fols_WestMt.csv\")\n\n# Plot foliation locations in map view\nplot(Fols$easting, Fols$northing, xlab = \"Easting (meters)\", ylab = \"Northing (meters)\")\n\n# Check how many measurments there are\nnrow(Fols)\n\n#————————————————————————————————————————————————————————————\n\n# 2) Foliation-lineation pairs\nFollins <- geoDataFromFile(\"data/Follins_WestMt.csv\")\n\n# Plot foliation-lineation locations in map view\nplot(\n Follins$easting,\n Follins$northing,\n xlab = \"Easting (meters)\",\n ylab = \"Northing (meters)\"\n)\n\n# Check how many measurements there are\nnrow(Follins)\n\n\n\n#==========================PART I: DIRECTIONAL STATISTICS ON FOLIATIONS========================================\n#==========================DEFINE GEOGRAPHIC DOMAINS FOR FOLIATION-ONLY DATA=================================\n\n#(After Braudy et al., 2017)\n\n# Define the geographic criteria that defines the different domains. The numbers are UTM coordinates\nFols_northCrit <- Fols$northing > 4922736\nFols_centerCrit <- Fols$northing < 4922736 & Fols$northing > 4919205\nFols_southCrit <- Fols$northing < 4919205\n\n# Create a new column in the dataframe in which to store the domain information\nFols$domain <- replicate(nrow(Fols), 1)\n\n# Classify the foliation-only dataset by domain\nFols$domain[Fols_northCrit] <- 1\nFols$domain[Fols_centerCrit] <- 2\nFols$domain[Fols_southCrit] <- 3\n\n# Plot the locations of the foliation-only data in map view, each domain a different color.\nplot(\n x = Fols$easting,\n y = Fols$northing,\n xlab = \"Easting (meters)\",\n ylab = \"Northing (meters)\",\n col = hues(Fols$domain),\n pch = 19\n)\n\n# Return the number of datapoints in each domain.\nlength(Fols$domain[Fols_northCrit])\nlength(Fols$domain[Fols_centerCrit])\nlength(Fols$domain[Fols_southCrit])\n\n#==========================DEFINE GEOGRAPHIC DOMAINS FOR FOLIATION-LINEATION DATA========================================\n\n# (After Braudy et al., 2017)\n\n# Define the geographic criteria that defines the different domains\nFollins_northCrit <- Follins$northing > 4922736\nFollins_centerCrit <- Follins$northing < 4922736 & Follins$northing > 4919205\nFollins_southCrit <- Follins$northing < 4919205\n\n# Create a new column in the dataframe in which to store the domain information\nFollins$domain <- replicate(nrow(Follins), 1)\n\n# Classify the foliation-lineation dataset by domain\nFollins$domain[Follins_northCrit] <- 1\nFollins$domain[Follins_centerCrit] <- 2\nFollins$domain[Follins_southCrit] <- 3\n\n# Plot the locations of the foliation-lineation data in map view, each domain a different color.\nplot(\n x = Follins$easting,\n y = Follins$northing,\n xlab = \"Easting (meters)\",\n ylab = \"Northing (meters)\",\n col = hues(Follins$domain),\n pch = 19\n)\n\n# Return the number of datapoints in each domain.\nlength(Follins$domain[Follins_northCrit])\nlength(Follins$domain[Follins_centerCrit])\nlength(Follins$domain[Follins_southCrit])\n\n#==========================FOLIATION-ONLY STATISTCAL TREATMENT========================================\n\n# 1) Some parametric two-sample tests. The null hypothesis for all tests is that the two domains being tested come from the same population.\n\n# Three Wellner tests (Wellner, 1979), one for each pair of domains. Each test is based on 10,000 permutations. This tests not only if the samples come from the populations with the same mean, but also with the same dispersion.\nlineWellnerInference(Fols$pole[Fols_northCrit], Fols$pole[Fols_southCrit], 10000)\nlineWellnerInference(Fols$pole[Fols_northCrit], Fols$pole[Fols_centerCrit], 10000)\nlineWellnerInference(Fols$pole[Fols_centerCrit], Fols$pole[Fols_southCrit], 10000)\n\n# Three Watson tests that assume large sample size (Mardia and Jupp, 2000), one for each pair of domains.\nlineLargeMultiSampleWatsonInference(list(Fols$pole[Fols_northCrit], Fols$pole[Fols_southCrit]))\nlineLargeMultiSampleWatsonInference(list(Fols$pole[Fols_northCrit], Fols$pole[Fols_centerCrit]))\nlineLargeMultiSampleWatsonInference(list(Fols$pole[Fols_centerCrit], Fols$pole[Fols_southCrit]))\n\n# Three Watson tests that assume tightly concentrated datasets (Mardia and Jupp, 2000), one for each pair of domains.\nlineConcentratedMultiSampleWatsonInference(list(Fols$pole[Fols_northCrit], Fols$pole[Fols_southCrit]))\nlineConcentratedMultiSampleWatsonInference(list(Fols$pole[Fols_northCrit], Fols$pole[Fols_centerCrit]))\nlineConcentratedMultiSampleWatsonInference(list(Fols$pole[Fols_centerCrit], Fols$pole[Fols_southCrit]))\n\n#————————————————————————————————————————————————————————————\n\n# 2) Non-parametric bootstrapping\n\n# Perform the bootstrapping routine for each domain. Each bootstrapped dataset is based on 10,000 iterations.\nFols_northBoots <- lineBootstrapInference(Fols$pole[Fols_northCrit], 10000, numPoints = 50)\nFols_centerBoots <- lineBootstrapInference(Fols$pole[Fols_centerCrit], 10000, numPoints = 50)\nFols_southBoots <- lineBootstrapInference(Fols$pole[Fols_southCrit], 10000, numPoints = 50)\n\n# Plot data for each domain. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n Fols$pole[Fols_northCrit],\n Fols$pole[Fols_centerCrit],\n Fols$pole[Fols_southCrit]\n)\n\n# Plot the bootstrapped mean clouds for each domain. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n Fols_northBoots$bootstraps,\n Fols_centerBoots$bootstraps,\n Fols_southBoots$bootstraps\n)\n\n# Plot the bootstrapped mean with 95% confidence ellipses superimposed. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n list(Fols_northBoots$center),\n list(Fols_centerBoots$center),\n list(Fols_southBoots$center),\n curves = list(\n Fols_northBoots$points,\n Fols_centerBoots$points,\n Fols_southBoots$points\n )\n)\n\n#————————————————————————————————————————————————————————————\n\n# 3) Compute the rotation between the north and south domains.\n\n# Create empty lists to store data\nnorthSouthDiff <- list()\n\n# Assign variables for the orientations of all bootstrapped means.\nnorthB <- Fols_northBoots$bootstraps\nsouthB <- Fols_southBoots$bootstraps\n\n# Calculate the smallest possible rotations that bring means from the northern bootstrap cloud to the southern bootstrap clouds.\ncount = 1\nfor (i in 1:300) {\n for (n in i:300) {\n northSouthDiff$rotation[[count]] = rotSmallestRotationFromTwoLines(northB[[i]], southB[[n]])\n if (n < 90000) {\n count = count + 1\n }\n }\n}\n\n# Display the raw results of the preceting for loop\nnorthSouthDiff\n\n# Plot these rotations in an equal volume plot\noriEqualVolumePlot(\n northSouthDiff$rotation,\n group = oriLineInPlaneGroup,\n simplePoints = TRUE\n)\n\n# Compute the axis and rotation amount from all the rotations\nFols_angleAxis <- lapply(northSouthDiff$rotation, function(s) rotAxisAngleFromMatrix(s))\n\n\n#Identify the rotation axes\nrotationAxes <- lapply(Fols_angleAxis, function(s) c(s[1], s[2], s[3]))\n\nrotationAxisMean <- lineProjectedMean(rotationAxes)\ninf <- rayMahalanobisInference(rotationAxes, rotationAxisMean, numPoints=100)\n\n# Plot the rotation axes in an equal area plot\nlineEqualAreaPlot(\n rotationAxes, \n shapes = '.',\n)\n\n# Plot the rotation axis mean orientation with the 95% confidence ellipse\nlineEqualAreaPlot(\n list(inf$center),\n curves = list(inf$points)\n)\n\n\n# Plot a histogram of rotation amount between the northern domain and the southern domain, in degrees.\nhist(\n as.numeric(lapply(Fols_angleAxis, function(s) s[4] * 180 / pi)),\n 30,\n xlab = \"Angular Distance (degrees)\",\n ylab = \"Frequency\",\n main = \"Angular distances, Northern to Southern\"\n)\n\n# Compute the mean and 1-sigma standard deviation of the rotation amount, in degrees\nmean(sapply(Fols_angleAxis, function(s) s[4] * 180 / pi))\nsd(sapply(Fols_angleAxis, function(s) s[4] * 180 / pi))\n\n# Compute the mean trend and plunge in degrees\nFols_axes <- lapply(Fols_angleAxis, function(s) c(s[1], s[2], s[3]))\nFols_meanAxisDeg <- geoTrendPlungeDegFromCartesian(lower(lineProjectedMean(Fols_axes)))\n\n#Print the mean axis of rotation, in trend and plunge\nFols_meanAxisDeg\n\n#==========================FOLIATIONS FROM FOLIATION-LINEATION PAIRS STATISTICAL TREATMENT========================================\n\n#### FOLIATIONS FROM FOLIATION-LINEATION PAIRS STATISTICAL TREATMENT\n\n# 1) Some parametric two-sample tests.\n\n# Three Wellner tests (Wellner, 1979), one for each pair of domains. Each test is based on 10,000 permutations.\nlineWellnerInference(Follins$pole[Follins_northCrit], Follins$pole[Follins_southCrit], 10000)\nlineWellnerInference(Follins$pole[Follins_northCrit], Follins$pole[Follins_centerCrit], 10000)\nlineWellnerInference(Follins$pole[Follins_centerCrit], Follins$pole[Follins_southCrit], 10000)\n\n# Three Watson tests that assume large sample size (Mardia and Jupp, 2000), one for each pair of domains.\nlineLargeMultiSampleWatsonInference(list(Follins$pole[Follins_northCrit], Follins$pole[Follins_southCrit]))\nlineLargeMultiSampleWatsonInference(list(Follins$pole[Follins_northCrit], Follins$pole[Follins_centerCrit]))\nlineLargeMultiSampleWatsonInference(list(Follins$pole[Follins_centerCrit], Follins$pole[Follins_southCrit]))\n\n# Three Watson tests that assume tightly concentrated datasets (Mardia and Jupp, 2000), one for each pair of domains.\nlineConcentratedMultiSampleWatsonInference(list(Follins$pole[Follins_northCrit], Follins$pole[Follins_southCrit]))\nlineConcentratedMultiSampleWatsonInference(list(Follins$pole[Follins_northCrit], Follins$pole[Follins_centerCrit]))\nlineConcentratedMultiSampleWatsonInference(list(Follins$pole[Follins_centerCrit], Follins$pole[Follins_southCrit]))\n\n#————————————————————————————————————————————————————————————\n\n# 2) Non-parametric bootstrapping\n\n# Perform the bootstrapping routine for each domain. Each bootstrapped dataset is based on 10,000 iterations.\nFollinFols_northBoots <- lineBootstrapInference(Follins$pole[Follins_northCrit], 10000, numPoints = 50)\nFollinFols_centerBoots <- lineBootstrapInference(Follins$pole[Follins_centerCrit], 10000, numPoints = 50)\nFollinFols_southBoots <- lineBootstrapInference(Follins$pole[Follins_southCrit], 10000, numPoints = 50)\n\n\n# Plot data for each domain. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n Follins$pole[Follins_northCrit], \n Follins$pole[Follins_centerCrit], \n Follins$pole[Follins_southCrit]\n)\n\n# Plot the bootstrapped mean clouds for each domain. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n FollinFols_northBoots$bootstraps,\n FollinFols_centerBoots$bootstraps,\n FollinFols_southBoots$bootstraps\n)\n\n# Plot the bootstrapped mean clouds with 95% confidence ellipses superimposed. Northern (red), central (green), southern (blue)\nlineEqualAreaPlotThree(\n list(FollinFols_northBoots$center),\n list(FollinFols_centerBoots$center),\n list(FollinFols_southBoots$center),\n curves = list(\n FollinFols_northBoots$points,\n FollinFols_centerBoots$points,\n FollinFols_southBoots$points\n )\n)\n\n#————————————————————————————————————————————————————————————\n\n# 3) Compute the rotation between the north and south domains.\n\n# Create empty lists to store data\nFollins_northSouthDif <- list()\n\n# Assign variables for the orientations of all bootstrapped means.\nFollins_northB <- FollinFols_northBoots$bootstraps\nFollins_southB <- FollinFols_southBoots$bootstraps\n\n# Calculate the smallest possible rotations that bring means from the northern bootstrap cloud to the southern bootstrap clouds.\ncount = 1\nfor (i in 1:100) {\n for (n in i:100) {\n Follins_northSouthDif$rotation[[count]] = rotSmallestRotationFromTwoLines(Follins_northB[[i]], Follins_southB[[n]])\n if (n < 1000) {\n count = count + 1\n }\n }\n}\n\n# Display the raw results of the preceting for loop\nFollins_northSouthDif\n\n# Plot these rotations in an equal volume plot\noriEqualVolumePlot(\n Follins_northSouthDif$rotation,\n group = oriLineInPlaneGroup,\n simplePoints = TRUE\n)\n\n# Compute the axis and rotation amount from all the rotations\nFollins_angleAxis <- lapply(Follins_northSouthDif$rotation, function(s) rotAxisAngleFromMatrix(s))\n\n# Plot the rotation axes in an equal area plot\nlineEqualAreaPlot(lapply(Follins_angleAxis, function(s) c(s[1], s[2], s[3])), shapes = '.')\n\n# Plot a histogram of rotation amount between the northern domain and the southern domain, in degrees.\nhist(\n as.numeric(lapply(Follins_angleAxis, function(s)\n s[4] * 180 / pi)),\n 30,\n xlab = \"Angular Distance (degrees)\",\n ylab = \"Frequency\",\n main = \"Angular distances, Northern to Southern\"\n)\n\n# Compute the mean and 1-sigma standard deviation of the rotation amount, in Follins_angleAxisrees\nmean(sapply(Follins_angleAxis, function(s) s[4] * 180 / pi))\nsd(sapply(Follins_angleAxis, function(s) s[4] * 180 / pi))\n\n# Compute the mean trend and plunge in Follins_angleAxisrees\nFollins_axes <- lapply(Follins_angleAxis, function(s) c(s[1], s[2], s[3]))\nFollins_meanAxisDeg <- geoTrendPlungeDegFromCartesian(lower(lineProjectedMean(Follins_axes)))\n\n#Print the mean axis of rotation, in trend and plunge\nFollins_meanAxisDeg\n\n#==========================COMPARE FOLIATIONS FROM THE TWO DATASETS========================================\n\n# (Foliation-only vs. Foliation-lineation datasets)\n\n# 1) Three plots to compare the foliations of the Fols (Foliation only data set) and Follins (Foliation-lineation dataset) in the northern domain\n\n# Equal area plot of the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(Follins$pole[Follins_northCrit], Fols$pole[Fols_northCrit])\n\n# Equal area plot of the bootstrapped means for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n FollinFols_northBoots$bootstraps,\n Fols_northBoots$bootstraps\n)\n\n# Equal area plot of 95% confidence ellipses from bootstrapping for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n list(FollinFols_northBoots$center),\n list(Fols_northBoots$center),\n curves = list(FollinFols_northBoots$points,\n Fols_northBoots$points\n )\n)\n\n#————————————————————————————————————————————————————————————\n\n# 2) Three plots to compare the foliations of the Fols (Foliation only data set) and Follins (Foliation-lineation dataset) in the central domain\n\n# Equal area plot of the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n Follins$pole[Follins_centerCrit], \n Fols$pole[Fols_centerCrit]\n)\n\n# Equal area plot of the bootstrapped means for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n FollinFols_centerBoots$bootstraps,\n Fols_centerBoots$bootstraps\n)\n\n# Equal area plot of 95% confidence ellipses from bootstrapping for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n list(FollinFols_centerBoots$center),\n list(Fols_centerBoots$center),\n curves = list(FollinFols_centerBoots$points,\n Fols_centerBoots$points\n )\n)\n\n#————————————————————————————————————————————————————————————\n\n# 3) Three plots to compare the foliations of the Fols (Foliation only data set) and Follins (Foliation-lineation dataset) in the southern domain\n\n# Equal area plot of the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n Follins$pole[Follins_southCrit], \n Fols$pole[Fols_southCrit]\n)\n\n# Equal area plot of the bootstrapped means for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n FollinFols_southBoots$bootstraps,\n Fols_southBoots$bootstraps\n)\n\n# Equal area plot of 95% confidence ellipses from bootstrapping for the Fols (cyan) and Follins (red)\nlineEqualAreaPlotTwo(\n list(FollinFols_southBoots$center),\n list(Fols_southBoots$center),\n curves = list(FollinFols_southBoots$points,\n Fols_southBoots$points\n )\n)\n\n\n#==================================================================\n#==================================================================\n\n\n\n#==========================PART II: ORIENTATION STATISTICS ON FOLIATION-LINEATION PAIRS========================================\n\n#These are all foliation-lineation pairs, so they are orientation data. We will proced with methods outlined in Davis and Titus, 2017.\n\n#Since lines on foliation are bidirectional, these are line-in-plane data, and have a four fold symmetry (see Davis and Titus, 2017).\n\n#==========================PLOT THE DATA========================================\n\n# Plot the data in Equal area plot. Lineation (red), Pole to foliation (cyan)\nlineEqualAreaPlotTwo(\n Follins$direction, \n Follins$pole\n)\n\n# Plot the data in an Equal Volume Plot (after Davis and Titus, 2017). Each point represents a foliation-lineation pair. (There are four copies of the data due to mathematical symmetry)\noriEqualVolumePlot(\n Follins$rotation, \n oriLineInPlaneGroup\n)\n\n# We can also do some basic directional kamb contouring for poles and lines. The numbers are the kamb intervals\nlineKambPlot(\n Follins$pole, \n c(2, 4, 6, 8, 10, 12, 14, 18)\n)\nlineKambPlot(\n Follins$direction, \n c(2, 4, 6, 8, 10, 12, 14, 18)\n)\n\n# [!!!]NOTE: This line requires c library to run--skip if you have not compiled c.\n# [!!!]Uncomment lines below to Plot 6-sigma kamb contour in an Equal volume plot of Follins.\n\n# oricKambPlot(Follins$rotation,\n# group=oriLineInPlaneGroup,\n# multiple = 6,\n# simplePoints = TRUE,\n# backgroundColor=\"white\", curveColor=\"black\",\n# boundaryAlpha=0,\n# colors=\"black\", axesColors=c(\"black\", \"black\", \"black\"),\n# fogStyle=\"exp\")\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n\n# afterMaximizingWindow(\"WestMt_kamb_EqualVol1.png\", \"WestMt_kamb_EqualVol2.png\")\n\n\n#==========================IDENTIFY GEOGRAPHIC TRENDS========================================\n\n# 1) Visually inspect the possibility of geographic trends in the data\n\n# Plot an Equal Volume plot (after Davis and Titus, 2017), colored by the three domains. Northern (red); Central (green); Southern (blue).\noriEqualVolumePlot(\n Follins$rotation,\n group = oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.2,\n colors = hues(Follins$domain),\n axesColors = c(\"black\", \"black\", \"black\")\n)\n\n# Plot an Equal volume plot of the data, colored by northing\noriEqualVolumePlot(\n Follins$rotation,\n group = oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.2,\n colors = hues(Follins$northing),\n axesColors = c(\"black\", \"black\", \"black\")\n)\n\n# Plot an Equal volume plot of the data, colored by easting\noriEqualVolumePlot(\n Follins$rotation,\n group = oriLineInPlaneGroup,\n backgroundColor = \"white\",\n curveColor = \"black\",\n boundaryAlpha = 0.2,\n colors = hues(Follins$easting),\n axesColors = c(\"black\", \"black\", \"black\")\n)\n\n# Save EqualVolumePlot figure. If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\n \"WestMt_domains_EqualVol.png\",\n \"WestMt_domains_EqualVol.png\"\n)\n\n# Plot Follins in an Equal area plot, colored by domain. Lineation (squares); Foliation (circles)\nlineEqualAreaPlot(\n c(Follins$pole, Follins$direction),\n col = hues(Follins$domain),\n shapes = c(replicate(length(Follins$pole), \"c\"),\n replicate(length(Follins$direction), \"s\"))\n)\n\n#————————————————————————————————————————————————————————————\n\n# 2) Run regressions to quantify any extant trends.\n\n# 2A) Geodesic regression on all data. Perform a geodesic regression with respect to azimuths every 10 degrees. Each regression asks the question: \"does orientation change linearly with respect to an azimuth towards x degrees\"\nregressionSWestAll <- regressionSweep(Follins, 10, Follins_northCrit | Follins_centerCrit | Follins_southCrit , 0)\nwestAllRegSum <- data.frame(regressionSWestAll[[19]])\nnames(westAllRegSum) <- c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n\n# Plot the R^2 value (y-axis) as a function of the azimuth in degrees (x-axis)\nplot(\n as.vector(westAllRegSum[, 1]),\n as.vector(westAllRegSum[, 4]),\n main = \"Geodesic regressions (all Domains)\",\n xlab = \"Azimuth in degrees\",\n ylab = \"R-squared\"\n) \n\n#————————————————————————————————————————————————————————————\n\n#2B) Perform geodesic regressions on each domain\n\n# Perform a geodesic regression for the northern domain with respect to azimuths every 10 degrees.\nregressionSNorth <- regressionSweep(Follins, 10, Follins_northCrit, 0)\nNorthRegSum <- data.frame(regressionSNorth[[19]])\nnames(NorthRegSum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# Check that \"Error\" = 0, \"Min_Eigen\" always > 0.\nNorthRegSum\n\n# Plot the R^2 value (y-axis) as a function of the azimuth in degrees (x-axis)\nplot(\n as.vector(NorthRegSum$Azimuth),\n as.vector(NorthRegSum$R_squared),\n main = \"Geodesic regressions (Northern Domain)\",\n xlab = \"Azimuth in degrees\",\n ylab = \"R-squared\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# Perform a geodesic regression for the southern domain with respect to azimuths every 10 degrees.\nregressionSCenter <- regressionSweep(Follins, 10, Follins_centerCrit, 0)\nCenterRegSum <- data.frame(regressionSCenter[[19]])\nnames(CenterRegSum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# Check that \"Error\" = 0, \"Min_Eigen\" always > 0.\nCenterRegSum\n\n# Plot the R^2 value (y-axis) as a function of the azimuth in degrees (x-axis)\nplot(\n as.vector(CenterRegSum$Azimuth),\n as.vector(CenterRegSum$R_squared),\n main = \"Geodesic regressions (Central Domain)\",\n xlab = \"Azimuth in degrees\",\n ylab = \"R-squared\"\n) \n\n#————————————————————————————————————————————————————————————\n\n# Perform a geodesic regression for the southern domain with respect to azimuths every 10 degrees.\nregressionSSouth <- regressionSweep(Follins, 10, Follins_southCrit, 0)\nSouthRegSum <- data.frame(regressionSSouth[[19]])\nnames(SouthRegSum) = c(\"Azimuth\", \"Error\", \"Min_Eigen\", \"R_squared\", \"Pvalue\")\n\n# Check that \"Error\" = 0, \"Min_Eigen\" always > 0.\nSouthRegSum\n\n# Plot the R^2 value (y-axis) as a function of the azimuth in degrees (x-axis)\nplot(\n as.vector(SouthRegSum$Azimuth),\n as.vector(SouthRegSum$R_squared),\n main = \"Geodesic regressions (Southern Domain)\",\n xlab = \"Azimuth in degrees\",\n ylab = \"R-squared\"\n)\n\n#————————————————————————————————————————————————————————————\n\n# 3) Perform a Kernal regression for all Follins.\n\n# Recategorize the symmetric copies of the data.\nmu <- oriFrechetMean(Follins$rotation, group=oriLineInPlaneGroup)\nFollins$rotation <- oriNearestRepresentatives(Follins$rotation, mu, group=oriLineInPlaneGroup)\n\n# A precomputed value for bandwidth--use this value to save time.\n\nbandwidth <- 0.5879134\n\n# Uncomment line below to compute the appropriate bandwidth for Kernal regression with respect to easting.\nbandwidth <- rotBandwidthForKernelRegression(Follins$easting,Follins$rotation, dnorm)\n\n#Run the kernel regression to generate a bunch of points.There were no errors and all minEigenvalues were >0\nkernelReg <- lapply(\n seq(from = min(Follins$easting), to = max(Follins$easting), by = 100),\n rotKernelRegression,\n Follins$easting,\n Follins$rotation,\n bandwidth,\n numSteps = 1000\n)\nsapply(kernelReg, function(regr) regr$error)\nsapply(kernelReg, function(regr) {regr$minEigenvalue > 0})\n\n# Plot the regression curve.\nkernelRegCurve <- lapply(kernelReg, function(regr) regr$r)\noriEqualVolumePlot(\n kernelRegCurve, \n simplePoints = TRUE,\n oriLineInPlaneGroup\n)\n\n# Compute the R^2.\nKernRsquared <- rotRsquaredForKernelRegression(Follins$easting, Follins$rotation, bandwidth, numSteps =\n 1000)\nKernRsquared\n\n# Do a permutation test for significance. For the sake of time, we do only 10 permutations, although that is far too few to tell us anything.\nrSquareds <- rotKernelRegressionPermutations(Follins$easting, Follins$rotation, bandwidth, numPerms =\n 1000)\nlength(rSquareds)\np <- sum(rSquareds > KernRsquared$rSquared)\np\n\n\n#==========================STATISTICAL DESCRIPTORS========================================\n\n# 1) Northern Domain, n = 16\n\n# Frechet mean (minimizes the Frechet variance).\nFrechetMeanNorth <- oriFrechetMean(Follins$rotation[Follins_northCrit], oriLineInPlaneGroup)\nFrechetVarNorth <- oriVariance(Follins$rotation[Follins_northCrit], FrechetMeanNorth, oriLineInPlaneGroup)\n\n# Plot the FrechetMean in an Equal Volume plot\nFrechetCurvesNorth <- lapply(Follins$rotation[Follins_northCrit], function(r) rotGeodesicPoints(FrechetMeanNorth, r, 10))\nrotEqualAnglePlot(points = Follins$rotation[Follins_northCrit], curves = FrechetCurvesNorth)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanNorth)\n\n# Print the Frechet variance.\nFrechetVarNorth\n\n#————————————————————————————————————————————————————————————\n\n# 2) Central Domain, n = 34\n#Frechet mean minimizes the Frechet variance.\nFrechetMeanCenter <- oriFrechetMean(Follins$rotation[Follins_centerCrit], oriLineInPlaneGroup)\nFrechetVarCenter <- oriVariance(Follins$rotation[Follins_centerCrit], FrechetMeanCenter, oriLineInPlaneGroup)\n\n#plot the FrechetMean\nFrechetCurvesCenter <- lapply(Follins$rotation[Follins_centerCrit], function(r) rotGeodesicPoints(FrechetMeanCenter, r, 10))\nrotEqualAnglePlot(\n points = Follins$rotation[Follins_centerCrit], \n curves = FrechetCurvesCenter\n)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanCenter)\n\n# Print the Frechet variance.\nFrechetVarCenter\n\n#————————————————————————————————————————————————————————————\n\n# 3) Southern Domain, n = 79\n#Frechet mean minimizes the Frechet variance.\nFrechetMeanSouth <- oriFrechetMean(Follins$rotation[Follins_southCrit], oriLineInPlaneGroup)\nFrechetVarSouth <- oriVariance(Follins$rotation[Follins_southCrit], FrechetMeanSouth, oriLineInPlaneGroup)\n\n#plot the FrechetMean\nFrechetCurvesSouth <- lapply(Follins$rotation[Follins_southCrit], function(r) rotGeodesicPoints(FrechetMeanSouth, r, 10))\nrotEqualAnglePlot(points = Follins$rotation[Follins_southCrit], curves = FrechetCurvesSouth)\n\n# Print the Strike, Dip, Rake of the Frechet mean.\ngeoStrikeDipRakeDegFromRotation(FrechetMeanSouth)\n\n# Print the Frechet variance.\nFrechetVarSouth\n\n#————————————————————————————————————————————————————————————\n\n# 4) Dispersion of the data\n\n#The standard way to get at dispersion is to compute the maximum matrix fisher likelihood. The matrix fisher distribution comprises a kind of \"mean\" and a positive definite symmetric matrix, which characterises the anisotropic dispersion.\n\n# Northern Domain, n = 16. Fisher maximum likelihood\nmleNorth <- rotFisherMLE(Follins$rotation[Follins_northCrit])\nmleNorth\neigen(mleNorth$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n#Central Domain, n = 34. Fisher maximum likelihood\nmleCenter <- rotFisherMLE(Follins$rotation[Follins_centerCrit])\nmleCenter\neigen(mleCenter$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n#Southern Domain, n = 79. Fisher maximum likelihood\nmleSouth <- rotFisherMLE(Follins$rotation[Follins_southCrit])\nmleSouth\neigen(mleSouth$kHat, symmetric = TRUE, only.value = TRUE)$values\n\n\n\n#==========================INFERENCE + HYPOTHESIS TESTING========================================\n\n# Here, we can perform some statistical techniques to use information about the samples (each domain) to compute a probability cloud of the mean of the population(s) from which those samples were taken.\n# From numerical work in Davis and Titus (2017), MCMC will work the best for small sample sizes that have the matrix fisher anisotropy (eigenvalues) of (large, large, small). All four domains have this anisotropy, and have too few data points to use the (computationally quicker) bootstrapping method.\n\n#We'll do both and compare.\n\n# Compute the bootstrap cloud of means\nFollins_northBoots <- oriBootstrapInference(Follins$rotation[Follins_northCrit], 10000, oriLineInPlaneGroup)\nFollins_centerBoots <- oriBootstrapInference(Follins$rotation[Follins_centerCrit], 10000, oriLineInPlaneGroup)\nFollins_southBoots <- oriBootstrapInference(Follins$rotation[Follins_southCrit], 10000, oriLineInPlaneGroup)\n\n# [!!!] Requires C libraries to run. \n# [!!!] Compute the Markov chain Monte Carlo cloud of means\n# [!!!]Uncomment lines if you have compiled C on your computer and have loaded the C libraries at the top of this script.\n# \n# northMCMC <- oricWrappedTrivariateNormalMCMCInference(Follins$rotation[Follins_northCrit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100\n# )\n# centerMCMC <- oricWrappedTrivariateNormalMCMCInference(Follins$rotation[Follins_centerCrit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100\n# )\n# southMCMC <- oricWrappedTrivariateNormalMCMCInference(Follins$rotation[Follins_southCrit],\n# group = oriLineInPlaneGroup,\n# numCollection = 100\n# )\n\n#————————————————————————————————————————————————————————————\n\n# 1) Northern v. Central domains\n\n# A) Using MCMC\n\n# [!!!] Uncomment if you ran the MCMC lines above, which required C to be compiled on your system.\n# Construct the 95% confidence ellipsoids from small triangles\n# trisNorthMCMC <- rotEllipsoidTriangles(northMCMC$mBar,\n# northMCMC$leftCovarInv,\n# northMCMC$q095,\n# numNonAdapt = 4)\n# trisCenterMCMC <- rotEllipsoidTriangles(centerMCMC$mBar,\n# centerMCMC$leftCovarInv,\n# centerMCMC$q095,\n# numNonAdapt = 4)\n# Plot the MCMC comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(northMCMC$ms, centerMCMC$ms),\n# boundaryAlpha = .1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# triangles = c(trisNorthMCMC, trisCenterMCMC),\n# simplePoints = TRUE,\n# colors = c(replicate(length(northMCMC$ms), \"black\"), replicate(length(centerMCMC$ms), \"orange\")),\n# group = oriTrivialGroup\n# )\n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_WestMt_NC_1.png\", \"MCMC_WestMt_NC_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(northMCMC$ms, function(s) s[1,]),\n# lapply(northMCMC$ms, function(s) s[2,])\n# ),\n# c(\n# lapply(centerMCMC$ms, function(s) s[1,]),\n# lapply(centerMCMC$ms, function(s) s[2,])\n# ))\n\n#....................................................................\n\n# B) Using bootstrapping\n\n# Construct the 95% confidence ellipsoids from small triangles\ntrisNorthBoot <-\n rotEllipsoidTriangles(\n Follins_northBoots$center,\n Follins_northBoots$leftCovarInv,\n Follins_northBoots$q095,\n numNonAdapt = 4\n )\ntrisCenterBoot <-\n rotEllipsoidTriangles(\n Follins_centerBoots$center,\n Follins_centerBoots$leftCovarInv,\n Follins_centerBoots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\nrotEqualAnglePlot(\n points = c(\n Follins_northBoots$bootstraps,\n Follins_centerBoots$bootstraps\n ),\n triangles = c(trisNorthBoot, trisCenterBoot),\n boundaryAlpha = .1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_northBoots$bootstraps), \"black\"\n ), replicate(\n length(Follins_centerBoots$bootstraps), \"orange\"\n ))\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_WestMt_NC_1.png\", \"Boots_WestMt_NC_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_northBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_northBoots$bootstraps, function(s) s[2,])\n ),\n c(\n lapply(Follins_centerBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_centerBoots$bootstraps, function(s) s[2,])\n))\n\n#————————————————————————————————————————————————————————————\n\n# 2) Northern vs. Southern domains\n\n# A) Using MCMC\n\n# [!!!] Uncomment if you ran the MCMC lines above, which required C to be compiled on your system.\n# Construct the 95% confidence ellipsoids from small triangles\n# trisNorthMCMC <-\n# rotEllipsoidTriangles(northMCMC$mBar,\n# northMCMC$leftCovarInv,\n# northMCMC$q095,\n# numNonAdapt = 5)\n# trisSouthMCMC <-\n# rotEllipsoidTriangles(southMCMC$mBar,\n# southMCMC$leftCovarInv,\n# southMCMC$q095,\n# numNonAdapt = 5)\n# \n# # Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(northMCMC$ms, southMCMC$ms),\n# triangles = c(trisNorthMCMC, trisSouthMCMC),\n# boundaryAlpha = 0.1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# simplePoints = TRUE,\n# colors = c(replicate(length(northMCMC$ms), \"black\"), replicate(length(southMCMC$ms), \"blue\")),\n# group = oriTrivialGroup\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_WestMt_NS_1.png\", \"MCMC_WestMt_NS_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(northMCMC$ms, function(s)\n# s[1,]),\n# lapply(northMCMC$ms, function(s)\n# s[2,])\n# ),\n# c(\n# lapply(southMCMC$ms, function(s)\n# s[1,]),\n# lapply(southMCMC$ms, function(s)\n# s[2,])\n# ))\n\n#....................................................................\n\n# B) Using bootstrapping\n# Construct the 95% confidence ellipsoids from small triangles\ntrisNorthBoot <-\n rotEllipsoidTriangles(\n Follins_northBoots$center,\n Follins_northBoots$leftCovarInv,\n Follins_northBoots$q095,\n numNonAdapt = 4\n )\ntrisSouthBoot <-\n rotEllipsoidTriangles(\n Follins_southBoots$center,\n Follins_southBoots$leftCovarInv,\n Follins_southBoots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids.\nrotEqualAnglePlot(\n points = c(\n Follins_northBoots$bootstraps,\n Follins_southBoots$bootstraps\n ),\n triangles = c(trisNorthBoot, trisSouthBoot),\n boundaryAlpha = .1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_northBoots$bootstraps), \"black\"\n ),\n replicate(\n length(Follins_southBoots$bootstraps), \"blue\"\n ))\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_WestMt_NS_1.png\", \"Boots_WestMt_NS_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_northBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_northBoots$bootstraps, function(s) s[2,])\n ),\n c(\n lapply(Follins_southBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_southBoots$bootstraps, function(s) s[2,])\n))\n\n\n\n#————————————————————————————————————————————————————————————\n\n# 3) Central vs. Southern domains\n\n# A) Using MCMC\n# [!!!] Uncomment if you ran the MCMC lines above, which required C to be compiled on your system.\n# # Construct the 95% confidence ellipsoids from small triangles\n# trisCenterMCMC <-\n# rotEllipsoidTriangles(centerMCMC$mBar,\n# centerMCMC$leftCovarInv,\n# centerMCMC$q095,\n# numNonAdapt = 4)\n# trisSouthMCMC <-\n# rotEllipsoidTriangles(southMCMC$mBar,\n# southMCMC$leftCovarInv,\n# southMCMC$q095,\n# numNonAdapt = 4)\n# \n# # Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\n# oriEqualAnglePlot(\n# points = c(centerMCMC$ms, southMCMC$ms),\n# triangles = c(trisCenterMCMC, trisSouthMCMC),\n# boundaryAlpha = 0.1,\n# axesColors = c(\"black\", \"black\", \"black\"),\n# fogStyle = \"none\",\n# background = \"white\",\n# simplePoints = TRUE,\n# colors = c(replicate(length(centerMCMC$ms), \"orange\"), replicate(length(southMCMC$ms), \"blue\")),\n# group = oriTrivialGroup\n# )\n# \n# # If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\n# afterMaximizingWindow(\"MCMC_WestMt_CS_1.png\", \"MCMC_WestMt_CS_2.png\")\n# \n# # Plot the MCMC comparison in an Equal Area plot\n# lineEqualAreaPlotTwo(c(\n# lapply(centerMCMC$ms, function(s)\n# s[1,]),\n# lapply(centerMCMC$ms, function(s)\n# s[2,])\n# ),\n# c(\n# lapply(southMCMC$ms, function(s)\n# s[1,]),\n# lapply(southMCMC$ms, function(s)\n# s[2,])\n# ))\n\n#....................................................................\n\n\n# B) Using bootstrapping\n\n# Construct the 95% confidence ellipsoids from small triangles\ntrisCenterBoot <-\n rotEllipsoidTriangles(\n Follins_centerBoots$center,\n Follins_centerBoots$leftCovarInv,\n Follins_centerBoots$q095,\n numNonAdapt = 4\n )\ntrisSouthBoot <-\n rotEllipsoidTriangles(\n Follins_southBoots$center,\n Follins_southBoots$leftCovarInv,\n Follins_southBoots$q095,\n numNonAdapt = 4\n )\n\n# Plot the bootstrap comparison in an equal Volume plot, with 95% confidence ellipsoids\noriEqualAnglePlot(\n points = c(\n Follins_centerBoots$bootstraps,\n Follins_southBoots$bootstraps\n ),\n triangles = c(trisCenterBoot, trisSouthBoot),\n boundaryAlpha = 0.1,\n axesColors = c(\"black\", \"black\", \"black\"),\n fogStyle = \"none\",\n background = \"white\",\n simplePoints = TRUE,\n colors = c(replicate(\n length(Follins_northBoots$bootstraps), \"orange\"\n ), replicate(\n length(Follins_southBoots$bootstraps), \"blue\"\n )),\n group = oriTrivialGroup\n)\n\n# If you wish to save this figure, maximize the plot window on your screen before running this line. It will save to your working directory folder.\nafterMaximizingWindow(\"Boots_WestMt_CS_1.png\", \"Boots_WestMt_CS_2.png\")\n\n# Plot the bootstrap comparison in an Equal Area plot\nlineEqualAreaPlotTwo(c(\n lapply(Follins_centerBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_centerBoots$bootstraps, function(s) s[2,])\n ),\n c(\n lapply(Follins_southBoots$bootstraps, function(s) s[1,]),\n lapply(Follins_southBoots$bootstraps, function(s) s[2,])\n))\n", "meta": {"hexsha": "b801bbd4904a0b0f6676c130ebaa4844ec7204b3", "size": 42861, "ext": "r", "lang": "R", "max_stars_repo_path": "JSG_statisticalAnalysis_WestMountain.r", "max_stars_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_stars_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-01T13:18:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T13:18:38.000Z", "max_issues_repo_path": "JSG_statisticalAnalysis_WestMountain.r", "max_issues_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_issues_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JSG_statisticalAnalysis_WestMountain.r", "max_forks_repo_name": "nicolasmroberts/UtilityofStatistics_JSG2019", "max_forks_repo_head_hexsha": "6e6030e64b5747fa6184ac6dc0add6ba86ce17ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1320224719, "max_line_length": 301, "alphanum_fraction": 0.6491682415, "num_tokens": 11156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.642048243453644}} {"text": "#' Wrapper of constraints to constraint object\r\n#' @param A\r\n#' @param b\r\n#' @param meq\r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @seealso \\code{\\link{}}\r\n#' @keywords constraint\r\n#' @examples\r\n#' @export\r\nconstraints = function(A,b,meq)\r\n{\r\n list(A=A,b=b,meq=meq)\r\n}\r\n\r\n\r\n#' GMV Portfolio with Constraints\r\n#' @param cset, if cset = NULL, then unconstrained gmv\r\n#' @param wts.only, for back-test use default wts.only = T, for efficient frontier use wts.only = F\r\n#' @param digits\r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @keywords constraint\r\n#' @examples\r\n#' @export\r\ngmv = function(returns,cset=NULL,wts.only=T,digits = NULL)\r\n{\r\n\trequire(quadprog)\r\n\trequire(Rglpk)\r\n\trequire(corpcor)\r\n returns.old <- returns\r\n \r\n if (any(c(\"turnover.hobbs\",\"propcost\") %in% cset$clist.names)){\r\n returns <- cbind(returns,returns,returns) \r\n } \r\n\t\r\n\tmakenullmat <- function(A){matrix(0,nrow=nrow(A),ncol=ncol(A))}\r\n\t\r\n if (\"turnover\" %in% cset$clist.names){\r\n\t\treturns <- cbind(returns,makenullmat(returns),makenullmat(returns)) \r\n\t} \r\n\t\r\n cov.mat <- cov(returns)\r\n Dmat <- 2*cov.mat\r\n #Make covariance positive definite\r\n #This should barely change the covariance matrix, as\r\n #the last few eigen values are very small negative numbers\r\n Dmat <- make.positive.definite(Dmat)\r\n mu <- apply(returns,2,mean)\r\n #no linear part in this problem\r\n p = ncol(returns)\r\n if(is.null(cset))\r\n {A = matrix(rep(1,p),ncol =1)\r\n b = 1\r\n meq = 1} else\r\n {A = cset$A\r\n b = cset$b\r\n meq = cset$meq}\r\n dvec <- rep(0,nrow(A))\r\n \r\n port.gmv = solve.QP(Dmat,dvec,A,b,meq)\r\n wts = port.gmv$solution # Get optimal weights\r\n \r\n if (any(c(\"turnover.hobbs\",\"propcost\") %in% cset$clist.names)){\r\n wts = wts[1:(p/3)]+wts[(p/3+1):(p/3*2)]+wts[(p/3*2+1):p]\r\n mu = sum(wts*mu[1:(p/3)])\r\n wts = as.matrix(wts)\r\n sd = as.numeric(sqrt((t(wts)%*%cov(returns.old)%*%wts)))\r\n wts = as.numeric(wts)\r\n names(wts)= dimnames(returns.old)[[2]]\r\n } \r\n\telse if(\"turnover\" %in% cset$clist.names){\r\n\t\twts = wts[1:(p/3)]\r\n\t\tmu = sum(wts*mu[1:(p/3)])\r\n\t\twts = as.matrix(wts)\r\n\t\tsd = as.numeric(sqrt((t(wts)%*%cov(returns.old)%*%wts)))\r\n\t\twts = as.numeric(wts)\r\n\t\tnames(wts)= dimnames(returns.old)[[2]]\r\n\t} \r\n\telse{ \r\n mu = sum(wts*mu)\r\n wts = as.matrix(wts)\r\n sd = as.numeric(sqrt((t(wts)%*%cov.mat%*%wts)))\r\n wts = as.numeric(wts)\r\n names(wts)= dimnames(returns)[[2]] }\r\n \r\n if(!is.null(digits)){\r\n out = list(WTS = wts,MU.PORT = mu,SD.PORT = sd)\r\n lapply(out,round,digits)} else\r\n {if(wts.only) wts else mu}\r\n}\r\n\r\n#' Compute the minimu of mean return using GMV\r\n#' @param returns\r\n#' @param cset\r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @seealso \\code{\\link{}}\r\n#' @keywords constraint\r\n#' @examples\r\n#' @export\r\nminmu = function(returns, cset = NULL)\r\n{\r\n gmv(returns,cset,wts.only = F)\r\n}\r\n\r\n\r\n#' Compute the Max Mean Return Portfolio with Constraints\r\n#' This is primarily to compute the maximum mean return with constraints\r\n#' @param returns\r\n#' @param cset\r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @seealso \\code{\\link{}}\r\n#' @keywords constraint\r\n#' @examples\r\n#' @export\r\nmaxmu = function(returns,cset,mu.only=TRUE,digits = NULL,verbose = FALSE)\r\n{\r\n returns.old <- returns\r\n \r\n# if (any(c(\"turnover\",\"propcost\") %in% cset$clist.names)){\r\n# returns <- cbind(returns,returns,returns) \r\n# } \r\n# \r\n cov.mat <- cov(returns)\r\n Dmat <- 2*cov.mat\r\n #Make covariance positive definite\r\n #This should barely change the covariance matrix, as\r\n #the last few eigen values are very small negative numbers\r\n Dmat <- make.positive.definite(Dmat)\r\n mu <- apply(returns,2,mean)\r\n\r\n p = ncol(returns)\r\n if(is.null(cset))\r\n {A = matrix(rep(1,p),ncol =1)\r\n b = 1\r\n meq = 1} else\r\n {\r\n A = cset$A\r\n b = cset$b\r\n meq = cset$meq\r\n }\r\n d = mu\r\n A = t(A) # Because solve.QP uses the transpose of A\r\n if(meq>0)\r\n dir = c(rep(\"==\",meq),rep(\">=\",length(b)-meq)) else\r\n dir = c(rep(\">=\",length(b)-meq)) \r\n# \r\n# A <- A[-(1:4),]\r\n# b <- b[-(1:4)]\r\n# dir <- dir[-(1:4)] \r\n port.maxmu = Rglpk_solve_LP(d,A,dir,b,max = TRUE,verbose = verbose)\r\n # Rglpk doesn't work with turnover/propcost\r\n if(port.maxmu$status!=0)\r\n warning(\"consider possibly relaxing constraints\")\r\n wts = port.maxmu$solution # Get optimal weights\r\n \r\n# \r\n# if (any(c(\"turnover\",\"propcost\") %in% cset$clist.names)){\r\n# wts = wts[1:(p/3)]+wts[(p/3+1):(p/3*2)]+wts[(p/3*2+1):p]\r\n# mu = sum(wts*mu[1:(p/3)])\r\n# wts = as.matrix(wts)\r\n# sd = as.numeric(sqrt((t(wts)%*%cov(returns.old)%*%wts)))\r\n# wts = as.numeric(wts)\r\n# names(wts)= dimnames(returns.old)[[2]]\r\n# } else{ \r\n mu = sum(wts*mu)\r\n wts = as.matrix(wts)\r\n sd = as.numeric(sqrt((t(wts)%*%cov.mat%*%wts)))\r\n wts = as.numeric(wts)\r\n names(wts)= dimnames(returns)[[2]] \r\n\r\n# }\r\n if(!is.null(digits)){\r\n out = list(WTS = wts,MU.PORT = mu,SD.PORT = sd)\r\n lapply(out,round,digits)} else\r\n {if(mu.only) mu else wts}\r\n}\r\n\r\n\r\n#' MVO Portfolio with Constraints\r\n#' @param returns\r\n#' @param mu0\r\n#' @param cset\r\n#' @param wts.only\r\n#' @author Kirk Li \\email{kirkli@@stat.washington.edu} \r\n#' @seealso \\code{\\link{}}\r\n#' @keywords constraint\r\n#' @examples\r\n#' @export\r\nmvo = function(returns,mu0,cset=NULL,wts.only=T,digits = NULL)\r\n{\r\n \r\n if(c(\"mu.target\") %in% cset$clist.names)\r\n stop(\"mvo can not handel mu.target constraint\")\r\n \r\n returns.old <- returns\r\n \r\n if (any(c(\"turnover.hobbs\",\"propcost\") %in% cset$clist.names)){\r\n returns <- cbind(returns,returns,returns) \r\n } \r\n \r\n \r\n makenullmat <- function(A){matrix(0,nrow=nrow(A),ncol=ncol(A))}\r\n \r\n \r\n if (\"turnover\" %in% cset$clist.names){\r\n\t returns <- cbind(returns,makenullmat(returns),makenullmat(returns)) \r\n } \r\n \r\n cov.mat <- cov(returns)\r\n Dmat <- 2*cov.mat\r\n #Make covariance positive definite\r\n #This should barely change the covariance matrix, as\r\n #the last few eigen values are very small negative numbers\r\n Dmat <- make.positive.definite(Dmat)\r\n mu <- apply(returns,2,mean)\r\n \r\n p = ncol(returns)\r\n if(is.null(cset))\r\n {A = cbind(mu,matrix(rep(1,p),ncol =1))\r\n b = c(mu0,1)\r\n meq = 2} else\r\n {A = cbind(mu,cset$A)\r\n b = c(mu0,cset$b)\r\n meq = cset$meq+1}\r\n dvec <- rep(0,nrow(A)) #no linear part in this problem\r\n port.gmv = solve.QP(Dmat,dvec,A,b,meq)\r\n wts = port.gmv$solution # Get optimal weights\r\n \r\n if (any(c(\"turnover.hobbs\",\"propcost\") %in% cset$clist.names)){\r\n wts = wts[1:(p/3)]+wts[(p/3+1):(p/3*2)]+wts[(p/3*2+1):p]\r\n mu = sum(wts*mu[1:(p/3)])\r\n wts = as.matrix(wts)\r\n sd = as.numeric(sqrt((t(wts)%*%cov(returns.old)%*%wts)))\r\n wts = as.numeric(wts)\r\n names(wts)= dimnames(returns.old)[[2]]\r\n } else if(\"turnover\" %in% cset$clist.names){\r\n\t wts = wts[1:(p/3)]\r\n\t mu = sum(wts*mu[1:(p/3)])\r\n\t wts = as.matrix(wts)\r\n\t sd = as.numeric(sqrt((t(wts)%*%cov(returns.old)%*%wts)))\r\n\t wts = as.numeric(wts)\r\n\t names(wts)= dimnames(returns.old)[[2]]\r\n } else{ \r\n mu = sum(wts*mu)\r\n wts = as.matrix(wts)\r\n sd = as.numeric(sqrt((t(wts)%*%cov.mat%*%wts)))\r\n wts = as.numeric(wts)\r\n names(wts)= dimnames(returns)[[2]] }\r\n \r\n if(!is.null(digits)){\r\n out = list(WTS = wts,MU.PORT = mu,SD.PORT = sd)\r\n lapply(out,round,digits)} else\r\n {if(wts.only) wts else c(mu,sd,wts)}\r\n}\r\n", "meta": {"hexsha": "0245bfc82aa9fd90926cd4a003d0865dce549890", "size": 7527, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mvo.constrained.r", "max_stars_repo_name": "kecoli/PCRM", "max_stars_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-15T15:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-15T15:17:44.000Z", "max_issues_repo_path": "R/mvo.constrained.r", "max_issues_repo_name": "kecoli/PCRM", "max_issues_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_issues_repo_licenses": ["MIT"], "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/mvo.constrained.r", "max_forks_repo_name": "kecoli/PCRM", "max_forks_repo_head_hexsha": "6603978752abbf33b40c0ea2ca4706d0a9393e2a", "max_forks_repo_licenses": ["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.6338582677, "max_line_length": 100, "alphanum_fraction": 0.5850936628, "num_tokens": 2546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6419093756796673}} {"text": "# VREDNOTENJE EKSOTIČNIH OPCIJ\n# Finančni praktikum 2020/21\n# Mitja Mandić\n\n\n\n\nlibrary(combinat)\nlibrary(Rlab)\n\n#PRVA NALOGA\n\n#Pot opcije, izplačilo prodajne, izplačilo nakupne\nprva.opcija <- c(50.00,52.50,49.88,52.37,49.75,52.24) #0, 0\ndruga.opcija <- c(50.00,52.50,55.12,57.88,60.78,63.81) #7.88,8.69\ntretja.opcija <- c(50.00,47.50,49.88,47.38,45.01,42.76) #0,0\ncetrta.opcija <- c(50.00,47.50,45.12,47.38,49.75,52.24) #2.26, 2.24\npeta.opcija <- c(50.00,52.50,49.88,52.37,54.99,57.74) #2.49, 5.24\n\n\n\nizplacilo <- function(vrsta, T, type){\n #če je opcija nakupna, odštevamo maksimume\n if(type == \"call\"){\n denar <- max((max(vrsta[(T+1):length(vrsta)]) - max(vrsta[1:T])),0)\n }\n #sicer odštevamo minimume\n else if(type == \"put\"){\n denar <- max((min(vrsta[(T+1):length(vrsta)]) - min(vrsta[1:T])),0)\n }\n return(denar)\n}\n\n\n#DRUGA NALOGA\n\n\n\nbinomski <- function(S0, u, d, U, R, T, type){\n q = (1 + R - d)/(u - d)\n \n diskontni.faktor <- 1/(1+R)^U\n \n #pripravimo si vse možne poti opcije\n \n poti <- hcube(rep(2,U), translation = -1) * u\n poti[poti < 1] <- d\n \n \n #pripravimo si posebno tabelo z verjetnostmi, dejansko nas pa zanima le vrednost zadnjega stolpca\n verjetnosti <- poti\n verjetnosti[verjetnosti == u] <- q\n verjetnosti[verjetnosti == d] <- 1-q\n \n #verjetnosti zmnožimo\n verjetnosti <- cbind(1,verjetnosti)\n verjetnosti <- t(apply(verjetnosti,1,cumprod))\n \n #sestavimo skupaj poti opcije in začetno vrednost, vse zmožimo\n cenovni.procesi <- cbind(S0, poti)\n \n cenovni.procesi <- t(apply(cenovni.procesi,1,cumprod))\n\n \n izplacila <- rep(0,length(cenovni.procesi[,1]))\n \n #izplačamo glede na tip opcije\n for(i in 1:length(cenovni.procesi[,1])){\n izplacila[i] <- izplacilo(cenovni.procesi[i,],T,type)\n }\n \n pricakovana.izplacila <- izplacila * verjetnosti[,U+1]\n \n premija <- sum(pricakovana.izplacila) * diskontni.faktor\n \n\n return(premija)\n}\n\n\n#druga b\n\nmonte <- function(S0,u,d,U,R,T,type,N){\n #pripravimo si začetne podatke\n q = (1+R-d)/(u-d)\n\n diskontni.faktor <- 1/(1+R)^U\n \n izplacila <- rep(0,N)\n \n #ponavljamo N-krat\n for (i in 1:N){\n #vzorec simuliramo glede na do tveganja nevtralno verjetnost\n vzorec <- sample(c(u,d), (U-1), replace = TRUE, prob = c(q,1-q))\n \n #sestavimo cenovni proces za ta vzorec poti\n cenovni.proces <- cumprod(append(S0, vzorec))\n \n #sestavljamo vektor izplačil\n izplacila[i] <- izplacilo(cenovni.proces,T,type) #* verjetnost\n \n }\n #vse skupaj povprečimo in dobimo rezultat\n povp1 <- 1/N\n \n pricakovana.izplacila <- sum(izplacila)\n \n premija <- sum(izplacila) * povp1 * diskontni.faktor\n \n return(premija)\n}\n\n\n#TRETJA NALOGA\n\n#Vrednostenje opcije po binomskem modelu\n\npo.modelu <- binomski(60,1.05,0.95,15,0.01,8,\"put\")\n\n#ponavljanje Monte carlo simulacij\n\ndesetkrat <- rep(0,100)\nstokrat <- rep(0,100)\ntisockrat <- rep(0,100)\nfor (i in 1:100) {\n desetkrat[i] <- monte(60,1.05,0.95,15,0.01,8,\"put\",10)\n stokrat[i] <- monte(60,1.05,0.95,15,0.01,8,\"put\",100)\n tisockrat[i] <- monte(60,1.05,0.95,15,0.01,8,\"put\",1000)\n}\n\n\n#Histogram desetkratne Monte carlo metode\nvar.desetkrat <- var(desetkrat)\npovp.desetkrat <- mean(desetkrat)\n\n\nhist(desetkrat,freq = 10, xlim = c(0,10), main = paste(\"Monte Carlo: N = 10\"), col = \"pink\")\nabline(v = povp.desetkrat,col = \"blue\",lwd=2)\nabline(v = po.modelu, col = \"green\", lty = 2)\narrows(x0=povp.desetkrat, y0=0, x1 = povp.desetkrat + var.desetkrat, col=\"blue\", length=0.1, lwd = 2)\narrows(x0=povp.desetkrat, y0=0, x1=povp.desetkrat - var.desetkrat, col=\"blue\", length=0.1, lwd = 2)\nlegend(\"topright\", legend=c(\"Monte Carlo\", \"analiza modela\"), col=c(\"blue\",\"green\"), lty=c(\"solid\",\"dashed\"), cex=0.9)\n\n#Histogram 100-kratne\nvar.stokrat <- var(stokrat)\npovp.stokrat <- mean(stokrat)\n\n\nhist(stokrat,freq = 10, xlim = c(0,10),main = paste(\"Monte Carlo: N = 100\"), col =\"pink\")\nabline(v = povp.stokrat, col = \"blue\",lwd=2)\nabline(v = po.modelu, col = \"green\",lty = 2)\narrows(x0=povp.stokrat, y0=0, x1 = povp.stokrat + var.stokrat, col=\"blue\", length=0.1, lwd = 2)\narrows(x0=povp.stokrat, y0=0, x1=povp.stokrat - var.stokrat, col=\"blue\", length=0.1, lwd = 2)\nlegend(\"topright\", legend=c(\"Monte Carlo\", \"analiza modela\"), col=c(\"blue\",\"green\"), lty=c(\"solid\",\"dashed\"), cex=0.9)\n\n#Histogram 1000 kratne\n\nvar.tisockrat <- var(tisockrat)\npovp.tisockrat <- mean(tisockrat)\n\nhist(tisockrat,freq = 10, xlim = c(0,10),main = paste(\"Monte Carlo: N = 1000\"), col = \"pink\")\nabline(v = mean(tisockrat), col = \"blue\",lwd=2)\nabline(v = po.modelu, col = \"green\",lty = 2)\narrows(x0=povp.tisockrat, y0=0, x1 = povp.tisockrat + var.tisockrat, col=\"blue\", length=0.1, lwd = 2)\narrows(x0=povp.tisockrat, y0=0, x1 = povp.tisockrat - var.tisockrat, col=\"blue\", length=0.1, lwd = 2)\nlegend(\"topright\", legend=c(\"Monte Carlo\", \"analiza modela\"), col=c(\"blue\",\"green\"), lty=c(\"solid\",\"dashed\"), cex=0.9)\n\n\n\n\n\n\n", "meta": {"hexsha": "0d1503ffe11a4d32c0bc1dca12f6eb71a3fb7641", "size": 4859, "ext": "r", "lang": "R", "max_stars_repo_path": "tretja_naloga/Mandic3.r", "max_stars_repo_name": "mitja-mandic/financni-praktikum", "max_stars_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tretja_naloga/Mandic3.r", "max_issues_repo_name": "mitja-mandic/financni-praktikum", "max_issues_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tretja_naloga/Mandic3.r", "max_forks_repo_name": "mitja-mandic/financni-praktikum", "max_forks_repo_head_hexsha": "fe7ececd401b7a002b9e11bd69938ba98a96a081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0867052023, "max_line_length": 118, "alphanum_fraction": 0.654661453, "num_tokens": 2101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6416450260492342}} {"text": "#--------------------------------------------------------------------------\n# formant -- Formant response spectrum\n#\n# Calculate a single-formant impulse response function given the formant \n# frequency (f), bandwidth (b), the number of points in the spectrum (np),\n# and the maximum frequency.\n#\n# 12/23/19 -- htb\n# Added scale option set to default to FALSE. If true, call frmAmpCorr()\n# to obtain a scaling factor based on the frequency and bandwidth that\n# can be applied to force unity gain for the resonator at the resonant\n# frequency.\n#\n\nformant <- function(f, b, np, maxf, scale=FALSE) {\n if (length(f) != length(b) && length(b) > 1)\n return(print(\"formant: number of bandwidths != number of formants\"))\n\n s <- matrix(seq(0, maxf, maxf/np),nrow=length(f),\n ncol=np+1, byrow=TRUE)\n if (scale)\n scale = 1/frmAmpCorr(f, b)\n else\n scale = 1.0\n\n bsq <- .25 * b^2\n anum <- (f^2 + bsq)\n return(scale * anum / sqrt(((s-f)^2 + bsq) * ((s+f)^2 + bsq)))\n}\n\nformant1d <- function(f, b, np, maxf) {\n#\n# Calculate a single-formant response function given the\n# formant frequency (f), bandwidth (b), the number of points\n# in the spectrum (np), and the maximum frequency.\n#\n s <- seq(0, maxf, maxf/np)\n bsq <- .25 * b^2\n fsq <- f^2\n fdif <- s - f\n fsum <- s + f\n a <- fdif^2 + bsq\n b <- fsum^2 + bsq\n step1 <- 2.0 * f / sqrt(a*b)\n step2 <- (fsq + bsq) * (a*fsum - b*fdif) / (a*b)^1.5\n return (step1 - step2)\n}\n\nband1d <- function(f, b, np, maxf) {\n#\n# Calculate a single-formant response function given the\n# formant frequency (f), bandwidth (b), the number of points\n# in the spectrum (np), and the maximum frequency.\n#\n s <- seq(0, maxf, maxf/np)\n bsq <- .25 * b^2\n bo2 <- 0.5 * b\n fsq <- f^2\n fdif <- s - f\n fsum <- s + f\n a <- fdif^2 + bsq\n b <- fsum^2 + bsq\n step1 <- bo2 / sqrt(a*b)\n step2 <- (fsq + bsq) * bo2 * (a+b) / (2.0*(a*b)^1.5)\n return (step1 - step2)\n}\n\nhpc1 <- function(nf, f, f1) {\n#\n# This is the higher pole correction originally given by\n# Fant (1960) Acoustic Theory of Speech Production\n#\n s <- pi^2/8\n for (j in c(1:nf)) {\n s <- s - 1.0/(j*2 - 1)^2\n }\n fr <- f/f1\n return(exp(fr^2 * s))\n}\n\nhpc2 <- function(nf, f, f1) {\n#\n# This is the second order higher pole correction given by\n# Gold & Rabiner (1968) Analysis of Digital and Analog Formant\n# Synthesizers. IEEE Transactions on Audio and Electroacoustics,\n# 16, 81-94.\n#\n s <- pi^2/8\n t <- pi^4/96\n for (j in c(1:nf)) {\n s <- s - 1.0/(j*2 - 1)^2\n t <- t - 1.0/(j*2 - 1)^4\n }\n fr <- f/f1\n return(exp(fr^2 * s + 0.5 * fr^4 * t))\n}\n\nhpc3 <- function(nf, f, f1) {\n#\n# This is the second order higher pole correction given by\n# Gold & Rabiner (1968) Analysis of Digital and Analog Formant\n# Synthesizers. IEEE Transactions on Audio and Electroacoustics,\n# 16, 81-94.\n#\n x <- c(0.23370055, 0.01467803,0.122589439,0.002332353,0.0825894390,\n 0.0007323526,0.0621812758,0.0003158595,0.0498355967,0.0001634437,\n 4.157113e-02,9.514233e-05,3.565397e-02,6.012955e-05,3.120953e-02,\n 4.037646e-05)\n dim(x) = c(2,8)\n x = t(x)\n s = x[nf,1]\n t = x[nf,2]\n fr <- f/f1\n return(exp(fr^2 * s + 0.5 * fr^4 * t))\n}\n\nfrmnt <- function(f, ff, fb)\n{\n if (ff < 0.0) {\n ff = abs(ff)\n pole = F\n } else {\n pole = T\n }\n bsq <- 0.25 * fb^2\n w <- ff^2 + bsq\n if (pole)\n return (w / sqrt(((f - ff)^2 + bsq) * ((f + ff)^2 + bsq)))\n else\n return (sqrt(((f - ff)^2 + bsq) * ((f + ff)^2 + bsq)) / w)\n}\n \n#----------------------------------------------------------------------------\n# frmAmpCorr -- Formant Amplitude Correction\n#\n# The amplitude of a resonator is proportional to both its frequency and\n# bandwidth. This function is designed to calculate a scaling factor that\n# will compensate both frequency and bandwidth factors to result in unit\n# amplitude at the resonator center frequency (i.e. amplitude = 1.0 at\n# the resonator characteristic frequency).\n#\n# The amplitude at the resonant frequency is inversely proportional to the\n# bandwidth plus a constant offset that is a nonlinear function of the\n# bandwidth. The latter function is approximated here via a 4th order\n# polynomial.\n#\n# See also: function formant() that calculates the discrete spectrum of the\n# resonator impulse response given the resonator frequency and bandwidth as\n# well as the bandwidth of the spectrum and the number of discrete spectral\n# bins. The formant function now also includes a scale argument that\n# defaults to FALSE for compatibility with previous versions of the function.\n# If scale=TRUE, the amplitude spectrum is scaled to have unit gain at the\n# resonator frequency.\n#\n# 12/23/19 -- htb original code\n# coe <- c(-1.683882e-03,4.234928e-04,-1.231765e-07,2.421068e-11,-2.066097e-15)\n# m <- 1.0 / band\n# b <- coe[1] + coe[2]*band + coe[3]*band^2 + coe[4]*band^3 + coe[5]*band^4\n# cat(paste0(\"m = \",m,\"; b = \",b,\"\\n\"))\n# amp <- m*freq + b\n# return(amp)\n#\n# 5/5/20 -- htb\n# After looking at the actual formula in formant(), I realized that I was\n# swatting flies with a cannon and replaced the 4th order polynomial fit\n# from the original code, with a simple closed-form exact calculation.\n# YEESH!!\n#\n#---------------------------------------------------------------------------\n#\nfrmAmpCorr <- function(f, b) {\n bsq <- .25 * b^2\n anum <- (f^2 + bsq)\n return(anum / sqrt(bsq * ((f+f)^2 + bsq)))\n}\n", "meta": {"hexsha": "e0b69a01065b4dc5648cef5879bebdf65953af16", "size": 5376, "ext": "r", "lang": "R", "max_stars_repo_path": "R/formant.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/formant.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/formant.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": 30.5454545455, "max_line_length": 80, "alphanum_fraction": 0.607328869, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6414286402976851}} {"text": "## create variable y, such that cor(x,y) == r\nrcor <- function(x,r) {\n e <- rnorm(length(x), mean=0, sd=sqrt(1-r^2))\n mx <- mean(x)\n sx <- sd(x)\n s <- (x-mx)/sx\n (r*s + e)*sx + mx\n}\n\n## create a variable that is correlated with a CpG site s\n## and only correlated with surrounding CpG sites to the\n## extent that they are correlated with site s.\ngenerate.fake.bump.var <- function(mat, chr, pos, cluster.sites=40, bump.sites=20, cluster.position=0.5, r=0.5, maxgap=500) {\n stopifnot(bump.sites <= cluster.sites)\n stopifnot(cluster.position >= 0 && cluster.position <= 1)\n stopifnot(r >= 0 && r <= 1)\n ## identify clusters\n clusters <- ewaff:::bh.clusterMaker(chr, pos, maxGap=maxgap)\n cluster.size <- table(clusters)\n \n stopifnot(length(which(cluster.size >= cluster.sites)) > 0)\n \n cluster.size <- cluster.size[which(cluster.size >= cluster.sites)]\n\n ## select a cluster\n cluster <- sample(names(cluster.size), 1)\n\n ## indices of cpg sites in the cluster\n cluster.idx <- which(clusters==cluster)\n\n ## indices of cpg sites in the bump within in the cluster\n bump.center <- max(1, floor(length(cluster.idx)*cluster.position))\n bump.start <- max(1, bump.center - floor(bump.sites/2))\n bump.end <- min(length(cluster.idx), bump.start + bump.sites -1)\n bump.idx <- cluster.idx[bump.start:bump.end]\n\n ## standardize methylation levels\n mat.scaled <- t(scale(t(mat[bump.idx,])))\n\n ## identify the middle CpG site, it will be associated with the variable of interest\n site.idx <- which(bump.idx == cluster.idx[bump.center])\n\n ## calculate correlation of other CpG sites with the middle CpG site\n r.sites <- apply(mat.scaled, 1, function(mat) cor(mat, mat.scaled[site.idx,]))\n\n ## generate 100 variables associated with the middle CpG site\n vars <- sapply(1:100, function(i) rcor(mat.scaled[site.idx,], r))\n ## calculate correlation of each variable with each cpg site in the 'bump'\n vars.r <- apply(vars, 2, function(var) apply(mat.scaled, 1, function(mat) cor(mat, var)))\n ## pick the variable that most resembles the relationship of the middle CpG site with the other bump cpG sites\n var.idx <- which.max(apply(vars.r, 2, function(var.r) cor(var.r, r.sites)))\n var <- vars[,var.idx]\n list(var=var, bump.idx=bump.idx, cluster.idx=cluster.idx)\n}\n\n## create a variable that corresponds to a true bump\ngenerate.true.bump.var <- function(mat, chr, pos, cluster.sites=40, bump.sites=20, cluster.position=0.5, r=0.5, maxgap=500) {\n stopifnot(bump.sites <= cluster.sites)\n stopifnot(cluster.position >= 0 && cluster.position <= 1)\n stopifnot(r >= 0 && r <= 1)\n ## identify clusters\n clusters <- ewaff:::bh.clusterMaker(chr, pos, maxGap=maxgap)\n cluster.size <- table(clusters)\n cluster.size <- cluster.size[which(cluster.size >= cluster.sites)]\n\n ## select a cluster\n cluster <- sample(names(cluster.size), 1)\n\n ## indices of cpg sites in the cluster\n cluster.idx <- which(clusters==cluster)\n\n ## indices of cpg sites in the bump within in the cluster\n bump.center <- max(1, floor(length(cluster.idx)*cluster.position))\n bump.start <- max(1, bump.center - floor(bump.sites/2))\n bump.end <- min(length(cluster.idx), bump.start + bump.sites -1)\n bump.idx <- cluster.idx[bump.start:bump.end]\n\n ## sum CpG sites after scaling methylation\n bump.mat <- t(scale(t(mat[bump.idx,,drop=F])))\n bump.avg <- colSums(bump.mat)\n\n ## create a random variable correlated with the sum\n var <- rcor(bump.avg,r)\n \n list(var=var, bump.idx=bump.idx, cluster.idx=cluster.idx)\n}\n\ngenerate.spatial <- function(x, distance) {\n mean.cor <- function(distance) 1/exp(distance/200)\n r <- rnorm(1, mean=mean.cor(distance), sd=0.15)\n if (r < -1) r <- -1\n if (r > 1) r <- 1\n rcor(x, r)\n}\n\ngenerate.methylation <- function(n, pos) {\n cpg.mean <- rep(NA, length(pos))\n cpg.mean[1] <- runif(1)\n cpg.change <- rnorm(length(pos), sd=0.1)\n for (i in 2:length(cpg.mean)) {\n new <- cpg.mean[i-1] + cpg.change[i]\n if (new < 0 | new > 1) cpg.change[i] <- -cpg.change[i]\n cpg.mean[i] <- cpg.mean[i-1] + cpg.change[i]\n }\n \n cpg.sd <- rnorm(length(pos), mean=0.2, sd=0.025)\n \n methylation <- matrix(NA, ncol=n, nrow=length(pos))\n methylation[1,] <- rnorm(ncol(methylation))\n distance <- tail(pos,-1) - head(pos,-1)\n for (i in 2:nrow(methylation))\n methylation[i,] <- generate.spatial(methylation[i-1,], distance[i-1])\n\n methylation <- t(scale(t(methylation)))\n methylation <- methylation*cpg.sd + cpg.mean\n idx <- which(methylation < 0 | methylation > 1, arr.ind=T)[,1]\n for (i in unique(idx)) {\n med.cpg <- median(methylation[i,])\n min.cpg <- min(methylation[i,])\n max.cpg <- max(methylation[i,])\n factor.min <- med.cpg/(med.cpg - min.cpg)\n factor.max <- (1-med.cpg)/(max.cpg - med.cpg)\n factor <- 1\n if (min.cpg < 0) factor <- min(factor.min, factor)\n if (max.cpg > 1) factor <- min(factor.max, factor) \n methylation[i,] <- (methylation[i,] - med.cpg)*factor + med.cpg\n }\n methylation\n}\n\n\n\n", "meta": {"hexsha": "cdbaefa25869162aaad266fcc8b437ee54314880", "size": 5183, "ext": "r", "lang": "R", "max_stars_repo_path": "tests/simulation-functions.r", "max_stars_repo_name": "perishky/ewaff", "max_stars_repo_head_hexsha": "80d181416d5eeb2fabb1b0daf522598d06f1aa3e", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-08T06:12:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T06:12:00.000Z", "max_issues_repo_path": "tests/simulation-functions.r", "max_issues_repo_name": "perishky/ewaff", "max_issues_repo_head_hexsha": "80d181416d5eeb2fabb1b0daf522598d06f1aa3e", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-12-04T15:29:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:27:13.000Z", "max_forks_repo_path": "tests/simulation-functions.r", "max_forks_repo_name": "perishky/ewaff", "max_forks_repo_head_hexsha": "80d181416d5eeb2fabb1b0daf522598d06f1aa3e", "max_forks_repo_licenses": ["Artistic-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.969924812, "max_line_length": 125, "alphanum_fraction": 0.63341694, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.641386291241789}} {"text": "#\n#\n\neuclidian.distance <- function (a,b) {\n sqrt (sum((a - b) * (a -b)))\n}\nlog.message <- function (a){\n cat (sprintf (\"\\n**** %s\\n\", a))\n}\n\nis.multiple <- function (a ,b) {\n abs(a - round (a / b) * b) < 1e-6\n}\n\nerror.mat <- function (name, h) {\n tab <- as.matrix (read.table (name))\n\n dim <- round (0.1 /h ) + 1\n mat = matrix (NA, dim,dim)\n for (p in 1:(length (tab[,1]))) {\n x<-tab[p, 1]\n y<-tab[p,2]\n if (is.multiple (x,h) && is.multiple (y,h))\n {\n x<- round (x/ h ) + 1\n y<- round (y/ h) + 1 \n mat[x,y] = tab[p,3]\n }\n }\n mat\n}\ncalc.h <- function (level) {\n 0.1/ (2 ^ level)\n}\n\nplot.error <- function (mat, h, title) {\n s <- seq (0,0.1,by=h)\n contour (s, s, mat, \n xlab = \"x [m]\",\n ylab = \"y [m]\",\n main ='displacement error',\n sub = title)\n}\n\nplot3d.error <- function (mat, h, title = \"bla\")\n{\n s <- seq (0,0.1,by=h)\n persp (s, s, mat, scale = TRUE,\n xlab = \"x [m]\",\n ylab = \"y [m]\",\n main ='displacement error',\n sub = title,\n zlab = \"u error [mm]\",\n expand = 0.3,\n phi = 20, theta=30,\n# ltheta = -120,\n# border = \"white\",\n shade = 0.75, box=TRUE, nticks=5,\n ticktype=\"detailed\"\n )\n}\n\nfile.mean.max <- function (nm)\n{\n mat <- read.table(nm)\n c(mean(mat[,3]), max(mat[,3]))\n}\n\nprint.mean.max <- function (nm)\n {\n q <- file.mean.max (nm)\n sprintf (\"Avg [mm] : %g, Max [mm]: %g\\n\", 10^3* q[1], 10^3* q[2])\n }\n\nbinary <- '../needle2d/out-barespeed/needle ' # -odynamic-friction-factor=1.0'\n\n\n# static.cmd <- paste(binary, ' -Ssynthetic-node-forces -ofix-planes=right -oouter-loop-tolerance=%g ', '-oprint-mesh=yes -oinitial-h=%lg -orefinement-h=%g')\nstatic.cmd <- paste(binary, ' -Sangled-forces -ofix-planes=right -oouter-loop-tolerance=%g ',\n '-oprint-mesh=yes -oinitial-h=%lg -oauto-insert-depth=0.075 -oauto-insert-y=0.0501 -orefinement-h=%g')\n\nmy.system <- function (c) {\n cat (sprintf (\"\\ninvoking `%s'\\n\", c))\n st <- system (c)\n if (st) {\n stop (sprintf (\"Command failed (%d)\\n\", st))\n }\n}\n\nplot.error.field <- function (fn, tit, max.level) {\n mat <- error.mat (fn, calc.h(max.level))\n h <- calc.h (max.level)\n reduced.h <- calc.h (min (max.level - 2,\n 7\n ))\n reduced.mat <- error.mat (fn, reduced.h)\n \n cat (\"Now processing: \", tit, \"\\n\")\n \n postscript (file = paste ('needle-', fn, \"-3d.eps\", sep=\"\"),\n paper=\"special\",\n width = 7.5, height=5,\n horizontal = FALSE)\n plot3d.error (10^3 * reduced.mat, reduced.h, tit)\n dev.off()\n \n postscript (file = paste ('needle-', fn, \"-cont.eps\", sep=\"\"),\n paper=\"special\",\n width = 6, height=4,\n horizontal = FALSE)\n plot.error (10^3 * mat, h, tit)\n dev.off() \n}\n\nmat.to.latex.table <- function (m, format=\"f\", digits=2) {\n for (x in 1:length (m[,1])) {\n strvec <- formatC( m[x,], format = format, digits=digits)\n cat (sub ('NA', ' ', strvec), sep=\"&\");\n cat (\"\\\\\\\\\\n\")\n }\n}\n\n\n\n\n\n################################################################\n# CG tolerance\n################################################################\n\n\n\ntolerance.experiment <- function (max.level) {\n try.tols <- c(0.3, 0.1, 0.03, 0.01, 0.003, 0.001)\n\n u <- max.level \n r <- max.level \n c <-sprintf (static.cmd, 1e-8, calc.h (u), calc.h (r))\n my.system (c)\n# my.system ('mv needle-deformation.state static-deformation-reference.state')\n my.system ('mv needle-deformation.state angled-deformation-reference.state') \n for (t in seq (along=try.tols)) {\n c <-sprintf (static.cmd, try.tols[t], calc.h (u), calc.h (r))\n my.system (c)\n my.system (sprintf ('mv error-plot error-plot-t%d', t))\n }\n\n avg.max.errs <- matrix (NA, length (try.tols), 3)\n\n for (t in seq(along=try.tols)) {\n fn <- paste (\"error-plot-t\",t, sep=\"\")\n tit <- paste (\"residual tolerance\", try.tols[t])\n\n plot.error.field(fn,tit, max.level)\n\n tab <- read.table (fn)\n \n avg.max.errs[t,1] <- try.tols[t]\n avg.max.errs[t,2] <- 10^3 * mean (tab[,3])\n avg.max.errs[t,3] <- 10^3 * max (tab[,3])\n }\n\n cat (\"Tolerance dependency, average/maximum error.\")\n mat.to.latex.table (avg.max.errs, digits=4)\n}\n\n\n################################################################\n# h dependency.\n################################################################\n\ncalc.static.reference.solution <- function (max.level) {\n cat (\"Calculating static reference solution.\\n\")\n \n c <- sprintf (static.cmd, 1e-10, calc.h (max.level), calc.h (max.level))\n my.system (c)\n# my.system ('mv needle-deformation.state static-deformation-reference.state')\n my.system ('mv needle-deformation.state angled-deformation-reference.state') \n}\n\n\nh.dependency.error.table <- function (max.level) {\n max.errs = matrix (NA, max.level + 1, max.level + 1)\n\n for (u in 1:max.level)\n max.errs[1,u+1] = calc.h (u)\n for (r in 1:max.level)\n max.errs[r+1,1] = calc.h (r)\n avg.errs <- max.errs\n iter.counts <- max.errs\n \n for (u in 1:(max.level -1)) {\n for (r in u:max.level) {\n fn <- sprintf (\"error-plot-r%d-u%d\",r,u)\n \n tab <- read.table (fn)\n mat <- tab[,3]\n \n avg.errs[u+1,r+1] = mean (mat)\n max.errs[u+1,r+1] = max (mat)\n\n tab <- read.table (sprintf (\"iteration-stats-r%d-u%d\", r,u))\n iter.counts [u+1,r+1] <- tab[1,1]\n }\n }\n cat (\"h_ref/h_initial error estimates\\n\")\n \n cat (\"Avg errors\\n\")\n mat.to.latex.table (10^3 * avg.errs)\n cat (\"Max errors\\n\")\n mat.to.latex.table (10^3* max.errs)\n cat (\"Iteration counts\\n\")\n mat.to.latex.table (iter.counts, format = \"d\")\n}\n\n\nplot.u.r.table <- function (u,r,max.level)\n{\n fn <- paste (\"error-plot-r\",r, \"-u\",u, sep=\"\")\n tit <- sprintf (\"h-refine = h_%d, h-start = h_%d\",r,u)\n plot.error.field(fn,tit, max.level)\n}\n\nstatic.experiments <- function (max.level) {\n calc.static.reference.solution (max.level)\n iter.counts = matrix (NA, max.level + 1, max.level + 1)\n \n tol <- 1e-8\n for (u in 1:(max.level -1)) {\n for (r in u:max.level) {\n c <- sprintf (static.cmd, tol, calc.h (u), calc.h (r))\n my.system (c)\n my.system (sprintf ('mv error-plot error-plot-r%d-u%d', r,u))\n my.system (sprintf ('mv deformed-mesh.eps needle-deformed-mesh-r%d-u%d.eps', r,u))\n\n my.system (sprintf ('mv iteration-statistics.txt iteration-stats-r%d-u%d', r,u))\n\n\n \n }\n }\n\n for (u in 1:(max.level -1)) {\n for (r in u:max.level) {\n plot.u.r.table (u,r,max.level)\n }\n }\n \n h.dependency.error.table (max.level)\n}\n\n################################################################\n# insertion speed\n################################################################\n\ncentral.insert.y = 0.050001\ninsertion.tol <- 0.001\ninsertion.cmd <- sprintf ('%s -oauto-insert-depth=0.08 -Sauto-insert -ofix-planes=right -oauto-insert-y=%g -oouter-loop-tolerance=%g',\n binary, central.insert.y, insertion.tol)\n\n\ntry.speeds <- c(3.0001, 1.0001, 0.3001, 0.1, 0.03, 0.01)\n\n##\n## Computing the deformation on the fully refined grid is rather expensive. Instead we calc\n## force distribution on adaptive grid, and use that force distr to compute a solution on a full\n## grid\n##\ncalc.insert.reference.solution <- function (u, ref) {\n log.message (\"Calculating insertion reference solution.\\n\")\n cmd <- sprintf ('%s -oauto-insert-speed=%g -orefinement-h=%g',\n insertion.cmd, 0.005, calc.h (ref))\n\n my.system (sprintf ('%s -oinitial-h=%g ', cmd, calc.h(u)))\n \n my.system ('mv graph-needle-forces.txt reference-needle-dump.txt')\n my.system (sprintf ('%s -oinitial-h=%g -Sread-needle-dump ', cmd, calc.h(ref)))\n \n my.system ('mv needle-deformation.state insert-reference.state')\n my.system (sprintf ('%s -oinitial-h=%g ',\n cmd, calc.h(u)))\n my.system ('mv error-plot needle-insert-shortcut-error')\n\n log.message(sprintf (\"Shortcut error: %s\\n\", print.mean.max ('needle-insert-shortcut-error' )))\n \n plot.error.field ('needle-insert-shortcut-error', \"Error caused by shortcutting by refined mesh\",\n ref)\n \n mat <- 10^3 * read.table ('needle-insert-shortcut-error')\n\n short.cut.errors <- file.mean.max ('needle-insert-shortcut-error')\n cat (sprintf (\"Error caused by short cut: mean %g/max %g\\n\", short.cut.errors[1],\n short.cut.errors[2]))\n\n #\n # we need the 0.0001 epsilon to prevent degeneracies causing endless loops in the needle\n # inserter.\n #\n speed.test.tol <- 0.001\n\n log.message (\"Experimenting with insertion speed.\\n\")\n \n speeds <- try.speeds\n for (i in seq (along =speeds)) {\n s <- speeds[i]\n c <- sprintf (\"%s -oauto-insert-speed=%e -oinitial-h=%g -orefinement-h=%g\",\n insertion.cmd, s,\n calc.h (u), calc.h (ref))\n \n my.system (c)\n \n my.system (sprintf ('mv error-plot speed-errors-s%d' , i))\n my.system (sprintf ('mv error-plot.xerror speed-errors-s%d.xerror' , i))\n }\n\n avg.max.errs <- matrix (NA, length (try.speeds), 3)\n\n for (i in seq (along=try.speeds)) {\n fn <- sprintf (\"speed-errors-s%d\",i)\n tit <- sprintf (\"speed %f h-refine\", try.speeds[i]);\n\n plot.error.field(fn, tit, ref)\n plot.error.field(paste (fn, \".xerror\", sep=\"\"), tit, ref)\n\n tab <- read.table (fn)\n \n avg.max.errs[i,1] <- try.speeds [i]\n avg.max.errs[i,2] <- 10^3 * mean (tab[,3])\n avg.max.errs[i,3] <- 10^3 * max (tab[,3])\n }\n cat (\"\\n\\nInsertion speed dependencies\\n\")\n cat (\"avg error [mm]&max error [mm]\")\n mat.to.latex.table (avg.max.errs)\n}\n\ninsertion.experiment <- function(u, r , ml)\n{\n calc.insert.reference.solution (u, r)\n}\n\n\n################################################################\n# Speed measurements\n################################################################\n\n\n# todo.\n\ncpu.speed.experiment <- function(u, r)\n{\n log.message ('Timing experiment')\n insertion.cmd <- sprintf ('%s -oauto-insert-depth=0.08 -Sauto-insert -ofix-planes=bottom -oauto-insert-y=%g -oouter-loop-tolerance=%g',\n binary, central.insert.y, 0.03)\n\n speed.tab <- matrix (NA, length (try.speeds), 6)\n for (i in seq (along =try.speeds)) {\n s <- try.speeds[i]\n cat (s)\n cat (insertion.cmd)\n c <- sprintf (\"%s -oauto-insert-speed=%e -oinitial-h=%g -orefinement-h=%g\", insertion.cmd, s, calc.h (u), calc.h (r))\n\n my.system (c)\n stats <- read.table ('speed-stats.txt')\n\n speed.tab[i,1] <- s\n speed.tab[i,2] <- stats[1, 1]\n speed.tab[i,3] <- stats[1, 2]\n speed.tab[i,4] <- stats[1, 2] / stats[1, 1]\n speed.tab[i,5] <- stats[1, 3] / stats[1, 2]\n speed.tab[i,6] <- stats[1, 4]\n }\n\n \n cat (\"time [s]&iterations&update freq [Hz]&avg CG iters&max CG iters\\n\")\n mat.to.latex.table (speed.tab)\n}\n\n################################################################\n# Node relocation (first try)\n################################################################\n\n\nrelocation.experiment <- function (max.level) {\n log.message ('relocation error analysis')\n \n relocate.cmd <- '%s -Sangled-forces -ofix-planes=right -orefinement-h=%g -oinitial-h=%g -oauto-insert-y=0.05 -oauto-insert-angle=10 -oauto-insert-depth=0.08 -oouter-loop-tolerance=%g '\n tol <- 1e-4\n c <- sprintf(relocate.cmd, binary, calc.h(max.level), calc.h(max.level),\n tol)\n\n my.system (c)\n my.system ('mv needle-deformation.state angled-deformation-reference.state')\n my.system ('mv iteration-statistics.txt reloc-no-reloc-stats.txt')\n\n c <- paste (c, ' -orelocate-nodes=yes')\n my.system (c)\n between.fine <- 10^3 * file.mean.max (\"error-plot\")\n\n my.system ('mv iteration-statistics.txt reloc-with-reloc-stats.txt')\n my.system ('mv error-plot relocate-error-between-fine-grid')\n\n ################\n coarse.ref.level <- max.level -1\n coarse.level <- 3\n coarse.h <- calc.h (coarse.level)\n coarse.ref.h <- calc.h (coarse.ref.level)\n \n c <- sprintf(relocate.cmd, binary, coarse.ref.h,coarse.h, \n tol)\n\n c <- paste (c, ' -oprint-mesh=yes -orelocate-nodes=yes')\n my.system (c)\n coarse.reloc.errors <- 10^3 * file.mean.max (\"error-plot\")\n\n my.system ('mv iteration-statistics.txt reloc-coarse-with-reloc-stats.txt')\n my.system ('mv error-plot relocate-error-coarse-with-relocate')\n my.system ('mv deformed-mesh.eps angled-insert-relocate.eps')\n \n ################\n c <- paste (c, ' -orelocate-nodes=no')\n my.system (c)\n coarse.hwn.errors <- 10^3*file.mean.max (\"error-plot\")\n my.system ('mv error-plot relocate-error-coarse-no-relocate')\n my.system ('mv iteration-statistics.txt reloc-coarse-no-reloc-stats.txt')\n my.system ('mv deformed-mesh.eps angled-insert.eps')\n my.system ('mv needle-deformation.state angled-deformation-reference.state')\n\n c <- paste (c, ' -orelocate-nodes=yes')\n my.system (c)\n between.coarse <- 10^3 * file.mean.max (\"error-plot\")\n\n #\n \n \n ################\n log.message (\"Relocation errors\");\n cat (sprintf (\"With relocation, |fine_{reloc} - fine_{hwn}| %g& %g\\n\",\n between.fine[1], between.fine[2]))\n cat (sprintf (\"With relocation, |coarse_{reloc} - fine_{hwn}| %g& %g\\n\",\n coarse.reloc.errors[1], coarse.reloc.errors[2]))\n cat (sprintf (\"Without relocation, |coarse_{hwn} - fine_{hwn}| %g& %g\\n\",\n coarse.hwn.errors[1], coarse.hwn.errors[2]))\n cat (sprintf (\"Between coarse, |coarse_{hwn} - coarse_{reloc}| %g& %g\\n\",\n between.coarse[1], between.coarse[2]))\n\n h.descr <- sprintf (\"h%d/h%d\", as.integer (coarse.ref.level), as.integer (coarse.level))\n \n plot.error.field (\"relocate-error-coarse-with-relocate\",\n paste (\"Error with relocation\", h.descr),\n max.level\n )\n \n plot.error.field (\"relocate-error-coarse-no-relocate\",\n paste (\"Error without relocation\", h.descr),\n max.level\n )\n\n plot.error.field (\"relocate-error-between-fine-grid\",\n sprintf (\"Difference between with and without relocation (h%d/h%d)\",\n as.integer (max.level),as.integer (max.level)),\n max.level\n )\n \n}\n\n################################################################\n# material linearity.\n################################################################\n\n\nnonlinearity.experiment <- function () {\n\n ref.level <- 6\n unif.level <- 3\n \n nl.cmd <- '%s -Sauto-insert -ofix-planes=right -orefinement-h=%g -oinitial-h=%g -oauto-insert-y=0.07 -oauto-insert-angle=0 -oauto-insert-speed=0.01 -oauto-insert-depth=0.12 -oouter-loop-tolerance=%g -ofix-planes=bottom -opoisson=0.0'\n tol <- 1e-2\n c <- sprintf(nl.cmd, binary, calc.h (ref.level), calc.h (unif.level),\n tol)\n\n \n ## Venant-Kirchoff elasticity has the tendency to hang the simulation, Probably\n ## element inversion is some kind of buckling where K(u) is non-invertible.\n ## Then relaxation does not converge. \n \n # c.1 <- paste (c, \" -oelasticity=nonlinear \")\n #my.system (c.1)\n #my.system ('mv deformed-mesh.eps nonlinear-mesh.eps')\n #Amy.system ('mv reference-mesh.eps nonlinear-ref-mesh.eps') \n \n c.1 <- paste (c, \" -oelasticity=neohooke -orelaxation-type=nonlinear \")\n my.system (c.1)\n my.system ('mv deformed-mesh.eps neohooke-mesh.eps')\n my.system ('mv reference-mesh.eps neohooke-ref-mesh.eps') \n my.system ('mv deformed-boundary.eps neohooke-boundary.eps')\n my.system ('mv reference-boundary.eps neohooke-ref-boundary.eps') \n \n c.1 <- paste (c, \" -oelasticity=consistent-veronda -orelaxation-type=nonlinear \")\n my.system (c.1)\n my.system ('mv deformed-mesh.eps consistent-vw-mesh.eps')\n my.system ('mv reference-mesh.eps consistent-vw-ref-mesh.eps') \n my.system ('mv deformed-boundary.eps consistent-vw-boundary.eps')\n my.system ('mv reference-boundary.eps consistent-vw-ref-boundary.eps') \n \n\n c.2 <- paste (c, \" -oelasticity=linear \")\n my.system (c.2)\n my.system ('mv deformed-mesh.eps linear-mesh.eps')\n my.system ('mv reference-mesh.eps linear-ref-mesh.eps') \n my.system ('mv deformed-boundary.eps linear-boundary.eps')\n my.system ('mv reference-boundary.eps linear-ref-boundary.eps') \n\n c.2 <- paste (c, \" -oelasticity=neohooke -orefinement-h=0.003125 -oinitial-h=0.025 \")\n my.system (c.2)\n my.system ('mv deformed-mesh.eps needle-nh-coarse-mesh.eps')\n my.system ('mv reference-mesh.eps needle-nh-coarse-ref-mesh.eps') \n my.system ('mv deformed-boundary.eps needle-nh-coarse-boundary.eps')\n my.system ('mv reference-boundary.eps needle-nh-coarse-ref-boundary.eps') \n}\n\n################################################################\n# misc examples\n################################################################\n\nforce.distribution.graph <- function() {\n my.system (paste (binary , '-Sgraph-friction '))\n\n fr <- read.table (\"force-graph.txt\")\n fr[,1] = max(fr[,1]) - fr[,1]\n \n postscript (file = 'needle-friction-graph.eps',\n paper = \"special\",\n width = 6, height=4,\n horizontal = FALSE)\n plot (fr[,1], fr[,2], ylab = 'Friction force [N/m]',\n xlab = 'Coordinate along needle [m]',\n type = 'l')\n dev.off()\n}\n\n\nbisection.example <- function( )\n {\n append.point <- function(nm) {\n f <- file (nm, \"a\")\n cat (\"\\n0.0702 0.0351 0.0015 0 360 arc closepath fill \\n \", file = f)\n close (f)\n }\n \n my.system (paste(binary, \" -Sshow-refinement\"))\n for (i in 0:9) {\n append.point (sprintf (\"maubach-refinement-%d.eps\", i))\n }\n append.point (sprintf (\"maubach-no-refinement.eps\", i)) \n }\n\n################################################################\n# all experiments\n################################################################\n\neverything <- function (ml) {\n my.system ('make conf=barespeed')\n \n out.dir <- 'experiments'\n oldwd <- getwd()\n setwd (out.dir)\n\n\n ################\n # put the newest at the top, since that is changed most often.\n nonlinearity.experiment ()\n static.experiments (ml)\n\n cpu.speed.experiment (3,7)\n cpu.speed.experiment (3,6)\n\n\n\n relocation.experiment (ml)\n\n insertion.experiment(3,6,6)\n\n \n tolerance.experiment (ml)\n\n ####\n \n bisection.example()\n force.distribution.graph ()\n\n setwd (oldwd)\n}\n", "meta": {"hexsha": "212a797836220fe80c434e6a38909cff61e8f714", "size": 18433, "ext": "r", "lang": "R", "max_stars_repo_path": "plot-h-error.r", "max_stars_repo_name": "hanwen/artisjokke", "max_stars_repo_head_hexsha": "608d76c5fad74ee4214162044c7ea3b781571e44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-06-06T02:25:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T09:49:56.000Z", "max_issues_repo_path": "plot-h-error.r", "max_issues_repo_name": "hanwen/artisjokke", "max_issues_repo_head_hexsha": "608d76c5fad74ee4214162044c7ea3b781571e44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plot-h-error.r", "max_forks_repo_name": "hanwen/artisjokke", "max_forks_repo_head_hexsha": "608d76c5fad74ee4214162044c7ea3b781571e44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-06-05T12:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-28T09:27:59.000Z", "avg_line_length": 31.084317032, "max_line_length": 236, "alphanum_fraction": 0.5598654587, "num_tokens": 5318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6413016912699604}} {"text": "################################################################################\n# Monte Carlo Simulation and Resampling Methods in Social Science #\n# Thomas M. Carsey and Jeffrey J. Harden #\n# Chapter 6 File (Parallel Processing 2 of 2) #\n# Last update: 1/31/13 #\n################################################################################\n\n# Negative Binomial vs. Zero-Inflated Negative Binomial (parallel processing)\nlibrary(pscl)\nlibrary(snow) \nlibrary(doSNOW) \nlibrary(foreach)\n\ncl.tmp <- makeCluster(4) \nregisterDoSNOW(cl.tmp) \n\n# Zero-inflated negative binomial random number generator\nrzinbinom <- function(n, mu, size, zprob){ \nifelse(runif(n) < zprob, 0, rnbinom(n, size = size, mu = mu))\n}\n\n# Simulation function\nzinb.sim <- function(n = 1000){\nrequire(pscl)\npar.est.zinb <- matrix(NA, nrow = 1, ncol = 4) # Empty matrix to store the\n # estimates \nb0 <- .2 # True value for the intercept\nb1 <- .5 # True value for the slope\nX <- runif(n, -1, 1) # Create a sample of n observations on the \n # independent variable X\n\n# Generate data with a zero-inflation component\nY.zi <- rzinbinom(n, mu = exp(b0 + b1*X), size = .5,\nzprob = exp(b0 + b1*X)/(1 + exp(b0 + b1*X)))\n# Generate data with no zero-inflation component\nY.nozi <- rzinbinom(n, mu = exp(b0 + b1*X), size = .5, zprob = 0) \nmodel.nb1 <- glm.nb(Y.zi ~ X) # Standard negative binomial\nmodel.nb2 <- glm.nb(Y.nozi ~ X)\nmodel.zinb1 <- zeroinfl(Y.zi ~ X | X, dist = \"negbin\") # Zero-inflated model\nmodel.zinb2 <- zeroinfl(Y.nozi ~ X | X, dist = \"negbin\") \n# Store the estimates of the coefficient on X (count equation)\npar.est.zinb[ , 1] <- model.nb1$coef[2] # Standard NB, with ZI\npar.est.zinb[ , 2] <- model.nb2$coef[2] # Standard NB, no ZI\npar.est.zinb[ , 3] <- as.numeric(model.zinb1$coef$count[2]) # ZI NB, with ZI\npar.est.zinb[ , 4] <- as.numeric(model.zinb2$coef$count[2]) # ZI NB, no ZI\nreturn(par.est.zinb)\n}\n\n# Parallel Processing\nset.seed(2837) # Set the seed for reproducible results\nreps <- 1000 # Set the number of repetitions\n\nstart.time <- Sys.time()\nresults <- foreach(i = 1:reps, .combine = rbind) %dopar% {\nzinb.sim(n = 1000)\n}\n\nend.time <- Sys.time()\nend.time - start.time", "meta": {"hexsha": "ff2a1c1c06a17f4a182eaeb05b0976c2cba0bd92", "size": 2362, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/extdata/parallel2.r", "max_stars_repo_name": "rmsharp/stepwiser", "max_stars_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-12T17:54:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-12T17:54:26.000Z", "max_issues_repo_path": "inst/extdata/parallel2.r", "max_issues_repo_name": "rmsharp/stepwiser", "max_issues_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inst/extdata/parallel2.r", "max_forks_repo_name": "rmsharp/stepwiser", "max_forks_repo_head_hexsha": "639eb2c055aa23a1d6e4d71b6df63dd3f4ad6f6d", "max_forks_repo_licenses": ["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.0338983051, "max_line_length": 80, "alphanum_fraction": 0.5749364945, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6411986475935951}} {"text": "# Propiedades numéricas del OLS, Gauss-Markov, sesgo de variable omitida\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n#################################################################\n# Motivacion\n#################################################################\n\n# Ademas de trabajar con incertidumbre (intervalos de confianza, p-values, etc.), \n# la estadistica inferencial (lo que estamos haciendo este semestre) \n# descansa sobre supuestos muy importantes.\n\n# Es importante conocer estos supuestos. Te daras cuenta que \n# la principal herramienta cuantitativa de las ciencias sociales \n# tiene muchos defectos y/o supuestos irreales. En consecuencia, siempre\n# actua con prudencia y humildad respecto a tus resultados.\n\n\n#################################################################\n# Supuestos de los modelos lineales\n#################################################################\n\n# (1) El error tiene promedio cero: por eso SIEMPRE calcula los errores y plotealos.\n# (2) El error tiene varianza constante: idem.\n# (3) El error no esta correlacionado (los errores son independientes entre si): idem.\n# (4) El error esta normalmente distribiuido: idem.\n# (5) Las X's estan medidas sin error, y son independientes del error.\n# (6) Las X's no son invariables, es decir, las X's son variables, no constantes.\n\n# (*) Punto sobre la diferencia entre ERROR y RESIDUO:\n## recuerda que y = b0 + b1x1 + e. \n## Ese \"e\" en realidad, es un residuo, no \"error\". \"Parametro de poblacion.\"\n\n#################################################################\n# Teorema de Gauss-Markov\n#################################################################\n\n# el fundamento matematico de OLS (modelos lineales), es el \n# Teorema de Gauss-Markov.\n\n# Consiste en lo siguiente: si\n## (a) el error tiene promedio cero, y\n## (b) si el error esta normalmente distribuido, y\n## (c) si el error tiene varianza constante,\n# entonces nuestros betas son los estimadores mas eficientes y sin sesgo.\n\n# En ingles, es conocido como \"BLUE\": \"best linear unbiased estimator\".\n\n# En otras palabras, cuando todos los supuestos funcionan, \n# la diferencia entre la MATRIZ QUE CONTIENE TODOS LOS BETAS CORRECTOS,\n# Y LA MATRIZ QUE NOSOTROS TENEMOS ACCESO (O POODEMOS OCUPAR) ES CERO.\n\n# (1) Punto del modelo \"real\" (\"true model\").\n# (2) Punto del epsilon (error) y la letra \"e\" (residuo).\n# (3) Punto del beta y la letra \"b\".\n\n# Son diferencias filosoficas. Importantes...pero filosoficas.\n\n\n# Que puede salir mal?\n## Ej.: los errores no son independientes; es decir, son dependientes. \n### Caso de las series de tiempo.\n\n\n#################################################################\n# Sesgo de Variable Omitida: \"omitted variable bias\"\n#################################################################\n\n# Todos los supuestos de OLS operan bajo otro supuesto: el modelo que \n# estimamos, es el \"verdadero modelo\". Es decir, no se nos queda ninguna\n# variable afuera: i.e., todas las variables que debieramos ocupar, estan \n# consideradas. Si esto falla, todo falla, y tenemos \"el sesgo de la variable\n# omitida\".\n\n# Mal que mal, OLS es una ecuacion, y el valor de los betas cambiara si es que \n# no incluimos todas las variables que debieramos incluir. \n\n## ILUSTRAR EN LA PIZARRA.\n\n# Para demostrar este punto, simularemos (inventaremos) unos datos. \n\n\n# Inventemos las variables independientes\nset.seed(2020)\nx1 = rnorm(1000, mean=0, sd=1) # como nunca, conocemos que el promedio REAL de esta variable es 0\nx2 = rnorm(1000, mean=2, sd=2) # como nunca, conocemos que el promedio REAL de esta variable es 2\nx3 = rnorm(1000, mean=1, sd=3) # como nunca, conocemos que el promedio REAL de esta variable es 1\nx4 = x1*x2\n\n\n# Definamos que, como debiera ser, el error tiene promedio cero.\ne = rnorm(1000, 0)\n\n# Establecer el valor real de los betas: conocemos con exactitud los valores,\n# porque nosotros los creamos!\nb1 = 1\nb2 = -1\nb3 = 5\nb4 = -2\n\n# El \"VERDADERO MODELO\": \"y\" es una combinacion lineal de todas las variables.\ny = b1*x1 + b2*x2 + b3*x3 + b4*x4 + e # true model\n\nhist(y)\n\n# Hagamos una regresion.\nmodelo.completo = lm(y ~ x1 + x2 + x3 + x4)\nsummary(modelo.completo) # sin sorpresa, los betas son los mismos que inventamos nosotros.\n\n# (1) La tabla de \"Residuals\" dice que la mediana es 0. Eso es genial. Pero sin sorpresas, nosotros inventamos todo, asi que obvio que resulta bien.\n# (2) Plotiemos los errores\n\nplot(modelo.completo$fitted.values, modelo.completo$residuals) \n\n\n# Perfecto! No notamos ningun patron.\n# Es decir, vemos una nube desordenada de puntos. \n# Aqui es cuando VEMOS lo que asumimos: los errores se cancelan entre si.\n\n\n\n# Variable Omitida: Que pasa con nuestros coeficientes cuando se nos quedan dos\n# variables afuera?\n\nmodelo.segado = lm(y ~ x1)\n\nsummary(modelo.segado) # Ya los resultados son muy diferentes.\n\n# (1) Mediana de los residuos? \n# (2) Plotiemos los errores?\n\nplot(modelo.segado$fitted.values, modelo.segado$residuals) \n\n\n# Promediemos el error\noptions(scipen = 1000000) # apagar notacion cientifica.\nmean(modelo.segado$residuals)\n\n# Que vemos aqui?\n# Que implica?\n\n#################################################################\n# Atencion\n#################################################################\n\n# Lo peor de todo, es que nunca sabras si te faltan variables o no.\n# Es por esto que lo que guia el proceso de anadir/remover variables, es \n# teoria. Es un proceso casi artistico.\n", "meta": {"hexsha": "d2d900d7b8b3b2d151f8f6b56c754eecb2546fbe", "size": 5478, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase15/Clase15.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Clase15/Clase15.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Clase15/Clase15.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2781456954, "max_line_length": 148, "alphanum_fraction": 0.6396495071, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6411076917406223}} {"text": "## Difference that maintains original array size by appending a row\n\n.fdiff <- function(X) rbind(diff(X), rep(NA,ncol(X)))\n\n## Ghiglia and Pritt's wrap operator. Thanks to Steve K.\n\nwrap <- function(phase) (phase+pi)%%(2*pi) - pi\n\n\n## Calculate residue map\n## A \"positive\" charged residue has value +1\n## A \"negative\" charge has value -1\n\nrmap <- function(phase, dx=NULL, dy=NULL, plot=FALSE, ...) {\n nr <- nrow(phase)\n nc <- ncol(phase)\n\n if (is.null(dx)) {\n dx <- wrap(.fdiff(phase))\n }\n if (is.null(dy)) {\n dy <- wrap(t(.fdiff(t(phase))))\n }\n d2y <- rbind(dy[1:(nr-1),]-dy[2:nr,],rep(NA,nc))\n d2x <- cbind(dx[,2:nc]-dx[,1:(nc-1)],rep(NA,nr))\n residues <- round((d2y+d2x)/(2*pi))\n if (plot) {\n ## positive charges\n chp <- which(residues ==1, arr.ind=TRUE)\n ## negative charges\n chm <- which(residues == -1, arr.ind=TRUE)\n image(1:nr, 1:nc, phase, col=grey256, asp=1, xlab=\"X\", ylab=\"Y\", useRaster=TRUE, ...)\n if(length(chp)>0) {\n points(chp, col=\"green\", pch=20)\n }\n if(length(chm)>0) {\n points(chm, col=\"red\", pch=20)\n }\n nr <- sum(abs(residues),na.rm=TRUE)\n nr\n } else {\n residues\n }\n}\n\n## \"Itoh's\" method for phase unwrapping.\n\n## integrate the wrapped phase differences\n## This is called by brcutpuw, or it can be called\n## directly by the user.\n\n## Note: as of July 2020 the unwrapper is written in C++ using Rcpp.\n## It's fastest to bypass the computation of dx and dy in R\n## and unwrap with a call to id_uw.\n## netflowpuw (in lppuw, and at present unsupported) passes values of dx and dy with ucall==TRUE.\n## brcutpuw passes dx and dy with ucall==FALSE.\n## The call to id_dxy_uw is slower by about 40%.\n\nidiffpuw <- function(phase, mask=phase, ucall=TRUE, dx=NULL, dy=NULL) {\n\n nr <- nrow(phase)\n nc <- ncol(phase)\n\t\n if (ucall) {\n if (is.null(dx)) {\n puw <- id_uw(as.integer(nr), as.integer(nc), as.vector(phase)/(2*pi))\n puw <- matrix(puw, nr, nc)\n } else {\n puw <- id_dxy_uw(as.integer(nr), as.integer(nc), as.vector(phase)/(2*pi),\n as.vector(mask), as.vector(dx/(2*pi)), as.vector(dy/(2*pi)),\n\t integer(nr*nc))\n puw <- matrix(puw, nr, nc)\n }\n puw[is.na(phase)] <- NA\n class(puw) <- \"pupil\"\n puw\n } else {\n if (is.null(dx)) dx <- wrap(.fdiff(phase))\n if (is.null(dy)) dy <- wrap(t(.fdiff(t(phase))))\n uw <- integer(nr*nc)\n puw <- id_dxy_uw(as.integer(nr), as.integer(nc), as.vector(phase)/(2*pi),\n as.vector(mask), as.vector(dx/(2*pi)), as.vector(dy/(2*pi)),\n\t uw)\n puw <- matrix(puw, nr, nc)\n puw[is.na(phase)] <- NA\n uw <- matrix(as.logical(uw), nr, nc)\n class(puw) <- \"pupil\"\n list(puw=2*pi*puw, uw=uw)\n }\n}\n\n\n## Quality guided unwrapper.\n## This is mostly a wrapper for a call to the C++ function \"q_uw\".\n\nqpuw <- function(phase, qual) {\n nr <- nrow(phase)\n nc <- ncol(phase)\n\t\n phase <- phase/(2*pi)\n qual[is.na(phase)] <- 0\n\t\n puw <- q_uw(as.integer(nr), as.integer(nc), as.vector(phase), as.vector(qual))\n puw <- matrix(puw, nr, nc)\n puw[is.na(phase)] <- NA\n class(puw) <- \"pupil\"\n puw\n}\n\n##\n## Branch cut algorithm.\n## This now solves a variant of the assignment problem to minimize\n## the total length of all branch cuts.\n##\n## note: parameter pen is a penalty added to distances from charges to edges.\n## I'm not sure this is really useful. Seems to work fine with the default\n## of 0.\n##\n\n \nbrcutpuw <- function(phase, pen=0, details=FALSE) {\n\n require(clue)\n\n ## distance between points specified by their x,y coordinates.\n \n dmat <- function(p1, p2) {\n fn <- function(x,y) abs(y-x)\n xleg <- outer(p1[,1], p2[,1], FUN=fn)\n yleg <- outer(p1[,2], p2[,2], FUN=fn)\n xleg+yleg\n }\n \n ## Make a branch cut\n \n brcut <- function(startp, endp, mask) {\n xl <- endp[1]-startp[1]\n yl <- endp[2]-startp[2]\n if (abs(yl) <= abs(xl)) {\n slope <- yl/xl\n ix <- startp[1]:endp[1]\n iy <- startp[2] + round(slope*(ix-startp[1]))\n } else {\n slope <- xl/yl\n iy <- startp[2]:endp[2]\n ix <- startp[1] + round(slope*(iy-startp[2]))\n }\n mask[cbind(ix,iy)] <- NA\n mask\n }\n \n res <- rmap(phase)\n ## no residues, so a single call to idiffpuw is all we need\n if (sum(abs(res),na.rm=TRUE) == 0) {\n return(idiffpuw(phase,ucall=TRUE))\n }\n \n\n nr <- nrow(phase)\n nc <- ncol(phase)\n dx <- wrap(.fdiff(phase))\n dy <- wrap(t(.fdiff(t(phase))))\n \n mask <- matrix(1,nr,nc)\n mask[is.na(phase)] <- NA\n \n ## positive charges\n chp <- which(res==1, arr.ind=TRUE)\n ncp <- nrow(chp)\n ## negative charges\n chm <- which(res== -1, arr.ind=TRUE)\n ncm <- nrow(chm)\n ## get the boundary points - ones one pixel outside the area of defined phase.\n ## step in\n ptsb <- which(is.na(phase) & (!is.na(rbind(phase[-1,], rep(NA, nc)))), arr.ind=TRUE)\n ptsb <- rbind(ptsb, which(is.na(phase) & (!is.na(cbind(phase[,-1], rep(NA, nr)))), arr.ind=TRUE))\n ## step out\n ptsc <- which((!is.na(phase)) & is.na(rbind(phase[-1,], rep(NA, nc))), arr.ind=TRUE)\n ptsc[,1] <- ptsc[,1]+1\n ptsb <- rbind(ptsb, ptsc)\n ptsc <- which((!is.na(phase)) & is.na(cbind(phase[,-1], rep(NA, nr))), arr.ind=TRUE)\n ptsc[,2] <- ptsc[,2]+1\n ptsb <- rbind(ptsb, ptsc)\n \n \n if ((ncp>0) & (ncm>0)) {\n \n ## distances between residues\n dpm <- dmat(chp, chm)\n \n ## distance from each positive charge to nearest edge\n dce <- dmat(chp, ptsb)\n ipb <- apply(dce, 1, which.min)\n dpe <- apply(dce, 1, min)+pen\n pec <- matrix(ptsb[ipb,], ncp, 2)\n \n ## distance from each negative charge to nearest edge\n dce <- dmat(chm, ptsb)\n ipb <- apply(dce, 1, which.min)\n dme <- apply(dce, 1, min)+pen\n mec <- matrix(ptsb[ipb,], ncm, 2)\n \n ## cost matrix of assigning p to edge and m to edge for each (p,m). This has the same dimension as dpm\n cost.ec <- outer(dpe, dme, \"+\")\n isd <- (dpm <= cost.ec)\n \n ## elementwise minimum of dpm and cost.ec. \n ## Idea is if dpm[p,m] < cost.ec[p,m] we should connect dipole, otherwise connect both to edge\n minc <- pmin(dpm, cost.ec)\n pecuts <- NULL\n mecuts <- NULL\n\n ## use Hungarian algorithm from package clue to get optimal assigments from p to m.\n ## Then figure out which are dipole cuts and which are edge cuts.\n ## If ncm > ncp there have to be some unassigned m's. Those connect to edge.\n \n if (ncm >= ncp) {\n yp <- solve_LSAP(minc)\n ass <- cbind(seq_along(yp), as.integer(as.vector(yp)))\n mecuts <- setdiff(1:ncm, ass[,2])\n } else {\n yp <- solve_LSAP(t(minc))\n ass <- cbind(as.integer(as.vector(yp)), seq_along(yp))\n pecuts <- setdiff(1:ncp, ass[,1])\n }\n dpcuts <- matrix(ass[which(isd[ass]),], ncol=2)\n edgecuts <- matrix(ass[which(!isd[ass]),], ncol=2)\n pecuts <- c(pecuts, edgecuts[,1])\n mecuts <- c(mecuts, edgecuts[,2])\n cost.dpcuts <- dpm[dpcuts]\n cost.pe <- dpe[pecuts]\n cost.me <- dme[mecuts]\n \n if (details) {\n cat(paste(nrow(dpcuts),\"dipole connections, total cost =\",sum(cost.dpcuts),\"\\n\"))\n cat(paste(length(pecuts),\"+ to edge, total cost =\",sum(cost.pe),\"\\n\"))\n cat(paste(length(mecuts),\"- to edge, total cost =\",sum(cost.me),\"\\n\"))\n }\n \n cutlen <- sum(cost.dpcuts)+sum(cost.pe)+sum(cost.me)\n \n for (i in seq_along(dpcuts[,1])) {\n startp <- chp[dpcuts[i, 1],]\n endp <- chm[dpcuts[i, 2],]\n mask <- brcut(startp, endp, mask)\n }\n for (i in seq_along(pecuts)) {\n startp <- chp[pecuts[i],]\n endp <- pec[pecuts[i],]\n mask <- brcut(startp, endp, mask)\n }\n for (i in seq_along(mecuts)) {\n startp <- chm[mecuts[i],]\n endp <- mec[mecuts[i],]\n mask <- brcut(startp, endp, mask)\n }\n }\n ## if there are only plus or minus charges connect to nearest edge (should be rare case, but...)\n else if (ncp > 0) {\n ## distance from each positive charge to nearest edge\n dce <- dmat(chp, ptsb)\n ipb <- apply(dce, 1, which.min)\n dpe <- apply(dce, 1, min)+pen\n pe <- matrix(ptsb[ipb,],ncp,2)\n for (i in 1:ncp) {\n startp <- chp[i,]\n endp <- pe[i,]\n mask <- brcut(startp, endp, mask)\n }\n }\n else if (ncm > 0) { \n ## distance from each negative charge to nearest edge\n dce <- dmat(chm, ptsb)\n ipb <- apply(dce, 1, which.min)\n dme <- apply(dce, 1, min)+pen\n me <- matrix(ptsb[ipb,],ncm,2)\n for (i in 1:ncm) {\n startp <- chm[i,]\n endp <- me[i,]\n mask <- brcut(startp, endp, mask)\n }\n }\n \n ## call idiffpuw to unwrap all unmasked pixels\n uwum <- idiffpuw(phase, mask, ucall=FALSE, dx=dx, dy=dy)\n puw <- uwum$puw\n uw <- uwum$uw\n uw[is.na(phase)] <- NA\n ## fill in whatever was left wrapped\n ## This inverts the logic of fill algorithm in idiffpuw\n ## todo initially contains a list of pixels that haven't been unwrapped\n ## that should be. We look for neighbors that have been unwrapped\n ## and unwrap from them, removing the newly unwrapped pixels from\n ## the todo list.\n ## This should work because branch cuts are just a pixel wide and should\n ## adjoin unmasked regions. It's possible that cuts could completely\n ## enclose an area, in which case it will still be filled\n ## with most likely erroneous values as we fill through the cuts.\n \n todo <- which(!uw)\n kn <- c(-1, 1, -nr, nr)\n while (length(todo) > 0) {\n for (i in 1:4) {\n b <- todo + kn[i]\n subs <- which(uw[b])\n puw[todo[subs]] <- puw[b[subs]] + switch(i, dx[b[subs]], -dx[todo[subs]],\n dy[b[subs]], -dy[todo[subs]])\n uw[todo[subs]] <- TRUE\n todo <- todo[-subs]\n if (length(todo)==0) break\n }\n }\n if (details) {\n bcuts <- matrix(NA, nr, nc)\n bcuts[is.na(mask) & (!is.na(phase))] <- 1\n list(puw=puw/(2*pi), cutlen=cutlen, bcuts=bcuts,\n dpm=dpm, dpe=dpe, dme=dme,\n dpcuts=dpcuts, pecuts=pecuts, mecuts=mecuts,\n cost.dpcuts=cost.dpcuts, cost.pe=cost.pe, cost.me=cost.me\n )\n } else\n puw/(2*pi)\n}\n", "meta": {"hexsha": "18c2291d9948d6fc564fada221af4c61928b9791", "size": 10600, "ext": "r", "lang": "R", "max_stars_repo_path": "R/puwalgs.r", "max_stars_repo_name": "mlpeck/zernike", "max_stars_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/puwalgs.r", "max_issues_repo_name": "mlpeck/zernike", "max_issues_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/puwalgs.r", "max_forks_repo_name": "mlpeck/zernike", "max_forks_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 32.7160493827, "max_line_length": 108, "alphanum_fraction": 0.549245283, "num_tokens": 3334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.641107149808453}} {"text": "# install.packages('lmtest')\n# install.packages('car')\n#install.packages(\"tseries\")\n#install.packages(\"forecast\")\nlibrary(forecast)\nlibrary(tseries)\nlibrary(lmtest)\nlibrary(car)\n\nsetwd('/Users/demg/Projects/FA/Course III/ECONOMETRICS/task8')\ndata <- read.csv('./check.csv', sep = \";\")\n\ny <- data$GDP\nx1 <- data$t\nx2 <- data$d1\nx3 <- data$d2\nx4 <- data$d3\n\n# Корреляционная матрица\ncor(data) \n\n# Диаграммы рассеяния\nplot(y, x1, col = 'red')\nplot(y, x2, col= 'blue')\nplot(y, x3, col = 'green')\nplot(y, x4, col = 'yellow')\n\n########################################################################################\n# Множественная модель\np_many <- lm(y~x1+x2+x3+x4)\ns_many <- summary(p_many)\ns_many\n\nA_many <- sum(abs(s_many$residuals/y)) / length(y) * 100 # Апроксимация\nA_many\n\nconfint(p_many, level = 0.95) # Доверительные интервалы\n\n# Сравнение моделей\ndeterm <- s_many$r.squared\nadjust_determ <- s_many$adj.r.squared\nst_error <- error_many\napprox <- A_many\nf_test <- s_many$fstatistic[1]\n\n#######В) Проверьте значимость модели регрессии в целом и каждого коэффициента модели по отдельности.######\ncompare <- data.frame(\n Коэффициент_детерминации=determ,\n Скорректированный_коэффициент=adjust_determ,\n Стандартная_ошибка_модели=st_error,\n Ошибка_аппроксимации=approx,\n F_тест=f_test\n)\nprint(compare)\n\n\"\nКачество модели хорошее:\nМодель очень качественная R^2 = 0.9628084\nR^2 = 0.9628 (приближено к 1)\nSe = 1051 (относительно у не очень много — качество нормальное (умеренное отношение))\nF = 226.5\np-value = < 2.2e-16\nОшибка_аппроксимации < 7 - модель хорошая (5.371801)\n\"\n\n\n#прогнозирование по модели с фиктивными переменными\npred=data.frame(c(41,42,43),c(1,0,0),c(0,1,0),c(0,0,1))\ncolnames(pred)=c(\"x1\",\"x2\",\"x3\",\"x4\")\npredictGDP=predict(p_many, newdata = pred)\npredictGDP\npred\n\n\ndwtest(p_many) # Тест Дарбина-Ватсона\n# 2.676e-08\nbgtest(p_many, order = 1, order.by = NULL, type = c(\"Chisq\", \"F\")) # Тест Бреуша-Годфри\n#pv 4.028e-06 > 0.1,0.05, 0.01 =>H0 принимается, автокорреляция первого порядка отсутствует\n\ngqtest(p_many, order.by = x1, fraction = 0) # Тест Голдфельда-Квандта для x1\n#p-value = 0.1982 - больше 0.1 0.05 0.01, отсутствует проблема гетероскедастичности\n\nbptest(p_many, studentize = TRUE) # Тест Бреуша-Пагана\n#p-value = 0.546, - больше 0.1 0.05 0.01, отсутствует проблема гетероскедастичности\n\nerror_many <- sqrt(deviance(p_many)/df.residual(p_many))\n\n#работа с временным рядом GDP \nGDP <- c(data$GDP)\nGDP1 <- ts(data=GDP,start=c(2009), name=\"GDP\", frequency = 4)\nGDP1\nACF <- Acf(GDP1) # выборочная автокорреляция\nACF\nPACF <- Pacf(GDP1) # частная автокорреляиця \nPACF\ntsdisplay(GDP1)\n#вывод: ряд нестационарный", "meta": {"hexsha": "0a93bb946d4da2a10ab5d41c4d1a04ba4e7a05e2", "size": 2634, "ext": "r", "lang": "R", "max_stars_repo_path": "Course III/ECONOMETRICS/task8/r.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course III/ECONOMETRICS/task8/r.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course III/ECONOMETRICS/task8/r.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 27.1546391753, "max_line_length": 107, "alphanum_fraction": 0.6996962794, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6410138298621197}} {"text": "###############\r\n## Section 5 ##\r\n###############\r\n\r\n#install.packages(\"mlogit\")\r\nlibrary(mlogit)\r\nlibrary(MASS)\r\n\r\nsetwd(\"C:\\\\dc_book\\\\Replication_Files_Element\")\r\n\r\nbes.data.raw <- read.csv(\"BES2015.csv\", header=TRUE)\r\n\r\nbes.data <- mlogit.data(bes.data.raw, choice=\"vote\", shape=\"long\", chid.var=\"respondent_id\", alt.var=\"party_id\")\r\n\r\n###############\r\n## Table 5.1 ##\r\n###############\r\n\r\nbes2015.mnl <- mlogit(vote ~ taxspend | approve_EU + NHS_improved + income + female + age, data=bes.data, reflevel=4)\r\nbes2015.mnl.results <- cbind(bes2015.mnl$coefficients, sqrt(diag(vcov(bes2015.mnl))), confint.default(bes2015.mnl, level=0.95))\r\nN <- length(unique(bes.data$respondent_id))\r\nA <- nrow(bes.data)\r\ncolnames(bes2015.mnl.results) <- c(\"Coeff\", \"(se)\", \"2.5%\", \"97.5%\")\r\nprint((round(bes2015.mnl.results, digits=3)))\r\nprint(N)\r\nprint(A)\r\n\r\n###############\r\n## Table 5.2 ##\r\n###############\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- with(bes.data, data.frame(\r\nconstant = rbind(0, diag(3)),\r\ntaxspend = tapply(taxspend, idx(bes2015.mnl, 2), median), \r\napprove_EU = median(approve_EU) * rbind(0, diag(3)), \r\nNHS_improved = median(NHS_improved) * rbind(0, diag(3)),\r\nincome=median(income) * rbind(0, diag(3)),\r\nfemale=median(female) * rbind(0, diag(3)),\r\nage=median(age) * rbind(0, diag(3))\r\n))\r\n\r\nbaseline.x <- baseline.x[order(rownames(baseline.x)),]\r\n\r\napproveEUcol <- grep(\"approve_EU\", colnames(baseline.x))\r\ndiff.x <- baseline.x\r\ndiff.x[,approveEUcol] <- rbind(diag(3), 0) * 2\r\n\r\nexb.baseline <- exp(betadraw %*% t(baseline.x))\r\nexb.diff <- exp(betadraw %*% t(diff.x))\r\n\r\nprobs.baseline <- exb.baseline/rowSums(exb.baseline)\r\nprobs.diff <- exb.diff/rowSums(exb.diff)\r\n\r\nsimprob.diff <- probs.diff - probs.baseline \r\n\r\nall.results <- cbind(probs.baseline, probs.diff, simprob.diff)\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nfirst.differences <- cbind(t(quantiles), sds)\r\ncolnames(first.differences) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(first.differences) <- c(\"Neutral:Conservative\", \"Neutral:Labour\", \"Neutral:LibDem\", \"Neutral:UKIP\", \"Disapprove:Conservative\", \"Disapprove:Labour\", \"Disapprove:LibDem\", \"Disapprove:UKIP\", \"Diff:Conservative\", \"Diff:Labour\", \"Diff:LibDem\", \"Diff:UKIP\")\r\nprint(round(first.differences, digits=3))\r\n\r\n\r\n\r\n#################\r\n## Figure 5.1 ##\r\n#################\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\nbaseline.x <- with(bes.data, data.frame(\r\nconstant = rbind(0, diag(3)),\r\ntaxspend = tapply(taxspend, idx(bes2015.mnl, 2), median), \r\napprove_EU = median(approve_EU) * rbind(0, diag(3)), \r\nNHS_improved = median(NHS_improved) * rbind(0, diag(3)),\r\nincome = median(income) * rbind(0, diag(3)),\r\nfemale = median(female) * rbind(0, diag(3)),\r\nage = median(age) * rbind(0, diag(3))\r\n))\r\n\r\n## the reference level is always first in idx \r\n# reorder rows to avoid confusion\r\nbaseline.x <- baseline.x[order(rownames(baseline.x)),]\r\n\r\nagecols <- grep(\"age\", colnames(baseline.x))\r\nage.range <- c(10:100)\r\n\r\nmlogit.probs1 <- matrix(NA, ndraws, length(age.range))\r\nmlogit.probs2 <- matrix(NA, ndraws, length(age.range))\r\nmlogit.probs3 <- matrix(NA, ndraws, length(age.range))\r\nmlogit.probs4 <- matrix(NA, ndraws, length(age.range))\r\n\r\nmlogit.mean.probs <- matrix(NA, 4, length(age.range))\r\n\r\n\r\nfor (i in 1:length(age.range)) {\r\n\r\n\tbaseline.x[,agecols] <- rbind(diag(3), 0) * age.range[i]\r\n\texb <- exp(betadraw %*% t(baseline.x))\t\r\n\t\r\n\tmlogit.probs1[,i] <- exb[,1]/rowSums(exb)\r\n\tmlogit.probs2[,i] <- exb[,2]/rowSums(exb)\r\n\tmlogit.probs3[,i] <- exb[,3]/rowSums(exb)\r\n\tmlogit.probs4[,i] <- exb[,4]/rowSums(exb)\r\n\t\r\n\tmprobs.mean <- exp(beta%*%t(baseline.x))\r\n\tmlogit.mean.probs[1,i] <- mprobs.mean[1]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[2,i] <- mprobs.mean[2]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[3,i] <- mprobs.mean[3]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[4,i] <- mprobs.mean[4]/sum(mprobs.mean)\r\n\t\r\n}\r\n\r\n\r\n# Conservative, Labour, Liberal Democrat, UKIP\r\n\r\ncolors <- c(\"#47E3FF80\", \"#FF634780\", \"#B1D87780\",\"#6347FF80\")\r\n\r\n\r\npdf(\"fig51.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 5.6), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(mlogit.mean.probs[1,]~age.range, xlim=c(18,90), ylim=c(0,0.8), type=\"n\", xlab=\"Age\", ylab=\"Probability\", xaxt=\"n\", las=1)\r\naxis(1, at=c(18, 30, 40, 50, 60, 70, 80, 90))\r\nfor (i in 1:length(age.range)){\r\n\tpoints(mlogit.probs1[i,] ~ age.range, type=\"l\", col=colors[1], lwd=1)\r\n\tpoints(mlogit.probs2[i,] ~ age.range, type=\"l\", col=colors[2], lwd=1)\r\n\tpoints(mlogit.probs3[i,] ~ age.range, type=\"l\", col=colors[3], lwd=1)\r\n\tpoints(mlogit.probs4[i,] ~ age.range, type=\"l\", col=colors[4], lwd=1)\r\n}\r\nlines(mlogit.mean.probs[1,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[2,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[3,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[4,]~age.range, col=rgb(0,0,0,0.5), lwd=2)\r\nmtext(\"Conservative\", side=4, at=mlogit.mean.probs[1,84], cex=1.1, las=1, line=0.3)\r\nmtext(\"Labour\", side=4, at=mlogit.mean.probs[2,84]+0.02, cex=1.1, las=1, line=0.3)\r\nmtext(\"Liberal\", side=4, at=mlogit.mean.probs[3,84]-0.01, cex=1.1, las=1, line=0.3)\r\nmtext(\"Democrat\", side=4, at=mlogit.mean.probs[3,84]-0.04, cex=1.1, las=1, line=0.3)\r\nmtext(\"UKIP\", side=4, at=mlogit.mean.probs[4,84], cex=1.1, las=1, line=0.3)\r\ndev.off()\r\n\r\n\r\n#################\r\n## Figure 5.2 ##\r\n#################\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\n\r\nbaseline.x <- with(bes.data, data.frame(\r\nconstant = rbind(0, diag(3)),\r\ntaxspend = tapply(taxspend, idx(bes2015.mnl, 2), median), \r\napprove_EU = median(approve_EU) * rbind(0, diag(3)), \r\nNHS_improved = median(NHS_improved) * rbind(0, diag(3)),\r\nincome = median(income) * rbind(0, diag(3)),\r\nfemale = median(female) * rbind(0, diag(3)),\r\nage = median(age) * rbind(0, diag(3))\r\n))\r\n\r\nbaseline.x <- baseline.x[order(rownames(baseline.x)),]\r\n\r\ntaxspendcol <- grep(\"taxspend\", colnames(baseline.x))\r\ntaxspend.range <- seq(-5,15,0.1) \r\nmlogit.probs1 <- matrix(NA, ndraws, length(taxspend.range))\r\nmlogit.probs2 <- matrix(NA, ndraws, length(taxspend.range))\r\nmlogit.probs3 <- matrix(NA, ndraws, length(taxspend.range))\r\nmlogit.probs4 <- matrix(NA, ndraws, length(taxspend.range))\r\n\r\nmlogit.mean.probs <- matrix(NA, 4, length(taxspend.range))\r\n\r\nfor (i in 1:length(taxspend.range)) {\r\n\r\n\tbaseline.x[rownames(baseline.x)==\"4\", taxspendcol] <- taxspend.range[i] \r\n\texb <- exp(betadraw %*% t(baseline.x))\r\n\tmlogit.probs1[,i] <- exb[,1]/rowSums(exb)\r\n\tmlogit.probs2[,i] <- exb[,2]/rowSums(exb)\r\n\tmlogit.probs3[,i] <- exb[,3]/rowSums(exb)\r\n\tmlogit.probs4[,i] <- exb[,4]/rowSums(exb)\r\n\t\r\n\tmprobs.mean <- exp(beta%*%t(baseline.x))\r\n\tmlogit.mean.probs[1,i] <- mprobs.mean[1]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[2,i] <- mprobs.mean[2]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[3,i] <- mprobs.mean[3]/sum(mprobs.mean)\r\n\tmlogit.mean.probs[4,i] <- mprobs.mean[4]/sum(mprobs.mean)\r\n}\r\n\r\n# Conservative, Labour, Liberal Democrat, UKIP\r\n\r\ncolors <- c(\"#47E3FF80\", \"#FF634780\", \"#B1D87780\",\"#6347FF80\")\r\n\r\npdf(\"fig52.pdf\")\r\npar(mar=c(5.1, 4.1, 4.1, 5.6), mgp=c(2.5, 1, 0), cex.lab=1.5)\r\nplot(mlogit.mean.probs[1,]~taxspend.range, xlim=c(1,10), ylim=c(0,0.6), type=\"n\", xlab=\"Tax/Spend Scale\", ylab=\"Probability\", xaxt=\"n\", las=1)\r\naxis(1, at=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))\r\nfor (i in 1:length(taxspend.range)){\r\n\tpoints(mlogit.probs1[i,] ~ taxspend.range, type=\"l\", col=colors[1], lwd=1)\r\n\tpoints(mlogit.probs2[i,] ~ taxspend.range, type=\"l\", col=colors[2], lwd=1)\r\n\tpoints(mlogit.probs3[i,] ~ taxspend.range, type=\"l\", col=colors[3], lwd=1)\r\n\tpoints(mlogit.probs4[i,] ~ taxspend.range, type=\"l\", col=colors[4], lwd=1)\r\n}\r\nlines(mlogit.mean.probs[1,]~taxspend.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[2,]~taxspend.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[3,]~taxspend.range, col=rgb(0,0,0,0.5), lwd=2)\r\nlines(mlogit.mean.probs[4,]~taxspend.range, col=rgb(0,0,0,0.5), lwd=2)\r\nmtext(\"Conservative\", side=4, at=mlogit.mean.probs[1,156], cex=1.1, las=1, line=0.3)\r\nmtext(\"Labour\", side=4, at=mlogit.mean.probs[2,156], cex=1.1, las=1, line=0.3)\r\nmtext(\"Liberal\", side=4, at=mlogit.mean.probs[3,156]+0.01, cex=1.1, las=1, line=0.3)\r\nmtext(\"Democrat\", side=4, at=mlogit.mean.probs[3,156]-0.01, cex=1.1, las=1, line=0.3)\r\nmtext(\"UKIP\", side=4, at=mlogit.mean.probs[4,156], cex=1.1, las=1, line=0.3)\r\ndev.off()\r\n\r\n\r\n###############\r\n## Table 5.3 ##\r\n###############\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\n## observed\r\n\r\nobserved.x <- with(bes.data, data.frame(\r\ncons1 = as.numeric(idx[2]==1),\r\ncons2 = as.numeric(idx[2]==2),\r\ncons3 = as.numeric(idx[2]==3),\r\ntaxspend = taxspend, \r\napprove_EU1 = approve_EU * as.numeric(idx[2]==1), \r\napprove_EU2 = approve_EU * as.numeric(idx[2]==2), \r\napprove_EU3 = approve_EU * as.numeric(idx[2]==3), \r\nNHS_improved1 = NHS_improved * as.numeric(idx[2]==1),\r\nNHS_improved2 = NHS_improved * as.numeric(idx[2]==2),\r\nNHS_improved3 = NHS_improved * as.numeric(idx[2]==3),\r\nincome1 = income * as.numeric(idx[2]==1),\r\nincome2 = income * as.numeric(idx[2]==2),\r\nincome3 = income * as.numeric(idx[2]==3),\r\nfemale1 = female * as.numeric(idx[2]==1),\r\nfemale2 = female * as.numeric(idx[2]==2),\r\nfemale3 = female * as.numeric(idx[2]==3),\r\nage1 = age * as.numeric(idx[2]==1),\r\nage2 = age * as.numeric(idx[2]==2),\r\nage3 = age * as.numeric(idx[2]==3),\r\nid = idx,\r\nweights = wt_combined_main\r\n))\r\n\r\nexb.party1.o <- exp(betadraw %*% t(subset(observed.x, id.alt==1, select=c(1:19))))\r\nexb.party2.o <- exp(betadraw %*% t(subset(observed.x, id.alt==2, select=c(1:19))))\r\nexb.party3.o <- exp(betadraw %*% t(subset(observed.x, id.alt==3, select=c(1:19))))\r\nexb.party4.o <- exp(betadraw %*% t(subset(observed.x, id.alt==4, select=c(1:19))))\r\nexb.all.o <- exb.party1.o + exb.party2.o + exb.party3.o + exb.party4.o\r\n\r\nprobs1.o <- exb.party1.o/exb.all.o\r\nprobs2.o <- exb.party2.o/exb.all.o\r\nprobs3.o <- exb.party3.o/exb.all.o\r\nprobs4.o <- exb.party4.o/exb.all.o\r\n\r\nid.weights <- observed.x$weights[observed.x$id.alt==1]\r\n\r\nshares.party1.o <- colSums(apply(probs1.o, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party2.o <- colSums(apply(probs2.o, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party3.o <- colSums(apply(probs3.o, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party4.o <- colSums(apply(probs4.o, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\n\r\n## counterfactual\r\n\r\ncounterfactual.x <- observed.x\r\ncounterfactual.x$rand.draw <- rep(runif(length(unique(counterfactual.x$id.chid))), each=4)\r\ncounterfactual.x$approve_EU1[counterfactual.x$approve_EU1 > 1 & counterfactual.x$rand.draw <= 0.25] <- counterfactual.x$approve_EU1[counterfactual.x$approve_EU1 > 1 & counterfactual.x$rand.draw <= 0.25] - 1\r\ncounterfactual.x$approve_EU2[counterfactual.x$approve_EU2 > 1 & counterfactual.x$rand.draw <= 0.25] <- counterfactual.x$approve_EU2[counterfactual.x$approve_EU2 > 1 & counterfactual.x$rand.draw <= 0.25] - 1\r\ncounterfactual.x$approve_EU3[counterfactual.x$approve_EU3 > 1 & counterfactual.x$rand.draw <= 0.25] <- counterfactual.x$approve_EU3[counterfactual.x$approve_EU3 > 1 & counterfactual.x$rand.draw <= 0.25] - 1\r\n\r\nexb.party1.c <- exp(betadraw %*% t(subset(counterfactual.x, id.alt==1, select=c(1:19))))\r\nexb.party2.c <- exp(betadraw %*% t(subset(counterfactual.x, id.alt==2, select=c(1:19))))\r\nexb.party3.c <- exp(betadraw %*% t(subset(counterfactual.x, id.alt==3, select=c(1:19))))\r\nexb.party4.c <- exp(betadraw %*% t(subset(counterfactual.x, id.alt==4, select=c(1:19))))\r\nexb.all.c <- exb.party1.c + exb.party2.c + exb.party3.c + exb.party4.c\r\n\r\nprobs1.c <- exb.party1.c/exb.all.c\r\nprobs2.c <- exb.party2.c/exb.all.c\r\nprobs3.c <- exb.party3.c/exb.all.c\r\nprobs4.c <- exb.party4.c/exb.all.c\r\n\r\nshares.party1.c <- colSums(apply(probs1.c, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party2.c <- colSums(apply(probs2.c, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party3.c <- colSums(apply(probs3.c, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party4.c <- colSums(apply(probs4.c, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\n\r\n## difference\r\n\r\nprobs1.diff <- probs1.c - probs1.o\r\nprobs2.diff <- probs2.c - probs2.o\r\nprobs3.diff <- probs3.c - probs3.o\r\nprobs4.diff <- probs4.c - probs4.o\r\n\r\nshares.party1.diff <- colSums(apply(probs1.diff, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party2.diff <- colSums(apply(probs2.diff, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party3.diff <- colSums(apply(probs3.diff, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\nshares.party4.diff <- colSums(apply(probs4.diff, 1, function(x){x * id.weights}))/sum(id.weights) * 100\r\n\r\nall.results <- cbind(shares.party1.o, shares.party2.o, shares.party3.o, shares.party4.o, shares.party1.c, shares.party2.c, shares.party3.c, shares.party4.c, shares.party1.diff, shares.party2.diff, shares.party3.diff, shares.party4.diff)\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nfirst.differences <- cbind(t(quantiles), sds)\r\ncolnames(first.differences) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(first.differences) <- c(\"Neutral:Conservative\", \"Neutral:Labour\", \"Neutral:LibDem\", \"Neutral:UKIP\", \"Disapprove:Conservative\", \"Disapprove:Labour\", \"Disapprove:LibDem\", \"Disapprove:UKIP\", \"Diff:Conservative\", \"Diff:Labour\", \"Diff:LibDem\", \"Diff:UKIP\")\r\nprint(round(first.differences, digits=3))\r\n\r\n###############\r\n## Table 5.4 ##\r\n###############\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\napproveEU.coeffs <- cbind(betadraw[,grep(\"approve_EU\", colnames(betadraw))], 0)\r\n\r\n## AME ##\r\n\r\nobserved.x <- with(bes.data, data.frame(\r\ncons1 = as.numeric(idx[2]==1),\r\ncons2 = as.numeric(idx[2]==2),\r\ncons3 = as.numeric(idx[2]==3),\r\ntaxspend = taxspend, \r\napprove_EU1 = approve_EU * as.numeric(idx[2]==1), \r\napprove_EU2 = approve_EU * as.numeric(idx[2]==2), \r\napprove_EU3 = approve_EU * as.numeric(idx[2]==3), \r\nNHS_improved1 = NHS_improved * as.numeric(idx[2]==1),\r\nNHS_improved2 = NHS_improved * as.numeric(idx[2]==2),\r\nNHS_improved3 = NHS_improved * as.numeric(idx[2]==3),\r\nincome1 = income * as.numeric(idx[2]==1),\r\nincome2 = income * as.numeric(idx[2]==2),\r\nincome3 = income * as.numeric(idx[2]==3),\r\nfemale1 = female * as.numeric(idx[2]==1),\r\nfemale2 = female * as.numeric(idx[2]==2),\r\nfemale3 = female * as.numeric(idx[2]==3),\r\nage1 = age * as.numeric(idx[2]==1),\r\nage2 = age * as.numeric(idx[2]==2),\r\nage3 = age * as.numeric(idx[2]==3),\r\nid = idx,\r\nweights = wt_combined_main\r\n))\r\n\r\napproveEU <- observed.x[observed.x$id.alt==1, grep(\"approve_EU1\", colnames(observed.x))]\r\n\r\nexb.party1 <- exp(betadraw %*% t(subset(observed.x, id.alt==1, select=c(1:19))))\r\nexb.party2 <- exp(betadraw %*% t(subset(observed.x, id.alt==2, select=c(1:19))))\r\nexb.party3 <- exp(betadraw %*% t(subset(observed.x, id.alt==3, select=c(1:19))))\r\nexb.party4 <- exp(betadraw %*% t(subset(observed.x, id.alt==4, select=c(1:19))))\r\nexb.all <- exb.party1 + exb.party2 + exb.party3 + exb.party4\r\n\r\nprobs1 <- exb.party1/exb.all\r\nprobs2 <- exb.party2/exb.all\r\nprobs3 <- exb.party3/exb.all\r\nprobs4 <- exb.party4/exb.all\r\n\r\nid.weights <- observed.x$weights[observed.x$id.alt==1]/observed.x$weights[observed.x$id.alt==1]\r\n\r\n## marginal effects\r\n\r\nme.approveEU.1 <- probs1 * (approveEU.coeffs[,1] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\nme.approveEU.2 <- probs2 * (approveEU.coeffs[,2] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\nme.approveEU.3 <- probs3 * (approveEU.coeffs[,3] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\nme.approveEU.4 <- probs4 * (approveEU.coeffs[,4] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\n\r\nme.AME.approveEU.1 <- colSums(apply(me.approveEU.1, 1, function(x){x * id.weights}))/sum(id.weights)\r\nme.AME.approveEU.2 <- colSums(apply(me.approveEU.2, 1, function(x){x * id.weights}))/sum(id.weights)\r\nme.AME.approveEU.3 <- colSums(apply(me.approveEU.3, 1, function(x){x * id.weights}))/sum(id.weights)\r\nme.AME.approveEU.4 <- colSums(apply(me.approveEU.4, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\n\r\n## elasticities\r\n\r\ne.approveEU.1 <- approveEU * (approveEU.coeffs[,1] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\ne.approveEU.2 <- approveEU * (approveEU.coeffs[,2] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\ne.approveEU.3 <- approveEU * (approveEU.coeffs[,3] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\ne.approveEU.4 <- approveEU * (approveEU.coeffs[,4] - ((probs1 * approveEU.coeffs[,1]) + (probs2 * approveEU.coeffs[,2]) + (probs3 * approveEU.coeffs[,3]) + (probs4 * approveEU.coeffs[,4])))\r\n\r\ne.AME.approveEU.1 <- colSums(apply(e.approveEU.1, 1, function(x){x * id.weights}))/sum(id.weights)\r\ne.AME.approveEU.2 <- colSums(apply(e.approveEU.2, 1, function(x){x * id.weights}))/sum(id.weights)\r\ne.AME.approveEU.3 <- colSums(apply(e.approveEU.3, 1, function(x){x * id.weights}))/sum(id.weights)\r\ne.AME.approveEU.4 <- colSums(apply(e.approveEU.4, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\n## MEM ##\r\n\r\nmean.x <- with(bes.data, data.frame(\r\nconstant = rbind(0, diag(3)),\r\ntaxspend = tapply(taxspend, idx(bes2015.mnl, 2), mean), \r\napprove_EU = mean(approve_EU) * rbind(0, diag(3)), \r\nNHS_improved = mean(NHS_improved) * rbind(0, diag(3)),\r\nincome=mean(income) * rbind(0, diag(3)),\r\nfemale=mean(female) * rbind(0, diag(3)),\r\nage=mean(age) * rbind(0, diag(3))\r\n))\r\n\r\nmean.x <- mean.x[order(rownames(mean.x)),]\r\nmean.approveEU <- mean(bes.data$approve_EU)\r\n\r\nexb.mean <- exp(betadraw %*% t(mean.x))\r\n\r\nprobs.mean <- exb.mean/rowSums(exb.mean)\r\n\r\n## marginal effects\r\n\r\nme.MEM.approveEU.1 <- probs.mean[,1] * (approveEU.coeffs[,1] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\nme.MEM.approveEU.2 <- probs.mean[,2] * (approveEU.coeffs[,2] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\nme.MEM.approveEU.3 <- probs.mean[,3] * (approveEU.coeffs[,3] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\nme.MEM.approveEU.4 <- probs.mean[,4] * (approveEU.coeffs[,4] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\n\r\n## elasticities \r\n\r\ne.MEM.approveEU.1 <- mean.approveEU * (approveEU.coeffs[,1] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\ne.MEM.approveEU.2 <- mean.approveEU * (approveEU.coeffs[,2] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\ne.MEM.approveEU.3 <- mean.approveEU * (approveEU.coeffs[,3] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\ne.MEM.approveEU.4 <- mean.approveEU * (approveEU.coeffs[,4] - ((probs.mean[,1] * approveEU.coeffs[,1]) + (probs.mean[,2] * approveEU.coeffs[,2]) + (probs.mean[,3] * approveEU.coeffs[,3]) + (probs.mean[,4] * approveEU.coeffs[,4])))\r\n\r\nall.results <- cbind(me.AME.approveEU.1, me.AME.approveEU.2, me.AME.approveEU.3, me.AME.approveEU.4, me.MEM.approveEU.1, me.MEM.approveEU.2, me.MEM.approveEU.3, me.MEM.approveEU.4, e.AME.approveEU.1, e.AME.approveEU.2, e.AME.approveEU.3, e.AME.approveEU.4, e.MEM.approveEU.1, e.MEM.approveEU.2, e.MEM.approveEU.3, e.MEM.approveEU.4)\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nmarginal.effects <- cbind(t(quantiles), sds)\r\ncolnames(marginal.effects) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(marginal.effects) <- c(\"Conservative:AME\", \"Labour:AME\", \"LibDem:AME\", \"UKIP:AME\", \"Conservative:MEM\", \"Labour:MEM\", \"LibDem:MEM\", \"UKIP:MEM\", \"Conservative: Average Elasticity\", \"Labour: Average Elasticity\", \"LibDem: Average Elasticity\", \"UKIP: Average Elasticity\", \"Conservative: Elasticity at the Mean\", \"Labour: Elasticity at the Mean\", \"LibDem: Elasticity at the Mean\", \"UKIP: Elasticity at the Mean\")\r\nprint(round(marginal.effects, digits=3))\r\n\r\n###############\r\n## Table 5.5 ##\r\n###############\r\n\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\n\r\ntaxspend.coeffs <- betadraw[,grep(\"taxspend\", colnames(betadraw))]\r\n\r\n## AME ##\r\n\r\nobserved.x <- with(bes.data, data.frame(\r\ncons1 = as.numeric(idx[2]==1),\r\ncons2 = as.numeric(idx[2]==2),\r\ncons3 = as.numeric(idx[2]==3),\r\ntaxspend = taxspend, \r\napprove_EU1 = approve_EU * as.numeric(idx[2]==1), \r\napprove_EU2 = approve_EU * as.numeric(idx[2]==2), \r\napprove_EU3 = approve_EU * as.numeric(idx[2]==3), \r\nNHS_improved1 = NHS_improved * as.numeric(idx[2]==1),\r\nNHS_improved2 = NHS_improved * as.numeric(idx[2]==2),\r\nNHS_improved3 = NHS_improved * as.numeric(idx[2]==3),\r\nincome1 = income * as.numeric(idx[2]==1),\r\nincome2 = income * as.numeric(idx[2]==2),\r\nincome3 = income * as.numeric(idx[2]==3),\r\nfemale1 = female * as.numeric(idx[2]==1),\r\nfemale2 = female * as.numeric(idx[2]==2),\r\nfemale3 = female * as.numeric(idx[2]==3),\r\nage1 = age * as.numeric(idx[2]==1),\r\nage2 = age * as.numeric(idx[2]==2),\r\nage3 = age * as.numeric(idx[2]==3),\r\nid = idx,\r\nweights = wt_combined_main\r\n))\r\n\r\nparty4.taxspend <- observed.x[observed.x$id.alt==4, grep(\"taxspend\", colnames(observed.x))]\r\n\r\nexb.party1 <- exp(betadraw %*% t(subset(observed.x, id.alt==1, select=c(1:19))))\r\nexb.party2 <- exp(betadraw %*% t(subset(observed.x, id.alt==2, select=c(1:19))))\r\nexb.party3 <- exp(betadraw %*% t(subset(observed.x, id.alt==3, select=c(1:19))))\r\nexb.party4 <- exp(betadraw %*% t(subset(observed.x, id.alt==4, select=c(1:19))))\r\nexb.all <- exb.party1 + exb.party2 + exb.party3 + exb.party4\r\n\r\nprobs1 <- exb.party1/exb.all\r\nprobs2 <- exb.party2/exb.all\r\nprobs3 <- exb.party3/exb.all\r\nprobs4 <- exb.party4/exb.all\r\n\r\nid.weights <- observed.x$weights[observed.x$id.alt==1]/observed.x$weights[observed.x$id.alt==1]\r\n\r\n## marginal effects for UKIP\r\nme.taxspend <- taxspend.coeffs * (probs4 * (1 - probs4))\r\nme.AME.taxspend <- colSums(apply(me.taxspend, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\n## cross-marginal effects\r\ncme.taxspend41 <- taxspend.coeffs * (probs1 * probs4)\r\ncme.taxspend42 <- taxspend.coeffs * (probs2 * probs4)\r\ncme.taxspend43 <- taxspend.coeffs * (probs3 * probs4)\r\n\r\ncme.AME.taxspend41 <- -1 * colSums(apply(cme.taxspend41, 1, function(x){x * id.weights}))/sum(id.weights)\r\ncme.AME.taxspend42 <- -1 * colSums(apply(cme.taxspend42, 1, function(x){x * id.weights}))/sum(id.weights)\r\ncme.AME.taxspend43 <- -1 * colSums(apply(cme.taxspend43, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\ncme.AME.taxspend <- cbind(cme.AME.taxspend41, cme.AME.taxspend42, cme.AME.taxspend43)\r\n\r\n## elasticities for UKIP\r\ne.taxspend <- taxspend.coeffs * t(party4.taxspend * t(1 - probs4))\r\ne.AME.taxspend <- colSums(apply(e.taxspend, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\n## cross-elasticities\r\nce.taxspend41 <- taxspend.coeffs * t(party4.taxspend * t(probs4))\r\nce.taxspend42 <- taxspend.coeffs * t(party4.taxspend * t(probs4))\r\nce.taxspend43 <- taxspend.coeffs * t(party4.taxspend * t(probs4))\r\n\r\nce.AME.taxspend41 <- -1 * colSums(apply(ce.taxspend41, 1, function(x){x * id.weights}))/sum(id.weights)\r\nce.AME.taxspend42 <- -1 * colSums(apply(ce.taxspend42, 1, function(x){x * id.weights}))/sum(id.weights)\r\nce.AME.taxspend43 <- -1 * colSums(apply(ce.taxspend43, 1, function(x){x * id.weights}))/sum(id.weights)\r\n\r\nce.AME.taxspend <- cbind(ce.AME.taxspend41, ce.AME.taxspend42, ce.AME.taxspend43)\r\n\r\n## MEM ##\r\n\r\nmean.x <- with(bes.data, data.frame(\r\nconstant = rbind(0, diag(3)),\r\ntaxspend = tapply(taxspend, idx(bes2015.mnl, 2), mean), \r\napprove_EU = mean(approve_EU) * rbind(0, diag(3)), \r\nNHS_improved = mean(NHS_improved) * rbind(0, diag(3)),\r\nincome=mean(income) * rbind(0, diag(3)),\r\nfemale=mean(female) * rbind(0, diag(3)),\r\nage=mean(age) * rbind(0, diag(3))\r\n))\r\n\r\nmean.x <- mean.x[order(rownames(mean.x)),]\r\n\r\ntaxspendcol <- grep(\"taxspend\", colnames(mean.x))\r\n\r\nexb.mean <- exp(betadraw %*% t(mean.x))\r\n\r\nprobs.mean <- exb.mean/rowSums(exb.mean)\r\n\r\n## marginal effects for UKIP\r\nme.MEM.taxspend <- taxspend.coeffs * probs.mean[,colnames(probs.mean)==\"4\"] * (1 - probs.mean[,colnames(probs.mean)==\"4\"])\r\n\r\n## cross-marginal effects\r\ncme.MEM.taxspend41 <- -1 * taxspend.coeffs * probs.mean[,colnames(probs.mean)==\"4\"] * probs.mean[,colnames(probs.mean)==\"1\"]\r\ncme.MEM.taxspend42 <- -1 * taxspend.coeffs * probs.mean[,colnames(probs.mean)==\"4\"] * probs.mean[,colnames(probs.mean)==\"2\"]\r\ncme.MEM.taxspend43 <- -1 * taxspend.coeffs * probs.mean[,colnames(probs.mean)==\"4\"] * probs.mean[,colnames(probs.mean)==\"3\"]\r\ncme.MEM.taxspend <- cbind(cme.MEM.taxspend41, cme.MEM.taxspend42, cme.MEM.taxspend43)\r\n\r\n## elasticities for UKIP\r\ne.MEM.taxspend <- taxspend.coeffs * mean.x[rownames(mean.x)==\"4\",taxspendcol] * (1 - probs.mean[,colnames(probs.mean)==\"4\"])\r\n\r\n## cross-elasticities\r\nce.MEM.taxspend41 <- -1 * taxspend.coeffs * mean.x[rownames(mean.x)==\"4\",taxspendcol] * probs.mean[,colnames(probs.mean)==\"4\"]\r\nce.MEM.taxspend42 <- -1 * taxspend.coeffs * mean.x[rownames(mean.x)==\"4\",taxspendcol] * probs.mean[,colnames(probs.mean)==\"4\"]\r\nce.MEM.taxspend43 <- -1 * taxspend.coeffs * mean.x[rownames(mean.x)==\"4\",taxspendcol] * probs.mean[,colnames(probs.mean)==\"4\"]\r\nce.MEM.taxspend <- cbind(ce.MEM.taxspend41, ce.MEM.taxspend42, ce.MEM.taxspend43)\r\n\r\nall.results <- cbind(me.AME.taxspend, me.MEM.taxspend, e.AME.taxspend, e.MEM.taxspend, cme.AME.taxspend, cme.MEM.taxspend, ce.AME.taxspend, ce.MEM.taxspend)\r\n\r\nquantiles <- apply(all.results, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(all.results, 2, sd)\r\nmarginal.effects <- cbind(t(quantiles), sds)\r\ncolnames(marginal.effects) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(marginal.effects) <- c(\"UKIP: AME\", \"UKIP: MEM\", \"UKIP: Average Elasticity\", \"UKIP: Elasticity at the Mean\", \"Conservative: Average CME\", \"Labour: Average CME\", \"LibDem: Average CME\", \"Conservative: CME at Mean\", \"Labour: CME at Mean\", \"LibDem: CME at Mean\", \"Conservative: Average CE\", \"Labour: Average CE\", \"LibDem: Average CE\", \"Conservative: CE at Mean\", \"Labour: CE at Mean\", \"LibDem: CE at Mean\")\r\nprint(round(marginal.effects, digits=3))\r\n\r\n\r\n###############\r\n## Table 5.6 ##\r\n###############\r\n\r\nN <- length(unique(bes.data$respondent_id))\r\nA <- nrow(bes.data)\r\nbeta <- bes2015.mnl$coefficients\r\ncovmat.beta <- vcov(bes2015.mnl)\r\nndraws <- 1000\r\n\r\nbetadraw <- mvrnorm(ndraws, beta, covmat.beta)\r\nexp.betadraw <- exp(betadraw)\r\nquantiles <- apply(exp.betadraw, 2, function(x) {quantile(x, probs=c(0.5, 0.025, 0.975))})\r\nsds <- apply(exp.betadraw, 2, sd)\r\nodds.ratios <- cbind(t(quantiles), sds)\r\ncolnames(odds.ratios) <- c(\"Median\", \"2.5%\", \"97.5%\", \"(se)\")\r\nrownames(odds.ratios) <- names(beta) \r\nprint(round(odds.ratios, digits=3))\r\nprint(N)\r\nprint(A)\r\n\r\n", "meta": {"hexsha": "62ee06d973f30f2ab1d55423ddf9b3768886ee30", "size": 28452, "ext": "r", "lang": "R", "max_stars_repo_path": "R Code/Section5.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/Section5.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/Section5.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": 47.9797639123, "max_line_length": 416, "alphanum_fraction": 0.6572121468, "num_tokens": 10399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6408137789433467}} {"text": "# 4. faza: Analiza podatkov\n\n#predvidevanje gibanja \npodatki <- brezposelnost_in_obsojeni2 %>% filter(obsojeni < 10 & brezposelni < 25)\n\nggplot(podatki, aes(x = brezposelni, y = obsojeni)) + \n geom_point() + geom_smooth(method=lm, se = FALSE) \n\n# izračun modela\nfit <- lm(obsojeni ~ brezposelni, data=podatki)\nsummary(fit)\n\n# primer predikcije\nnovi.brezposelni <- data.frame(brezposelni=c(25, 30,35))\npredict(fit, novi.brezposelni)\nnapoved <- novi.brezposelni %>% mutate(obsojeni=predict(fit, .))\n\n# izris napovedi\nggplot(podatki, aes(x = brezposelni, y = obsojeni)) + \n geom_point(shape=1) + \n geom_smooth(method=lm) +\n geom_point(data=napoved, aes(x = brezposelni, y = obsojeni), color='red', size=3)\n\n# dodajanje enačbe kot anotacije \nenacba <- function(x) {\n lm_coef <- list(a = round(coef(x)[1], digits = 2),\n b = round(coef(x)[2], digits = 2),\n r2 = round(summary(x)$r.squared, digits = 2));\n lm_eq <- substitute(italic(y) == a + b %.% italic(x)*\",\"~~italic(R)^2~\"=\"~r2,lm_coef)\n as.character(as.expression(lm_eq)); \n}\n\nenacba(fit)\n\nggplot(podatki, aes(x = brezposelni, y = obsojeni)) + \n geom_point(shape=1) + \n geom_smooth(method=lm) +\n geom_point(data=napoved, aes(x = brezposelni, y = obsojeni), color='red', size=3) +\n annotate(\"text\", x = 20, y = 10, label = enacba(fit), parse = TRUE) +\n ggtitle('Linearna regresija') + \n theme_bw()\n\n", "meta": {"hexsha": "91d55b7ebed6fc148131ada6dec834fa32141839", "size": 1411, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "katarinabrilej/APPR-2017-18", "max_stars_repo_head_hexsha": "b73937f989072217499b6d3db8a833cffb24ff22", "max_stars_repo_licenses": ["MIT"], "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": "katarinabrilej/APPR-2017-18", "max_issues_repo_head_hexsha": "b73937f989072217499b6d3db8a833cffb24ff22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-11-23T08:02:35.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-17T22:05:58.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "katarinabrilej/APPR-2017-18", "max_forks_repo_head_hexsha": "b73937f989072217499b6d3db8a833cffb24ff22", "max_forks_repo_licenses": ["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.8139534884, "max_line_length": 87, "alphanum_fraction": 0.6477675408, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6406792231465227}} {"text": "#pca: componente principal a graficar\n#n: limite de comp a grafica\n#j desde donde se iniciara la graifcacion\ngraf<-function(pca,j,n)\n{\n\tpar(mfrow=c(n-j+1,1))\n\tfor(i in j:n)\n\t{\n\t\tplot(-1*loadings(pca)[,i],type=\"h\",col=\"blue\",ylab=paste(\"Componente\",i),xaxt = \"n\")\n\t\tabline(h=0)\n\t\taxis(1, at = 1:nrow(loadings(pca)),\n\t\t\tlabels = rownames(loadings(pca)))\n\t}\n}\ngraf1<-function(pca)\n{\n\tplot(pca$sdev^2,ylab=expression(lambda),xaxt=\"n\",pch=21,bg=\"blue\",xlab=\"Componentes\")\n\taxis(1, at = 1:ncol(loadings(pca)),\n\t\tlabels = colnames(loadings(pca)))\n\tabline(h=mean(pca$sdev^2),col=\"red\")\n}\n\n#Articulo\nnorma<-function(x)\n{\n\tif(ncol(x)==1||is.null(ncol(x)))\n\t{\n\t\tx<-matrix(x,nrow=1)\n\t\tsal<-sqrt(x%*%t(x))\n\t\treturn(sal)\n\t}\n\tsal<-sqrt(x%*%t(x))\n\tsal<-sal[col(sal)==row(sal)]\n\treturn(sal)\n}\nfuncion1<-function(Patrones)\n{\n\tSIGMA<-Patrones\n\tA<-SIGMA-rowMeans(SIGMA)\n\tv1<-eigen(t(A)%*%A)$vectors\n\tl1<-eigen(t(A)%*%A)$values\n\tv<-A%*%v1\n\tv<-qr.Q(qr(v))\n\treturn(list(A,v,l1))\n}\nfuncion2<-function(A,v)\n{\n\tOmega<-NULL\n\tfor( h in 1:ncol(A))\n\t{\n\t\tWW<-NULL\n\t\tfor(i in 1:ncol(v))\n\t\t{\n\t\t\tpesodelaimagen<-v[,i]%*%A[,h] \n\t\t\tWW<-c(WW,pesodelaimagen)\n\t\t}\n\t\tOmega<-cbind(Omega,WW)\n\t}\n\treturn(Omega)\n}\nfuncion3<-function(NF,v,Omega,Patrones)\n{\n\tNFe<-NF-rowMeans(Patrones)\n\tWWn<-NULL\n\tfor(i in 1:ncol(v))\n\t{\n\t\tpesodelaimagen<-v[,i]%*%NFe \n\t\tWWn<-c(WWn,pesodelaimagen)\n\t}\n\tOmegaN<-WWn\n\tclase<-1:ncol(v)\n\tdistancia<-dist(t(cbind(OmegaN,Omega)))[1:3]\n\tclase<-clase[distancia==min(distancia)]\n\treturn(list(distancia,clase))\n}\n\nProyeccion<-function(u,v)\n{\n\tif((ncol(u)==1||is.null(ncol(u)))&&(ncol(v)==1||is.null(ncol(v))))\n\t{\n\t\tsal<-((u%*%v)/(norma(v)^2))*v\n\t\treturn(sal)\n\t}\n\n\tif(ncol(u)==1||is.null(ncol(u)))\n\t{\n\t\tu<-matrix(u,nrow=1)\n\t\tsal<-as.numeric(t(u%*%t(v)/norma(v)^2))*v\n\t\treturn(sal)\n\t}\n\n\tif(ncol(v)==1||is.null(ncol(v)))\n\t{\n\t\tv<-matrix(v,ncol=1)\n\t\tsal<-as.numeric((u%*%v)/as.numeric(norma(v)^2))*t(matrix(rep(v,nrow(u)),ncol=nrow(u)))\n\t\treturn(sal)\n\t}\n\n\n}\nProporcion<-function(v,A)\n{\n\tnorma(v)/sum(norma(A))\n}\n\n#Combinacion muestra optima para pca\n#n = numero de iteraciones\n#y = muestra total 100%\n#k = el numero la muestra a seleccionar el aproximado al 30%\n#c = indica el varlo de la variable cor para el PCA\nPCAoptimo<-function(y, n, k, c)\n{\n\tacum <- 0\n\tindices_opti <- NULL\n\n\tindice<-sample(1:nrow(y),k)\n\tytrain<-y[indice,1:5]\n\n\tpr <- prcomp(ytrain, scale = TRUE,cor=c)\n\n\tfor(i in 1:n){\n\t\tindice<-sample(1:nrow(y),k)\n\t\tytrain<-y[indice,1:5]\n\n\t\tpr <- prcomp(ytrain, scale = TRUE,cor=c)\n\t\tvars <- apply(pr$x, 2, var) \n\t\tprops <- vars / sum(vars)\n\n\t\tif(cumsum(props)[1] > acum)\n\t\t{\n\t\t\tacum <- cumsum(props)[1]\n\t\t\tindices_opti <- indice\n\t\t\tprint(cumsum(props))\n\t\t}\n\t}\n\n\treturn(list(indices=indices_opti, acum=acum))\n}\n\nmyTrain<-function(m,s,capas, P, P_v, target, claseT, p_ecm){\n\nnet1 <- newff(n.neurons=c(2,capas,2), learning.rate.global=p_ecm, momentum.global=m,\nerror.criterium=\"LMS\", Stao=NA, hidden.layer=\"sigmoid\",\noutput.layer=\"sigmoid\", method=\"ADAPTgdwm\")\nresult1 <- train(net1,P , target, error.criterium=\"LMS\", report=TRUE, show.step=s, n.shows=5 )\ns <- sim(result1$net, P)\nprint(\"Entrenando\")\ntasa_1<-rep(FALSE,nrow(s))\ntasa_1[round(s)[,1]== target[,1] & round(s)[,2]== target[,2]]<-TRUE\ntasa_1 <- sum(tasa_1==TRUE)*100/length(tasa_1)\n\nprint(tasa_1)\nECM_1 <- error.LMS(c(s,target,net1))\nprint(ECM_1) \n\nprint(\"Validando\")\ns <- sim(result1$net, P_v)\n\ntasa_2<-rep(FALSE,nrow(s))\ntasa_2[round(s)[,1]== claseT[,1] & round(s)[,2]== claseT[,2]]<-TRUE\ntasa_2 <- sum(tasa_2==TRUE)*100/length(tasa_2)\n\nprint(tasa_2)\n\nECM_2 <- error.LMS(c(s,claseT,net1))\nprint(ECM_2) \n\n#return(list(ecm_1=as.numeric(ECM_1), t_1=as.numeric(tasa_1), ecm_2=as.numeric(ECM_2), t_2=as.numeric(tasa_2)))\nreturn(c(as.numeric(ECM_1), as.numeric(tasa_1),as.numeric(ECM_2), as.numeric(tasa_2)))\n}\n\nvalidacion_cruzada<-function(y, iteraciones) {\n#########################################\n# Calculo de grupos de salida\n#\n# Conglomerado Total se asigna una etiqueta a cada caso segun su nota de calculo 1\nsal <- y[,6]\nsal\nconglomeradoT<-rep(FALSE,length(sal))\nconglomeradoT[sal<=10]<-1 #Nivel Bajo\nconglomeradoT[sal>=11&sal<16]<-2 #Nivel Medio\nconglomeradoT[sal>=16]<-3 #Nivel Alto\n\n########################\n#Generación de clase\n########################\nmedias<-c(mean(data[conglomeradoT==1,7]),mean(data[conglomeradoT==2,7]),mean(data[conglomeradoT==3,7]))\nmedias\nnames(medias)<-c(1,2,3)\nclaseC<-as.numeric(names(sort(medias)))\n\ntrains <- NULL\ntrains\nfor(i in 1:iteraciones){\n\tprint(\"------------------------------------------------\")\n\tprint(i*100/iteraciones)\n\tprint(\"------------------------------------------------\")\n\tindice <- PCAoptimo(y,1,87,F)$indices\n\tytrain<-y[indice,1:5]\n\tytest<-y[-indice,1:5]\n\tcomp <-princomp(ytrain,cor=F)\n\tcargas<-comp$loadings[,]\n\tcomT<-score(ytest,cargas)\n\tconglomerado_train<-conglomeradoT[indice]\n\tconglomerado_test<-conglomeradoT[-indice]\n\n\tclase<-matrix(NA, ncol=2, nrow=nrow(ytrain))\n\tclase[conglomerado_train==claseC[1],]<-matrix(rep(t(c(0,0)), sum(conglomerado_train==claseC[1])), byrow=TRUE, ncol=2 )\n\tclase[conglomerado_train==claseC[2],]<-matrix(rep(t(c(0,1)), sum(conglomerado_train==claseC[2])), byrow=TRUE, ncol=2 )\n\tclase[conglomerado_train==claseC[3],]<-matrix(rep(t(c(1,1)), sum(conglomerado_train==claseC[3])), byrow=TRUE, ncol=2 )\n\tclaseT<-matrix(NA, ncol=2, nrow=nrow(ytest))\n\tclaseT[conglomerado_test==claseC[1],]<-matrix(rep(t(c(0,0)), sum(conglomerado_test==claseC[1])), byrow=TRUE, ncol=2 )\n\tclaseT[conglomerado_test==claseC[2],]<-matrix(rep(t(c(0,1)), sum(conglomerado_test==claseC[2])), byrow=TRUE, ncol=2 )\n\tclaseT[conglomerado_test==claseC[3],]<-matrix(rep(t(c(1,1)), sum(conglomerado_test==claseC[3])), byrow=TRUE, ncol=2 )\n\n\ttarget<-clase\n\tP<-matrix(c(comp$score[,1],comp$score[,2]),ncol=2,byrow=TRUE)\n\tP_v <-comT[,1:2]\n\n\ttrains <- matrix(rbind(trains, myTrain(0.7, 13, c(2,2), P, P_v, clase,claseT, 0.1)), byrow=FALSE, ncol=4 )\n}\nreturn (trains)\n\n}\n\nscore<-function(y,carga)\n{\nyc<-y-matrix(rep(colMeans(y),nrow(y)),ncol=ncol(y),byrow=TRUE)\nsalida<-as.matrix(yc)%*%carga\nreturn(salida)\n}\n", "meta": {"hexsha": "0bd80b5c90f49f6d3af558422d134ab556134896", "size": 6002, "ext": "r", "lang": "R", "max_stars_repo_path": "src/AppBundle/R/PCAfunction.r", "max_stars_repo_name": "1211agarcia/SistemaPrediccion", "max_stars_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AppBundle/R/PCAfunction.r", "max_issues_repo_name": "1211agarcia/SistemaPrediccion", "max_issues_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AppBundle/R/PCAfunction.r", "max_forks_repo_name": "1211agarcia/SistemaPrediccion", "max_forks_repo_head_hexsha": "5be10e228130777112792ddc70c31a8caa30c95c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8706896552, "max_line_length": 119, "alphanum_fraction": 0.6459513496, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6406792080229675}} {"text": "#' Fitting Heffernan-Tawn model to wave data\r\n\r\n#' @description \r\n#' This function fits a Heffernan-Tawn (\\code{ht}) model to the given wave data. The marginal distributions are\r\n#' a mixture model with an empirical distribution below a specified threshold, and the generalised Pareto distribution\r\n#' (GPD) above the threshold. The dependence structure is the conditional extreme value model proposed in\r\n#' Heffernan and Tawn (2004).\r\n#' \r\n#' @param data the wave data in the form a \\code{data.table} with wave height \\code{hs} and wave period\r\n#' \\code{tp} as columns\r\n#' \r\n#' @param npy the number of data points per year, usually estimated by the number of rows in the\r\n#' supplied wave data divided by the total period of data coverage (in years)\r\n#' \r\n#' @param margin_thresh_count an integer indicating the number of exceedances strcitly above the threshold\r\n#' used for fitting the Generalised Pareto Distribution (GPD) for the upper tail of the marginal distribution\r\n#' for \\code{hs} and \\code{tp}\r\n#' \r\n#' @param dep_thresh_count an integer indicating the number of exceedances (of the conditioning variable)\r\n#' strcitly above the threshold used for fitting the conditional multivariate extreme value model of\r\n#' Heffernan and Tawn (2004)\r\n#' \r\n#' @details\r\n#' The input \\code{data} must be a \\code{data.table} object with \\code{hs} and \\code{tp} columns. This can be\r\n#' generated by reading a CSV file using function \\code{\\link[data.table]{fread}}.\r\n#' \r\n#' By the asymptotic properties of the GPD and the HT model, the model bias is only negligible when the \r\n#' thresholds are sufficiently high. This function prompts the user with the exceedance probability implied by\r\n#' their choie of the arguments \\code{margin_thresh_count} and \\code{dep_thresh_count} to remind them that\r\n#' the exceedance probability needs to be quite small for the fit of GPD and HT to be valid.\r\n#' \r\n#' @return An joint distribution object of class \\code{ht} containing the key information of a fitted\r\n#' Heffernan-Tawn model, including the marginal distribution parameters and the dependence model parameters.\r\n#'\r\n#' @examples\r\n#' # Load data\r\n#' data(ww3_pk)\r\n#' \r\n#' # Fit Heffernan-Tawn model\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 100, dep_thresh_count = 100)\r\n#' \r\n#' @references Heffernan, Janet & A. Tawn, Jonathan. (2004). A Conditional Approach for Multivariate Extreme Values.\r\n#' Journal of the Royal Statistical Society Series B. 66. 497-546. 10.1111/j.1467-9868.2004.02050.x. \r\n#' \r\n#' @seealso \\code{\\link{fit_wln}}, \\code{\\link{sample_jdistr}}\r\n#' \r\n#' @export\r\nfit_ht = function(data, npy, margin_thresh_count, dep_thresh_count){\r\n \r\n data = as.data.table(data)\r\n res = list()\r\n class(res) = \"ht\"\r\n res$npy = npy\r\n \r\n # Marginal models\r\n hs_thresh = sort(data$hs, decreasing = T)[margin_thresh_count+1]\r\n tp_thresh = sort(data$tp, decreasing = T)[margin_thresh_count+1]\r\n p_margin_thresh = 1-margin_thresh_count/(data[,.N])\r\n \r\n res$margin = list(\r\n p_margin_thresh = p_margin_thresh,\r\n hs = .fit_gpd_emp(data$hs, thresh = hs_thresh),\r\n tp = .fit_gpd_emp(data$tp, thresh = tp_thresh))\r\n \r\n # Dep models\r\n dep_data = copy(data)\r\n dep_data[, u_hs:=rank(hs, ties.method = \"random\")/(.N+1)]\r\n dep_data[, u_tp:=rank(tp, ties.method = \"random\")/(.N+1)]\r\n dep_data[u_hs<0.5, l_hs:=log(2*u_hs)]\r\n dep_data[u_hs>=0.5, l_hs:=-log(2-2*u_hs)]\r\n dep_data[u_tp<0.5, l_tp:=log(2*u_tp)]\r\n dep_data[u_tp>=0.5, l_tp:=-log(2-2*u_tp)]\r\n\r\n op_hs = nlminb(\r\n start = c(1,0), objective = .nll_ht_pair,\r\n lower = c(-1, -100), upper = c(1, 1-.limit_zero),\r\n cond_var = dep_data[frank(u_hs)>.N-dep_thresh_count, l_hs],\r\n dep_var = dep_data[frank(u_hs)>.N-dep_thresh_count, l_tp])\r\n \r\n op_tp = nlminb(\r\n start = c(1,0), objective = .nll_ht_pair,\r\n lower = c(-1, -100), upper = c(1, 1-.limit_zero),\r\n cond_var = dep_data[frank(u_tp)>.N-dep_thresh_count, l_tp],\r\n dep_var = dep_data[frank(u_tp)>.N-dep_thresh_count, l_hs])\r\n \r\n p_dep_thresh = 1-dep_thresh_count/(data[,.N])\r\n res$dep = list(\r\n p_dep_thresh = p_dep_thresh,\r\n hs = list(\r\n par = c(a = op_hs$par[1], b = op_hs$par[2]),\r\n resid = dep_data[frank(u_hs)>.N-dep_thresh_count, (l_tp-op_hs$par[1]*l_hs)/(l_hs^op_hs$par[2])]), \r\n tp = list(\r\n par = c(a = op_tp$par[1], b = op_tp$par[2]),\r\n resid = dep_data[frank(u_tp)>.N-dep_thresh_count, (l_hs-op_tp$par[1]*l_tp)/(l_tp^op_tp$par[2])]),\r\n dep_data = dep_data)\r\n\r\n # Return\r\n message(paste0(\r\n \"The input margin_thresh_count corresponds to an exceedance probability of \",\r\n signif(1-p_margin_thresh, 2),\".\"))\r\n message(paste0(\r\n \"The input dep_thresh_count corresponds to an exceedance probability of \",\r\n signif(1-p_dep_thresh, 2),\".\"))\r\n return(res)\r\n}\r\n\r\n\r\n.nll_ht_pair = function(theta, cond_var, dep_var){\r\n a = theta[1]\r\n b = theta[2]\r\n resid = (dep_var-a*cond_var)/(cond_var^b)\r\n mean_resid = mean(resid)\r\n sd_resid = sd(resid)\r\n \r\n nll = -dnorm(\r\n x = dep_var, log = TRUE,\r\n mean = a*cond_var+(cond_var^b)*mean_resid,\r\n sd = (cond_var^b)*sd_resid)\r\n \r\n return(sum(nll))\r\n}\r\n\r\n.fit_gpd_emp = function(data, thresh){\r\n gpd = evd::fpot(data, threshold = thresh, cmax = F, std.err = F)\r\n \r\n res = list()\r\n class(res) = \"gpd\"\r\n res$par = c(loc = thresh, gpd$param[1], gpd$param[2])\r\n res$emp = data\r\n res$conv = gpd$convergence\r\n \r\n return(res)\r\n}\r\n\r\n.convert_unif_to_lap = function(unif){\r\n calc = data.table(unif=unif, lap=NA_real_)\r\n calc[unif>0.5, lap:=-log(2-2*unif)]\r\n calc[unif<=0.5, lap:=log(2*unif)]\r\n return(calc$lap)\r\n}\r\n\r\n.convert_lap_to_unif = function(lap){\r\n calc = data.table(lap=lap, unif=NA_real_)\r\n calc[lap>0, unif:=1-.5*exp(-lap)]\r\n calc[lap<=0, unif:=.5*exp(lap)]\r\n return(calc$unif)\r\n}\r\n\r\n.convert_unif_to_origin = function(unif, p_thresh, gpd_par, emp){\r\n calc = data.table(unif=unif, x=NA_real_)\r\n calc[unif=p_thresh, x:=evd::qgpd(\r\n p = (unif-p_thresh)/(1-p_thresh),\r\n loc = gpd_par[1], scale = gpd_par[2], shape = gpd_par[3])]\r\n return(calc$x)\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "c1255c498c2305ed52d728a112be33f1f77c519d", "size": 6116, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/fit_ht.r", "max_stars_repo_name": "ECSADES/ecsades-r", "max_stars_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-17T00:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:13:22.000Z", "max_issues_repo_path": "ecsades/R/fit_ht.r", "max_issues_repo_name": "ECSADES/ecsades-r", "max_issues_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-22T13:00:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-04T16:45:59.000Z", "max_forks_repo_path": "ecsades/R/fit_ht.r", "max_forks_repo_name": "ECSADES/ecsades-r", "max_forks_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9875776398, "max_line_length": 119, "alphanum_fraction": 0.6724983649, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6405936984137212}} {"text": "# Coded by Anderson Borba data: 07/07/2020 version 1.0\n# Article submitted \n# Fusion of Evidences in Intensities Channels for Edge Detection in PolSAR Images \n# GRSL - IEEE Geoscience and Remote Sensing Letters \n# Anderson A. de Borba, Maurı́cio Marengoni, and Alejandro C Frery\n# Despriction (function)\n# Finds the l(j) using total-likelihood\n# Input: Le, Ld, mue e mud > 0 estimed parameters \n# \n# Output: pixel j - Edge evidence estimated\nfunc_obj_l_L_mu <- function(param){\n j <- param\n Le <- matdf1[j,1]\n Ld <- matdf2[j,1]\n mue <- matdf1[j,2]\n mud <- matdf2[j,2]\n #\n aux1 <- Le * log(Le)\n aux2 <- Le * sum(log(z[1: j])) / j\n aux3 <- Le * log(mue)\n aux4 <- log(gamma(Le))\n aux5 <- (Le / mue) * sum(z[1:j]) / j\n #\n aux6 <- Ld * log(Ld)\n aux7 <- Ld * sum(log(z[(j + 1): N])) / (N - j)\n aux8 <- Ld * log(mud) \n aux9 <- log(gamma(Ld)) \n aux10 <- (Ld / mud) * sum(z[(j + 1): N]) / (N - j) \n #\n a1 <- aux1 + aux2 - aux3 - aux4 - aux5\n a2 <- aux6 + aux7 - aux8 - aux9 - aux10\n #### Beware! The signal is negative because GenSA finds the point of minimum\n func_obj_l_L_mu <- -(j * a1 + (N - j) * a2) \n return(func_obj_l_L_mu)\n}\n", "meta": {"hexsha": "9dc0ba353c816a409c12cbe1490fd7f99f8fc811", "size": 1163, "ext": "r", "lang": "R", "max_stars_repo_path": "Code_r/func_obj_l_L_mu.r", "max_stars_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_stars_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-19T09:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T01:35:11.000Z", "max_issues_repo_path": "Code_r/func_obj_l_L_mu.r", "max_issues_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_issues_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code_r/func_obj_l_L_mu.r", "max_forks_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_forks_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-31T02:35:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T08:12:58.000Z", "avg_line_length": 32.3055555556, "max_line_length": 82, "alphanum_fraction": 0.6010318143, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6405936869305455}} {"text": "#############################################\n# M-H Algorithm does\n#############################################\n# 1. Propose a new value\n# 2. Calculate the probability of accepting the new value\n# 3. Flip a coin to determine if we accept the proposal or not\n# 4. Update the state of the chain\n## A generic MH sampler\nmh.sample <- function( U.data, old.state,\n cc.log.density, proposal.function ) {\n \n ## Step 1: Call the proposal function\n prop <- proposal.function( old.state )\n ## which returns:\n ## ... prop$param.name, the name of the parameter \n ## ... prop$state, the new state object \n ## ... prop$log.density, the log density of the proposal\n \n ## Step 2: Calculate the (log) acceptance probability \n log.alpha.star <- (\n ## Complete conditional at the proposal \n cc.log.density( U.data, prop$state )\n ## Complete conditional at the \"old\" value\n - cc.log.density( U.data, old.state )\n ## Proposal density calculated to the proposal\n + prop$log.density( prop$state, old.state )\n ## Proposal density calculated to the \"old\" value\n - prop$log.density( old.state, prop$state )\n )\n \n ## Step 3: Accept proposal draws\n ## ... Flip coins with the calculated probabilities \n acc.new <- ifelse(\n log(runif( length(log.alpha.star) )) <= log.alpha.star,\n 1, 0 )\n ##\n ## ... Update the chain to its \"current\" state\n ## ... ... Copy the old state object\n cur.state <- old.state\n ## ... ... Update the state object for this parameter \n cur.state[[ prop$param.name ]] <- ifelse(\n acc.new==1,\n prop$state[[ prop$param.name ]],\n old.state[[ prop$param.name ]])\n \n ## Step 4: Update the acceptance probability \n ## ... add the new average acceptance probability\n cur.state$ACC[[ prop$param.name ]] <- (\n old.state$ACC[[ prop$param.name ]] + mean( acc.new )\n )\n ## ... record that we added a new acceptance probability \n name.n <- paste( prop$param.name, \".n\", sep=\"\")\n cur.state$ACC[[ name.n ]] <- old.state$ACC[[name.n]] + 1\n \n ## Step 5: Return the current state\n return(cur.state)\n}\n", "meta": {"hexsha": "8f7381cabc1bdbfebb646c8bf2f1c7cfc79a1856", "size": 2440, "ext": "r", "lang": "R", "max_stars_repo_path": "2PL/functions/mh_sample.r", "max_stars_repo_name": "jevanluo/BayesianIRT", "max_stars_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-23T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:45:25.000Z", "max_issues_repo_path": "2PL/functions/mh_sample.r", "max_issues_repo_name": "jevanluo/BayesianIRT", "max_issues_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2PL/functions/mh_sample.r", "max_forks_repo_name": "jevanluo/BayesianIRT", "max_forks_repo_head_hexsha": "788b34e951968222493b7ad2c65f3086ddff84e5", "max_forks_repo_licenses": ["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.0689655172, "max_line_length": 71, "alphanum_fraction": 0.518852459, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6403352234547683}} {"text": "\n\n#The below function replicates the operation of Rnd() from Visual Basic 6 when a positive input parameter is used.\nExcelRand64<-function(ExcelSeed,outputmax)\n{\n\tvara = as.integer64(ExcelSeed)\n\tvarb = as.integer64(1140671485)\n\tvarc = as.integer64(12820163)\n\tfirstflag<-TRUE\n\tValueA<-0\n\twhile(ValueA>=outputmax | firstflag){\n\t\tfirstflag<-FALSE\n\t\tvara = as.integer64(ExcelSeed)\n\t\tExcelSeed<-as.integer64(vara *varb +varc )%%as.integer64(2^24)\n\t\tValueA<- outputmax*ExcelSeed/2^24+1\n\t}\n\treturnHelp<-list()\n\treturnHelp[[\"Step\"]]<-ExcelSeed\n\treturnHelp[[\"ExcelOutput\"]]<-ExcelSeed/2^24\n\treturnHelp[[\"RATSTAT\"]]<-ValueA\n\treturnHelp\n}\n\n#The below function replicates the operation of the Visual Based 6 function Randomize()\nExcelRandomize64<-function(startingpoint,ExcelSeed){\n\ttesthelptemp<-writeBin(as.double(startingpoint),raw(),size=8)\n\tbitlist<-rawToBits(testhelptemp)[33:64]\n\tbitseed<-intToBits(as.integer(ExcelSeed))\n\tvara<-packBits(c(bitlist[1:16],intToBits(0)[1:16]),\"integer\")\n\tvarb<-packBits(c(bitlist[17:32],intToBits(0)[1:16]),\"integer\")\n\tmoshedbitsA<-intToBits(bitwXor(vara,varb))\n\tfinalmosh<-(c(intToBits(0)[1:8],moshedbitsA[1:16],intToBits(0)[1:8]) | c(bitseed[1:8],intToBits(0)[1:24]))\n\tnewSeed<-packBits(finalmosh ,\"integer\")\n\tnewSeed\n}\n\n#The below function replicates the operation of the Visual Basic 6 function Rnd() when a negative input parameter is used. \nExcelRandInit<-function(initvar)\n{\n\ttesthelp<-writeBin(as.double(initvar),raw(),size=4)\n\ttesthelp<-rawToBits(testhelp)\n\tpackBits(c(testhelp[25:32],intToBits(0)[1:24]),\"integer\") +packBits( c(testhelp[1:24],intToBits(0)[1:8]),\"integer\")\n}\n\n#This replication requires the \"bit64\" library.\nlibrary(bit64)\n\n\n#Emulates Rnd(-1)\nCurrentSeed<-ExcelRandInit(-1)\n#Emulates Rnd()\nCurrentSeed<-ExcelRand64(CurrentSeed,30269)[[\"Step\"]]\n#The above two lines of code result in the value 3758214 which is listed in Step 1 of the detailed specification\n\n\n#Emulates the Visual Basic function Randomize() given the seed entered by the user or the system clock if no seed is provided\nCurrentSeed<-ExcelRandomize64(102284,CurrentSeed)\n#The above line of code equates to steps 2 through 5 in the detailed specification document\n\n\n#Emulates the three calls to the Visual Basic 6 function Rnd().\nResA<-ExcelRand64(CurrentSeed,30269)\nResB<-ExcelRand64(ResA[[\"Step\"]],30307)\nResC<-ExcelRand64(ResB[[\"Step\"]],30323)\n#The above three lines of code equate to Steps 6 through 15 in the detailed specification document\n\n#Given the three seed generated from the Excel functions Rnd() and Randomize(), RAT-STATS uses the standard Wichmann-Hill algorithm \n#to generate the actual random numbers. The below code emulates the algorithm using R.\n\nSeed_A<-floor(ResA[[\"RATSTAT\"]])\nSeed_B<-floor(ResB[[\"RATSTAT\"]])\nSeed_C<-floor(ResC[[\"RATSTAT\"]])\nsamsiz<-70\nRandomNumber<-NA*(1:samsiz)\nLowb<-0\nUpb<-101\nrepcheck<-0*(1:(Upb-Lowb+1))\nfor(j in 1:samsiz){\n\trepflag=TRUE\n\twhile(repflag){\t\n\t\tTerm_1=floor(Seed_A/177)\n\t\tTerm_2=Seed_A - (177*Term_1)\n\t\tSeed_A = 171*Term_2 - 2*Term_1\n\t\tif (Seed_A <= 0) {Seed_A = Seed_A +30269}\n\n\t\tTerm_1=floor(Seed_B/176)\n\t\tTerm_2=Seed_B - (176*Term_1)\n\t\tSeed_B = 172*Term_2 - 35*Term_1\n\t\tif (Seed_B <= 0){Seed_B = Seed_B +30307}\n\n\t\tTerm_1=floor(Seed_C/178)\n\t\tTerm_2=Seed_C - (178*Term_1)\n\t\tSeed_C = 170*Term_2 - 63*Term_1\n\t\tif (Seed_C <= 0) {Seed_C = Seed_C +30323}\n\t\n\t\tTerm_4 = Seed_A/30269 + Seed_B/30307 + Seed_C/30323\n\t\tRandomNumber[j] = floor((Term_4 - floor(Term_4))*(Upb-Lowb+1))+Lowb\n\t\tif(repcheck[RandomNumber[j]-Lowb]==0)\n\t\t{\n\t\t\trepcheck[RandomNumber[j]-Lowb]=1\n\t\t\trepflag=FALSE\n\t\t}\n\t}\n}\n\nsum(RandomNumber)\nprint(RandomNumber)\nprint(sum(RandomNumber))\n\n", "meta": {"hexsha": "c0af6e18fb51b506fdf070c0d4b952a5a969da51", "size": 3626, "ext": "r", "lang": "R", "max_stars_repo_path": "sdk/contrib/Function - Single Stage Random Numbers/randomReplicate_03js.r", "max_stars_repo_name": "cbtek/RStats2017", "max_stars_repo_head_hexsha": "e383416ee52784be6486b9a2e5f517fbfaf8a416", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/contrib/Function - Single Stage Random Numbers/randomReplicate_03js.r", "max_issues_repo_name": "cbtek/RStats2017", "max_issues_repo_head_hexsha": "e383416ee52784be6486b9a2e5f517fbfaf8a416", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-07-12T17:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-21T19:06:59.000Z", "max_forks_repo_path": "sdk/contrib/Function - Single Stage Random Numbers/randomReplicate_03js.r", "max_forks_repo_name": "cbtek/RStats2017", "max_forks_repo_head_hexsha": "e383416ee52784be6486b9a2e5f517fbfaf8a416", "max_forks_repo_licenses": ["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.9636363636, "max_line_length": 132, "alphanum_fraction": 0.7382790954, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6402516007985694}} {"text": "#' Compute discharge and hyrdaulic geometry\n#' @param Ac Vector of catchment area for calibration points in $m^2$\n#' @param Qc Vector of discharge for calibration points in $m^3/s$\n#' @param Ap Vector or raster of catchment area for prediction\n#' @param use_prior Logical, use the prior for scaling? See 'details'\n#' @details Computes discharge from catchment area as \\eqn{\\log Q = \\log b + m \\log A}.\n#' \t\tIf a single point in `calib` is included, the relationship will be re-parameterised by\n#' \tadjusting the intercept parameter `b` so that the calibration point falls on the line\n#' \t\t(while keeping the slope the same).\n#'\n#' \t\tWith multiple points, a regression model is fit. If `use_prior == TRUE`, this is a Bayesian model\n#' \t\tusing the parameters from Burgers et al (2014). These priors are calibrated from a variety of rivers,\n#' \t\tand the prior is quite strong, so it is possible with a small number of calibration points that the line\n#' \t\tis quite far from the calibration. In this case, either re-run this function with a single calibration point,\n#' \t\tor run with `use_prior = FALSE` (but this is only recommended if `range(Ac)` is similar to `range(Ap)`.\n#'\n#' \t\tFor discharge scaling, catchment area units are expected to be in\n#' \t\t\\eqn{m^2}, and discharge will be computed in \\eqn{m^3 s^{-1}}.\n#'\n#' \t\tFollowing computation of discharge, other aspects of hydralic geometry are computed following Raymond et al (2012).\n#' @references Burgers HE et al. 2014. Size relationships of water discharge in rivers: scaling\n#' \t\tof discharge with catchment area, main-stem lengthand precipitation.\n#' \t\t*Hydrological Processes*. **28**:5769-5775.\n#'\n#' Raymond, PA et al. 2012. Scaling the gas transfer velocity and hydraulic\n#' \t\tgeometry in streams and small rivers. *Limnology and Oceanography: Fluids and\n#' \t\tEnvironments*. **2**:41-53.\n#' @examples\n#' \\donttest{\n#' library(sf)\n#' data(kamp_q)\n#' data(kamp_dem)\n#'\n#' kamp = delineate(kamp_dem)\n#' kamp_Tp = pixel_topology(kamp)\n#' CA = catchment(kamp, type = 'reach', Tp = kamp_Tp)\n#'\n#' ## need to transform coordinate system for kamp_q to match\n#' ## need to snap to stream\n#' ## need to make sure this works\n#' ## should probably update kamp_q projection to match kamp_dem\n#'\n#' kamp_q$ca = catchment(kamp, type = 'points', y = st_geometry(kamp_q), Tp = kamp_Tp)\n#' x = hydraulic_geometry(kamp_q$ca, kamp_q$discharge, CA)\n#' }\n#' @return A data.frame with the following variables:\n#' * CA; the input catchment area\n#' * Q; discharge\n#' * v; water velocity\n#' * z; water depth\n#' * w; width\n#' * Ax; stream cross-sectional area\n#' @export\nhydraulic_geometry = function(Ac, Qc, Ap, use_prior = TRUE) {\n\tif(length(Ac) != length(Qc))\n\t\tstop(\"Ac and Qc must have the same length\")\n\n\t## set up units to make conversion easy\n\tif(!is(Ap, \"units\")) {\n\t\twarning(\"No units set for Ap, assuming m^2\")\n\t\tAp = units::set_units(Ap, \"m^2\")\n\t}\n\tif(!is(Ac, \"units\")) {\n\t\twarning(\"No units set for Ac, assuming m^2\")\n\t\tAc = units::set_units(Ac, \"m^2\")\n\t}\n\tif(!is(Qc, \"units\")) {\n\t\twarning(\"No units set for Qc, assuming m^3/s\")\n\t\tQc = units::set_units(Qc, \"m^3/s\")\n\t}\n\n\t## convert the input units to those expected from Burgers et al, then drop the units\n\tAp_km = units::set_units(Ap, \"km^2\")\n\tAc = units::set_units(Ac, \"km^2\")\n\tQc = units::set_units(Qc, \"km^3/day\")\n\tAp_km = units::drop_units(Ap_km)\n\tAc = units::drop_units(Ac)\n\tQc = units::drop_units(Qc)\n\n\tif(length(Ac) == 1) {\n\t\tpars = .q_prior[1,]\n\t\tpars[\"log_intercept\"] <- log(Qc) - pars[\"slope\"] * log(Ac)\n\t} else {\n\t\tpars = .q_calib(Ac, Qc)\n\t}\n\tqq = .q_predict(pars, Ap_km)\n\tQp = units::set_units(qq, \"km^3/day\")\n\tQp = units::set_units(Qp, \"m^3/s\")\n\n\t## parameters from Raymond et al\n\tres = data.frame(\n\t\tCA = Ap,\n\t\tQ =\tQp,\n\t\tv = units::set_units(exp(-1.64 + 0.285 * log(qq)), \"m/s\"),\n\t\tz = units::set_units(exp(-0.895 + 0.294 * log(qq)), \"m\"),\n\t\tw = units::set_units(exp(2.56 + 0.423 * log(qq)), \"m\"))\n\tres\n}\n\n#' @name q_calib\n#' @rdname q_calib\n#' @title Calibrate discharge\n#' Runs a bayesian linear regression to compute discharge from catchment area\n#' @param x A [raster] stream map, such as one created by [delineate()].\n#' @return An `sf` stream layer\n#' @keywords internal\n.q_calib = function(a, q) {\n\tpar = rnorm(3, .q_prior()[1,], .q_prior()[2,]*2)\n\tnames(par) = c(\"log_intercept\", \"slope\", 'log_sd')\n\toptim(par, .q_lpost, a = a, q = q, control=list(fnscale=-1))$par\n}\n\n#' @rdname q_calib\n#' @keywords internal\n.q_prior = function() {\n\tmatrix(c(log(6.3e-6), 0.4137399, 0.78, 0.03571429, 0, 5), nrow=2,\n\t\t dimnames = list(c(\"pr_mean\", \"pr_sd\"), c(\"log_intercept\", \"slope\", 'log_sd')))\n}\n\n#' @rdname q_calib\n#' @keywords internal\n.q_predict = function(par, a) {\n\texp(par[\"log_intercept\"] + par[\"slope\"] * log(a))\n}\n\n#' @rdname q_calib\n#' @keywords internal\n.q_lpost = function(par, a, q) {\n\tsum(dnorm(q, .q_predict(par, a), exp(par['log_sd']), log=TRUE)) +\n\t\tsum(dnorm(par, .q_prior()[1,], .q_prior()[2,], log=TRUE))\n}\n", "meta": {"hexsha": "d766f22d325522ef7c09cd301e4204658cf9fdb0", "size": 5013, "ext": "r", "lang": "R", "max_stars_repo_path": "R/hydrology.r", "max_stars_repo_name": "frawalther/watershed", "max_stars_repo_head_hexsha": "2d47c4c59c0b159e26273fea9ae245ba5747e3d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-13T10:18:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-13T10:18:05.000Z", "max_issues_repo_path": "R/hydrology.r", "max_issues_repo_name": "frawalther/watershed", "max_issues_repo_head_hexsha": "2d47c4c59c0b159e26273fea9ae245ba5747e3d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-14T11:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T11:09:18.000Z", "max_forks_repo_path": "R/hydrology.r", "max_forks_repo_name": "frawalther/watershed", "max_forks_repo_head_hexsha": "2d47c4c59c0b159e26273fea9ae245ba5747e3d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-14T09:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T09:45:37.000Z", "avg_line_length": 37.9772727273, "max_line_length": 120, "alphanum_fraction": 0.6610811889, "num_tokens": 1583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6402515885565828}} {"text": "n <- 1000\nx <- 1:n\nS <- sum(x)\nonethird <- function(n) sum(3/10^c(1:n))\n1/3 - onethird(4)\n1/3 - onethird(10)\n1/3 - onethird(16)\n# integral example\nwidth <- 0.01\nx <- seq(2,4,width)\nareaofbars <- f(x)*width\nf = function(n) n^1.5\nareaofbars <- f(x)*width\nsum(areaofbars)\nhead(dat)\nview(dat)\nView(dat)\nlibrary(dplyr)\ncontrol <- filter(dat, Diet==\"chow\") %>%\nselect(Bodyweight) %>%\nunlist\ntreatment <- filter(dat,Diet==\"nf\") %>%\nselect(Bodyweight) %>%\nunlist\nprint(mean(treatment))\ntreatment <- filter(dat,Diet==\"hf\") %>%\nselect(Bodyweight) %>%\nunlist\nprint( mean(treatment))\nprint( mean(control))\nobsdiff <- mean(treatment) - mean(control)\nprint(obsdiff)\n# Random Variables\nfilename <- \"femaleControlsPopulation.csv\"\nif (!file.exists(filename))\ndownload(url,destfile=filename)\npopulation <- read.csv(filename)\npopulation unlist(population)\npopulation <- unlist(population)\ncontrol <- sample(population,12)\nmean(control)\ncontrol <- sample(population,12)\nmean(control)\ncontrol <- sample(population,12)\nmean(control)\nView(population )\n# The Null Hypothesis\nurl <- \"https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/femaleControlsPopulation.csv\"\nfilename <- \"femaleControlsPopulation.csv\"\nif (!file.exists(filename))\ndownload(url,destfile=filename)\ndownload(url,destfile=filename)\npopulation <- read.csv(filename)\npopulation <- unlist(population)\ncontrol <- samlpe(population,12)\ncontrol <- sample(population,12)\nmean(control)\nmean(control)\nmean(control)\nmean(control)\n# The Null Hypothesis\ncontrol <- sample(population,12)\ntreatment <- sample(population,12)\nprint(mean(treatment) - mean(treatment))\nprint(mean(treatment) - mean(control))\n# Now let's do this 10000 times\nn <- 10000\nnull <- vector(\"numeric\",n)\nfor (i in 1:n){}\nfor (i in 1:n){\ntreatment <- sample(population,12)\ncontrol <- sample(population,12)\nnull[i] <- mean(treatment) - mean(control)\n}\nmean(null >= obsdiff)\nView(n)\n# Distributions\nlibrary(UsingR)\ninstall.packages(\"UsingR\")\nlibrary(UsingR)\nx <- father.son$fheight\nround(sample(x,10),1)\nsmallest <- floor( min(x))\nlargest <- ceiling( max(x))\nvalues <- seq(smallest, largest, len=300)\nheightecdf <- ecdf(x)\nView(x)\nplot(values, heightecdf(values), type=\"l\", xlab=\"a (Height in inches)\", ylab=\"Pr(x <= a)\")\n?ecdf\nplot(values, heightecdf(values), type=\"l\", xlab=\"a (Height in inches)\", ylab=\"Pr(x <= a)\")\n# Histograms\nhist(x)\nbins <- seq(smallest, largest)\nhist(x,breaks=bins,xlab=\"Height (in inches)\", main=\"Adult men heights\")\nhist(x)\nhist(x,breaks=bins,xlab=\"Height (in inches)\", main=\"Adult men heights\")\n# Probability Distribution\nn <- 500\nlibrary(rafalib)\nnullplot(-5,5,1,30, xlab=\"Observed differences (grams)\", ylab=\"Frequency\")\ntotals <- vector(\"numeric\",11)\nfor (i in 1:n) {\ncontrol <- sample(population, 12)\ntreatment <- sample(population,12)\nnulldiff <- mean(treatment) - mean(control)\nj <- pmax(pmin(round(nulldiff)+6,11),1)\ntotals[j] <- totals[j]+1\ntext(j-6,totals[j],pch=15,round(nulldiff,1))\nif(i <15) Sys.sleep(1)\n}\nhist(null, freq=TRUE)\nabline(v=obsdiff, col=\"red\", lwd=2)\n# Normal Distribution\npnorm(obsdiff,mean(null),sd(null))\n# Populations, Samples and Estimates\nurl <- \"https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/mice_pheno.csv\"\nfilename <- \"mice_pheno.csv\"\ndownload(url,destfile=filename)\ndat <- read.csv(filename)\ncontrolPopulation <- filter(dat,Sex == \"F\" & Diet == \"chow\") %>%\nselect(Bodyweight) %>%\nunlist\nView(dat)\ncontrolPopulation <- filter(dat,Sex == \"F\" & Diet == \"chow\") %>%\nselect(\"Bodyweight\") %>%\nunlist\ncontrolPopulation <- filter(dat,Sex == \"F\" & Diet == \"chow\") %>%\nselect(\"Bodyweight\") %>%\nunlist\ncontrolPopulation <- filter(dat,Sex == \"F\" & Diet == \"chow\") %>% select(Bodyweight) %>% unlist\nlibrary(dplyr)\ncontrolPopulation <- filter(dat, Sex==\"F\" & Diet==\"chow\") %>%\nselect(Bodyweight)\nselect(Bodyweight) <- controlPopulation unlist\ncontrolPopulation <- controlPopulation unlist\ncontrolPopulation <- unlist controlPopulation\nunlist(controlPopulation)\ncontrolPopulation <- unlist(controlPopulation)\nhfPopulation <- filter(dat, Sex == \"F\" & Diet==\"hf\") %>%\nselect(Bodyweight)\nhfPopulation <- unlist(hfPopulation)\nlibrary(rafalib)\nmypar(1,2)\nhist(hfPopulation)\nhist(controlPopulation)\nmypar(1,2)\nqqnorm(hfPopulation)\nqqline(hfPopulation)\nqqnorm(controlPopulation)\nqqline(controlPopulation)\n# The Central Limit Theorem in Practice\ndat <- read.csv(\"mice_pheno.csv\")\nhead(dat)\nlibrary(dplyr)\ncontrolPopulation <- filter(dat,Sex==\"F\" & Diet == \"chow\") %>%\nselect(Bodyweight) %>% unlist\nhfPopulation <- filter(dat,Sex==\"F\" & Diet==\"hf\") %>%\nselect(Bodyweight) %>% unlist\nmu_hf <- mean(hfPopulation)\nmu_control <- mean(controlPopulation)\nprint(mu_hf - mu_control)\nx <- controlPopulation\nN <- length(x)\npopulationvar <- mean((x-mean(x))^2)\nidentical var(x), populationvar)\nidentical(var(x), populationvar)\nvar(x)\nidentical(var(x)*(N-1)/N, populationvar)\nlibrary(rafalib)\nsd_hf <- popsd(hfPopulation)\nsd_control <- popsd(controlPopulation)\nN <- 12\nhf <- sample(hfPopulation, 12)\ncontrol <- sample(controlPopulation, 12)\nNs <- c(3,12,25,50)\nB <- 10000 # number of simulations\nres <- sapply(Ns,function(n) {\nreplicate(B,mean(sample(hfPopulation,n)) - mean(sample(controlPopulation,n)))\n})\nmypar(2,2)\nfor (i in seq(along=Ns)) {}\nfor (i in seq(along=Ns)) {\ntitleavg <- signif(mean(res[,i],3),3)\ntitlesd <- signif(popsd(res[,i]),3)\ntitle <- paste0(\"N=\",Ns[i],\" Avg=\",titleavg,\"SD=\",titlesd)\nqqnorm(res[,i],main=title)\nqqline(res[,i],col=2)\n}\ncomputestat <- function(n) {}\ny <- sample(hfPopulation,n)\ncomputestat <- function(n) {\ny <- sample(hfPopulation,n)\nx <- sample(controlPopulation,n)\n(mean(y)-mean(x))/sqrt(var(y)/n+var(x)/n)\n}\nres < sapply(Ns,function(n) {)\nres < sapply(Ns,function(n) {\nreplicate(B,computestat(n))\n})\nmypar(2,2)\nfor (i in seq(along=Ns)) {}\nfor (i in seq(along=Ns)) {\nqqnorm(res[,i],main=Ns[i])\nqqline(res[,i],col=2)\n}\n# t-tests in practice\n# Read in and prepare data\ndat <- read.csv(\"femaleMiceWeights.csv\")\ncontrol <- filter(dat, Diet==\"chow\") %>%\nselect(Bodyweight) %>% unlist\ntreatment <- filter(dat, Diet==\"hf\") %>%\nselect(Bodyweight) %>% unlist\ndiff <- mean(treatment) - mean(control)\npritn(diff)\nprint(diff)\n# calculate SE\nsd(control)/sqrt(length(control))\nse <- sqrt(\nvar(treatment)/length(treatment) +\nvar(control)/length(control)\n)\ntstat <- diff/se\nrighttail <- 1 - pnorm(abs(tstat))\nlefttail <- pnorm(-abs(tstat))\npval <- lefttail + righttail\nprint(pval)\n# The t-distribution in practice\nmypar(1,2)\nqqnorm(treatment)\nqqline(treatment,col=2)\nqqnorm(control)\nqqline(control,col=2)\nt.test(treatment, control)\nresult <- t.test(treatment, control)\nresult$p.value\ndat <- read.csv(\"mice_pheno.csv\")\ncontrol <- filter(dat, Diet==\"chow\") %>%\nselect(Bodyweight)\ntreatment <- filter(dat, Diet==\"hf\")\ntreatment <- filter(dat, Diet==\"hf\") %>%\nselect(Bodyweight)\nt.test(treatment, control)\n# Confidence Intervals\ndat <- read.csv(\"mice_pheno.csv\")\nchowPopulation <- dat[dat$Sex==\"F\" & dat$Diet==\"chow\",3]\nView(chowPopulation)\nmu_chow <- mean(chowPopulation)\npritn(mu_chow)\nprint(mu_chow)\nN <- 30\nchow <- sample(chowPopulation,N)\nprint(mean(chow))\nse <- sd(chow)/sqrt(N)\nprint(se)\npnorm(2) - pnorm(-2)\npnorm(1-0.02/2) - pnorm(-2)\npnorm(1-0.05/2) - pnorm(-2)\nQ <- qnorm(1- 0.05/2)\ninterval <- c(mean(chow)-Q*se, mean(chow)+Q*se )\ninterval\ninterval[1] < mu_chow & interval[2] > mu_chow\nB <- 250\nmypar()\nplot(mean(chowPopulation)+c(-7,7),c(1,1),type=\"n\", xlab=\"weight\",ylab=\"interval\",ylim=c(1,B))\nabline(v=mean(chowPopulation))\nfor (i in 1:B) {}\nfor (i in 1:B) {\nchow <- sample(chowPopulation,N)\nse <-sd(chow)/sqrt(N)\ninterval <- c(mean(chow)-Q*se, mean(chow)+Q*se)\ncovered <- mean(chowPopulation) <= interval[2] & mean(chowPopulation) >= interval[1]\ncolor <- ifelse(covered,1,2)\nlines(interval, c(i,i),col=color)\n}\nplot(mean(chowPopulation)+c(-7,7),c(1,1),type=\"n\", xlab=\"weight\",ylab=\"interval\",ylim=c(1,B))\nabline(v=mean(chowPopulation))\nQ <- qnorm(1- 0.05/2)\nN <- 5\nfor (i in 1:B) {\nchow <- sample(chowPopulation,N)\nse <- sd(chow)/sqrt(N)\ninterval <- c(chowPopulation) <= interval[2] & mean(chowPopulation) >= interval[1]\ncolor <- ifelse(covered,1,2)\nlines(interval, c(i,i),col=color)\n}\n}\nplot(mean(chowPopulation)+c(-7,7),c(1,1),type=\"n\", xlab=\"weight\",ylab=\"interval\",ylim=c(1,B))\nabline(v=mean(chowPopulation))\nQ <- qnorm(1- 0.05/2)\nN <- 5\nfor (i in 1:B) {\nchow <- sample(chowPopulation,N)\nse <- sd(chow)/sqrt(N)\ninterval <- c(mean(chow)-Q*se, mean(chow)+Q*se)\ncovered <- mean(chowPopulation) <= interval[2] & mean(chowPopulation) >= interval[1]\ncolor <- ifelse(covered,1,2)\nlines(interval, c(i,i),col=color)\n}\nplot(mean(chowPopulation)+c(-7,7),c(1,1),type=\"n\", xlab=\"weight\",ylab=\"interval\",ylim=c(1,B))\nabline(v=mean(chowPopulation))\nQ <- qt(1- 0.05/2, df=4)\nN <- 5\nfor (i in 1:B) {\nchow <- sample(chowPopulation,N)\nse <- sd(chow)/sqrt(N)\ninterval <- c(mean(chow)-Q*se, mean(chow)+Q*se)\ncovered <- mean(chowPopulation) <= interval[2] & mean(chowPopulation) >= interval[1]\ncolor <- ifelse(covered,1,2)\nlines(interval, c(i,i),col=color)\n}\nqt(1- 0.05/2, df=4)\nqnorm(1- 0.05/2)\n# Power Calculations\ndat <- read.csv(\"mice.pheno.csv\") # Previously downloaded\ndat <- read.csv(\"mice_pheno.csv\") # Previously downloaded\ncontrolPopulation <- filter(dat,Sex==\"F\" & Diet==\"chow\") %>% select(Bodyweight) %>% unlist\nhfPopulation <- filter(dat,Sex==\"F\" & Diet==\"hf\") %>%\nselect(Bodyweight) %>% unlist\nmu_hf <- mean(hfPopulation)\nmu_control <- mean(controlPopulation)\nprint(mu_hf - mu_control)\nprint((mu_hf - mu_control)/mu_control*100) # percent increase\nset.seed(1)\nN<-5\nhf <- sample(controlPopulation,N)\ncontrol <- sample(controlPopulation,N)\nt.test(hf,control)$p.value\nhf <- sample(controlPopulation,N)\ncontrol <- sample(controlPopulation,N)\nt.test(hf,control)$p.value\n# Type I error - False Posotive\n# Type II error - False Negative\nN <- 12\nalpha <- 0.05\nB <- 2000\nreject <- function(N, alpha=0.05){\nhf <- sample(hfPopulation,N)\ncontrol <- sample(controlPopulation,N)\npval <- t.test(hf,control)$p.value\npval <- alpha\n}\nreject <- function(N, alpha=0.05){\nhf <- sample(hfPopulation,N)\ncontrol <- sample(controlPopulation,N)\npval <- t.test(hf,control)$p.value\npval < alpha\n}\nreject(12)\nrejections <- replicate(B,reject(N))\nmean(rejections)\nNs <- seq(5, 50, 5)\npower <- sapply(NS,function(N){\nrejections <- replicate(B, reject(N))\nmean(rejections)\n})\npower <- sapply(Ns,function(N){\nrejections <- replicate(B, reject(N))\nmean(rejections)\n})\nplot(Ns, power, type=\"b\")\nN <- 30\nalphas <- c(0.1,0.05,0.01,0.001,0.0001)\npower <- sapply(alphas,function(alpha){\nrejections <- replicate(B,reject(N,alpha=alpha))\nmean(rejections)\n})\nplot(alphas, power, xlab=\"alpha\", type=\"b\", log=\"x\")\n# p-valueas are arbitrary under the Alternative Hypothesis\ncalculatePvalue <- function(N) {\nhf <- sample(hfPopulation,N)\ncontrol <- sample(controlPopualtion,N)\ncontrol <- sample(controlPopulation,N)\nt.test(hf,control)$p.value\n}\nNs <- seq(10,200,by=10)\nNs_rep <- rep(Ns,each=10)\npvalueas <- sapply(Ns_rep, calculatePvalue)\ncalculatePvalue <- function(N) {\nhf <- sample(hfPopulation,N)\ncontrol <- sample(controlPopulation,N)\nt.test(hf,control)$p.value\n}\npvalues <- sapply(Ns_rep, calculatePvalue)\nplot(Ns_rep, pvalues, log=\"y\", xlab=\"sample size\", ylab=\"p-values\")\nabline(h=c(.01, .05), col=\"red\", lwd=2)\nN <- 12\nhf <- sample(hfPopulation,N)\ncontrol <- sample(controlPopulation, N)\ndiff <- mean(hf) - mean(control)\ndiff / mean(control) * 100\ncontrol <- sample(controlPopulation, N)\nhf <- sample(hfPopulation,N)\ndiff <- mean(hf) - mean(control)\ndiff / mean(control) * 100\nt.test(hf, control)$conf.int / mean(control) * 100\n# Cohen's d\nsd_pool <- sqrt(((N-1)*var(hf) + (N-1)*var(control))/(2*N-2))\ndiff/sd_pool\n## Monte Carlo Simulation\nlibrary(dplyr)\ndat <- read.csv(\"mice_pheno.csv\")\ncontrolPopulation <- filter(Sex==\"F\" & Diet==\"chow\")\ncontrolPopulation <- filter(dat,Sex==\"F\" & Diet==\"chow\") %>% select(Bodyweight) %>% unlist\nttestgenerator <- function(n) {\n#note that here we have a false \"high fa\" group where we actually sample from the nonsmokers. this is because we are modeling the *null*\ncases <- sample(controlPopulation,n)\ncontrols <- sample(controlPopulation,n)\ntstat <- (mean(cases)-mean(controls)) / sqrt(var(cases)/n + var(controls)/n)\nreturn(tstat)\n}\nttests <-replicate(1000,ttestgenerator(10))\nhist(ttests)\nqqnorm(ttests)\nabline(0,1)\n# how about a sample size of three\nttests <- replicate(1000, ttestgenerator(3))\nqqnorm(ttests)\nabline(0,1)\nps <- (seq(0,999)+0.5)/1000\nqqplot(qt(ps,df=2*3-2),ttests,xlim=c(-6,6),ylim=c(-6,6))\nabline(0,1)\nqqnorm(controlPopulation)\nqqline(controlPopulation)\n# Parametric Simulations for the Observations\ncontrols <- rnorm(5000, mean=24, sd=3.5)\nttestgenerator <- function(n, mean=24, sd=3.5) {\ncases <- rnorm(n,mean,sd)\ncontrols <- rnorm(n,mean,sd)\ntstat <- (mean(cases)-mean(controls))/sqrt(var(cses)/n + var(controls)/n)\nreturn(tstat)\n}\n# Permutation tests\ndat=read.csv(\"femaleMiceWeights.csv\")\ncontrol <- filter(dat,Diet==\"chow\") %>%\nselect(Bodyweight) %>%\nunlist\ntreatment <- filter(dat,Diet==\"hf\") %>%\nselect(Bodyweight) %>%\nunlist\nobsdiff <- mean(treatment)-mean(control)\nN <- 12\navgdiff <- replicate(1000, {\nall <- sample(c(control,treatment))\nnewcontrols <- all[1:N]\nnewtreatments <- all[(N+1):(2*N)]\nreturn(mean(newtreatments) - mean(newcontrols))\n})\nhist(avgdiff)\nabline(v=obsdiff, col=\"red\", lwd=2)\n# the proportion of permutations with larger difference\n(sum(abs(avgdiff) > abs(obsdiff))+1) / (length(avgdiff) + 1)\n# and again with a smaller dataset\nN <- 5\ncontrol <- sample(control,N)\ntreatment <- sample(treatment,N)\nobsdiff<- mean(treatment) - mean(control)\navgdiff <- replicate(1000,{\nall <- sample(c(control,treatment))\nnewcontrols <- all[1:N]\nnewtreatments <- all[(N+1):(2*N)]\nreturn(mean(newtreatments) - mean(newcontrols))\n})\nhist(avgdiff)\nabline(v=obsdiff, col=\"red\", lwd=2)\n# Association Tests\ntab <- matrix(c(3,1,1,3),2,2)\nrownames(tab)<-c(\"poured Before\", \"Poured After\")\ncolnames(tab) <- c(\"Guessed before\",\"Guessed after\")\ntab\nrownames(tab)<-c(\"Poured Before\", \"Poured After\")\ntab\nfisher.text(tab,alternative=\"greater\")\nfisher.test(tab,alternative=\"greater\")\n# Chi-squared test\ndisease = factor(c(rep(0,180),rep(1,20),rep(1,40),rep(1,10)),labels=c(\"control\",\"cases\"))\ngenotype=factor(c(rep(\"AA/Aa\",200),rep(\"aa\",50)),levels=c(\"AA/Aa\",\"aa\"))\ndat <- data.frame(disease,genotype)\ndat <- dat[sample(nrow(dat)),]\nhead(dat)\ndat <- dat[sample(nrow(dat)),] # shuffle them up\nhead(dat)\ntable(genotype)\ntable(disease)\ntab <- table(genotype,disease)\ntab\n# Odds Ratio\n(tab[2,2]/tab[2,1]) / (tab[1,2]/tab[1,1])\ndisease = factor(c(rep(0,180),rep(1,20),rep(1,40),rep(1,10)),labels=c(\"control\",\"cases\")))\ndisease = factor(c(rep(0,180),rep(1,20),rep(0,40),rep(1,10)),labels=c(\"control\",\"cases\"))\ndat <- data.frame(disease, genotype)\ndat <- dat[sample(nrow(dat)),] # shuffle it up\nhead(dat)\ntab <- table(genotype,disease)\ntab\n(tab[2,2]/tab[2,1]) / (tab[1,2]/tab[1,1])\np=mean(disease==\"cases\")\nexpected <- rbind(c(1-p,p)*sum(genotype==\"AA/Aa\"),c(1-p,p)*sum(genotype==\"aa\"))\ndimnames(expected)dimnames(tab)\ndimnames(expected) <- dimnames(tab)\nexpected\nchisq.test(tab)$p.value\ntab <- tab*10\nchisq.test(tab)$p.value\n# Large Samples, Small p-values\n# Confidence Intervals For The Odd Ratio\nfit <- glm(disease~genotype,family=\"binomial\",data=dat)\ncoeftab <- summary(fit)$coef\ncoaeftab\ncoeftab\nci <- coeftab[2,1] + c(-2,2)*coeftab[2,2]\nexp(ci)\nsavehistory(\"~/repos/RLifeSciences/Chappie1/worklog.r\")\n", "meta": {"hexsha": "a419a0c79aaaa6025aafa6b29ec9361135d2a8ca", "size": 15390, "ext": "r", "lang": "R", "max_stars_repo_path": "worklog.r", "max_stars_repo_name": "5x5x5x5/RLifeSciences", "max_stars_repo_head_hexsha": "423d76a86003ed6758620c9cc8b3d4e8c40d4046", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "worklog.r", "max_issues_repo_name": "5x5x5x5/RLifeSciences", "max_issues_repo_head_hexsha": "423d76a86003ed6758620c9cc8b3d4e8c40d4046", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "worklog.r", "max_forks_repo_name": "5x5x5x5/RLifeSciences", "max_forks_repo_head_hexsha": "423d76a86003ed6758620c9cc8b3d4e8c40d4046", "max_forks_repo_licenses": ["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.0, "max_line_length": 136, "alphanum_fraction": 0.6983755686, "num_tokens": 4928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6402257215664848}} {"text": "################################################################################\n# The contents of this file are Teradata Public Content\n# and have been released to the Public Domain.\n# Licensed under BSD; see \"license.txt\" file for more information.\n# Copyright (c) 2021 by Teradata\n################################################################################\n#\n# R And Python Analytics with SCRIPT Table Operator\n# Orange Book supplementary material\n# Alexander Kolovos - October 2021 - v.2.1\n#\n# Example 5: Linear Regression with the CALCMATRIX table operator (R version)\n# File : ex5r.r\n#\n# (Adapted from the Teradata Developer Exchange online example by Mike Watzke:\n# http://developer.teradata.com/extensibility/articles/\n# in-database-linear-regression-using-the-calcmatrix-table-operator)\n#\n# Use case:\n# A simple example of linear regression with one dependent and two independent\n# variables (univariate, multiple variable regression). For the regression\n# computations, we need to calculate the sums of squares and cross-products\n# matrix of the data. The example illustrates how to use the CALCMATRIX table\n# operator for this task. The script returns the estimates of the regression\n# coefficients.\n#\n# Script accounts for the general scenario that an AMP might have no data.\n#\n# Required input:\n# - ex5tbl table data from file \"ex5dataTblDef.sql\"\n#\n# Output:\n# - varName: Regression coefficient name\n# - B : Regression coefficient estimated value\n#\n################################################################################\n\nDELIMITER='\\t'\n\nstdin <- file(description=\"stdin\",open=\"r\")\n\ninputDF <- data.frame();\n\n# Need to know in advance the type of all input columns. Cite them in following\n# vector to feed the colClasses argument of the read.table() function.\ncv <- c(\"numeric\",\"character\",\"numeric\",\"numeric\",\"numeric\",\"numeric\",\"numeric\")\ninputDF <- try(read.table(stdin, sep=DELIMITER, flush=TRUE, header=FALSE,\n quote=\"\", na.strings=\"\", colClasses=cv, strip.white=TRUE),\n silent=TRUE)\n\nclose(stdin)\n\n# For AMPs that receive no data, choose to simply quit the script immediately.\nif (class(inputDF) == \"try-error\") {\n inputDF <- NULL\n quit()\n}\n\nnObs <- nrow(inputDF)\ncolnames(inputDF) <- c('rownum', 'rowname', 'c', 's', 'x1', 'x2', 'y')\n\n# Determine the position of the independent variable columns\nxcols <- which(!names(inputDF) %in% c('rownum','rowname','c','y'))\n# Extract partial X'X\npXX <- inputDF[ inputDF[['rowname']] != 'y' , c(xcols)]\n# Extract observation count\nobscount <- inputDF[ inputDF[['rowname']] == 'y' , c('c')]\n# Extract X variable summations\nXsum <- inputDF[ inputDF[['rowname']] != 'y' , c('s')]\n# Build first row of matrix X'X\nXX <- data.matrix(obscount)\nXX <- cbind(XX, t(data.matrix(Xsum)))\n# Append partial X'X\nXX <- rbind(XX, data.matrix(pXX))\n# Invert X'X\niXX <-solve(XX)\n\n# Extract Y variable summations\nYsum <- inputDF[ inputDF[['rowname']] == 'y' , c('s')]\n# Extract partial X'Y\nXY <- inputDF[ inputDF[['rowname']] != 'y' , 'y']\n# Build X'Y of matrix\nXY <- rbind(data.matrix(Ysum), data.matrix(XY))\n# Multiply inverted X'X * X'Y to obtain coefficients\nB <- iXX %*% XY\n\n# Gather names of variables\nvarName <- inputDF[ inputDF[['rowname']] != 'y' , c('rowname')]\nvarName <- c(\"Intercept\", varName)\n\n# Build export data frame:\noutput <- data.frame(varName, B)\n\n# Export results to the SQL Engine database through standard output\nwrite.table(output, file=stdout(), col.names=FALSE, row.names=FALSE,\n quote=FALSE, sep=\"\\t\", na=\"\")\n", "meta": {"hexsha": "1cacfb6a94f9d8643ddeacf2f7ea47a30b7235c2", "size": 3551, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/ex5r.r", "max_stars_repo_name": "Teradata/r-python-sto-orangebook-scripts", "max_stars_repo_head_hexsha": "c8cff0ea2f2f45520c1025c95270ae326549d85a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-03T19:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T17:46:46.000Z", "max_issues_repo_path": "scripts/ex5r.r", "max_issues_repo_name": "Teradata/r-python-sto-orangebook-scripts", "max_issues_repo_head_hexsha": "c8cff0ea2f2f45520c1025c95270ae326549d85a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/ex5r.r", "max_forks_repo_name": "Teradata/r-python-sto-orangebook-scripts", "max_forks_repo_head_hexsha": "c8cff0ea2f2f45520c1025c95270ae326549d85a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-09-21T14:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T20:18:20.000Z", "avg_line_length": 36.6082474227, "max_line_length": 80, "alphanum_fraction": 0.6510842016, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6402257126481504}} {"text": "#' Power Analysis for Two Sided T-Test\n#'\n#' @description This is a function that performs\n#' a power analysis of the two-sided t-test.\n#' Given the effect size, significance level, and power,\n#' the required sample size can be calculated\n#' (although the control or treatment sample size must be given).\n#' Also, given the sample size of the two groups, effect size,\n#' and significance level, the power can be calculated.\n#' Given the sample size of two groups, significance level,\n#' and power of the two groups, the effect size can be calculated.\n#' Given the sample size of two groups, effect size,\n#' and power of the two groups, the significance level can be calculated.\n#'\n#' @param n0 numeric. Number of observations in the control.\n#' @param n1 numeric. Number of observations in the treatment.\n#' @param d numeric. Effect size.\n#' @param alpha numeric. Statistically significance\n#' (probability of Type I error).\n#' @param power numeric. Power (1 - probability of Type II error).\n#'\n#' @importFrom stats pt\n#' @importFrom stats qt\n#' @importFrom stats uniroot\n#'\n#' @export\n#'\n#'\nttest_power <- function(n0,\n n1,\n d,\n alpha,\n power) {\n # extract arguments\n comp <- as.list(match.call())[-1]\n full_args <- c(\"n0\", \"n1\", \"d\", \"alpha\", \"power\")\n miss_arg <- full_args[!(full_args %in% names(comp))]\n\n # check length(comp) == 4\n if (length(comp) != 4) abort_empty_num(5 - length(comp), 1)\n\n # define function which returns specified power - calculated power\n power_func <- function(n0, n1, d, alpha, power) {\n delta <- d * sqrt(1 / n1 + 1 / n0) ^ (-1)\n df <- n1 + n0 - 2\n critical <- qt(alpha / 2, df = df)\n power - (pt(-critical, df = df, ncp = delta, lower.tail = FALSE) +\n pt(critical, df = df, ncp = delta, lower.tail = TRUE))\n }\n comp$f <- power_func\n\n # set interval\n if (missing(n0) | missing(n1)) {\n comp$interval <- c(0, 1e+09)\n } else if (missing(d)) {\n comp$interval <- c(0, 10)\n } else {\n comp$interval <- c(0, 1)\n }\n message(paste0(\n \"Find value between [\", comp$interval[1], \",\", comp$interval[2], \"].\"\n ))\n\n # find missing value satisfying specified power - claculated power = 0\n comp[[miss_arg]] <- do.call(\"uniroot\", comp)$root\n\n # output\n data.frame(comp[full_args])\n}\n\n#'\n#' @importFrom dplyr bind_rows\n#' @importFrom stats model.frame\n#' @importFrom stats model.matrix\n#' @importFrom stats formula\n#' @importFrom rlang enquo\n#' @importFrom rlang eval_tidy\n#'\n#'\npower_calculation <- function(treat = NULL,\n data = NULL,\n treat_levels = NULL,\n treat_labels = NULL,\n ctrl = NULL,\n subset = NULL,\n sd = 1,\n ...) {\n # clean data\n order_d <- reorder_arms(treat_levels, treat_labels, ctrl)\n model <- formula(paste(\"~\", treat))\n clean <- clean_RCTdata(\n model,\n data = data,\n treat_levels = order_d$levels,\n treat_labels = order_d$labels,\n subset = enexpr(subset)\n )\n use <- clean$design[, -1]\n\n # perform power analysis\n pass_ttest_power <- list(...)\n pass_ttest_power$n0 <- sum(1 - rowSums(use))\n pwr <- apply(use, MARGIN = 2, function(n) {\n pass_ttest_power$n1 <- sum(n)\n do.call(\"ttest_power\", pass_ttest_power)\n })\n\n # output dataframe\n out <- bind_rows(pwr)\n out$arms <- gsub(treat, \"\", names(pwr))\n\n # calculate unstandarized effect\n out$sd <- sd\n out$diff_mean <- out$d * out$sd\n\n # add row containing control information\n out <- bind_rows(\n data.frame(\n n0 = pass_ttest_power$n0,\n n1 = pass_ttest_power$n0,\n arms = order_d$labels[1]\n ),\n out\n )\n\n # convert character of treatment to factor\n out$arms <- factor(out$arms, order_d$labels)\n\n # output\n out\n}\n", "meta": {"hexsha": "9243eed37e69227efa8a8fbcc02c873f8ef6e7e1", "size": 3898, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Method-internal-power.r", "max_stars_repo_name": "KatoPachi/multiarmRCT", "max_stars_repo_head_hexsha": "fe75143c5dc194abac8579aba49814fdb0b3acb6", "max_stars_repo_licenses": ["MIT"], "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/Method-internal-power.r", "max_issues_repo_name": "KatoPachi/multiarmRCT", "max_issues_repo_head_hexsha": "fe75143c5dc194abac8579aba49814fdb0b3acb6", "max_issues_repo_licenses": ["MIT"], "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/Method-internal-power.r", "max_forks_repo_name": "KatoPachi/multiarmRCT", "max_forks_repo_head_hexsha": "fe75143c5dc194abac8579aba49814fdb0b3acb6", "max_forks_repo_licenses": ["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.5303030303, "max_line_length": 73, "alphanum_fraction": 0.6069779374, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.640153864667631}} {"text": "Please read the source of NAGComplexExample.java for a better understanding of how to use NAGComplex\n\n*****BASICS*****\n\nConstructing z1 and z2;\nz1 = (0.0, 0.0)\nz2 = (2.0, 3.0)\n\nChanging z1 values using NAGComplex.setRe() and NAGComplex.setIm();\nz1 = (3.0, 4.0)\n\nCopying z2 to z3 using NAGComplex.clone();\nz3 = (2.0, 3.0)\nCopying z1 to z4 using static method NAGComplex.clone(NAGComplex z)\nz4 = (3.0, 4.0)\n\nArray created using NAGComplex.createArray(5);\n(0.0, 0.0) (0.0, 0.0) (0.0, 0.0) (0.0, 0.0) (0.0, 0.0)\n\nThe same array updated using NAGComplex[i].setRe() and NAGComplex[i].setIm();\n(1.0, 9.0) (2.0, 8.0) (3.0, 7.0) (4.0, 6.0) (5.0, 5.0)\n\n*****ARITHMETIC*****\n\nz1 = (3.0, 4.0)\nz2 = (2.0, 3.0)\nz3 = (6.0, -2.0)\nz4 = (4.0, -5.0)\n\nz1 + z2 = (5.0, 7.0)\nz3 + z4 = (10.0, -7.0)\n\nz1 - z2 = (1.0, 1.0)\nz3 - z4 = (2.0, 3.0)\n\nz1 * z2 = (-6.0, 17.0)\nz3 * z4 = (14.0, -38.0)\n\nz1 / z2 = (1.3846153846153846, -0.07692307692307696)\nz3 / z4 = (0.829268292682927, 0.5365853658536587)\n\n-(z1) = (-3.0, -4.0)\n-(z2) = (-2.0, -3.0)\n\nconjugate(z1) = (3.0, -4.0)\nconjugate(z2) = (2.0, -3.0)\n\nz3 == z4? - false\nz4 = (6.0, -2.0)\nz3 == z4? - true\n|z1| = 5.0\n|z2| = 3.6055512754639896\n\narg(z1) = 0.9272952180016122\narg(z2) = 0.982793723247329\n\nz5 = (-5.0, 12.0)\nz6 = (-9.0, 40.0)\nSqrt(z5) = (2.0, 3.0)\nSqrt(z6) = (4.0, 5.0)", "meta": {"hexsha": "2040ba14212a328bf0d45350f59c850054efdbf7", "size": 1299, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/nagcomplexexample.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/nagcomplexexample.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/nagcomplexexample.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": 21.65, "max_line_length": 100, "alphanum_fraction": 0.5758275597, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6401435575782265}} {"text": "\nqmix <- function (p, params, pro = c(.5, .5), expand=.1, dist = \"binorm\") {\n nr <- 1000000\n XX <- rbinom(n=nr, size=1, prob=pro)\n if(dist == \"binorm\") {\n sd.s <- 1\n x = rnorm(n=nr, params[1], sd.s)*XX + rnorm(n=nr, params[2], sd.s)*(1-XX)\n } else if(dist == \"bibeta\") {\n x = rbeta(n=nr, params[[1]][1], params[[1]][2])*XX + rbeta(n=nr, params[[2]][1], params[[2]][2])*(1-XX)\n } \n span <- seq(min(x) - expand * diff(range(x)), max(x) + expand * diff(range(x)), length = nr)\n cdf <- vector(mode = \"numeric\", length = nr)\n if(dist == \"binorm\") {\n sd.s <- 1\n cdf = pnorm(span, params[1], sd.s)*pro[1] + pnorm(span, params[2], sd.s)*(1-pro[1])\n } else if(dist == \"bibeta\") {\n cdf = pbeta(span, params[[1]][1], params[[1]][2])*pro[1] + pbeta(span, params[[2]][1], params[[2]][2])*(1-pro[1])\n } \n quants <- stats::spline(cdf, span, method = \"hyman\", xout = p)$y\n quants[which(p < 0L | p > 1L)] <- NaN\n quants[which(p == 0L)] <- -Inf\n quants[which(p == 1L)] <- Inf\n if (any(is.nan(quants)))\n warning(\"Some quantile values could not be calculated. If all 'p's are within [0,1], try reducing the value of 'expand' and try again.\")\n return(as.vector(quants))\n}\n\n\nadd.alpha <- function(col, alpha=1){\n if(missing(col))\n stop(\"Please provide a vector of colours.\")\n apply(sapply(col, col2rgb)/255, 2, \n function(x) \n rgb(x[1], x[2], x[3], alpha=alpha)) \n}\n\n\ncomputeTrueKDiff <- function(){\n \n if(dist == \"binorm\" | dist == \"bibeta\") {\n c1 <- qmix(1-r, params[[1]], c(pi.0.true, 1-pi.0.true), expand=.1, dist = dist)\n c2 <- qmix(1-r, params[[2]], c(pi.0.true, 1-pi.0.true), expand=.1, dist = dist)\n } else {\n stop(\"Wrong dist\")\n }\n \n if (dist == \"binorm\") {\n sd.s = 1\n F.plus1 <- pnorm(c1, mean = params[[1]][1], sd.s)\n F.plus2 <- pnorm(c2, mean = params[[2]][1], sd.s)\n } else if (dist == \"bibeta\") {\n F.plus1 <- pbeta(c1, params[[1]][[1]][1], params[[1]][[1]][2])\n F.plus2 <- pbeta(c2, params[[2]][[1]][1], params[[2]][[1]][2])\n } \n \n k.true1 <- vector(length = length(F.plus1))\n pi.true1 <- vector(length = length(F.plus1))\n k.true2 <- vector(length = length(F.plus2))\n pi.true2 <- vector(length = length(F.plus2))\n \n for (i in 1:length(k.true1)) {\n k.true1[i] <- 1 - F.plus1[i]\n pi.true1[i] <- k.true1[i]*pi.0.true/r[i]\n k.true2[i] <- 1 - F.plus2[i]\n pi.true2[i] <- k.true2[i]*pi.0.true/r[i]\n }\n \n # if k or pi is above 1, then they should actually be slightly below 1\n k.true1 <- ifelse(k.true1 > 1, 1 - 1E-10, k.true1)\n pi.true1 <- ifelse(pi.true1 > 1, 1 - 1E-10, pi.true1)\n k.true2 <- ifelse(k.true2 > 1, 1 - 1E-10, k.true2)\n pi.true2 <- ifelse(pi.true2 > 1, 1 - 1E-10, pi.true2)\n \n \n return(k.true1 - k.true2)\n}\n\n\nfig_label <- function(text, region=\"figure\", pos=\"topleft\", cex=NULL, ...) {\n \n region <- match.arg(region, c(\"figure\", \"plot\", \"device\"))\n pos <- match.arg(pos, c(\"topleft\", \"top\", \"topright\", \n \"left\", \"center\", \"right\", \n \"bottomleft\", \"bottom\", \"bottomright\"))\n \n if(region %in% c(\"figure\", \"device\")) {\n ds <- dev.size(\"in\")\n # xy coordinates of device corners in user coordinates\n x <- grconvertX(c(0, ds[1]), from=\"in\", to=\"user\")\n y <- grconvertY(c(0, ds[2]), from=\"in\", to=\"user\")\n \n # fragment of the device we use to plot\n if(region == \"figure\") {\n # account for the fragment of the device that \n # the figure is using\n fig <- par(\"fig\")\n dx <- (x[2] - x[1])\n dy <- (y[2] - y[1])\n x <- x[1] + dx * fig[1:2]\n y <- y[1] + dy * fig[3:4]\n } \n }\n \n # much simpler if in plotting region\n if(region == \"plot\") {\n u <- par(\"usr\")\n x <- u[1:2]\n y <- u[3:4]\n }\n \n sw <- strwidth(text, cex=cex) * 60/100\n sh <- strheight(text, cex=cex) * 60/100\n \n x1 <- switch(pos,\n topleft =x[1] + sw, \n left =x[1] + sw,\n bottomleft =x[1] + sw,\n top =(x[1] + x[2])/2,\n center =(x[1] + x[2])/2,\n bottom =(x[1] + x[2])/2,\n topright =x[2] - sw,\n right =x[2] - sw,\n bottomright =x[2] - sw)\n \n y1 <- switch(pos,\n topleft =y[2] - sh,\n top =y[2] - sh,\n topright =y[2] - sh,\n left =(y[1] + y[2])/2,\n center =(y[1] + y[2])/2,\n right =(y[1] + y[2])/2,\n bottomleft =y[1] + sh,\n bottom =y[1] + sh,\n bottomright =y[1] + sh)\n \n old.par <- par(xpd=NA)\n on.exit(par(old.par))\n \n text(x1, y1, text, cex=cex, ...)\n return(invisible(c(x,y)))\n}\n", "meta": {"hexsha": "5c2ba178e4f4e353514c5a60ad08194824174b2e", "size": 4710, "ext": "r", "lang": "R", "max_stars_repo_path": "simulation_files/final_figure/convenience.r", "max_stars_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_stars_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation_files/final_figure/convenience.r", "max_issues_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_issues_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation_files/final_figure/convenience.r", "max_forks_repo_name": "jrash/Enrichment-Inference-Supplemental-Materials", "max_forks_repo_head_hexsha": "0f0191cfcc5bf4a80cc39a593e912a59e5970cbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1690140845, "max_line_length": 140, "alphanum_fraction": 0.4949044586, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.639760441630876}} {"text": "# simple example of data cloning taken from their web pages (with slight modification)\n\n# Copyright 2017 Province of British Columbia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software 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 limitations under the License.\n\nset.seed(23423423)\nn <- 25\np <- .3\ny <- rbinom(n=1, size=n, p=p)\n\n\nlibrary(dclone)\nlibrary(rjags)\n\n\nmodel <- dclone::custommodel(\"\nmodel {\n y ~ dbin(p, n) # likelihood\n \n p ~ dunif(.001, .999) # prior\n\n # compute the likelihood\n loglik <- log( pbin(y, p, n))\n}\n\")\n\n\ndata.list <- list(y=y, n=n)\ndata.list\n\n\nmonitor.list <- c(\"p\",\"loglik\")\n\nfit <- jags.fit(data =data.list, \n params =monitor.list,\n model = model)\n\nsummary(fit)\nplot(fit)\n\n\n#---------------------------------------------------\n# Now for the data cloning\n\nmodel.clone <- dclone::custommodel(\"\nmodel {\n for(k in 1:K){ # cloning loop\n y[1,k] ~ dbin(p, n) # likelihood\n loglikc[1,k] <- log( dbin(y[1,k], p, n))\n } \n \n loglik <- mean(loglikc[1,1:K]) # the mean loglikelihood?\n p ~ dunif(.001, .999) # prior\n }\n\")\n\ndata.list.clone <- list( y=dcdim(data.matrix(y)), n=n, K=1)\ndata.list.clone\n\nmonitor.list <- c(\"p\", \"loglik\")\n\nfit.clone <- dc.fit(data =data.list.clone,\n params=monitor.list,\n model =model.clone,\n n.clones=c(1,2,4,8,16),\n unchanged=\"n\",\n multiply=\"K\")\n\nsummary(fit.clone)\nphat <- summary(fit.clone)$statistics[\"p\",\"Mean\"]\nphat\n# actual log likelihood\ndbinom(y, n, phat, log=TRUE )\n\n\n\ncoef(fit.clone)\nphat <- y/n\ncat(\"MLE \", phat, \"\\n\" )\ndcsd(fit.clone)\ncat('Theoretical SE ', sqrt(p*(1-p)/n), \"\\n\")\ncat(\"Empirical SE \", sqrt(phat*(1-phat)/n), \"\\n\")\n\nvcov(fit.clone)\nconfint(fit.clone)\n", "meta": {"hexsha": "6f00eb16391366fe0e54377f443b67cbbdfceef3", "size": 2215, "ext": "r", "lang": "R", "max_stars_repo_path": "DataCloningTesting/clone.binom.r", "max_stars_repo_name": "bcgov/SSD-methods", "max_stars_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-19T05:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-01T05:50:56.000Z", "max_issues_repo_path": "DataCloningTesting/clone.binom.r", "max_issues_repo_name": "bcgov/SSD-methods", "max_issues_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-03-01T22:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T19:13:14.000Z", "max_forks_repo_path": "DataCloningTesting/clone.binom.r", "max_forks_repo_name": "bcgov/SSD-methods", "max_forks_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-01T04:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-01T04:03:46.000Z", "avg_line_length": 23.3157894737, "max_line_length": 135, "alphanum_fraction": 0.6036117381, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.639655135491283}} {"text": "#### SimulationFunctions\nCorrMatrixNegFixed <- function(blocks, a, corr, off) {\n Corr <- NULL\n for (i in 1:blocks) {\n Corr[[i]] <- matrix(NA, ncol = a, nrow = a)\n diag= rep(1,a)\n offdiag = corr\n Corr[[i]][lower.tri(Corr[[i]])] <- offdiag\n Corr[[i]][upper.tri(Corr[[i]])] <- t(Corr[[i]])[upper.tri(t(Corr[[i]]))]\n diag(Corr[[i]]) <- diag\n for ( k in ((ncol(Corr[[i]])/2)+1):(ncol(Corr[[i]])) ) {\n for( j in 1:(nrow(Corr[[i]])/2) ) {\n Corr[[i]][j,k] <- -1*Corr[[i]][j,k]\n }\n }\n\n for ( k in ((nrow(Corr[[i]])/2)+1):(nrow(Corr[[i]])) ) {\n for( j in 1:(ncol(Corr[[i]])/2) ) {\n Corr[[i]][k,j] <- -1*Corr[[i]][k,j]\n }\n }\n\n }\n res <- as.matrix(bdiag(Corr))\n res[which(res == 0, arr.ind = TRUE)] <- off\n return(res)\n}\n\n\n##################################################################################\n## This function Simulates complete data sets.\n## We are creating a dataset of size N (samples) by p (Metabolites)\n##################################################################################\n\nSimulatedData <- function(n, p, covar, low, high) {\n\t## No of Samples == N\n\t## No of Metabolites = p\n Means <- runif(p, min = low, max = high)\n data <- rmvnorm(n, mean = Means, sigma = covar)\n\treturn(data)\n}\n\n\n##################################################################################\n###### Create MissingValues Datasets\n##################################################################################\n\nMissingData <- function(data, totalmiss, mar, perc) {\n\tmissdata <- data\n\n ## First create Missing Not At Random (MNAR)\n belowthresh <- which(data < quantile(data, probs = c(totalmiss-mar)/100), arr.ind = TRUE)\n missdata[belowthresh] <- NA\n\n\n\t## Next create Missing At Random (MAR)\n dataVector <- c(1:length(data))\n randommiss <- sample(dataVector[-which(is.na(missdata))], (mar/100)*length(data) )\n missdata[randommiss] <- NA\n\n\t## Next exclude metabolites with more that 'perc' missing\n NumberMissing <- apply(missdata, 2, function(x) length(which(is.na(x))))\n\n ind <- which(NumberMissing >= (nrow(data)*perc))\n if(length(ind) > 0 ){\n missdata <- missdata[,-ind]\n data <- data[,-ind]\n }\n\n\treturn(list(missdata, data, NumberMissing))\n}\n\n", "meta": {"hexsha": "d5a7d1c525c43f0a882bf645b4aeca56e9637f68", "size": 2411, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/NAguideRapp/Trunc_KNN/Simulation.r", "max_stars_repo_name": "wangshisheng/NAguideR", "max_stars_repo_head_hexsha": "15ec86263d5821990ad39a8d9f378cf4d76b25fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17, "max_stars_repo_stars_event_min_datetime": "2020-01-15T05:41:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T05:02:11.000Z", "max_issues_repo_path": "inst/NAguideRapp/Trunc_KNN/Simulation.r", "max_issues_repo_name": "wangshisheng/NAguideR", "max_issues_repo_head_hexsha": "15ec86263d5821990ad39a8d9f378cf4d76b25fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-01-11T13:46:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T12:24:51.000Z", "max_forks_repo_path": "inst/NAguideRapp/Trunc_KNN/Simulation.r", "max_forks_repo_name": "wangshisheng/NAguideR", "max_forks_repo_head_hexsha": "15ec86263d5821990ad39a8d9f378cf4d76b25fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2020-06-12T08:33:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:39:46.000Z", "avg_line_length": 33.0273972603, "max_line_length": 97, "alphanum_fraction": 0.4620489423, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6396457350287417}} {"text": "### TITLE: Full Matching Effect Ratio Code ###\n### MAINTAINER: Hyunseung Kang (hskang at stanford dot edu)\n### LAST UPDATE: Nov. 29, 2015\n### SUMMARY: The code implements the full matching IV method \n### described in the paper Kang, Kreuels, May, \n### and Small (2015+). Specifically, the main \n### function, estLambda(), estimates the \n### effect ratio parameter described in the \n### said paper.\n### REQUIRES: MASS, optmatch, AER (R packages, install them \n### from CRAN) \n### USAGE: Copy-paste the R code below. At the end of\n### the code is a simple running example of\n### the code from simulated data. \n\n### Libraries to Load ####\nlibrary(optmatch)\nlibrary(AER)\n\n### Functions ###\n##### smahal: Obtain rank-based Mahalanobis distance\n### FUNCTION: Creates a rank-based Mahalanobis distance. \n### INPUT: 1) Z: instruments (n by 1 vector), Z =1 (treated) and Z = 0 (not treated)\n### 2) X: covariates (n by p matrix}\n### OUTPUT: 1) n by n rank-based Mahalanobis distance matrix \nsmahal= function(Z,X){\n X<-as.matrix(X)\n n<-dim(X)[1]\n rownames(X)<-1:n\n k<-dim(X)[2]\n m<-sum(Z)\n for (j in 1:k) X[,j]<-rank(X[,j])\n cv<-cov(X)\n vuntied<-var(1:n)\n rat<-sqrt(vuntied/diag(cv))\n cv<-diag(rat)%*%cv%*%diag(rat)\n out<-matrix(NA,m,n-m)\n Xc<-X[Z==0,]\n Xt<-X[Z==1,]\n rownames(out)<-rownames(X)[Z==1]\n colnames(out)<-rownames(X)[Z==0]\n icov<-ginv(cv)\n for (i in 1:m) out[i,]<-mahalanobis(Xc,Xt[i,],icov,inverted=T)\n out\n}\n\n##### addcaliper: adds caliper to the matching matrix\n### FUNCTION: Creates a calipered rank-based Mahalanobis distance from a distance matrix.\n### INPUT: 1) dmat: distance matrix.\n### 2) Z: instruments (n by 1 vector), Z =1 (treated) and Z = 0 (not treated)\n### 3) logitp: logit propensity scores from logistic regression (n by 1 vector)\n### 4) calipersd, indicator on when to caliper\n### 5) penalty, how much penalty for exceeding caliper bounds\n### OUTPUT: 1) n by n with caliper added\naddcaliper=function(dmat,Z,logitp,calipersd=.2,penalty=1000){\n sd.logitp=sd(logitp)\n adif=abs(outer(logitp[Z==1],logitp[Z==0],\"-\"))\n adif=(adif-(calipersd*sd.logitp))*(adif>(calipersd*sd.logitp))\n dmat=dmat+adif*penalty\n dmat\n}\n\n##### matching: does full matching\n### FUNCTION: creates a vector that matches treatment to control\n### INPUT: 1) Z: a n-length vector that lists treatment (as 1) and control (as 0)\n### 2) X: a n-by-p matrix of covariates\n### 3) type: type of matching, defaults to full matching\n### 4) ratio: if full matching or 1:m matching, checks to see the control/treatment ratio\n### 5) matchInfo: should the function print out the matching information?\n### OUTPUT: 1) a n-vector vector containing match numbers.\n### NOTE: The matching function (smahal, prop.score, caliper, and fullmatch) are\n### very sensitive to how the observations are ordered. Currentyl, smahal\n### orders the observations by how Z is ordered.\nmatching = function(Z,X,type=c(\"full\",\"pair\",\"1:m\"),ratio,matchInfo=FALSE) {\n type = match.arg(type)\n \n # Pre-processing\n Z = as.logical(Z);\n \n # Rank-based distance matrix\n rank.mat = smahal(Z,X)\n \n # Propensity scores\n model = glm(Z ~ X,family=\"binomial\"); prop.score = predict(model);\n \n # Fix rank-based distance matrix by propensity score calipers\n rank.mat.caliper = addcaliper(rank.mat,Z,prop.score)\n\n # Actual matching\n if(type == \"pair\") pairmatchvec = pairmatch(rank.mat.caliper,data=1:length(Z))\n if(type == \"full\") {\n \t if(missing(ratio)) pairmatchvec = fullmatch(rank.mat.caliper,data=1:length(Z))\n \t else pairmatchvec = fullmatch(rank.mat.caliper,data=1:length(Z),min.controls=1/ratio,max.controls=ratio)\n }\n if(type == \"1:m\") pairmatchvec = pairmatch(rank.mat.caliper,data=1:length(Z),controls=ratio)\n if(matchInfo) print(summary(pairmatchvec))\n \n # Post-processing\n pairmatchvec = as.numeric(substr(pairmatchvec,start=3,stop=20)) \n return(pairmatchvec) \n}\n\n##### estLambda: estimates Lambda, provide confidence interval, and p-value\n### FUNCTION: provides point est, confidence interval, and p-value\n### INPUT: Z: instrument (n by 1 vector)\n### R: response (n by 1 vector)\n### D: dose (n by 1 vector)\n### X: covariate matrix (n by p) \n### matchedNumber: matching vector from matching() function\n### null: the lambda_0 value in H0: lambda = lambda_0\n### alphaLevel: alpha level for the confidence interval\n### OUTPUT: point Est, confidence interval, and p-value\nestLambda = function(Z,R,D,X,matchedNumber,null = 0,alphaLevel = 0.05) {\n if(alphaLevel >= 0.5) stop(\"alphaLevel is improperly set\")\n \n X.factorize = model.matrix(~X) \n if(missing(matchedNumber)) matchedNumber = matching(Z,X,\"full\")\n \t\t\t \n # Deal with non-matched individuals #\n R.matchedIndiv = R[!is.na(matchedNumber)]\n D.matchedIndiv = D[!is.na(matchedNumber)]\n Z.matchedIndiv = Z[!is.na(matchedNumber)]\n matchedNumber.matchedIndiv = matchedNumber[!is.na(matchedNumber)]\n\n # Sort individuals in ascending matching order\n matchedNumber.sortedIndex = sort(matchedNumber.matchedIndiv,index.return=TRUE)$ix\n R.sorted = R.matchedIndiv[matchedNumber.sortedIndex]\n D.sorted = D.matchedIndiv[matchedNumber.sortedIndex]\n Z.sorted = Z.matchedIndiv[matchedNumber.sortedIndex]\n matchedNumber.sorted = matchedNumber.matchedIndiv[matchedNumber.sortedIndex]\n \n # Calculate the size of each matched set and the corresponding weights\n ni = tabulate(matchedNumber.sorted); \n ni = ni[!(ni == 0)] #this cleans up a flaw with matching algorithm \n #where some matched numbers (e.g. 1:I) are not used between\n\t\t \t \t \t \t #1 to I\n I = length(ni)\n wi = ni^2 / (ni - 1) #Actual formula: ni^2 /(mi * (ni - mi))\n\n # Calculate Vi, Gi, and Hi\n # Formula\n # Vi = Gi - lambda * Hi\n # Gi = wi*(Zij - Zimean)(Rij - Rimean) = wi*(ZijRij - ni*Zmean.*Rmean.)\n # Hi = wi*(Zij - Zimean)(Dij - Dimean) = wi*(ZijDij - ni*Zmean.*Dmean.)\n\n # This requires some thought. Basically, because R,D,Z are all ordered based on matchedset number,\n # we use cumsum to obtain means of R, D, and Z within each group as well as means of RZ and DZ.\n # The key here is using the cumsum(ni), which keeps track of the indices in all the ordered vectors\n ni.cumsum = cumsum(ni)\n RZ.cumsum = cumsum(R.sorted*Z.sorted); DZ.cumsum = cumsum(D.sorted*Z.sorted)\n R.cumsum = cumsum(R.sorted); D.cumsum = cumsum(D.sorted); Z.cumsum = cumsum(Z.sorted)\n R.means = (R.cumsum[ni.cumsum] - c(0,R.cumsum[ni.cumsum[-length(ni.cumsum)]]))/ni\n Z.means = (Z.cumsum[ni.cumsum] - c(0,Z.cumsum[ni.cumsum[-length(ni.cumsum)]]))/ni\n D.means = (D.cumsum[ni.cumsum] - c(0,D.cumsum[ni.cumsum[-length(ni.cumsum)]]))/ni\n \n RZ.group = RZ.cumsum[ni.cumsum] - c(0,RZ.cumsum[ni.cumsum[-length(ni.cumsum)]])\n DZ.group = DZ.cumsum[ni.cumsum] - c(0,DZ.cumsum[ni.cumsum[-length(ni.cumsum)]])\n\n Gi = wi * RZ.group - wi * ni * R.means * Z.means\n Hi = wi * DZ.group - wi * ni * D.means * Z.means\n \n # Compute the point estimate \n pointEst = sum(Gi) / sum(Hi)\n \n # Compute the p-value under the null\n ViNull = Gi - null * Hi\n testStatNull = mean(ViNull) / sqrt(1/(I *(I-1)) * sum( (ViNull - mean(ViNull))^2) )\n pvalue = 2* (1 - pnorm(abs(testStatNull)))\n \n # Compute the quadratic terms for CI\n # A*lambda^2 + B*lambda + C = 0 (technically, it's A*lambda^2 + B*lambda + C <= 0)\n q = qnorm(1 - alphaLevel/2)\n A = sum(Hi)^2/I^2 - q^2 /(I * (I-1)) * sum( (Hi - mean(Hi))^2)\n B = -2 * (sum(Hi) * sum(Gi) / I^2 - q^2 / (I * (I-1)) * sum( (Hi - mean(Hi)) * (Gi - mean(Gi))))\n C = sum(Gi)^2/I^2 - q^2/(I * (I-1)) * sum( (Gi - mean(Gi))^2)\n\n detQuad = round(B^2 - 4*A*C,9) #6 is set for numerical accuracy\n if( detQuad <= 0) {\n if(A < 0) {\n cis = matrix(c(-Inf,Inf),1,2)\n } else {\n cis = matrix(c(NA,NA),1,2)\n\t} \n }\n if(detQuad > 0) {\n if(A < 0) {\n up.ci = (-B - sqrt(detQuad))/ (2*A) \n low.ci = (-B + sqrt(detQuad)) / (2*A) \n cis = matrix(c(-Inf,low.ci,up.ci,Inf),2,2,byrow=TRUE)\n\t} else {\n\t low.ci = (-B - sqrt(detQuad))/ (2*A) \n up.ci = (-B + sqrt(detQuad)) / (2*A) \n cis = matrix(c(low.ci,up.ci),1,2)\n\t}\n }\n return(list(pointEst = pointEst,cis = cis,pvalue = pvalue))\n} \n###### est2SLS\n### FUNCTION: computes the 2SLS estimate using the AER package\n### INPUT: Z: instrument (n by 1 vector)\n### R: response (n by 1 vector)\n### D: dose (n by 1 vector)\n### X: covariate matrix (n by p) \n### null: null Value under H_0:\n### OUTPUT: point Est, confidence interval, and p-value\nest2SLS <- function(Z,R,D,X,null=0) {\n library(AER)\n model = ivreg(R ~ D + X | Z + X)\n model.summary = summary(model)\n coefficientTable = model.summary$coefficients\n dfTest = model.summary$df[2]\n estValue = as.numeric(coefficientTable[2,1])\n stdError = as.numeric(coefficientTable[2,2])\n tValue = abs( (estValue - null) / stdError)\n pvalue = 2*(1 - pt(tValue,dfTest))\n confInt = matrix(as.numeric(confint(model)[2,]),1,2)\n return(list(pointEst = estValue,cis = confInt,pvalue = pvalue))\n}\n\n###### estOLS\n### FUNCTION: computes the OLS estimate \n### INPUT: Z: instrument (n by 1 vector), note this is not used in OLS\n### R: response (n by 1 vector)\n### D: dose (n by 1 vector)\n### X: covariate matrix (n by p) \n### OUTPUT: point Est, confidence interval, and p-value\nestOLS <- function(Z,R,D,X) {\n model = lm(R ~ D + X)\n estValue = as.numeric(coefficients(model))[2]\n pvalue = as.numeric(summary(model)$coefficients[2,4])\n confInt = matrix(as.numeric(confint(model)[2,]),1,2)\n return(list(pointEst = estValue,cis = confInt,pvalue=pvalue))\n}\n\n##### sensInt \n### FUNCTION: does sensitivity analysis\n### INPUT: Gamma: a scalar value \n### Z: binary treatment/control vector (n time 1) \n### R: binary response (n * 1)\n### pairmatchvec: vector of matches (handles no matches)\n### OUTPUT: lower and upper bounds for sensitivity analysis\n### NOTE: Can only handle sensitivity analysis if there are multiple controls \n### (but not if there are multiple treatments) AND if the response is binary\nsensInt <- function(Gamma,Z,R,pairmatchvec) {\n matchedSets = unique(pairmatchvec[!is.na(pairmatchvec)]); \n cs.plus = rep(0,length(I))\n ps.plus = rep(0,length(I))\n ps.minus = rep(0,length(I))\n testStat = rep(0,length(I))\n ds= rep(0,length(I))\n for(i in 1:length(matchedSets)) { \n index = matchedSets[i]\n matchedSetID = which(pairmatchvec == index)\n ni = length(matchedSetID); mi = sum(Z[matchedSetID])\t \n cs.plus[i] = sum(R[matchedSetID])\n ps.plus[i] = Gamma * cs.plus[i]/(Gamma*cs.plus[i] + ni - cs.plus[i])\n ps.minus[i] = cs.plus[i]/(cs.plus[i] + (ni - cs.plus[i])*Gamma)\n ds[i] = ni/(mi*(ni - mi))\n testStat[i] = ds[i] * sum(Z[matchedSetID] * R[matchedSetID])\n }\n T = sum(testStat)\n lowerBound = (T - sum(ds * ps.plus)) /(sqrt(sum(ds^2 * ps.plus * (1 - ps.plus))))\n upperBound = (T - sum(ds * ps.minus)) /(sqrt(sum(ds^2 * ps.minus * (1 - ps.minus))))\n return(c(lowerBound,upperBound))\n}\n\n##### balanceCheck \n### FUNCTION: checks the balance of covariates before and after matching\n### INPUT: Z: treatment/control vector (n time 1) \n### X: covariates (n * p)\n### pairmatchvec: vector of matches (handles no matches)\n### OUTPUT: a table of standardized differences\nbalanceCheck <- function(Z,X,pairmatchvec) {\n # Before Matching #\n X.C.BeforeMatch = X[Z == 0,]; X.T.BeforeMatch = X[Z == 1,];\n overallSD = sqrt(apply(X.C.BeforeMatch,2,var) + apply(X.T.BeforeMatch,2,var)/2)\n stdDiff.Before = abs((colMeans(X.T.BeforeMatch) - colMeans(X.C.BeforeMatch))/overallSD)\n # After Matching #\n matchedSets = unique(pairmatchvec[!is.na(pairmatchvec)]); \n X.C.AfterMatch = matrix(0,length(matchedSets),ncol(X)); X.T.AfterMatch = matrix(0,length(matchedSets),ncol(X));\n nTreatedAfterMatch = rep(0,length(matchedSets))\n for(i in 1:length(matchedSets)) { \n treatedZ = which(pairmatchvec == matchedSets[i] & Z == 1)\n controlZ = which(pairmatchvec == matchedSets[i] & Z == 0)\n X.C.AfterMatch[i,] = colMeans(X[controlZ,,drop=FALSE]); X.T.AfterMatch[i,] = colMeans(X[treatedZ,,drop=FALSE])\n nTreatedAfterMatch[i] = length(treatedZ)\n }\n stdDiff.After = apply( X.T.AfterMatch - X.C.AfterMatch,2,function(x){ sum(x * nTreatedAfterMatch) / sum(nTreatedAfterMatch)}) / overallSD\n stdDiff.After = abs(stdDiff.After)\n output = cbind(stdDiff.Before,stdDiff.After)\n colnames(output) = c(\"Standardized differences before matching\",\"Standardized differences after matching\")\n return(output)\n}\n\n##### effectSampleSize \n### FUNCTION: computes the asymptotic variance of effectRatio estimator and the maximum strata size for effectratio estimator\n### INPUT: Z: treatment/control vector (n time 1) \n### matchedNumber: vector of matches\n### OUTPUT: a two-dimensional vector, the first dimension being the effective sample size and the second dimension being the maximum strata size.\neffectSampleSize <- function(Z,matchedNumber) {\n # Deal with non-matched individuals #\n Z.matchedIndiv = Z[!is.na(matchedNumber)]\n matchedNumber.matchedIndiv = matchedNumber[!is.na(matchedNumber)]\n\n # Sort individuals in ascending matching order\n matchedNumber.sortedIndex = sort(matchedNumber.matchedIndiv,index.return=TRUE)$ix\n Z.sorted = Z.matchedIndiv[matchedNumber.sortedIndex]\n matchedNumber.sorted = matchedNumber.matchedIndiv[matchedNumber.sortedIndex]\n \n # Calculate the size of each matched set and the corresponding weights\n ni = tabulate(matchedNumber.sorted); I = length(ni)\n ni.max = max(ni)\n asympVarEffectRatio = (sum(ni^3 / (ni - 1)) * 1/I) / (sum(ni) / I)^2\n print(paste(\"Asymptotic variance of effect ratio estimator is\",asympVarEffectRatio))\n print(paste(\"Maximmum strata size is\",ni.max))\n return(c(asympVarEffectRatio,ni.max))\n}\n\n##### matchSizeAnalysis\n### FUNCTION: analyzes the size of matched Sets as a function of the covariates\n### INPUT: pairmatchvec: vector of of matches\n### Z: treatment/control vector \n### X: covariates\n### OUTPUT: a two-dimensional vector, the first dimension being the effective sample size and the second dimension being the maximum strata size.\nmatchSizeAnalysis <- function(pairmatchvec,Z,X) {\n matchedSets = unique(pairmatchvec[!is.na(pairmatchvec)]); I = length(matchedSets)\n Y.sizeMatch = rep(0,I)\n Y.controlMatch = rep(0,I)\n X.covAvg = matrix(0,I,ncol(X))\n \n for(i in 1:I) {\n set.i = which(matchedSets[i] == pairmatchvec)\n Y.controlMatch[i] = sum(Z[set.i])\n Y.sizeMatch[i] = length(set.i)\n for(j in 1:ncol(X.covAvg)) {\n X.covAvg[i,j] = mean(X[set.i,j])\n }\n }\n colnames(X.covAvg) = colnames(X)\n return(data.frame(Y.sizeMatch = Y.sizeMatch,Y.controlMatch=Y.controlMatch,X.covAvg))\n}\n", "meta": {"hexsha": "6a3d72e4a105eb370519fea4ec8c93a45124ccba", "size": 14804, "ext": "r", "lang": "R", "max_stars_repo_path": "effectRatio.r", "max_stars_repo_name": "hyunseungkang/matchIV", "max_stars_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-11-01T17:10:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T06:30:30.000Z", "max_issues_repo_path": "effectRatio.r", "max_issues_repo_name": "hyunseungkang/matchIV", "max_issues_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "effectRatio.r", "max_forks_repo_name": "hyunseungkang/matchIV", "max_forks_repo_head_hexsha": "975121100a53ba76e34f499e5fb34ac1eb4b4714", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2865497076, "max_line_length": 145, "alphanum_fraction": 0.6586057822, "num_tokens": 4538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6395092499052913}} {"text": "# Estadiistica descriptiva (I): Teoría de probabilidades: distribuciones, varianza.\n\n#################################################################\n# Limpiemos todo primero.\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n## Este truco instala el paquete si es que no esta instalado, y lo llama usando \"library\".\n## Si NO está instalado, lo instala, y despues lo llama usando \"library\".\n## Es, básicamente, un instalador y cargador CONDICIONAL de paquetes.\n## Este paquete que ejecuta esta accion condicional, se llama \"pacman\".\n\n# Usuarios MAC: asegurarse de tener XQuartz instalado\n# https://dl.bintray.com/xquartz/downloads/XQuartz-2.7.11.dmg\n\ninstall.packages(\"cem\")\nlibrary(cem)\n\nif (!require(\"pacman\")) install.packages(\"pacman\"); library(pacman) # Ahora cargaremos \"pacman\"\np_load(cem) # y aqui le decimos a pacman que revise si tienes el paquete \"cem\" que utilizaremos para el sgte. ej. Si no lo tienes, lo instalará, y lo llamará.\n# En resumen, p_load() reemplaza install.packages(\"paquete\") y \"library(paquete)\".\n\n# En la libreria \"cem\" vive una base de datos muy famosa, conocida como LaLonde. Carguemosla para la sgte. actividad.\ndata(LL)\n\n# Veamos en que consiste. \nhead(LL)\n\n## Variables\n\n# treated: Indicator variable for whether the participant received the treatment. \n# age: Measured in years. \n# education: Years of education. \n# black: Indicator variable for whether the participant is African-American. \n# married: Indicator variable for whether the participant is married. \n# nodegree: Indicator variable for not possessing a high school diploma\n# re74: Real earnings in 1974. re75: \n# Real earnings in 1975. \n# re78: Real earnings in 1978. \n# hispanic: Indicator variable for whether the participant is Hispanic. \n# u74: Indicator variable for unemployed in 1974. \n# u75: Indicator variable for unemployed in 1975.\n\n\n#################################################################\n# Estadistica Descriptiva\n#################################################################\n\n# En esta seccion revisaremos los estadisticos descriptivos mas usados.\n\n\n#################################################################\n# Promedio (o media) (o \"mean\" en ingles).\n#################################################################\n\n# 1) Es la medida mas usada para medir la centralidad de la distribucion.\n# 2) Todos los datos, como vimos, siguen una distribucion. Por ej., veamos la distribucion \n# etarea de los sujetos entrevistados en esta base de datos.\n\n## Un histograma\nhistogram(LL$age) # El promedio debiera ser cercano a 20 años.\n\n## Veamos ahora el promedio de esta variable usando el comando \"mean()\"\nmean(LL$age)\n\n## Redondear numeros usando el comando \"round\"\nround(mean(LL$age), 1) # con un decimal.\nround(mean(LL$age), 0) # con 0 decimales.\n\n#################################################################\n# Mediana (o \"median\" en ingles).\n#################################################################\n\n# Muestra el valor que vive al medio de la distribucion.\n# Ventaja: es mas robusta (o resistente) a los valores extremos, si la comparamos con el promedio.\n# Recuerda. Para calcular el promedio, debemos incorporar los valores extremos (los muy altos, y los muy bajos).\n# Y esto afecta el promedio. No asi con la mediana: no cambia si agregamos valores extremos.\n# En la distribucion normal: mediana = media = moda.\n\n### Primero, ordenemos los numeros de mayor a menor. \nLL$age\nll.age.ordenado = sort(LL$age)\nll.age.ordenado\n\n\n# Calculemos la mediana\nmedian(LL$age)\n\n### OK. Los valores estan ordenados de menor a mayor. Segundo, veamos que largo tiene este vector (usando el comando \"lenght\", que significa \"largo\").\nlength(ll.age.ordenado) \n\nlength(ll.age.ordenado)/2 # OK. Ahora, veamos el elemento que vive al medio de esta lista de numeros.\n# 361. \n\n## 1) OK. Es un numero impar. Que significa eso? \n## 2) Qué pasa con los numeros pares?\n\n## OK. Ahora llamemos al elemento 361\nll.age.ordenado[361]\n\n## Comprobemos que nuestro calculo esta correcto.\nmedian(LL$age) == ll.age.ordenado[361] # OK.\n\n## Conclusion preliminar # 1\nround(mean(LL$age), 0) > median(LL$age)\n## Que significa eso? \n## \"Skewness\" positiva. Hay ciertos valores \"extremos\" que estan inflando el promedio (hacia arriba).\n\n#################################################################\n# Un resumen un poco mas completo\n#################################################################\n\nsummary(LL) # de toda la base\nsummary(LL$age) # de la variable \"age\" (\"edad\")\n\n# 1) Voluntari@ para dibujar un _________ en la pizarra? Usando esta informacioón, cómo se vería este gráfico?\n\n#################################################################\n# Tablas de Frecuencia\n#################################################################\n\n# Por ej., cuantos estan casados (\"married\") en nuestra base de datos?\ntable(LL$married)\n\n# Otro ejemplo, cuantos Afro-Americanos estan casados?\ntable(LL$married, LL$black) # Siempre es table(FILA, COLUMNA). Ese orden (FILA, COLUMNA) siempre es asi en R.\n## En ese sentido, los casados van en la fila, y los Afroamericanos en las columnas.\n\n#################################################################\n# Medidas de Dispersion\n#################################################################\n\n# Ademas de ver cuan centrada esta nuestra distrubucion, tambien queremos ver \n# cuan dispersas estan las observaciones del promedio.\nvar(LL$age)\n\n# 1) Que significa eso?\n# Como lo solucionamos?\n\n# Solucion: desviacion estandard.\nsd(LL$age)\n\n## redondear\nround(sd(LL$age),0) # 7\n\n# La DS es la raiz cuadrada (\"square root\", comando \"sqrt\") de la varianza (comando \"var\"), que esta en escala cuadrada.\nsqrt(var(LL$age)) == sd(LL$age) # Comprobando.\n\n# Qué significa todo esto? \n## Existe la regla \"68-95-99.7\" que aplica sólo a distribuciones normales (nuestra variable de edad NO es normal...). \n\n## 68% de los datos caen dentro del rango de +/- 1 DS de la media. Es decir: \nmean(LL$age) - round(sd(LL$age),0) # rango minimo\nmean(LL$age) + round(sd(LL$age),0) # rango maximo\n\n## 95% de los datos caen dentro del rango de +/- 2 DS's de la media.\nmean(LL$age) - 2*(round(sd(LL$age),0)) # rango minimo\nmean(LL$age) + 2*(round(sd(LL$age),0)) # rango maximo\n\n## 99.7% de los datos caen dentro del rango de +/- 3 DS's de la media.\nmean(LL$age) - 3*(round(sd(LL$age),0)) # rango minimo\nmean(LL$age) + 3*(round(sd(LL$age),0)) # rango maximo\n\n", "meta": {"hexsha": "27dabe855e2c157016edf7db75652cec8812e466", "size": 6384, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase6/Clase6.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Clase6/Clase6.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Clase6/Clase6.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6909090909, "max_line_length": 158, "alphanum_fraction": 0.632518797, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6395092437157348}} {"text": "# ----------------------------------------\n# App Title: Benford's Law and Sequences\n# Author: Jimmy Doi\n# ----------------------------------------\n\nlibrary(RColorBrewer)\nlibrary(shinyIncubator)\n\n########################################\nseq.gen <- function(length,val.1,val.2){\n \n seq <- numeric(length)\n seq[1] <- val.1\n seq[2] <- val.2\n \n for (i in 3:length) { \n seq[i] <- seq[i-1]+seq[i-2]\n } \n return(seq)\n}\n\n########################################\npow.gen <- function(base,length){\n \n seq <- base**(1:length)\n \n return(seq)\n}\n\n########################################\nprime.gen <- function(n){\n n <- as.integer(n)\n if(n > 1e8) stop(\"n too large\")\n primes <- rep(TRUE, n)\n primes[1] <- FALSE\n last.prime <- 2L\n fsqr <- floor(sqrt(n))\n while (last.prime <= fsqr)\n {\n primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE\n sel <- which(primes[(last.prime+1):(fsqr+1)])\n if(any(sel)){\n last.prime <- last.prime + min(sel)\n }else last.prime <- fsqr+1\n }\n which(primes)\n}\n\n########################################\nstring.1st <- function(sequence,max){\n string1 <- substr(as.character(sequence[1:max]),1,1)\n # string1<-paste(\" \",string1,sep=\"\")\n return(string1)\n}\n\n########################################\nstring.2nd <- function(sequence,max){\n string2 <- substr(as.character(sequence[1:max]),2,1000000L)\n string2.a<-paste(string2,\", \",sep=\"\")\n string2.a[max]<-string2[max]\n return(string2.a)\n}\n\n########################################\nprint.string <- function(string,num){\n #names(string)<-\"\"\n return(string[num])\n}\n\n########################################\ngoodness.test <- function(sequence){\n \n string <- substr(as.character(sequence),1,1)\n \n first.digits <- as.integer(string)\n \n # In the event any of the 9 possible digits is not observed in the string, \n # table(first.digits) will not display all digits 1, 2, ..., 9. An example is\n #\n # NAME 1 2 3 4 5 6 7 9\n # FREQ 12 11 9 8 6 5 4 2\n #\n # Here, obs <- as.integer(table(first.digits)) would only contain 8 elements.\n # To correct for this, initialize obs to a zero vector, loop through NAME, \n # find FREQ corresponding to NAME,then paste that FREQ in obs[NAME].\n # This will also work for the case when all 9 possible digits are observed.\n \n Obs <- seq(0,0,,9)\n \n for (i in as.numeric(names(table(first.digits)))) {\n pos <- which(as.numeric(names(table(first.digits)))==i)\n Obs[i]<- as.numeric(table(first.digits))[pos]\n } \n i <- seq(1,9)\n \n Exp <- length(sequence)*log10(1+1/i)\n \n Digit <- seq(1,9)\n \n #print(info)\n \n chisq <- sum(((Obs-Exp)**2)/Exp)\n \n Exp <- round(Exp,3)\n info <- cbind(Digit,Obs,Exp)\n rownames(info)<-rep(\"\",nrow(info))\n \n #print(chisq)\n \n p.value <- 1-pchisq(chisq,8)\n \n text.chi <- paste(\"Chi Square = \",format(round(chisq,3),nsmall=3),sep=\"\")\n names(text.chi)<-\"\"\n \n text.pval <- paste(\"P Value = \",format(round(p.value,3),nsmall=3),sep=\"\")\n names(text.pval)<-\"\"\n \n print(info)\n print(text.chi,quote=F)\n print(text.pval,quote=F)\n \n}\n\n########################################\npr.goodness.test <- function(sequence,big.n){\n \n string <- substr(as.character(sequence),1,1)\n \n first.digits <- as.integer(string)\n \n # In the event any of the 9 possible digits is not observed in the string, \n # table(first.digits) will not display all digits 1, 2, ..., 9. An example is\n #\n # NAME 1 2 3 4 5 6 7 9\n # FREQ 12 11 9 8 6 5 4 2\n #\n # Here, obs <- as.integer(table(first.digits)) would only contain 8 elements.\n # To correct for this, initialize obs to a zero vector, loop through NAME, \n # find FREQ corresponding to NAME,then paste that FREQ in obs[NAME].\n # This will also work for the case when all 9 possible digits are observed.\n \n Obs <- seq(0,0,,9)\n \n for (i in as.numeric(names(table(first.digits)))) {\n pos <- which(as.numeric(names(table(first.digits)))==i)\n Obs[i]<- as.numeric(table(first.digits))[pos]\n } \n\n i <- seq(1,9)\n \n alpha <- 1/(log(big.n)-1.10)\n \n gbl <- 1/(10**(1-alpha)-1)*((i+1)**(1-alpha)-i**(1-alpha))\n \n Exp <- length(sequence)*gbl\n \n Digit <- seq(1,9)\n \n chisq <- sum(((Obs-Exp)**2)/Exp)\n \n Exp <- round(Exp,3)\n info <- cbind(Digit,Obs,Exp)\n rownames(info)<-rep(\"\",nrow(info))\n \n p.value <- 1-pchisq(chisq,8)\n \n text.chi <- paste(\"Chi Square = \",format(round(chisq,3),nsmall=3),sep=\"\")\n names(text.chi)<-\"\"\n \n text.pval <- paste(\"P Value = \",format(round(p.value,3),nsmall=3),sep=\"\")\n names(text.pval)<-\"\"\n \n print(info)\n print(text.chi,quote=F)\n print(text.pval,quote=F)\n \n}\n\n############################################\npmf.compare<-function(sequence){\n \n string <- substr(as.character(sequence),1,1)\n \n first.digits <- as.integer(string)\n \n # In the event any of the 9 possible digits is not observed in the string, \n # table(first.digits) will not display all digits 1, 2, ..., 9. An example is\n #\n # NAME 1 2 3 4 5 6 7 9\n # FREQ 12 11 9 8 6 5 4 2\n #\n # Here, obs <- as.integer(table(first.digits)) would only contain 8 elements.\n # To correct for this, initialize obs to a zero vector, loop through NAME, \n # find FREQ corresponding to NAME,then paste that FREQ in obs[NAME].\n # This will also work for the case when all 9 possible digits are observed.\n \n Obs <- seq(0,0,,9)\n \n for (i in as.numeric(names(table(first.digits)))) {\n pos <- which(as.numeric(names(table(first.digits)))==i)\n Obs[i]<- as.numeric(table(first.digits))[pos]\n } \n i <- seq(1,9)\n \n pmf.Exp <- cbind(seq(1,9)+0.065,log10(1+1/i))\n pmf.Obs <- cbind(seq(1,9)-0.065,Obs/sum(Obs))\n \n col1 <- brewer.pal(n = 12, name = \"Paired\")[8]\n col2 <- brewer.pal(n = 12, name = \"Paired\")[2]\n \n par(mar=c(3.5,4.5,2,0))\n \n my.lwd <- 3.75\n \n if (max(pmf.Obs[,2])>=max(pmf.Exp[,2])){\n plot(pmf.Obs[,1],pmf.Obs[,2],type=\"n\",col=col1,xlim=c(0.75,9.25), xlab=\"\",ylab=\"Proportion\", xaxt=\"n\", main=\"Proportion of First Digits\")\n axis(1, at=seq(1,9), labels=c(\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"))\n mtext(\"First Digit\",1,line=2.5)\n for (i in 1:nrow(pmf.Obs)){\n lines(c(pmf.Obs[i,1],pmf.Obs[i,1]),c(0,pmf.Obs[i,2]),col=col1,lwd=my.lwd)\n }\n for (i in 1:nrow(pmf.Exp)){\n lines(c(pmf.Exp[i,1],pmf.Exp[i,1]),c(0,pmf.Exp[i,2]),col=col2,lwd=my.lwd)\n legend(\"topright\", inset=.02,\n c(\"Observed Proportion\",\"Benford's Law\"), fill=c(col1,col2), horiz=F)\n }\n }\n \n if (max(pmf.Obs[,2])=max(pmf.Exp[,2])){\n plot(pmf.Obs[,1],pmf.Obs[,2],type=\"n\",col=col1,xlim=c(0.75,9.25), xlab=\"\",ylab=\"Proportion\", xaxt=\"n\", main=\"Proportion of First Digits\", \n ylim=c(0.06,\n max(1.05*max(pmf.Obs[,2]),1.05*max(pmf.Exp[,2])))\n )\n axis(1, at=seq(1,9), labels=c(\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"))\n mtext(\"First Digit\",1,line=2.5)\n for (i in 1:nrow(pmf.Obs)){\n lines(c(pmf.Obs[i,1],pmf.Obs[i,1]),c(0,pmf.Obs[i,2]),col=col1,lwd=my.lwd)\n }\n for (i in 1:nrow(pmf.Exp)){\n lines(c(pmf.Exp[i,1],pmf.Exp[i,1]),c(0,pmf.Exp[i,2]),col=col2,lwd=my.lwd)\n legend(\"topright\", inset=.02,\n c(\"Observed Proportion\",\"Generalized Benford's Law\"), fill=c(col1,col2), horiz=F)\n }\n }\n \n if (max(pmf.Obs[,2]) 0 && m > 0 ) {\n count <- (m-1) %/% n\n n * count * (count+1) / 2\n } else\n \"INVALID\"\n}", "meta": {"hexsha": "345a016565fed8d5b60840adbd0372c36191be25", "size": 132, "ext": "r", "lang": "R", "max_stars_repo_path": "8_kyu/Sum_of_Multiples.r", "max_stars_repo_name": "UlrichBerntien/Codewars-Katas", "max_stars_repo_head_hexsha": "bbd025e67aa352d313564d3862db19fffa39f552", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "8_kyu/Sum_of_Multiples.r", "max_issues_repo_name": "UlrichBerntien/Codewars-Katas", "max_issues_repo_head_hexsha": "bbd025e67aa352d313564d3862db19fffa39f552", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "8_kyu/Sum_of_Multiples.r", "max_forks_repo_name": "UlrichBerntien/Codewars-Katas", "max_forks_repo_head_hexsha": "bbd025e67aa352d313564d3862db19fffa39f552", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8571428571, "max_line_length": 29, "alphanum_fraction": 0.4166666667, "num_tokens": 58, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6393674825773931}} {"text": "# ......................................................................................\n# .........................Cvičení 4 - Spojitá náhodná veličina.........................\n# ..................Martina Litschmannová, Adéla Vrtková, Michal Béreš..................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# **Obsah tohoto skriptu je pouze jako doplňující ilustrace k cvičení, není nutno znát\n# ke zkoušce. Důležité je to umět spočítat ručně.**\n# * Numerická integrace v Rku ####\n# Rkovská funkce **integrate**\n# integrate(f, a, b) = $\\int_{a}^{b}f(x)dx$\n# - **f** je Rková funkce (námi definovaná) která má jeden vstupní argument - vektor\n# hodnot ve kterém má vrátit své hodnoty\n# - **a** dolní integrační mez\n# - **b** horní integrační mez\n\n\nf = function(x){return(x*x)} # x^2\na = -1\nb = 2\nintegrate(f, a, b)\n\n# Příklady ####\n# * Příklad 1. ####\n# Náhodná veličina X má distribuční funkci\n# $F(x)=\\begin{cases}\n# 0 & x \\leq 0 \\\\\n# cx^2 & 0 < x \\leq 1 \\\\\n# 1 & 1 < x\n# \\end{cases}$\n# Jaké hodnoty může nabývat konstanta c?\n\n\n# derovací F(x) získáme hustotu pravd. f(x)\n# příslušná hustota pravděpodobnosti na intrvalu <0,1>\nf = function(x){return(2*x)} # f(x) = 2x\na = 0\nb = 1\nintegrate(f, a, b)$value\n\n# c = 1, proto distribuční funkce vypadá takto:\nF.dist = function(x){\n res = x*x # x^2\n res[x<=0] = 0 # 0 pro x<=0\n res[x>1] = 1 # 1 pro x>1\n return(res)\n}\n\nx = seq(from = -1, to = 2, by = 0.01) # body na ose x\nFX = F.dist(x) # hodnoty F(x)\nplot(x, FX, type = 'l') # vykreslit jako čáru\n\n# * Příklad 2. ####\n# Rozdělení náhodné veličiny X je dáno hustotou\n# $f(x)=\\begin{cases}\n# 2x+2 & x \\in <-1;0> \\\\\n# 0 & x \\notin <-1;0>\n# \\end{cases}$\n# Určete:\n# ** 2. a) ####\n# $F(x)$,\n\n\nf.dens = function(x){\n res = 2*x + 2 \n # pozor na x<-1 protože '<-' je v rku přiřazení\n res[x < -1] = 0 # 0 pro x<=0\n res[x > 0] = 0 # 1 pro x>1\n return(res)\n}\n\nx = seq(from = -2, to = 1, by = 0.01) # body na ose x\nfx = f.dens(x) # hodnoty f(x)\nplot(x, fx, cex=0.2) # vykreslit tečky (cex je velikost)\n\nF.dist = function(x){\n res = x*x+2*x+1 # x^2+2x+1\n res[x < -1] = 0 # 0 pro x<=0\n res[x > 0] = 1 # 1 pro x>1\n return(res)\n}\n\nx = seq(from = -2, to = 1, by = 0.01) # body na ose x\nFX = F.dist(x) # hodnoty f(x)\nplot(x, FX, type='l') # vykreslit tečky (cex je velikost)\n\n# ** 2. b) ####\n# P(−2 ≤ X ≤ −0.5), P(−2 ≤ X ≤ −1), P(X > 0.5), P(X = 0.3)\n\n\n# P(−2 ≤ X ≤ −0.5)\nintegrate(f.dens, -2, -0.5)$value\nintegrate(f.dens, -1, -0.5)$value\n\n# P(−2 ≤ X ≤ −1)\nintegrate(f.dens, -2, -1)$value\n\n# P(X > 0.5)\nintegrate(f.dens, 0.5, 1e16)$value # tohle nebude vždy fungovat\n\n# P(X = 0.3)\nintegrate(f.dens, 0.3, 0.3)$value\n# je jasné že tato pravděpodobnost je 0\n# odpovídá integrálu s a=b tedy s nulovou velikostí na ose x\n\n# ** 2. c) ####\n# střední hodnotu, rozptyl a směrodatnou odchylku náhodné veličiny X.\n\n\n# E(X)\nx_fx = function(x){\n fx = f.dens(x)\n return(x*fx)\n} \n# integrujeme jen tam kde víme, že je f(x) nenulová\nE_X = integrate(x_fx, -1, 0)$value\nE_X\n-1/3\n\n# E(X^2)\nxx_fx = function(x){\n fx = f.dens(x) \n return(x*x*fx)\n} \n# integrujeme jen tam kde víme, že je f(x) nenulová\nE_XX = integrate(xx_fx, -1, 0)$value\nE_XX\n1/6\n\n# D(X)\nD_X = E_XX - E_X^2\nD_X\n1/18\n\n# sigma(x)\nstd_X = sqrt(D_X)\nstd_X\nsqrt(2)/6\n\n# ** 2. d) ####\n# modus $\\hat{x}$\n\n\n# modus = 0 \n\n# ** 2. e) ####\n# medián $x_{0,5}$\n\n\nx = seq(from = -2, to = 1, by = 0.001) # body na ose x\nFX = F.dist(x)\nplot(x, FX, type='l')\nlines(c(-2, 1),c(0.5, 0.5))\n\nx[FX >= 0.5][1] # první prvek z x pro který F(x)>=0.5\n(-2+sqrt(2))/2\n\n# * Příklad 3. ####\n# Náhodná veličina Y je definována jako: Y = 3X+1, kde X je náhodná veličina z\n# předcházejícího\n# příkladu. Určete:\n# ** 3. a) ####\n# $F_Y(y)$\n\n\nFY.dist = function(y){\n # spočteno ze vztahu FY(y) = P(Y < y) = P(3X + 1 < y) = ...\n x = (y-1)/3 \n FY = F.dist(x)\n return(FY)\n}\ny = seq(from = -3, to = 2, by = 0.001) # body na ose x\nFY = FY.dist(y)\nplot(y, FY, type='l')\n\n# ** 3. b) ####\n# $f_Y(y)$\n\n\n# derivace F_Y\nfY.dens = function(y){\n res = 2/9*(y + 2) \n res[y < -2] = 0 # 0 pro x<-2\n res[y > 1] = 0 # 1 pro x>1\n return(res)\n}\nintegrate(fY.dens,-2,1)$value # kontrola celkového integrálu\ny = seq(from = -3, to = 2, by = 0.001) # body na ose x\nfY = fY.dens(y)\nplot(y, fY, cex=0.2)\n\n# ** 3. c) ####\n# E(Y), D(Y), σ(Y)\n\n\n# E(Y)\ny_fy = function(y){\n fy = fY.dens(y)\n return(y*fy)\n} \n# integrujeme jen tam kde víme, že je f(y) nenulová\nE_Y = integrate(y_fy, -2, 1)$value\nE_Y\n0\n\n# alternativně\nE_Y = 3*E_X + 1\nE_Y\n\n# E(Y^2)\nyy_fy = function(y){\n fy = fY.dens(y)\n return(y*y*fy)\n} \n# integrujeme jen tam kde víme, že je f(y) nenulová\nE_YY = integrate(yy_fy, -2, 1)$value\nE_YY\n1/2\n\n# D(Y)\nD_Y = E_YY - E_Y^2\nD_Y\n1/2\n\n# alternativně\nD_Y = 3^2*D_X\nD_Y\n\n# sigma(Y)\nsqrt(D_Y)\nsqrt(2)/2\n\n# * Příklad 4. (není ze sbírky) ####\n# Spočtěte $\\omega$ takové, aby náhodná veličina X s hustotou pravděpodobnosti:\n# $f(x)=\\begin{cases}\n# 0 & x < 0 \\\\\n# 3e^{-3x} & x \\geq 0\n# \\end{cases}$ \n# byla s pravděpodobností 0.3 větší než $\\omega$\n\n\nF.dist = function(x){\n res = 1 - exp(-3*x)\n res[x < 0] = 0 # 0 pro x<=0\n return(res)\n}\n\nx = seq(from = -1, to = 3, by = 0.001) # body na ose x\nFX = F.dist(x)\nplot(x, FX, type='l')\nlines(c(-1, 3),c(0.7, 0.7))\n\nx[FX >= 0.7][1]\n\n-1/3*log(0.3)\n\n\n\n", "meta": {"hexsha": "81c45e4b2d2910065ff677ba01c39064915c7a06", "size": 5535, "ext": "r", "lang": "R", "max_stars_repo_path": "CV4/cv4_SNV.r", "max_stars_repo_name": "Atheloses/VSB-S8-PS", "max_stars_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CV4/cv4_SNV.r", "max_issues_repo_name": "Atheloses/VSB-S8-PS", "max_issues_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CV4/cv4_SNV.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": 21.1259541985, "max_line_length": 88, "alphanum_fraction": 0.5443541102, "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.639237026325226}} {"text": "# Figure to simulate the growth rate of productivity\n\n# Fixed parameters\ntheta <- .01\nlambda <- 1\ngR <- .02\nphi <- 0\n\n# Initialize dynamic process\nRcurr <- 10 # this stays the same for both\nAbase <- 2 # baseline scenario\nAalt <- 10 # alternative scenario\n\ndfbase = NULL # initialize a dataframe\ndfalt = NULL # initialize a dataframe\nname = \"A\" # name of base case is \"A\"\nnamealt = \"B\" # name of alt case is \"B\"\n\n# This will simulate the process for gA and A period by period\nfor (t in 1:250) # do for this many periods\n{\n # Base case\n gA <- theta*(Rcurr^lambda)/(Abase^(1-phi)) # calculate growth rate of A given current A and R\n dfbase = rbind(dfbase, data.frame(t,Abase,gA,name)) # add this new row to base dataframe\n Abase <- (1+gA)*(Abase) # Update the value of A\n \n # Alternative case\n gA <- theta*(Rcurr^lambda)/(Aalt^(1-phi)) # calculate growth rate of A given current A and R\n dfalt = rbind(dfalt, data.frame(t,Aalt,gA,namealt)) # add this new row to alt dataframe\n Aalt <- (1+gA)*(Aalt) # Update the value of A\n \n # Update the value of R for both cases\n Rcurr <- (1+gR)*Rcurr\n}\n\ncolnames(dfalt) <- c(\"t\",\"Abase\",\"gA\",\"name\") # rename cols of alt DF to match base DF\ndfgraph = rbind(dfbase,dfalt) # bind these two for graphing\ndfgraph$ratio <- dfgraph$gA/theta # solve for ratio of R/A\n\n# Create animated figure\nfig <- plot_ly(dfgraph,\n x = ~ratio, \n y = ~gA, \n color = ~name,\n frame = ~t, \n text = ~t,\n hoverinfo = \"text\",\n type = 'scatter',\n mode = 'markers',\n marker = list(size = 15)\n ) %>% animation_opts(frame=0, transition=0)\nfig <- fig %>% animation_slider(\n hide = T\n)\nfig <- fig %>% animation_button(\n x = 1, xanchor = \"right\", y = 0.4, yanchor = \"bottom\"\n)\nfig <- layout(fig, title = list(text = 'Dynamics of productivity growth', x=0),\n xaxis = list(title = 'Ratio of R/A'),\n yaxis = list (title = 'Growth rate',range=c(0,.06))\n)\n\napi_create(fig, filename = \"me-gA-dynamics\")\n", "meta": {"hexsha": "ab4392c15bfdca32ea448057767d54f1384011ad", "size": 1965, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_ME_gA.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_Sim_gA.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_Sim_gA.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 30.703125, "max_line_length": 95, "alphanum_fraction": 0.6442748092, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6391985026336117}} {"text": " ZGGSVD Example Program Results\n\n Number of infinite generalized singular values (K)\n 2\n Number of finite generalized singular values (L)\n 2\n Numerical rank of (A**H B**H)**H (K+L)\n 4\n\n Finite generalized singular values\n 2.0720E+00 1.1058E+00\n\n Unitary matrix U\n 1 2\n 1 ( -1.3038E-02, -3.2595E-01) ( -1.4039E-01, -2.6167E-01)\n 2 ( 4.2764E-01, -6.2582E-01) ( 8.6298E-02, -3.8174E-02)\n 3 ( -3.2595E-01, 1.6428E-01) ( 3.8163E-01, -1.8219E-01)\n 4 ( 1.5906E-01, -5.2151E-03) ( -2.8207E-01, 1.9732E-01)\n 5 ( -1.7210E-01, -1.3038E-02) ( -5.0942E-01, -5.0319E-01)\n 6 ( -2.6336E-01, -2.4772E-01) ( -1.0861E-01, 2.8474E-01)\n \n 3 4\n 1 ( 2.5177E-01, -7.9789E-01) ( -5.0956E-02, -2.1750E-01)\n 2 ( -3.2188E-01, 1.6112E-01) ( 1.1979E-01, 1.6319E-01)\n 3 ( 1.3231E-01, -1.4565E-02) ( -5.0671E-01, 1.8615E-01)\n 4 ( 2.1598E-01, 1.8813E-01) ( -4.0163E-01, 2.6787E-01)\n 5 ( 3.6488E-02, 2.0316E-01) ( 1.9271E-01, 1.5574E-01)\n 6 ( 1.0906E-01, -1.2712E-01) ( -8.8159E-02, 5.6169E-01)\n \n 5 6\n 1 ( -4.5947E-02, 1.4052E-04) ( -5.2773E-02, -2.2492E-01)\n 2 ( -8.0311E-02, -4.3605E-01) ( -3.8117E-02, -2.1907E-01)\n 3 ( 5.9714E-02, -5.8974E-01) ( -1.3850E-01, -9.0941E-02)\n 4 ( -4.6443E-02, 3.0864E-01) ( -3.7354E-01, -5.5148E-01)\n 5 ( 5.7843E-01, -1.2439E-01) ( -1.8815E-02, -5.5686E-02)\n 6 ( 1.5763E-02, 4.7130E-02) ( 6.5007E-01, 4.9173E-03)\n\n Unitary matrix V\n 1 2\n 1 ( 9.8930E-01, 1.9041E-19) ( -1.1461E-01, 9.0250E-02)\n 2 ( -1.1461E-01, -9.0250E-02) ( -9.8930E-01, 1.9041E-19)\n\n Unitary matrix Q\n 1 2\n 1 ( 7.0711E-01, 0.0000E+00) ( 0.0000E+00, 0.0000E+00)\n 2 ( 0.0000E+00, 0.0000E+00) ( 7.0711E-01, 0.0000E+00)\n 3 ( 7.0711E-01, 0.0000E+00) ( 0.0000E+00, 0.0000E+00)\n 4 ( 0.0000E+00, 0.0000E+00) ( 7.0711E-01, 0.0000E+00)\n \n 3 4\n 1 ( 6.9954E-01, 4.7274E-19) ( 8.1044E-02, -6.3817E-02)\n 2 ( -8.1044E-02, -6.3817E-02) ( 6.9954E-01, -4.7274E-19)\n 3 ( -6.9954E-01, -4.7274E-19) ( -8.1044E-02, 6.3817E-02)\n 4 ( 8.1044E-02, 6.3817E-02) ( -6.9954E-01, 4.7274E-19)\n\n Nonsingular upper triangular matrix R\n 1 2\n 1 ( -2.7118E+00, 0.0000E+00) ( -1.4390E+00, -1.0315E+00)\n 2 ( -1.8583E+00, 0.0000E+00)\n 3\n 4\n \n 3 4\n 1 ( -7.6930E-02, 1.3613E+00) ( -2.8137E-01, -3.2425E-02)\n 2 ( -1.0760E+00, 3.1016E-02) ( 1.3292E+00, 3.6772E-01)\n 3 ( 3.2537E+00, 0.0000E+00) ( -6.3858E-17, 6.3858E-17)\n 4 ( -2.1084E+00, 0.0000E+00)\n\n Estimate of reciprocal condition number for R\n 1.3E-01\n\n Error estimate for the generalized singular values\n 1.7E-15\n", "meta": {"hexsha": "fe58eb2dbed508325231617ce607cdfa2b4515b1", "size": 3026, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/zggsvd_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/zggsvd_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/zggsvd_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 40.8918918919, "max_line_length": 59, "alphanum_fraction": 0.4814937211, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6391984942109251}} {"text": "###PCA3d on a data frame names f_table2, without the two first columns used for grouping\r\n### with one column named \"group\"\r\nfor (i in 1: nrow(f_table)){\r\n f_table$sum[i]=sum(f_table[i,4:14])\r\n}\r\n\r\nrequire(rgl)\r\n#####PCA\r\ncreate.mean.table <- function(data_table,groups,data_cols=1,group_col=ncol(data_table)) { \r\n mean_table = data.frame()\r\n\tsd_table = data.frame()\r\n\tse_table = data.frame()\r\n\tfor (g in groups) {\r\n\t\tdata = data_table[data_table[group_col]==g,]\r\n\t\tmean_table = rbind(mean_table,data.frame(t(colMeans(data[data_cols],na.rm=TRUE))))\r\n\t\tsd_table = rbind(sd_table,data.frame(t(sd(data[data_cols],na.rm=TRUE))))\r\n\t\tse_table = sd_table/sqrt(nrow(data))\r\n\t}\r\n\trownames(mean_table) = groups\r\n\trownames(sd_table) = groups\r\n\t\r\n\terg <- list(mean_table,sd_table,se_table)\r\n\tnames(erg) <- c(\"means\",\"sds\",\"ses\")\r\n\treturn(erg)\r\n}\r\n##\r\n\r\n\r\nh_table<-f_table2[,c(3:(length(f_table2)))]\r\nrownames (h_table) = paste (c(1:length(f_table2[,1])),f_table2[,2])\r\n#h_table<-f_table2[,c(3:13,16:length(f_table2))]\r\ng_table <- na.omit(h_table)\r\n head(g_table)\r\nmydata.pca <- prcomp(g_table, retx= TRUE, center= TRUE, scale.=TRUE)\r\nsd <- mydata.pca$sdev \r\nloadings <- mydata.pca$rotation \r\nrownames(loadings) <- colnames(g_table) \r\nscores <- mydata.pca$x\r\n\r\n\r\n\r\nPCA_res= data.frame(scores)\r\nPCA_res$group = i_table[,2]\r\n\r\n\r\n\r\n\r\nPCA1to3 = data.frame(PCA_res$PC1,PCA_res$PC2,PCA_res$PC3,PCA_res$group)\r\nMean_PCA_3d = create.mean.table(PCA1to3,levels(PCA1to3$PCA_res.group),1:3)\r\n\r\nscalingfact=15\r\n###\r\n### Plot variables plot in 3D (arrow plot)\r\n\r\nplot3d(loadings[,1]*scalingfact,loadings[,3]*scalingfact,loadings[,2]*scalingfact,\r\n type = \"n\",box =FALSE,axes=TRUE,xlab=\"PC1\",ylab=\"PC3\",zlab=\"PC2\")\r\n\r\nfor (j in 1:nrow(loadings)){\r\nA=matrix (c(0,0,0,loadings[j,1]*scalingfact,loadings[j,3]*scalingfact,loadings[j,2]*scalingfact),2,3,byrow =TRUE)\r\nsegments3d(A, col=j)\r\n\r\ntext3d(loadings[j,1]*scalingfact*1.1,loadings[j,3]*scalingfact*1.1,loadings[j,2]*scalingfact*1.1, \r\n rownames(loadings)[j], col=j+1, cex=0.7, add=TRUE)\r\n}\r\n\r\n\r\n###\r\n### Plot data, mean +- ses on the 3 axes, and ellipse of X=20% confidence interval\r\n## beware: no legend\r\nLEV=0.7\r\nplot3d(loadings[,1]*scalingfact,loadings[,3]*scalingfact,loadings[,2]*scalingfact,\r\n type = \"n\",box =FALSE,axes=TRUE,xlab=\"PC1\",ylab=\"PC3\",zlab=\"PC2\")\r\n\r\n for (i in 1:length(levels(PCA_res$group))){\r\n X = subset(PCA_res,PCA_res$group == levels(PCA_res$group)[i])\r\n points= data.frame(X$PC1, X$PC3,X$PC2)\r\n plot3d(points, col=i,type= \"p\",add=TRUE)\r\n #plot3d(X$PC1, X$PC3,X$PC2, col=i,type= \"p\",add=TRUE)\r\n #Ell= sd(points)/sqrt(nrow(points))\r\n plot3d(ellipse3d(cor(points), centre = mean(points), level=LEV), col=i, alpha=0.3 , add=TRUE)\r\n \r\n plot3d(ellipse3d(cov(points), centre = mean(points), level=LEV), col=i+2, alpha=0.3 , add=TRUE)\r\n \r\nx=Mean_PCA_3d$means$PCA_res.PC1[i]\r\ny=Mean_PCA_3d$means$PCA_res.PC3[i]\r\nz=Mean_PCA_3d$means$PCA_res.PC2[i]\r\nx2=Mean_PCA_3d$ses$PCA_res.PC1[i]\r\ny2=Mean_PCA_3d$ses$PCA_res.PC3[i]\r\nz2 =Mean_PCA_3d$ses$PCA_res.PC3[i] \r\n A= matrix (c(x-x2,y,z,x+x2,y,z,x,y-y2,z,x,y+y2,z,x,y, z-z2,x,y,z+z2),6,3, byrow =TRUE)\r\n segments3d(A, col=i)\r\n } \r\n\r\n # text3d(max(points[1]),max(points[3]),max(points[2]), \r\n # levels(PCA_res$group)[i], col=i, cex=0.7, add=TRUE)\r\n \r\n\r\n#################\r\n###################\r\n#################\r\n########## code to move the visualisation\r\n rgl.viewpoint(theta = 0, phi = 0, fov = 45, zoom = 0.8)\r\n\r\n########## code for making a snapshot\r\n\r\n\r\n######## multiple snapshot to transform into a video\r\nfor (i in 0:180) {\r\n rgl.viewpoint(theta = -180+2*i, phi =-90+(i ), fov = 45, zoom = 1)\r\n filename <- paste(\"pic1_\",1000+i,\".png\",sep=\"\") \r\n \r\n #rgl.snapshot(filename, fmt=\"png\")\r\n}\r\nfor (k in 0:90) {\r\n \r\n rgl.viewpoint(theta = 0, phi =k, fov = 45, zoom = 1)\r\n filename <- paste(\"pic2_\",1000+k,\".png\",sep=\"\") \r\n #rgl.snapshot(filename, fmt=\"png\")\r\n }\r\n\r\n\r\n\r\n# F=c()\r\n# for (g in 1: nrow(loadings)) F=c(F,0)\r\n# \r\n# loadings2= rbind(loadings,F)", "meta": {"hexsha": "fbc85d170649662f7c29129be312163b01ced707", "size": 4003, "ext": "r", "lang": "R", "max_stars_repo_path": "CeTrAn/other_codes/3Dplots_for_PCA.r", "max_stars_repo_name": "brembslab/CeTrAn", "max_stars_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-02-26T12:51:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T08:36:32.000Z", "max_issues_repo_path": "CeTrAn/other_codes/3Dplots_for_PCA.r", "max_issues_repo_name": "brembslab/CeTrAn", "max_issues_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:08:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-18T13:31:53.000Z", "max_forks_repo_path": "CeTrAn/other_codes/3Dplots_for_PCA.r", "max_forks_repo_name": "brembslab/CeTrAn", "max_forks_repo_head_hexsha": "830a3072acb735ea43029310650f03951783813a", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2015-01-09T13:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-21T12:55:17.000Z", "avg_line_length": 31.7698412698, "max_line_length": 114, "alphanum_fraction": 0.6402697977, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6390875012556638}} {"text": "#' Jacobian transformation adjustment\n#'\n#' compute the Jacobian adjustment for transformations as done in the X-13ARIMA-SEATS program\n#'\n#' @param Y numeric vector, original time series.\n#' @param Nspobs Integer scalar, Length of \\code{Y}.\n#' @param Nintvl Integer scalar, Number of differences in model used. Default is 2.\n#' @param Adj numeric vector, prior adjustment factor time series. Default is NULL, which indicates there is no prior adjustment.\n#' @param Logit logical scalar, if TRUE the logit transformation is used. Default is FALSE.\n#' @param Trans logical scalar, if TRUE a Box-Cox transform is used. Default is TRUE\n#' @param Lam numeric scalar, Box-Cox transformation parameter. Default is 0 (Log transform).\n#' @return Jacobean adjustment to the likelihood of estimated models to allow AIC and other likelihood statistics to be compared for different transformations.\n#' @examples\n#' Nspobs <- length(ic_obs)\n#' ic_jacadj_log <- jacobian_trans_adj(ic_obs, Nspobs, 2, Trans = TRUE, Lam = 0.0) \n#' @import stats\n#' @export\njacobian_trans_adj <- function(Y, Nspobs, Nintvl = 2, Adj = NULL, Logit = FALSE, Trans = TRUE, Lam=0.0) {\n # Author: Brian C. Monsell (OEUS), Version 2.5, 3/2/2022\n this_index <- seq(Nintvl+1, Nspobs)\n if (is.null(Adj)) {\n Adj <- rep(1.0, Nspobs)\n } else {\n nadj <- length(Adj)\n if (nadj != Nspobs) {\n stop(\"series and prior adjustments not the same length\")\n }\n }\n \n yi <- Y[this_index]\n jaci <- Adj[this_index]\n \n \n# logit adjustment : jaci=jaci/(jaci*Y(i)-Y(i)**2)\n if (Logit) {\n jacadj <- sum(log(jaci/(yi - yi*yi)))\n } else {\n# transformation adjustment : jaci=(abs(yi)**(Lam-ONE))/jaci\n if (Trans) {\n jacadj <- sum(log((abs(yi)^(Lam-1))/jaci))\n } else {\n jacadj <- 0\n }\n }\n \n return(jacadj)\n}", "meta": {"hexsha": "d685ca5d2a80b10313c5d4a76286b125307b9923", "size": 1849, "ext": "r", "lang": "R", "max_stars_repo_path": "R/jacobian_trans_adj.r", "max_stars_repo_name": "bcmonsell/airutilities", "max_stars_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_stars_repo_licenses": ["MIT"], "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/jacobian_trans_adj.r", "max_issues_repo_name": "bcmonsell/airutilities", "max_issues_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_issues_repo_licenses": ["MIT"], "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/jacobian_trans_adj.r", "max_forks_repo_name": "bcmonsell/airutilities", "max_forks_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_forks_repo_licenses": ["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.3404255319, "max_line_length": 159, "alphanum_fraction": 0.6587344511, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6390603369589953}} {"text": "# computing likelihood intervals at certain alpha levels\nli<- function(th,like,alpha=0.15){\n that <- mean(th[like==max(like)])\n lowth <- th[th < that] \n lowlik <- like[th < that] \n if (length(lowth)<2) {lowval <- min(th) }\n if (length(lowth)>1)\n { lowval <- approx(lowlik,lowth,xout=alpha)$y}\n\n upth <- th[th > that]\n if (length(upth)<2 ) {return(c(lowval,max(th))) }\n if (length(upth)> 1){\n uplik <- like[th > that] \n upval <- approx(uplik,upth,xout=alpha)$y\n return(c(lowval,upval))\n }\n }\n", "meta": {"hexsha": "eaf3542081edd6837fd1077ff2ca7614d293c714", "size": 521, "ext": "r", "lang": "R", "max_stars_repo_path": "R/LKPACK/li.r", "max_stars_repo_name": "covuworie/in-all-likelihood", "max_stars_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_stars_repo_licenses": ["MIT"], "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/LKPACK/li.r", "max_issues_repo_name": "covuworie/in-all-likelihood", "max_issues_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:53:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:16:17.000Z", "max_forks_repo_path": "R/LKPACK/li.r", "max_forks_repo_name": "covuworie/in-all-likelihood", "max_forks_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T10:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T10:24:59.000Z", "avg_line_length": 28.9444444444, "max_line_length": 56, "alphanum_fraction": 0.6007677543, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6390016713957701}} {"text": "#Find factors\r\n\r\nprint_factors = function(n) {\r\nprint(paste(\"The factors of\",n,\"are:\"))\r\nfor(i in 1:n) {\r\nif((n %% i) == 0) {\r\nprint(i)\r\n}\r\n}\r\n}\r\nprint_factors(4)\r\nprint_factors(7)\r\nprint_factors(12)", "meta": {"hexsha": "c9c1d27869c19d25eb612b4b028b129eec15c1bc", "size": 199, "ext": "r", "lang": "R", "max_stars_repo_path": "factors.r", "max_stars_repo_name": "maansisrivastava/Practice-code-R", "max_stars_repo_head_hexsha": "24f1469908195050472831db7b1ebe83744d422c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "factors.r", "max_issues_repo_name": "maansisrivastava/Practice-code-R", "max_issues_repo_head_hexsha": "24f1469908195050472831db7b1ebe83744d422c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factors.r", "max_forks_repo_name": "maansisrivastava/Practice-code-R", "max_forks_repo_head_hexsha": "24f1469908195050472831db7b1ebe83744d422c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3076923077, "max_line_length": 40, "alphanum_fraction": 0.608040201, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.638614517628242}} {"text": "#This script will compute the bulk modulus from a plot of pressure vs volumetric strain.\n#\n#License information:\n#\n#MIT License\n#\n#Copyright (c) 2019 Will Pisani\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nif (Sys.info()['sysname']==\"Linux\"){\n setwd(\"/path/to/directory/on/linux\")\n} else {\n# Paths in Windows in R require \\\\ instead of \\\n setwd(\"C:\\\\path\\\\to\\\\directory\\\\on\\\\Windows\") \n\n}\n\n#Read in csv file\nbkfile <-\"your_file_name_here_BK_RData.csv\"\nbkdat <- read.csv(bkfile)\nbkfilename <- strsplit(bkfile,\"\\\\.\")[[1]]\n\n#create vectors for pressure and volumetric strain\nbkpress <- bkdat[,1] *1.01325*10^5/1000000 # Converting atm to MPa\nbkvolstrain <- bkdat[,2]\nbkendpoint <- length(bkpress)\nbkpress <- bkpress[1:bkendpoint]\nbkvolstrain <- bkvolstrain[1:bkendpoint]\n\n#fit a regular linear model to data, this is for the segmented command\nlin.mod <- lm(bkpress ~ bkvolstrain)\n\n#use segmented package to calculated breakpoint (bk)\nsegmented.mod <- segmented::segmented(lin.mod, seg.Z = ~bkvolstrain, psi=-0.05)\n#Define moving average function\n#mav <- function(x,n=1000){filter(x,rep(1/n,n),sides=2)}\n\n\n#bkdens_ma <- mav(bkdens,1500)\n\n# Get point at bk_value\n# Get slope of first line\nbk_modulus <- summary(segmented.mod)$coefficients[2,1]/1000 # Going from MPa to GPa\nbk_modulus <- abs(round(bk_modulus,2)) # Round to 2 decimal places\nbk_value <- segmented.mod$psi[2]\nbk_value_stderror <- segmented.mod$psi[3]\nbk_y_value <- segmented.mod$coefficients[2]*bk_value+segmented.mod$coefficients[1]\n\n# Save regular plot to pdf\npdf(paste(bkfilename[1],\"pdf\",sep=\".\"))\nplot(bkvolstrain,bkpress,col=\"blue\",xlim=c(0,min(bkvolstrain)),ylim=c(-2000,3500),main = paste(\"Bulk Modulus=\",bk_modulus,\"GPa\"),xlab = 'Volumetric strain',ylab = 'Pressure (MPa)')\n#plot(bktemp,bkdens)\npar(new = TRUE)\nplot(segmented.mod,col=\"red\",xlim=c(0,min(bkvolstrain)),ylim=c(-2000,3500),xlab = '',ylab = '',rug=FALSE)\npar(new = TRUE)\nplot(bk_value,bk_y_value,pch=24,col=\"white\",bg=\"white\",xlim=c(0,min(bkvolstrain)),ylim=c(-2000,3500),xlab = '',ylab = '')\ndev.off()", "meta": {"hexsha": "9b5001ae6b9c828a64b8ddea97dfef9c0c04a88e", "size": 3023, "ext": "r", "lang": "R", "max_stars_repo_path": "R/BKPlot.r", "max_stars_repo_name": "wapisani/PhD", "max_stars_repo_head_hexsha": "9f6ba9bde659e6032cc7a5fa10532e480163e779", "max_stars_repo_licenses": ["MIT"], "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/BKPlot.r", "max_issues_repo_name": "wapisani/PhD", "max_issues_repo_head_hexsha": "9f6ba9bde659e6032cc7a5fa10532e480163e779", "max_issues_repo_licenses": ["MIT"], "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/BKPlot.r", "max_forks_repo_name": "wapisani/PhD", "max_forks_repo_head_hexsha": "9f6ba9bde659e6032cc7a5fa10532e480163e779", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-10-16T13:33:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T13:33:23.000Z", "avg_line_length": 48.7580645161, "max_line_length": 462, "alphanum_fraction": 0.7476017201, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6383313941568197}} {"text": "#' Rotate global coordinates in a data frame to model coordinates.\n#' \n#' This function reads in a data frame that contains\n#' X and Y coordinates and converts those coordinates to a model coordinate system (i.e., zero rotation and X_off = Y_off = 0).\n#' @param df This is the data frame containing the X and Y coordinates\n#' @param X_off This is the global X coordinate offset\n#' @param Y_off This is the global Y coordinate offset\n#' @param ROT This is the rotation angle in units of degrees\n#' @param Xin This is the dataframe column containing the X coordinate location\n#' @param Yin This is the dataframe column containing the Y coordinate location\n#' @export\n#' @examples\n#' obk_demo\n#' # A tibble: 19 x 6\n#' ID LITHO K_cms K X Y\n#' \n#' 1 MW-07 5.88e-04 1.66677165 2980417 1927119\n#' 2 MW-09 SW 2.58e-03 7.31338583 2980038 1927879\n#' 3 MW-10 2.51e-03 7.11496063 2980659 1927796\n#' 4 MW-13 2.22e-03 6.29291339 2980753 1927708\n#' 5 MW-15 GM 2.00e-02 56.69291339 2980915 1927664\n#' 6 MW-16 SW 6.07e-03 17.20629921 2981707 1928835\n#' 7 MW-18 GM 3.91e-03 11.08346457 2981401 1929334\n#' 8 MW-21 GM 9.10e-04 2.57952756 2981287 1928896\n#' 9 MW-25 GM 1.25e-03 3.54330709 2981012 1928750\n#' 10 MW-26 ML/GM 2.55e-03 7.22834646 2981059 1928830\n#' 11 MW-27 GM 1.60e-03 4.53543307 2980973 1929291\n#' 12 MW-29 GM 1.75e-04 0.49606299 2980824 1928950\n#' 13 MW-30 sandstone 6.55e-04 1.85669291 2980486 1929689\n#' 14 MW-31 ML 1.04e-05 0.02948031 2980409 1929362\n#' 15 MW-32 ML 1.03e-02 29.19685039 2979395 1928257\n#' 16 PZ-04 SP/ML 9.41e-06 0.02667402 2980207 1927028\n#' 17 PZ-05 SP/GM 2.80e-04 0.79370079 2981367 1928068\n#' 18 PZ-06 SW 3.06e-04 0.86740157 2981831 1927966\n#' \n#' X_off <- 2970450\n#' Y_off <- 1926010\n#' rot <- -45\n#' obk_demo %>% rot2mod(X_off = X_off, Y_off = Y_off, ROT = -45)\n#' # A tibble: 19 x 8\n#' ID LITHO K_cms K X Y Xout Yout\n#' \n#' 1 MW-07 5.88e-04 1.66677165 2980417 1927119 6263.672 7831.879\n#' 2 MW-09 SW 2.58e-03 7.31338583 2980038 1927879 5458.256 8100.912\n#' 3 MW-10 2.51e-03 7.11496063 2980659 1927796 5955.897 8481.173\n#' 4 MW-13 2.22e-03 6.29291339 2980753 1927708 6085.184 8486.123\n#' 5 MW-15 GM 2.00e-02 56.69291339 2980915 1927664 6230.735 8569.561\n#' 6 MW-16 SW 6.07e-03 17.20629921 2981707 1928835 5962.466 9957.563\n#' 7 MW-18 GM 3.91e-03 11.08346457 2981401 1929334 5393.075 10093.737\n#' 8 MW-21 GM 9.10e-04 2.57952756 2981287 1928896 5621.676 9703.563\n#' 9 MW-25 GM 1.25e-03 3.54330709 2981012 1928750 5530.678 9405.567\n#' 10 MW-26 ML/GM 2.55e-03 7.22834646 2981059 1928830 5507.973 9495.461\n#' 11 MW-27 GM 1.60e-03 4.53543307 2980973 1929291 5120.889 9760.895\n#' 12 MW-29 GM 1.75e-04 0.49606299 2980824 1928950 5256.879 9413.974\n#' 13 MW-30 sandstone 6.55e-04 1.85669291 2980486 1929689 4495.396 9698.061\n#' 14 MW-31 ML 1.04e-05 0.02948031 2980409 1929362 4671.784 9412.086\n#' 15 MW-32 ML 1.03e-02 29.19685039 2979395 1928257 4736.611 7913.883\n#' 16 PZ-04 SP/ML 9.41e-06 0.02667402 2980207 1927028 6179.576 7619.259\n#' 17 PZ-05 SP/GM 2.80e-04 0.79370079 2981367 1928068 6264.471 9174.908\n#' 18 PZ-06 SW 3.06e-04 0.86740157 2981831 1927966 6664.969 9430.704\n\nrot2mod <- function(df, \n X_off = 0, \n Y_off = 0, \n ROT = 0, \n Xin = X, \n Yin = Y){\n \n Xin <- enquo(Xin)\n Yin <- enquo(Yin)\n RAD <- -ROT * pi / 180\n mutate(df, \n Xout = ((!!Xin) - X_off) * cos(RAD) - ((!!Yin) - Y_off) * sin(RAD), \n Yout = ((!!Xin) - X_off) * sin(RAD) + ((!!Yin) - Y_off) * cos(RAD)\n ) \n }\n", "meta": {"hexsha": "80c484ddff93cdc01dfa5531634b9796515105ee", "size": 4151, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rot2mod.r", "max_stars_repo_name": "dpphat/MFtools", "max_stars_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-12-23T21:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T14:52:25.000Z", "max_issues_repo_path": "R/rot2mod.r", "max_issues_repo_name": "dpphat/MFtools", "max_issues_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_issues_repo_licenses": ["MIT"], "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/rot2mod.r", "max_forks_repo_name": "dpphat/MFtools", "max_forks_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-21T18:07:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-21T18:07:26.000Z", "avg_line_length": 53.9090909091, "max_line_length": 127, "alphanum_fraction": 0.588051072, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6380250117638212}} {"text": "LISP Interpreter Run\n\n[[[[[\n\n Proof that the halting problem is unsolvable by using\n it to construct a LISP expression that halts iff it doesn't.\n\n]]]]]\n\ndefine (turing x) \n[Insert supposed halting algorithm here.]\nlet (halts? S-exp) false [<=============]\n[Form ('x)]\nlet y [be] cons \"' cons x nil [in]\n[Form (('x)('x))]\nlet z [be] display cons y cons y nil [in]\n[If (('x)('x)) has a value, then loop forever, otherwise halt]\nif (halts? z) [then] eval z [loop forever]\n [else] nil [halt]\n\ndefine turing\nvalue (lambda (x) ((' (lambda (halts?) ((' (lambda (y) (\n (' (lambda (z) (if (halts? z) (eval z) nil))) (dis\n play (cons y (cons y nil)))))) (cons ' (cons x nil\n ))))) (' (lambda (S-exp) false))))\n\n\n[\n (turing turing) decides whether it itself has a value, \n then does the opposite!\n\n Here we suppose it doesn't have a value, \n so it turns out that it does:\n]\n\n(turing turing)\n\nexpression (turing turing)\ndisplay ((' (lambda (x) ((' (lambda (halts?) ((' (lambda (\n y) ((' (lambda (z) (if (halts? z) (eval z) nil))) \n (display (cons y (cons y nil)))))) (cons ' (cons x\n nil))))) (' (lambda (S-exp) false))))) (' (lambda\n (x) ((' (lambda (halts?) ((' (lambda (y) ((' (lam\n bda (z) (if (halts? z) (eval z) nil))) (display (c\n ons y (cons y nil)))))) (cons ' (cons x nil))))) (\n ' (lambda (S-exp) false))))))\nvalue ()\n\n\ndefine (turing x) \n[Insert supposed halting algorithm here.]\nlet (halts? S-exp) true [<==============]\n[Form ('x)]\nlet y [be] cons \"' cons x nil [in]\n[Form (('x)('x))]\nlet z [be] [[[[display]]]] cons y cons y nil [in]\n[If (('x)('x)) has a value, then loop forever, otherwise halt]\nif (halts? z) [then] eval z [loop forever]\n [else] nil [halt]\n\ndefine turing\nvalue (lambda (x) ((' (lambda (halts?) ((' (lambda (y) (\n (' (lambda (z) (if (halts? z) (eval z) nil))) (con\n s y (cons y nil))))) (cons ' (cons x nil))))) (' (\n lambda (S-exp) true))))\n\n\n[\n And here we suppose it does have a value, \n so it turns out that it doesn't.\n\n It loops forever evaluating itself again and again!\n]\n\n(turing turing) \n\nexpression (turing turing)\nStorage overflow!\n", "meta": {"hexsha": "e816781d8040189147764df54a92313f9a0f54b8", "size": 2271, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/turing.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/turing.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/turing.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 28.746835443, "max_line_length": 62, "alphanum_fraction": 0.5420519595, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6379307477010024}} {"text": "# ************************************************\n### simon munzert\n### time series\n# ************************************************\n\nsource(\"packages.r\")\nsource(\"functions.r\")\n\n\n## CRAN Task View on time series analysis\nbrowseURL(\"https://cran.r-project.org/web/views/TimeSeries.html\")\n\n\n# ************************************************\n# Working with times using the lubridate package -\n\nlibrary(lubridate)\n\n# create a year-month-day variable\ndates_char <- c(\"2017-09-01\", \"2017-08-31\", \"2017-08-30\")\n#dates_char <- c(\"20170901\", \"20170831\", \"20170830\")\n#dates_char <- c(\"2017/09/01\", \"2017/08/31\", \"2017/08/30\")\nclass(dates_char)\nplot(dates_char)\ndates <- ymd(dates_char) # ymd() function to deal with year-month-day input\ndates\nplot(dates)\n\n# other formats work, too\nmdy(\"09-24-2017\")\ndmy(\"24.09.2017\")\n\n# there are many other things you can do with the package, for instance\n # work with time zones\n # compute time intervals\n # do arithmetic with date times (durations, periods)\n\n# check out the following vignette for more info!\nbrowseURL(\"https://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html\")\n\n\n\n# ************************************************\n# Managing time series data with the xts package -\n\nlibrary(xts) # also loads zoo package\n\n# import fertility data from Wooldridge\n?fertil3\nnames(fertil3)\nView(fertil3)\ndat <- fertil3\n\n# plot time series\nplot(dat$gfr)\n\n# create xts time series object\ndat_ts <- ts(dat, frequency = 1, start = 1913) # creat time-series object: provide time of the first observation and frequency \ndat_xts <- as.xts(dat_ts)\n\n# dat_xts <- xts(dat, yearmon(dat$year)) # alternative assignment of time scheme with yearmon() function from the zoo package\nplot(dat_xts$gfr)\n\n# create lag variables\ndat$gfr\nlag(dat$gfr, 1)\nlag(dat$gfr, 2)\nlead(dat$gfr, 1)\n\n\n\n# ************************************************\n# Exercise: The Efficient Markets Hypothesis -----\n\ndata(nyse)\n?nyse\n\n# plot time series\nplot(nyse$price, type = \"l\")\nplot(nyse$return, type = \"l\")\n\n# do past returns help explain future returns?\nsummary(lm(return ~ lag(return), data = nyse))\n\n# Augmented Dickey-Fuller test\nplot(nyse$t, nyse$return, type = \"l\")\nadf.test(nyse$return[-1])\n\n# How does the Dickey-Fuller test work?\n # tests the predictive power of an autoregressive process on the integrated time series\n # the null hypothesis for the test is that the time-series has a unit root (i.e. is not stationary).\n # the more negative it is, the stronger the rejection of the hypothesis that there is a unit root at some level of confidence\nx <- rnorm(1000) # no unit-root = stationary\nadf.test(x)\ny <- diffinv(x) # contains a unit-root = non-stationary\nadf.test(y)\n\n# assess autocorrelation\nacf(nyse$return, na.action = na.pass)\nacf(nyse$price, na.action = na.pass, lag.max = 200)\n\n# assess autocorrelation in disturbances using the Durbin-Watson test for autocorrelation\nmodel <- lm(price ~ lag(price), data = nyse)\nsummary(model)\ndwtest(model) # be careful; in LDV models, the DW test statistic uses to underestimate autocorrelation\n\n\n\n# ************************************************\n# Finite distributed lag (FDL) models ------------\n\n# scatterplot\nplot(dat$pe, dat$gfr)\n\n# parallel time series\npar(mfrow = c(2, 1))\nplot(dat_xts$gfr)\nplot(dat_xts$pe)\n\n# OLS\nmodel_out <- lm(gfr ~ pe, data = dat) # static model; only impact propensity assessed\nsummary(model_out)\nmodel_out <- lm(gfr ~ pe + lag(pe, 1) + lag(pe, 2), data = dat) # assess long-run propensity with two lags\nsummary(model_out)\n\n\n\n# ************************************************\n# Lag dependent variable (LDV) models ------------\n\n# check for autocorrelation\nacf(dat$gfr, na.action = na.pass)\ncor(dat$gfr, lag(dat$gfr), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 2), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 3), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 4), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 10), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 11), use = \"pairwise.complete\")\ncor(dat$gfr, lag(dat$gfr, 12), use = \"pairwise.complete\")\n\n# build simple LDV model\nsummary(lm(gfr ~ lag(gfr, 1) + lag(gfr, 2), data = dat))\n\n\n\n# ************************************************\n# Seasonal adjustment ----------------------------\n\nunemp <- read_csv(\"../data/unemployment-ger-monthly.csv\")\nhead(unemp)\nnames(unemp) <- c(\"month\", \"total\")\n\nunemp_ts <- ts(unemp$total, start=c(1948,1), frequency = 12)\nplot(unemp_ts)\nunemp_stl <- stl(unemp_ts, s.window = \"periodic\")\nplot(unemp_stl)\n\nsummary(unemp_stl)\nunemp_stl_df <- unemp_stl$time.series\n\n\n\n# ************************************************\n# Modeling linear trends; de-trending ------------\n\n\nmodel_out <- lm(gfr ~ pe + ww2 + pill + t + I(t^2), data = dat) # static model\nsummary(model_out)\n\n# add linear trend!\n# fertility increasing or decreasing in sample period?\n# add quadratic trend!\n# replicate results via de-trending\n# test for lagged effect of personal exemption\n\n\n\n\n", "meta": {"hexsha": "ccf76c09335118e75932d217a7d857133217aa1f", "size": 4983, "ext": "r", "lang": "R", "max_stars_repo_path": "code/04-time-series.r", "max_stars_repo_name": "simonmunzert/stats-II-hertie-2017", "max_stars_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_stars_repo_licenses": ["MIT"], "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/04-time-series.r", "max_issues_repo_name": "simonmunzert/stats-II-hertie-2017", "max_issues_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_issues_repo_licenses": ["MIT"], "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/04-time-series.r", "max_forks_repo_name": "simonmunzert/stats-II-hertie-2017", "max_forks_repo_head_hexsha": "f577db8b0b5f2599e7896907233ef6871d793253", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-18T08:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-22T08:28:12.000Z", "avg_line_length": 27.8379888268, "max_line_length": 127, "alphanum_fraction": 0.6427854706, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6379307356722748}} {"text": "#' Power calculations in an experiment with group clusters.\n#' \n#' @param unclustered Results from twomeans not adjusting for clusters\n#' @param rho Specifies the intraclass correlation coefficient\n#' @param obsclus Number of observations in each cluster\n#' @param numclus Maximum number of clusters\n#' @return returns an object with all the study parameters\n#' @export\n#' @importFrom magrittr %>%\n#' @examples\n#' twomeans(m1 = 12, m2 = 16, sd = 5) %>% clustered(obsclus = 10, rho = 0.3)\nclustered <- function(unclustered, rho, obsclus = NULL, numclus = NULL) {\n \n if(is.null(numclus)) {\n deff <- 1 + (obsclus - 1) * rho\n n1clus <- unclustered$n1 * deff\n n2clus <- unclustered$n2 * deff\n numclus <- (n1clus + n2clus) / obsclus\n }\n \n if(is.null(obsclus)) {\n tot <- (unclustered$n1 * (1 - rho) + unclustered$n2 * (1 - rho)) /\n (1 - (unclustered$n1 * rho / numclus) -\n (unclustered$n1 * rho / numclus))\n if(tot <= 0) {\n stop(\"Number of clusters is too small.\")\n }\n obsclus <- ceiling(tot / numclus)\n deff <- 1 + (obsclus - 1) * rho\n n1clus <- unclustered$n1 * deff\n n2clus <- unclustered$n2 * deff\n }\n\n # Round everyone\n n1clus <- ceiling(n1clus)\n n2clus <- ceiling(n2clus)\n obsclus <- ceiling(obsclus)\n numclus <- ceiling(numclus)\n\n METHOD = \"Two-sample t-test power calculation\"\n NOTE = paste(\"m1 and m2 are the means of group 1 and 2, respectively.\",\n \"n1 and n2 are the obs. of group 1 and 2, respectively.\",\n sep = \"\\r\\n\")\n\n structure(list(m1 = unclustered$m1,\n m2 = unclustered$m2,\n \"n1 (unadjusted)\" = unclustered$n1,\n \"n2 (unadjusted)\" = unclustered$n2,\n rho = rho,\n \"Average per cluster\" = obsclus,\n \"Minimum number of clusters\" = numclus,\n \"n1 (adjusted)\" = n1clus,\n \"n2 (adjusted)\" = n2clus,\n sig.level = unclustered$sig.level,\n power = unclustered$power,\n alternative = \"two.sided\",\n method = METHOD,\n note = NOTE), \n class = \"power.htest\")\n\n}\n\n.check.clustered <- function(unclustered, rho, obsclus = NULL, numclus = NULL) {\n if(all(is.null(obsclus), is.null(numclus))) {\n stop(\"Either obsclus or numclus must be specified.\")\n }\n}\n\n", "meta": {"hexsha": "d87b286a00cffa180a8d946f23b5b7531a3bb28c", "size": 2679, "ext": "r", "lang": "R", "max_stars_repo_path": "R/clustered.r", "max_stars_repo_name": "vikjam/pwrcalc", "max_stars_repo_head_hexsha": "031b6ef344121cc5b1004524182cb0b770adeab6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-26T14:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T04:38:53.000Z", "max_issues_repo_path": "R/clustered.r", "max_issues_repo_name": "vikjam/pwrcalc", "max_issues_repo_head_hexsha": "031b6ef344121cc5b1004524182cb0b770adeab6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2017-04-27T01:48:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T22:40:33.000Z", "max_forks_repo_path": "R/clustered.r", "max_forks_repo_name": "vikjam/pwrcalc", "max_forks_repo_head_hexsha": "031b6ef344121cc5b1004524182cb0b770adeab6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2017-05-02T16:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T08:41:07.000Z", "avg_line_length": 38.8260869565, "max_line_length": 80, "alphanum_fraction": 0.5139977604, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6378781323016123}} {"text": "#' Weight of Evidence and Information Value in Credit Scoring\n#' \n#' Calculate Information Value and Weight of Evidence for variables in data frame. Information Value is used in credit scoring to compare predictive power among variables.\n#' Weight of Evidence (WoE): \\deqn{WoE = \\ln(\\frac{\\%good_i}{\\%bad_i})}\n#' Information Value:\n#' \\deqn{IV = \\Sigma_{i=1}^{n}(\\ln(\\frac{\\%good_i}{\\%bad_i})*(\\%good_i - \\%bad_i))}\n#' @docType package\n#' @name woe\n#' @import ggplot2 \n#' @importFrom plyr rbind.fill\n#' @importFrom RColorBrewer brewer.pal\n#' @import rpart\n#' @importFrom sqldf sqldf\nNULL", "meta": {"hexsha": "15d17ccc5702304d71a23492a69b518d8bff1726", "size": 587, "ext": "r", "lang": "R", "max_stars_repo_path": "Classification & Clustering/others/woe-package.r", "max_stars_repo_name": "SpekBin/DataScienceR", "max_stars_repo_head_hexsha": "3ae1881663d3e1d429fa3617d51506301b94466c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1932, "max_stars_repo_stars_event_min_datetime": "2015-12-15T13:43:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:22:25.000Z", "max_issues_repo_path": "Classification & Clustering/others/woe-package.r", "max_issues_repo_name": "SpekBin/DataScienceR", "max_issues_repo_head_hexsha": "3ae1881663d3e1d429fa3617d51506301b94466c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-05T12:54:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-05T12:54:12.000Z", "max_forks_repo_path": "Classification & Clustering/others/woe-package.r", "max_forks_repo_name": "SpekBin/DataScienceR", "max_forks_repo_head_hexsha": "3ae1881663d3e1d429fa3617d51506301b94466c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 915, "max_forks_repo_forks_event_min_datetime": "2015-12-19T05:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T08:43:11.000Z", "avg_line_length": 41.9285714286, "max_line_length": 171, "alphanum_fraction": 0.7103918228, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6377662223158255}} {"text": "# Adapted from http://horn.tau.ac.il/software/qc.m\n#\n# David Horn and Assaf Gottlieb. Algorithm for Data Clustering Pattern\n# Recognition Problems Based on Quantum Mechanics (Physical Review Letters\n# 88, 2002).\n\n#' Summarize standard deviation\n#'\n#' Summarize the standard deviation of a data set with multiple columns into a single value. This function accomplishes this task by finding the length of a vector containing the standard deviation of each column. This function may be useful in establishing a \\code{sigma} for qc().\n#'\n#' @param dataset The cleaned input data to be clustered in either data.frame or matrix format. This should contain only numeric data and must not have any factors, strings, NAs, etc. It also should not contain any irrelevant columns such as observation ID or redundant data.\n#'\n#' @return The function returns a double containing the approximated standard deviation of the entire data set.\n#'\n#' @examples \n#' data(iris)\n#' iris_data <- iris[, -5] # Drop the species factor\n#' sigma <- 0.4 * calcSD(iris_data)\n#'\n#' @export\ncalcSD <- function(dataset) {\n sd <- c()\n p <- ncol(dataset)\n\n if(is.null(p)) {\n sd <- sd(dataset)\n } else {\n for(i in seq(1, p)) {\n sd <- c(sd, sd(dataset[, i]))\n }\n sd <- (sum(sd^2)) ^ (1/2)\n }\n\n sd\n}\n\n#' Cluster data\n#'\n#' Cluster data using a non-linear clustering algorithm which finds organic groups of data from eigenfunctions and does not suffer from the curse of dimensionality. The algorithm is approximately O(n^2).\n#'\n#' @param dataset The cleaned input data to be clustered in either data.frame or matrix format. This should contain only numeric data and must not have any factors, strings, NAs, etc. It also should not contain any irrelevant columns such as observation ID or redundant data.\n#' @param sigma A double which controls how closely related data in clusters should be. The smaller the number, more clusters will be created with fewer observations in each. If sigma is too small, observations either will not be clustered or will be in their own individual clusters. If sigma is too large, most -- if not all -- observations will be in the first cluster.\n#' @param steps An integer specifying the number of expectation-maximization steps to take. If faster, less accurate results are required, this may be reduced from the default of 21.\n#' @param min_d_factor A double which controls how close data points must be in order to be considered in the same cluster. Specifically, this value is the number of sigmas of distance to be within said threshold. This value should probably not be changed unless there is a strong reason to do so.\n#' @param n_clusters_max An integer specifying the maximum number of clusters to return. These clusters will always be the most common clusters with the most observations in them.\n#' @param verbose A boolean value which toggles the algorithm's verbosity for details as to how far along it is.\n#'\n#' @return The function returns a vector of the numeric clusters assigned to each row in \\code{dataset}.\n#'\n#' @examples \n#' # Set up parallel execution\n#' library(doMC)\n#' registerDoMC(cores=2) # Replace `2` with the number of cores in your machine\n#'\n#' data(iris)\n#' iris_data <- iris[, -5] # Remove the classification of the iris data set\n#' clusters <- qc(iris_data, 1.0)\n#' secondary_cluster_rows <- which(clusters == 2)\n#' print(iris[secondary_cluster_rows, ])\n#'\n#' @export\nqc <- function(dataset, sigma, steps=21, min_d_factor=2,\n n_clusters_max=1000, verbose=FALSE) {\n\n ETA_DECAY <- 0.9\n\n main <- function(dataset, sigma, steps, min_d_factor,\n n_clusters_max) {\n min_d <- getMinD(sigma, min_d_factor)\n eta <- getEta(sigma)\n q <- getQ(sigma)\n\n qc_log(paste0(\"Starting gradient decent with sigma \", sigma,\n \" and q \", q))\n D <- gradDesc(dataset, dataset, q, steps, eta, steps)\n qc_log(\"Gradient descent done\")\n\n derived_clusters <- assignClusters(D, min_d, n_clusters_max)\n derived_clusters\n }\n\n gradDesc <- function(data_points, D, q, init_steps, eta, steps) {\n\n vecNorm <- function(v) {\n squared_sum <- sum(v^2)\n if(squared_sum == 0) {\n return(v)\n }\n \n # A new variable would be preferred, but for performance purposes,\n # overwrite in order to avoid reallocating a new vector\n v <- v / sqrt(squared_sum)\n v\n }\n\n start <- Sys.time()\n dV <- gradient(data_points, q, D)\n dV <- t(apply(dV, MARGIN=1, FUN=vecNorm))\n qc_log(paste0(\"Gradient descent step: \", (init_steps - steps) + 1,\n \" done\")) \n endtime <- Sys.time()\n qc_log(endtime - start)\n\n # Faster to overwrite and avoid allocating a new matrix\n D <- D - eta * dV\n eta <- eta * ETA_DECAY\n\n if (steps <= 1) {\n D\n }\n else {\n gradDesc(data_points, D, q, init_steps, eta, (steps - 1))\n }\n }\n\n gradient <- function(ri, q, r=ri) {\n n <- nrow(ri)\n p <- ncol(ri)\n\n V <- matrix(0, n, 1)\n dP2 <- matrix(0, n, 1)\n P <- matrix(0, n, 1)\n\n dV1 <- matrix(0, n, p)\n dV2 <- matrix(0, n, p)\n dV <- matrix(0, n, p)\n\n point_iter <- seq(1, n)\n results <- foreach(point=point_iter,\n .combine=c, .inorder=TRUE) %dopar% {\n calcPoint(point, r, ri, n, q, p)\n }\n\n # Merge the results from the list returned above\n # (No clean multiple assignment in R working with foreach results)\n result_offset <- 4\n for(point in point_iter) {\n list_index <- point - 1\n curr_index <- list_index * result_offset\n\n P[point] <- results[[curr_index + 1]]\n dP2[point] <- results[[curr_index + 2]]\n dV1[point, ] <- results[[curr_index + 3]]\n dV2[point, ] <- results[[curr_index + 4]]\n }\n\n P_zero_ind = which(P == 0)\n if(length(P_zero_ind) > 0) {\n P_non_zero_min <- min(P[-P_zero_ind])\n P[P_zero_ind] <- P_non_zero_min\n }\n\n V <- -p/2 + q*dP2/P\n E <- -min(V)\n V <- V + E\n\n for(dim in seq(1, p)) {\n dV[, dim] <- -q*dV1[, dim] + (V - E + (p + 2) / 2) * dV2[, dim]\n }\n dV[P_zero_ind, ] <- 0\n\n dV\n }\n\n calcPoint <- function(point, r, ri, n, q, p) {\n\n repRow <- function(X, row_reps, col_reps){\n p <- length(X)\n matrix(X, row_reps, p, byrow=T)\n }\n\n empty_col <- matrix(0, n, 1)\n empty_row <- matrix(0, 1, p)\n empty_matrix <- matrix(0, n, p)\n\n single_laplace <- empty_col\n dV1 <- empty_row\n dV2 <- empty_row\n\n squared_matrix <- repRow(r[point, ], n, 1)\n squared_matrix <- squared_matrix - ri\n unsquared_mat <- squared_matrix\n squared_matrix <- squared_matrix^2\n\n D2 <- apply(squared_matrix, MARGIN=1, FUN=sum)\n single_point <- exp(-q * D2)\n\n for(dim in seq(1, p)) {\n single_laplace <- single_laplace + squared_matrix[, dim] *\n single_point\n }\n\n for(dim in seq(1, p)) {\n curr_col <- unsquared_mat[, dim]\n dV1[, dim] <- dV1[, dim] + sum(curr_col * single_laplace)\n dV2[, dim] <- dV2[, dim] + sum(curr_col * single_point)\n }\n\n\n P <- sum(single_point)\n dP2 <- sum(single_laplace)\n\n results <- list(P=P, dP2=dP2, dV1=dV1, dV2=dV2)\n results\n }\n\n assignClusters <- function(data_points, min_d, n_clusters_max) {\n\n isAssigned <- function(clusters, index) {\n clusters[index] != 0\n }\n\n qc_log(\"Assigning clusters\")\n\n n <- nrow(data_points)\n p <- ncol(data_points)\n clusters <- rep(0, n)\n label <- 1\n start_index = 1\n\n for (start_index in seq(1, n)) {\n\n if (min(clusters) > 0) {\n break\n }\n\n if (!isAssigned(clusters, start_index)) {\n\n clusters[start_index] <- label\n for(row in seq(start_index, n)) {\n if (!isAssigned(clusters, row)) {\n ref_dist <- distance(data_points[start_index, ],\n data_points[row, ])\n if (ref_dist <= min_d) {\n clusters[row] <- label\n }\n }\n }\n\n label <- label + 1\n }\n }\n\n clusters\n }\n\n getMinD <- function(sigma, min_d_factor=2) {\n min_d_factor * sigma\n }\n\n getEta <- function(sigma) {\n sigma / 2.5\n }\n\n getQ <- function(sigma) {\n 1 / (2 * sigma^2)\n }\n\n distance <- function(x, y) {\n sqrt(sum((x - y) ^ 2))\n }\n\n qc_log <- function(out_text) {\n if(verbose) {\n print(out_text)\n }\n }\n\n orderClusters <- function(training, derived_clusters, n_clusters_max) {\n \n getPopularClusters <- function(derived_clusters, n_clusters_max) {\n popular_clusters_table <- tail(sort(table(derived_clusters)),\n n=n_clusters_max)\n popular_clusters <- rev(as.integer(names(popular_clusters_table)))\n popular_clusters\n }\n\n popular_clusters <- getPopularClusters(derived_clusters,\n n_clusters_max)\n\n clusters <- rep(0, nrow(training))\n i <- 1\n for(label in popular_clusters) {\n clusters[which(derived_clusters == label)] <- i\n i <- i + 1\n }\n\n clusters\n }\n\n dataset <- as.matrix(dataset)\n derived_clusters <- main(dataset, sigma, steps, min_d_factor,\n n_clusters_max)\n ordered_clusters <- orderClusters(dataset, derived_clusters,\n n_clusters_max=n_clusters_max)\n ordered_clusters\n}\n", "meta": {"hexsha": "0ebb15ea7880c0261e2e2cb15391b4ae9df94a6a", "size": 10171, "ext": "r", "lang": "R", "max_stars_repo_path": "R/qc.r", "max_stars_repo_name": "rdtaylor/quantumClustering", "max_stars_repo_head_hexsha": "80b85645a0e5d61227c571fd6882fdf7b8091e35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2015-04-07T15:52:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T05:07:17.000Z", "max_issues_repo_path": "R/qc.r", "max_issues_repo_name": "rdtaylor/quantumClustering", "max_issues_repo_head_hexsha": "80b85645a0e5d61227c571fd6882fdf7b8091e35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-04-29T22:31:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-29T22:33:16.000Z", "max_forks_repo_path": "R/qc.r", "max_forks_repo_name": "rdtaylor/quantumClustering", "max_forks_repo_head_hexsha": "80b85645a0e5d61227c571fd6882fdf7b8091e35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-10-02T22:07:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-05T23:19:23.000Z", "avg_line_length": 34.1308724832, "max_line_length": 375, "alphanum_fraction": 0.5733949464, "num_tokens": 2488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6377370215808427}} {"text": "#Series temporais e analises preditivas - Fernando Amaral\r\nlibrary(urca)\r\nlibrary(forecast)\r\n\r\n#teste de estacionariedade\r\nx = ur.kpss(AirPassengers)\r\nprint(x)\r\n\r\n#faz a diferenciacao\r\nz = diff(AirPassengers)\r\n#testa novamente\r\nx = ur.kpss(z)\r\nprint(x)\r\n\r\nsplit.screen( figs = c( 2, 1 ) )\r\nscreen(1)\r\nplot(AirPassengers)\r\nscreen(2)\r\nplot(z)\r\nclose.screen( all = TRUE )\r\n", "meta": {"hexsha": "6e9ab6c4148806c392c9a7fee8cabd54d3f8cabf", "size": 370, "ext": "r", "lang": "R", "max_stars_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/5.2.Teste de Estacionariedade.r", "max_stars_repo_name": "tarsoqueiroz/Rlang", "max_stars_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/5.2.Teste de Estacionariedade.r", "max_issues_repo_name": "tarsoqueiroz/Rlang", "max_issues_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Udemy/Series Temporais e Analises Preditivas/Resources/Codigo/5.2.Teste de Estacionariedade.r", "max_forks_repo_name": "tarsoqueiroz/Rlang", "max_forks_repo_head_hexsha": "b2d4fdd967ec376fbf9ddb4a7250c11d3abab52e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.619047619, "max_line_length": 58, "alphanum_fraction": 0.6972972973, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6376824153773226}} {"text": "# Sum-product and beliefs update examples\nA=matrix(c(.8,.2),2,1)\nB=matrix(c(.6,.4,.3,.7),2,2)\nC=matrix(c(.5,.5,.8,.8),2,2)\nD=matrix(c(.3,.7,.4,.6),2,2)\n\nBs = t(A) %*% t(B)\nCs = Bs %*% t(C)\nDs = Cs %*% t(D)\nDs\n", "meta": {"hexsha": "ae0db1874a1bf21313399c5a717c037236f16354", "size": 209, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter 02/chapter2_1.r", "max_stars_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_stars_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2016-05-29T14:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:33.000Z", "max_issues_repo_path": "Chapter 02/chapter2_1.r", "max_issues_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_issues_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 02/chapter2_1.r", "max_forks_repo_name": "PacktPublishing/Learning-Probabilistic-Graphical-Models-in-R", "max_forks_repo_head_hexsha": "dc72f58a4a9e7990d889dca23d90ccc71b681f14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26, "max_forks_repo_forks_event_min_datetime": "2016-05-25T10:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-18T06:08:58.000Z", "avg_line_length": 19.0, "max_line_length": 41, "alphanum_fraction": 0.5167464115, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6374942528561626}} {"text": "#' p_atm_z\n#' \n#' Calculate local air ressure as function of elevation/altitude in meters and sea-level pressure.\n#' \n#' @param z numeric elevation/altitude (m).\n#' @param p_sl numeric pressure at sea level, per weather report (hPa),Default 101235 Pa. \n#' \n#' @author Istituto per la Bioeconomia CNR Firenze Italy Alfonso Crisci \\email{alfonso.crisci@@ibe.cnr.it}\n#' @references 2005 ASHRAE Handbook - Fundamentals (SI) ch.6 (3)\n#' @return numeric pressure (Pa)\n#' @export\n#' \n\np_atm_z <- function(z, p_sl = 1013.25) {\n p_sl * (1 - 2.25577e-5 * z)^5.2559 \n}\n", "meta": {"hexsha": "6d0fa4e06aaa68097079b4f2b7f8eb5b9893f5ae", "size": 621, "ext": "r", "lang": "R", "max_stars_repo_path": "R/p_atm_z.r", "max_stars_repo_name": "alfcrisci/rBiometeo", "max_stars_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-04-23T13:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:36.000Z", "max_issues_repo_path": "R/p_atm_z.r", "max_issues_repo_name": "alfcrisci/rBiometeo", "max_issues_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/p_atm_z.r", "max_forks_repo_name": "alfcrisci/rBiometeo", "max_forks_repo_head_hexsha": "1fe0113d017372393de2ced18b884f356c76049b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-19T15:28:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T19:35:47.000Z", "avg_line_length": 36.5294117647, "max_line_length": 107, "alphanum_fraction": 0.6280193237, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6371353446805331}} {"text": "m = 10000\na = 5 \nb = 3 \n\nbeta = rbeta(m, shape1=a, shape2=b)\n\nsuccess = beta/(1-beta)\n\nmean(beta/(1-beta))\n\nind = success > 1 \n\nmean(ind)\n\n\nm = 100000\na = 0 \nb = 1\nnorm = rnorm(m,a,b)\n\nqnorm(0.3,mean=a,sd=b)\n\nquantile(norm, prob=0.3)", "meta": {"hexsha": "c1c5317c77e6974bc4ba57dd4900196cfae8fc19", "size": 233, "ext": "r", "lang": "R", "max_stars_repo_path": "montyCarlo/loanApplication.r", "max_stars_repo_name": "CharlieShelbourne/algos_practice", "max_stars_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "montyCarlo/loanApplication.r", "max_issues_repo_name": "CharlieShelbourne/algos_practice", "max_issues_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montyCarlo/loanApplication.r", "max_forks_repo_name": "CharlieShelbourne/algos_practice", "max_forks_repo_head_hexsha": "bf32a739a9ab88f177461057fededb42e2d7fe10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 10.1304347826, "max_line_length": 35, "alphanum_fraction": 0.5879828326, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6367329509771825}} {"text": "lp = function(trainingset, testset, column, upperBound = 1e16){\n\n matrixA = subset(trainingset, select = column)\n effort = trainingset$Effort\n nV = length(column)\n\n nConstrains = 2*length(column) + 4*dim(trainingset)[1]\n nVar = length(column) + 2*dim(trainingset)[1]\n mat1 = matrix(NA, ncol = nVar, nrow = dim(trainingset)[1])\n mat2 = matrix(NA, ncol = nVar, nrow = dim(trainingset)[1])\n mat3 = matrix(NA, ncol = nVar, nrow = dim(trainingset)[1])\n mat4 = matrix(0, ncol = nVar, nrow = nV)\n mat5 = matrix(0, ncol = nVar, nrow = nV)\n mat6 = matrix(0, ncol = nVar, nrow = dim(trainingset)[1])\n\n tzip = (1:dim(mat1)[1]*2+nV-1)\n cVec = rep(0, nVar)\n cVec[tzip] = 1\n for(i in 1:dim(matrixA)[1]){\n for(j in 1:dim(matrixA)[2]){\n mat1[i,j] = matrixA[i,j]\n }\n }\n mat1[is.na(mat1)] = 0\n b1 = rep(0, dim(mat1)[1])\n mat2 = mat1\n\n tzip= cbind((1:dim(mat2)[1]), (1:dim(mat2)[1]*2+nV-1))\n mat2[tzip] = -1\n effzip= cbind((1:dim(mat2)[1]), (1:dim(mat2)[1]*2+nV))\n mat2[effzip] = -1\n b2 = rep(0, dim(mat2)[1])\n\n mat3 = mat2\n tzip= cbind((1:dim(mat3)[1]), (1:dim(mat3)[1]*2+nV-1))\n mat3[tzip] = 1\n b3 = rep(0, dim(mat3)[1])\n\n diag(mat4) = 1\n b4 = rep(0, dim(mat4)[1])\n diag(mat5) = 1\n\n b5 = rep(upperBound, dim(mat5)[1])\n effzip= cbind((1:dim(mat6)[1]), (1:dim(mat6)[1]*2+nV))\n mat6[effzip] = 1\n b6 = effort\n A = rbind(mat1,mat2,mat3,mat4,mat5,mat6)\n constr = c(rep(\">\", dim(mat1)[1]), rep(\"<=\", dim(mat2)[1]), rep(\">=\", dim(mat3)[1]), rep(\">=\", dim(mat4)[1]), rep(\"<=\", dim(mat5)[1]), rep(\"=\", dim(mat6)[1]))\n B = c(b1,b2,b3,b4,b5,b6)\n solSimplex = solveLP(cVec, B, A, const.dir = constr,lpSolve = TRUE, zero = 1e-16, tol = 1E-3)\n variablesValue = solSimplex$solution[1:nV]\n matrixATest = subset(testset, select = column)\n measured = testset$Effort\n\n prediction = rowSums(sweep(matrixATest, MARGIN = 2, variablesValue, `*`))\n\n return(list(data.frame(prediction,measured), variablesValue))\n}\n", "meta": {"hexsha": "7be2432465fc9388d2156a5ff885ecd7243d36db", "size": 2021, "ext": "r", "lang": "R", "max_stars_repo_path": "experiments/lp4ee.r", "max_stars_repo_name": "arennax/contemporary2020", "max_stars_repo_head_hexsha": "1da86d384a5b7e1afea0d3e309799728a0734e9f", "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": "experiments/lp4ee.r", "max_issues_repo_name": "arennax/contemporary2020", "max_issues_repo_head_hexsha": "1da86d384a5b7e1afea0d3e309799728a0734e9f", "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": "experiments/lp4ee.r", "max_forks_repo_name": "arennax/contemporary2020", "max_forks_repo_head_hexsha": "1da86d384a5b7e1afea0d3e309799728a0734e9f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-14T23:56:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T23:56:11.000Z", "avg_line_length": 34.2542372881, "max_line_length": 162, "alphanum_fraction": 0.5754576942, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6367329239794899}} {"text": "score <- function(input) {\n return((((((((((((((36.367080746577244) + ((input[1]) * (-0.10861311354908008))) + ((input[2]) * (0.046461486329936456))) + ((input[3]) * (0.027432259970172148))) + ((input[4]) * (2.6160671309537777))) + ((input[5]) * (-17.51793656329737))) + ((input[6]) * (3.7674418196772255))) + ((input[7]) * (-0.000021581753164971046))) + ((input[8]) * (-1.4711768622633645))) + ((input[9]) * (0.2956767140062958))) + ((input[10]) * (-0.012233831527259383))) + ((input[11]) * (-0.9220356453705304))) + ((input[12]) * (0.009038220462695552))) + ((input[13]) * (-0.542583033714222)))\n}\n", "meta": {"hexsha": "5a5ea44ceaba6c2a34dfb9c89797490fa0cefe0b", "size": 603, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/regression/linear.r", "max_stars_repo_name": "Symmetry-International/m2cgen", "max_stars_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2161, "max_stars_repo_stars_event_min_datetime": "2019-01-13T02:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:24:09.000Z", "max_issues_repo_path": "generated_code_examples/r/regression/linear.r", "max_issues_repo_name": "Symmetry-International/m2cgen", "max_issues_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 380, "max_issues_repo_issues_event_min_datetime": "2019-01-17T15:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:59:20.000Z", "max_forks_repo_path": "generated_code_examples/r/regression/linear.r", "max_forks_repo_name": "Symmetry-International/m2cgen", "max_forks_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-02-13T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:45:46.000Z", "avg_line_length": 150.75, "max_line_length": 573, "alphanum_fraction": 0.5903814262, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6364850840799493}} {"text": "# percentile of normal distribution using r\r\n# we will use qnorm function \r\n# 10 th percentile of Normal distribution Mean = 70 and SD=13\r\nqnorm(0.10,70,13)", "meta": {"hexsha": "248b629b5202b8e0430525ab0355f3a0e48b025d", "size": 156, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.18/Ex4_18.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.18/Ex4_18.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH4/EX4.18/Ex4_18.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 39.0, "max_line_length": 62, "alphanum_fraction": 0.75, "num_tokens": 44, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6364831234926942}} {"text": "## Dati\r\n\r\nrigasopra <- c(-2.22, -0.53, 0.81)\r\nrigaverticale <- c(-4.1, -1.46, -0.16)\r\n\r\nprob <- c(7,4,5,\r\n 8,3,9,\r\n 6,2,1)\r\n\r\nlibrary(MASS)\r\n\r\nk <- fractions(1/sum(prob))\r\nmarginale_x <-c((prob[1]+prob[2]+prob[3])*k,\r\n (prob[4]+prob[5]+prob[6])*k,\r\n (prob[7]+prob[8]+prob[9])*k)\r\n\r\nmarginale_y <-c((prob[1]+prob[4]+prob[7])*k,\r\n (prob[2]+prob[5]+prob[8])*k,\r\n (prob[3]+prob[6]+prob[9])*k)\r\n\r\natteso_x <- sum(marginale_x *rigaverticale)\r\n\r\nvarianza_y <- sum(marginale_y * (rigasopra)^2) - sum(marginale_y * (rigasopra))^2\r\n\r\nprint(k)\r\nprint(marginale_x)\r\nprint(marginale_y)\r\nprint(atteso_x)\r\nprint(varianza_y)\r\n", "meta": {"hexsha": "a53a4740f10ba1745b6a86802fff322ad853815f", "size": 703, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 45.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 45.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 45.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4333333333, "max_line_length": 82, "alphanum_fraction": 0.5220483642, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603708, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6364681432149655}} {"text": "rm(list = ls()) # clear console\n\n# ADETAYO ADEGOKE\n# WEEK 01 Homework - Logic, using Boolean Algebra and Finite Fields\n# Due: February 05, 2020\n# Mathematics E-23c, Spring 2020\n\n\n\n# Questions 1 (a), (b) and (c)\n\n# (p & q) IMPLIES (r | s) is equivalent to [not(p & q) | (r | s)]\n# the le column represents this logical expression\neg <- expand.grid(c(TRUE, FALSE), c(TRUE, FALSE), c(TRUE, FALSE), c(TRUE, FALSE)); eg\nttbl <- data.frame(eg[,c(4:1)]); ttbl # reverse the columns\ncolnames(ttbl) <- c('p', 'q', 'r', 's'); ttbl #change the column names to match variable names, and display the truth table\n\n# Had trouble with attach :(\n# Construct the columns that will be used to compute the logical expression\nttbl$pq <- (ttbl$p & ttbl$q)\nttbl$notpq <- (!(ttbl$p & ttbl$q))\nttbl$rors <- (ttbl$r | ttbl$s)\nttbl$le <- (ttbl$notpq | ttbl$rors); ttbl # logical expression column\n\n# The constructive normal form (aka cnf column below)for the LE looking at the truth table is\n# (!p | !q | r | s)\nttbl$cnf <- (!(ttbl$p) | !(ttbl$q) | ttbl$r | ttbl$s); ttbl # voila, column le and cnf match in the truth table!\n\nrm(list = ls()) # clear console\n\n\n# Questions 2(a)\n\n# setwd(\"/Users/adegade/OneDrive/Documents/Education/Harvard/Software Engineering/Spring-2020-MATH-E-23C/Homework\")\nGssl <- read.csv(\"GSSLogical.csv\") # load the input file\nhead(Gssl) # test that it and review columns\nattach(Gssl)\nindex <- which(!is.na(Male) & !is.na(Republican) & !is.na(GunOwner) &\n (Male == \"FALSE\") & (Republican == \"FALSE\") & (GunOwner == \"TRUE\")); index\nlength(index) # 37 = number of participants in the survey who were female democrats who owned guns\n\n# Clean Up!\ndetach(Gssl)\nrm(list = ls()) # clear console\n\n\n# Questions 2(b)\n\n# setwd(\"/Users/adegade/OneDrive/Documents/Education/Harvard/Software Engineering/Spring-2020-MATH-E-23C/Homework\")\nRedsox <- read.csv(\"RedSox2013.csv\") # load the input file\nhead(Redsox) # test that it and review columns\nattach(Redsox)\nTRuns <- R + RA # create a new column that totals up runs\nHRuns <- subset(Redsox, TRuns >= 10); HRuns # get a subset of data with for games with 10 runs or more\nmin(HRuns$Duration)\n\n\n# Question 2(c)\n\nboxplot(R ~ DayNight) # display box plot of runs in day and night Red Sox games \n\n\n# Question 2(d)\n\ntbl <- table(WonLost, Away); tbl # create the table for observed WonLost and Away comparison\nExpected <- outer(rowSums(tbl), colSums(tbl))/sum(tbl); Expected # create the table for expected WonLost and Away comparison \nchisq.test(tbl, Expected) # there is a 16.73% chance that the discreptancy b/w expected and observed comparison between WonLost and Away\n# is not statistically relevant, assuming the null hypothesis of independence. The dataset does not provide enough evidence to support\n# the null hypothesis of independence (0.1673 > 0.05). Red Sox did not seem to have an advantage in Home or Away games.\n\ntbl <- table(WonLost, DayNight); tbl # create the table for observed WonLost and Away comparison\nExpected <- outer(rowSums(tbl), colSums(tbl))/sum(tbl); Expected # create the table for expected WonLost and Away comparison \nchisq.test(tbl, Expected) # there is a 43.8% chance that the discreptancy b/w expected and observed comparison between WonLost and DayNight\n# is not statistically relevant, assuming the null hypothesis of independence. The dataset does not provide enough evidence to support\n# the null hypothesis of independence (0.438 > 0.05). Red Sox did not seem to have an advantage in Home or Away games.\n\n# Clean Up!\ndetach(Redsox)\nrm(list = ls()) # clear console\n\n\n# Question 3(a)\n\nattach(airquality) # attach the data frame\nhead(airquality) # display the first few rows of the data frame\nboxplot(Ozone ~ Month) # display box plot of how Ozone depends on Month\nboxplot(Solar.R ~ Month) # display box plot of how Solar Radiation depends on Month\nboxplot(Wind ~ Month) # display box plot of how Wind depends on Month\nboxplot(Temp ~ Month) # display box plot of how Temperature depends on Month\n\n\n# Question 3(b)\n\naq <- get(\"airquality\"); head(airquality) # get and display the airquality data frame\nattach(aq)\n\nplot(Temp, Solar.R) # create a plot of Temperature versus Solar Radiation\nmodel <- lm(Solar.R ~ Temp) # create a Model\nabline(model$coefficients[1], model$coefficients[2]) # draw the regression line on the plot\n# data points in the plot are widely dispersed, as such temperature does not seem to be good predictor for solar radiation\n\nplot(Temp, Ozone) # create a plot of Temperature versus Ozone\nmodel <- lm(Ozone ~ Temp) # create a Model\nabline(model$coefficients[1], model$coefficients[2]) # draw the regression line on the plot\n# data points in the plot are relatively close together with a strong positive linear relationship, as such temperature \n# does seem to be good predictor for solar radiation\n\n\n# Question 3(c)\n\n# Define new logical vectors while accounting for the NA data points in the set\nsmoggy <- Ozone > mean(Ozone, na.rm = TRUE); head(smoggy)\nwindy <- Wind> mean(Wind, na.rm = TRUE); head(windy)\nsunny <- Solar.R > mean(Solar.R, na.rm = TRUE); head(sunny)\nhot <- Temp > mean(Temp, na.rm = TRUE); head(hot)\n\n# Select the days where all four logical vectors defined above are true\nsubset(airquality, (smoggy == TRUE) & (windy == TRUE) & (sunny == TRUE) & (hot == TRUE))\n\n\n# Question 3(d)\n\nchisq.test(smoggy, windy) # there is a 4.29 x 10^(-4)% chance that observed dependencies between the two factors being compared\n# happened by chance. Since this is a lot less than 5%, we will reject the null hypothesis of independence between the\n# two variables and propose that they are both probably dependent\n# smoggy and windy are probably dependent variables\n\nchisq.test(windy, sunny) # there is a 68.23% chance that observed dependencies between the two factors being compared\n# happened by chance. Since this is a lot more than 5%, we will fail to reject the null hypothesis of independence between the\n# two variables and propose that they are both probably independent\n# windy and sunny are probably independent variables\n\n#Clean Up!\ndetach(airquality)\nrm(list = ls()) # clear console", "meta": {"hexsha": "4076452612ae031c522dc8ffe0a10f8a9f410332", "size": 6102, "ext": "r", "lang": "R", "max_stars_repo_path": "adetayo-adegoke-wk01-hw.r", "max_stars_repo_name": "adegade/math-e23c", "max_stars_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adetayo-adegoke-wk01-hw.r", "max_issues_repo_name": "adegade/math-e23c", "max_issues_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adetayo-adegoke-wk01-hw.r", "max_forks_repo_name": "adegade/math-e23c", "max_forks_repo_head_hexsha": "6343e13d7dfea44d4b6d24665b15afce88ebf8d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2, "max_line_length": 139, "alphanum_fraction": 0.7302523763, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.6364561789216377}} {"text": "# test statistic\r\nt=.26528/.10127\r\nprint(t)\r\ndf=17\r\nt1value=qt(1-0.01,df)\r\nt2value=qt(1-0.005,df)\r\nprint(t1value)\r\nprint(t2value)\r\n # Thus, H0 would be rejected at the alpha= .01 level but not at the alpha= .005 level\r\npvalue =pt(-t, df)\r\nprint(pvalue)", "meta": {"hexsha": "c4b299048129b06811480a43d8fa78530bad564c", "size": 255, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.16/Ex12_16.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.16/Ex12_16.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH12/EX12.16/Ex12_16.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 23.1818181818, "max_line_length": 90, "alphanum_fraction": 0.6784313725, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6364561726405021}} {"text": "change.base <- function(n, base)\n{\n ret <- integer(as.integer(logb(x=n, base=base))+1L)\n\n for (i in 1:length(ret))\n {\n ret[i] <- n %% base\n n <- n %/% base\n\n }\n\n return(ret)\n}\n\nsum.digits <- function(n, base=10)\n{\n if (base < 2)\n stop(\"base must be at least 2\")\n\n return(sum(change.base(n=n, base=base)))\n}\n\nsum.digits(1)\nsum.digits(12345)\nsum.digits(123045)\nsum.digits(0xfe, 16)\nsum.digits(0xf0e, 16)\n", "meta": {"hexsha": "759b872eeabd1e8541f56d40ab255ecf5de126f7", "size": 418, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 14.9285714286, "max_line_length": 53, "alphanum_fraction": 0.5980861244, "num_tokens": 149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6364561726405021}} {"text": "library(combinat)\n\npermute.me <- c(\"A\", \"B\", \"C\", \"D\")\nperms <- permn(permute.me) # list of all permutations\nperms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T) # matrix of all permutations\nperms3 <- apply(perms2, 1, paste, collapse=\"\") # vector of all permutations\n\nincomplete <- c(\"ABCD\", \"CABD\", \"ACDB\", \"DACB\", \"BCDA\", \"ACBD\", \"ADCB\", \"CDAB\",\n \"DABC\", \"BCAD\", \"CADB\", \"CDBA\", \"CBAD\", \"ABDC\", \"ADBC\", \"BDCA\",\n \"DCBA\", \"BACD\", \"BADC\", \"BDAC\", \"CBDA\", \"DBCA\", \"DCAB\")\n\nsetdiff(perms3, incomplete)\n", "meta": {"hexsha": "c3f591cc303d6e7ba88f16479a3fad870ad2f5ee", "size": 546, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Find-the-missing-permutation/R/find-the-missing-permutation.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Find-the-missing-permutation/R/find-the-missing-permutation.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/Find-the-missing-permutation/R/find-the-missing-permutation.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": 42.0, "max_line_length": 95, "alphanum_fraction": 0.5860805861, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.63640981196895}} {"text": "# Expectation-Maximizaton to fins clusters and alpha, beta, tau parameters \n# of each cluster\n#\n# author: Alberto Lumbreras\nlibrary(data.table)\nlibrary(neldermead)\nlibrary(dfoptim)\n#source('optimization.r')\n\nupdate_responsabilities <- function(df.trees, u, pis, alphas, betas, taus){\n # Compute E(z_uk) over the posterior distribution p(z_uk | X, theta)\n \n K <- length(alphas) # number of clusters\n Xu <- filter(df.trees, user==u) # all posts from user\n \n logfactors <- rep(0,K)\n for (k in 1:K){\n logfactors[k] <- log(pis[k]) + sum(apply(Xu, 1, likelihood.post, alphas[k], betas[k], taus[k]))\n }\n \n logfactors <- logfactors - max(logfactors) # avoid numerical underflow\n denominator <- sum(exp(logfactors))\n responsabilities_u <- exp(logfactors)/denominator\n responsabilities_u\n}\n\n\n# Likelihood computation using the dataframe\nlikelihood.post <- function(row, alpha, beta, tau){\n c(as.matrix(\n log(alpha * row['popularity'] + beta*(row['parent']==1) + tau^row['lag']) - \n log(2*alpha*(row['t']-1) + beta + tau*(tau^row['t']-1)/(tau-1))\n )\n )\n}\n\nQopt <- function(params, resp_k, df.trees){\n # sum of E[lnp(X,Z|\\theta)] likelihoods for all clusters and all users\n # given the current responsabilities\n # Note that the optimizations can be done separatedly\n a <- resp_k[df.trees$user]\n b <- apply(df.trees, 1, function(x) likelihood.post(x, params[1], params[2], params[3]))\n sum(a*b) # each likelihood b is weighted according to how much dos the user belong to the cluster\n}\n\n# Wrapper for the optimization function\n# so that the only parameters are the ones to optimize\n#cost.function <- function(params){\n# -1*Qopt(alpha=params[1], beta=params[2], tau=params[3], responsabilities[,k], df.trees)\n#}\n\n#Qopt.prima <- function(alpha, beta, tau, resp_k, df.trees){\n# sum(apply(df.trees, 1, likelihood.post, alpha, beta, tau))\n#}\n\n\nEM <-function(df.trees, alphas, betas, taus){\n # Expectation-Maximizationo to find groups of users with different\n # alpha, beta, tau parameters\n # Arguments:\n # trees: a list of igraph objects representing discussion threads\n # alphas, betas, taus: initial assignment of users to clusters\n K <- length(alphas)\n users <- unique(df.trees$user)\n U <- length(users)\n \n responsabilities <- matrix(nrow = U, ncol = K)\n pis <- rep(1/ncol(responsabilities), ncol(responsabilities))\n\n niters <- 10\n traces <- matrix(0, nrow=niters, ncol=K)\n for(iter in 1:niters){\n cat(\"\\n**********ITERATION**********: \", iter, \"\\n\")\n # EXPECTATION\n # Given the parameters of each cluster, find the responsability of each user in each cluster \n #################################################################\n # (this can be parallelizable)\n for (u in 1:U){\n responsabilities[u,] <- update_responsabilities(df.trees, u, pis, alphas, betas, taus) \n }\n \n #print(responsabilities)\n cat(\"Best vectors:\\n\", apply(responsabilities, 1, which.max))\n \n # MAXIMIZATION\n # Given the current responsabilities and pis, find the best parameters for each cluster\n ################################################################\n for(k in 1:K){\n # Optimization for cluster k\n # neldermead::fminbnd does not deal well with boundaries\n # nlminb and nmkb give the same solution.\n # nmkb is a little bit faster\n # sol <- nlminb(c(alphas[k],betas[k],taus[k]), cost.function,\n # scale = 1, lower=c(0,0,0), upper=c(Inf, Inf, 1))\n sol <- nmkb(c(alphas[k], betas[k], taus[k]), Qopt, \n lower = c(0,0,0), upper = c(Inf, Inf, 1), \n control = list(maximize=TRUE),\n resp_k = responsabilities[,k], df.trees = df.trees)\n alphas[k] <- sol$par[1]\n betas[k] <- sol$par[2]\n taus[k] <- sol$par[3]\n traces[iter,k] <- sol$value\n }\n \n # Update pis\n pis <- colSums(responsabilities)/nrow(responsabilities)\n \n ###############################################################\n # EVALUATION OF FULL LIKELIHOOD p(X, Z | \\theta)\n ###############################################################\n cat(\"\\n\\nalphas:\", alphas)\n cat(\"\\nbetas:\", betas)\n cat(\"\\ntaus:\", taus)\n }\n \n list(alphas=alphas,\n betas=betas,\n taus=taus,\n z=z,\n traces=traces)\n \n}\n\nif(TRUE){\n #load('trees.Rda')\n \n # True parameters\n alphas <- c(0.1, 0.5, 1)\n betas <- c(1, 6, 3)\n taus <- c(0.7, 0.1, 0.2)\n\n # The first two posts of every thread are trivial since they have no choice\n df.trees <- filter(df.trees, t>2)\n \n # Expectation-Maximization\n res <- EM(df.trees, alphas, betas, taus)\n plot(rowSums(res$traces))\n \n #-7840\n #-7839\n #-7893\n \n}", "meta": {"hexsha": "c0ba30571fb6e5ec3f0247c1de650089e8afe112", "size": 4767, "ext": "r", "lang": "R", "max_stars_repo_path": "em.r", "max_stars_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_stars_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "em.r", "max_issues_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_issues_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "em.r", "max_forks_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_forks_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_forks_repo_licenses": ["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.3356643357, "max_line_length": 99, "alphanum_fraction": 0.5894692679, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6363067549426825}} {"text": "orderBalancedTree <- Vectorize(function(r, h) {\n # computes the number of vertices in a balanced tree of breadth \"r\" and height \"h\"\n #\n # Args:\n # r: The breadth (branching factor) of the balanced tree\n # h: The height of the balanced tree\n #\n # Returns:\n # The number of vertices in a balanced tree\n #\n \n total <- 0\n hseq <- seq.int(0, h)\n total <- sum(r ^ hseq)\n\n \n return(total)\n})\n\n\n\n\n\n\n", "meta": {"hexsha": "7fcab5d3e1d3a778990001e331077862d2bf9b37", "size": 423, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/semanticaxelrod/R/balanced-trees.r", "max_stars_repo_name": "mmadsen/madsenlipo2014", "max_stars_repo_head_hexsha": "7984775d0deba022c8474c3217718e45451ee5db", "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": "analysis/semanticaxelrod/R/balanced-trees.r", "max_issues_repo_name": "mmadsen/madsenlipo2014", "max_issues_repo_head_hexsha": "7984775d0deba022c8474c3217718e45451ee5db", "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": "analysis/semanticaxelrod/R/balanced-trees.r", "max_forks_repo_name": "mmadsen/madsenlipo2014", "max_forks_repo_head_hexsha": "7984775d0deba022c8474c3217718e45451ee5db", "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": 16.92, "max_line_length": 85, "alphanum_fraction": 0.6028368794, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6358755649231999}} {"text": "Dragon<-function(Iters){\n Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix\n Iteration<-list() ###################################Set up list for segment matrices for 1st\n Iteration[[1]] <- matrix(rep(0,16), ncol = 4)\n Iteration[[1]][1,]<-c(0,0,1,0)\n Iteration[[1]][2,]<-c(1,0,1,-1)\n Moveposition<-rep(0,Iters) ##########################Which point should be shifted to origin\n Moveposition[1]<-4\n if(Iters > 1){#########################################where to move to get to origin\n for(l in 2:Iters){#####################################only if >1, because 1 set before for loop\n Moveposition[l]<-(Moveposition[l-1]*2)-2#############sets vector of all positions in matrix where last point is\n }}\n Move<-list() ########################################vector to add to all points to shift start at origin\nfor (i in 1:Iters){\nhalf<-dim(Iteration[[i]])[1]/2\nhalf<-1:half\nfor(j in half){########################################Rotate all points 90 degrees clockwise\n Iteration[[i]][j+length(half),]<-c(Iteration[[i]][j,1:2]%*%Rotation,Iteration[[i]][j,3:4]%*%Rotation)\n}\nMove[[i]]<-matrix(rep(0,4),ncol=4)\nMove[[i]][1,1:2]<-Move[[i]][1,3:4]<-(Iteration[[i]][Moveposition[i],c(3,4)]*-1)\nIteration[[i+1]]<-matrix(rep(0,2*dim(Iteration[[i]])[1]*4),ncol=4)##########move the dragon, set next Iteration's matrix\nfor(k in 1:dim(Iteration[[i]])[1]){#########################################move dragon by shifting all previous iterations point\n Iteration[[i+1]][k,]<-Iteration[[i]][k,]+Move[[i]]###so the start is at the origin\n}\nxlimits<-c(min(Iteration[[i]][,3])-2,max(Iteration[[i]][,3]+2))#Plot\nylimits<-c(min(Iteration[[i]][,4])-2,max(Iteration[[i]][,4]+2))\nplot(0,0,type='n',axes=FALSE,xlab=\"\",ylab=\"\",xlim=xlimits,ylim=ylimits)\ns<-dim(Iteration[[i]])[1]\ns<-1:s\nsegments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red')\n}}#########################################################################\n", "meta": {"hexsha": "dac01e9e74af30d112e01f5e9de983a7c610b786", "size": 1996, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Dragon-curve/R/dragon-curve-1.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Dragon-curve/R/dragon-curve-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/Dragon-curve/R/dragon-curve-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": 60.4848484848, "max_line_length": 129, "alphanum_fraction": 0.5355711423, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6355804457362281}} {"text": "#' Loads the necessary libraries, which are: huge, MASS, thav.glasso, scalreg, igraph, matrixcalc, genscore, scio, stargazer, glasso\n#'\n#' @export\nload_libraries <- function()\n{\n libraries <- c(\"huge\", \"MASS\", \"thav.glasso\", \"scalreg\", \"igraph\", \"matrixcalc\", \"genscore\", \"scio\", \"stargazer\", \"glasso\")\n lapply(libraries, library, character.only=TRUE)\n}\n\n#' Turns a covariance matrix into the correlation matrix\n#'\n#' @param theta Covariance matrix\n#' @return Correlation matrix\n#' @export\nnormalize_theta <- function(theta)\n{\n for(j in 1:dim(theta)[1])\n {\n for(i in 1:dim(theta)[1])\n {\n theta[i,j] <- theta[i,j] / (sqrt(theta[i,i]) * sqrt(theta[j, j]))\n }\n }\n return(theta)\n}\n\n#' Computes the adaptive validation graphical lasso\n#' \n#' @param data Data matrix of size n x d \n#' @param C constant C that is used to calibrate the AV regularization parameter\n#' @return The selected regularization parameter\n#' @return The resulting graphical lasso estimate\n#' @examples \n#' theta <- generateGraph(d=100)[[1]]\n#' Sigma <- solve(theta)\n#' data <- scale(mvrnorm(n=200, mu=rep(0, 100), Sigma=Sigma))\n#' av <- av_glasso(data)\n#' av_tp <- av$TuningParameter\n#' av_est <- av$Thetahat\n#' @export\nav_glasso <- function(data, C=0.7) \n{\n empvar <- var(data)\n \n # Automatically set max(seq_r) <- tp that sets all offdiagonal entries to zero\n max_r <- max( abs(empvar[upper.tri(empvar)]))\n seq_r <- seq(0.05, max_r, length.out = 40)\n \n r <- max(seq_r)\n estimates <- list()\n \n #calculate glasso[max(r)] and setup the warm start\n glasso <- glasso(empvar, rho=r, penalize.diagonal=FALSE)\n warm <- list(glasso$wi, glasso$w)\n estimates[[length(seq_r)]] <- normalize_theta(warm[[1]]) #warm[[1]] #\n \n counter_r <- length(seq_r) #used to fill the list estimates with corresponding estimates\n while(r > min(seq_r))\n {\n #compute glasso[r] using a warm start\n counter_r <- counter_r - 1\n r <- seq_r[counter_r]\n newwarm <- glasso(empvar, rho=r, penalize.diagonal=FALSE, start=\"warm\", wi.init=warm[[1]], w.init=warm[[2]])\n estimates[[counter_r]] <- normalize_theta(newwarm$wi) \n warm <- list(newwarm$wi, newwarm$w)\n \n counter_r_dash <- length(seq_r)\n r_dash <- seq_r[counter_r_dash]\n while(r_dash > r)\n {\n #if l(...) > Cr_dash + Cr\n if(avtest(estimates, seq_r, counter_r, counter_r_dash, C)) \n {\n return(list(TuningParameter=seq_r[counter_r + 1], Thetahat=estimates[[counter_r + 1]]))\n }\n counter_r_dash <- counter_r_dash - 1\n r_dash <- seq_r[counter_r_dash]\n }\n }\n estimates[[1]] <- normalize_theta(glasso(empvar, rho=min(seq_r), penalize.diagonal=FALSE, start=\"warm\", wi.init=warm[[1]], w.init=warm[[2]])$wi)\n return(list(TuningParameter=seq_r[1], Thetahat=estimates[[1]])) \n}\n\n#' Computes the test that is used in the AV calibration scheme\n#' \n#' @param estimates List of the graphical lasso estimators so far\n#' @param seq_r List of possible regularization paraeters\n#' @param counter_r position of the current r in r_seq (see algorithm)\n#' @param counter_r_dash position of the current r_dash in seq_r (see algorithm)\n#' @param C constant C that is used for the AV calibration\n#' @return TRUE if l(...) > Cr_dash + Cr, else FALSE\n#' @export\navtest <- function(estimates, seq_r, counter_r, counter_r_dash, C)\n{\n infloss(estimates[[counter_r]], estimates[[counter_r_dash]]) > C * (seq_r[counter_r] + seq_r[counter_r_dash])\n}\n\n#' Thresholds the AV estimator\n#' \n#' @param av List AV containing the regularization parameter and the estimator, which is obtained by applying the av_glasso function\n#' @param C Constant C that was used to calibrate the AV\n#' @param lambda Threshold factor lambda: We threshold the AV solution by lambda*C*av$TuningParameter\n#' @return The thresholded AV estimator\n#' @export\nthreshold <- function( av, C=0.7, lambda=1)\n{\n return( apply( av$Thetahat, c(1,2), function(x) if( abs(x) <= lambda*C*av$TuningParameter){ return(0)} else{ return(x)}))\n}\n\n#' Computes the thAV estimator\n#' \n#' @param data Data matrix of size n x d \n#' @param C constant C that is used to calibrate the AV regularization parameter\n#' @param lambda Threshold factor lambda: We threshold the AV solution by lambda*C*av$TuningParameter\n#' @param mute If FALSE, the method prints the selected AV regularization parameter. The default value is TRUE.\n#' @return The thresholded AV estimator\n#' @examples \n#' theta <- generateGraph(d=100)[[1]]\n#' Sigma <- solve(theta)\n#' data <- scale(mvrnorm(n=200, mu=rep(0, 100), Sigma=Sigma))\n#' thav <- thAV.estimator(data)\n#' @export\nthAV.estimator <- function( data, C=0.7, lambda=1, mute=TRUE)\n{\n av <- av_glasso(data, C) \n \n if(!mute)\n {\n print(paste0(\"Selected Regularization Parameter: \", round(av$TuningParameter,2)))\n }\n return( threshold(av, C, lambda))\n}\n\n\n#' Computes the rSME via eBIC\n#'\n#' @param data Data matrix of size n x d\n#' @param gamma Parameter that is used in the eBIC criterion. Usually gamma=0.5 or gamma=1. The default value is set to 1.\n#' @return rSME estimator that is tuned via eBIC\n#' @export\nscore_ebic <- function(data, gamma=1)\n{\n d <- dim(data)[2]\n domain <- make_domain(\"R\", p=d)\n elts <- get_elts(NULL, data, \"gaussian\", domain)\n max_r <- lambda_max(elts, \"symmetric\")\n seq_r <- seq(0.05, max_r, length.out = 40)\n best_eBIC <- 10^5\n for(j in 1:length(seq_r))\n {\n result <- get_results(elts, \"symmetric\", seq_r[j])\n if(eBIC(result, elts, gammas=gamma)[1] < best_eBIC)\n {\n ebic_est <- result$K\n best_eBIC <- eBIC(result, elts, gammas=gamma)[1]\n }\n }\n return(ebic_est)\n}\n\n#' Computes the adaptive validation regularized score matching estimator rSME (AV)\n#' \n#' @param data Data matrix of size n x d\n#' @param C constant C that is used to calibrate the AV regularization parameter\n#' @return The selected regularization parameter\n#' @return The resulting AV regularized score matching estimator rSME (AV)\n#' @export\nav_rsme <- function(data, C=2)\n{\n empvar <- var(data)\n seq_r <- seq(5e-4, 0.3, length.out = 40)\n #initialization\n r <- max(seq_r)\n \n domain <- make_domain(\"R\", p=dim(empvar)[1])\n estimates <- estimate(data, \"gaussian\", domain, scale=\"sd\", return_raw=TRUE, lambda1s=seq_r,\n verbose=FALSE, verbosetext=FALSE)$raw_estimate\n estimates <- rev(estimates) # genscore implementation returns a list of estimates \n # where the first entry corresponds to the largest TP estimate\n # normalize each theta\n for(j in 1:40)\n {\n estimates[[j]] <- normalize_theta(estimates[[j]])\n }\n counter_r <- length(seq_r) #used to fill the list estimates with corresponding estimates\n while(r != min(seq_r))\n {\n counter_r <- counter_r - 1\n r <- seq_r[counter_r]\n\n counter_r_dash <- length(seq_r)\n r_dash <- seq_r[counter_r_dash]\n while(r_dash > r)\n {\n #if l(...) > Cr_dash + Cr\n if(avtest(estimates, seq_r, counter_r, counter_r_dash, C))\n {\n return(list(TuningParameter=seq_r[counter_r + 1], Thetahat=estimates[[counter_r + 1]]))\n }\n counter_r_dash <- counter_r_dash - 1\n r_dash <- seq_r[counter_r_dash]\n }\n }\n return(list(TuningParameter=seq_r[1], Thetahat=estimates[[1]]))\n}\n\n#' Computes the trace of a matrix\n#'\n#' @param matrix Matrix\n#' @return Trace of matrix\n#' @export\ntr <- function(matrix)\n{\n return(sum(diag(matrix)))\n}\n\n#' Computation of the Bregman loss as defined in \"Weidong Liu, Xi Luo, Fast and adaptive sparse precision matrix estimation in high dimensions, Journal of Multivariate Analysis, Volume 135, 2015, Pages 153-162\"\n#'\n#' @param sigma Covariance matrix Sigma\n#' @param theta Precision matrix Theta\n#' @return Bregman loss\nbregman_loss <- function(sigma, theta)\n{\n return(tr(sigma %*% theta) - log(det(theta)))\n}\n\n#' Computation of the Sparse Columnwise Inverse Operator (SCIO) estimator tuned via the Bregman loss: We pick the regularization parameter that minimizes the Bregman loss.\n#'\n#' @param data Data matrix of size n x d \n#' @return SCIO estimator\n#' @export \nscio_bregman <- function(data)\n{\n empvar <- var(data)\n seq_r <- seq(0.05, max(abs(empvar[upper.tri(empvar)])), length.out = 40)\n \n bregman <- rep(0, length(seq_r))\n for(j in 1:length(seq_r))\n {\n bregman[j] <- bregman_loss(empvar, scio(empvar, lambda=seq_r[j])$w)\n }\n best_r <- seq_r[which.min(bregman)]\n return(scio(empvar, lambda=best_r)$w)\n}\n\n#' Computation of the adaptive validation SCIO\n#' \n#' @param data Data matrix of size n x d\n#' @param C constant C that is used to calibrate the AV regularization parameter\n#' @return The selected regularization parameter\n#' @return The resulting AV-SCIO estimate\n#' @export\nav_scio <- function(data, C=0.7)\n{\n empvar <- var(data)\n max_r <- max(abs(empvar[upper.tri(empvar)]))\n seq_r <- seq(0.05, max_r, length.out = 40)\n #initialization\n r <- max(seq_r)\n estimates <- list()\n \n \n estimates[[length(seq_r)]] <- normalize_theta(scio(empvar, lambda=r)$w)\n \n counter_r <- length(seq_r) #used to fill the list estimates with corresponding estimates\n while(r != min(seq_r))\n {\n counter_r <- counter_r - 1\n r <- seq_r[counter_r]\n estimates[[counter_r]] <- normalize_theta(scio(empvar, lambda=r)$w)\n \n \n counter_r_dash <- length(seq_r)\n r_dash <- seq_r[counter_r_dash]\n while(r_dash > r)\n {\n #if l(...) > Cr_dash + Cr\n if(avtest(estimates, seq_r, counter_r, counter_r_dash, C))\n {\n return(list(TuningParameter=seq_r[counter_r + 1], Thetahat=estimates[[counter_r + 1]]))\n }\n counter_r_dash <- counter_r_dash - 1\n r_dash <- seq_r[counter_r_dash]\n }\n }\n return(list(TuningParameter=seq_r[1], Thetahat=estimates[[1]]))\n}\n\n\n#' Computes the reweighted l1 regularization to compute the graphical lasso with power law regularization (Liu & Ihler(2011)).\n#' \n#' @param est Estimation of Theta from the previous iteration\n#' @param alpha Regularization parameter\n#' @return The reweighted penalties as a dxd matrix. \n#' @export\npenalty_matrix <- function(est, alpha)\n{\n d <- dim(est)[1]\n eps <- diag(est) \n lambda <- matrix(rep(0, d*d), ncol=d)\n for(j in 1:(d-1))\n {\n for(i in j:d)\n {\n if(i==j)\n {\n lambda[i, i] <- 0\n }\n else\n {\n lambda[i, j] <- lambda[j, i] <- alpha * ( 1/(sum(abs(est[i, ])) + eps[i]) + 1/(sum(abs(est[j, ])) + eps[j]))\n }\n }\n }\n return(lambda)\n}\n\n#' Computes the graphical lasso with power law regularization sf_glasso (Liu & Ihler(2011)).\n#' \n#' @param data Data matrix of size n x d\n#' @param alpha Regularization parameter\n#' @return Graphical lasso with power law regularization\n#' @export\nsf_glasso <- function(data, alpha)\n{\n d <- dim(data)[2]\n est <- diag(d)\n empvar <- var(data)\n for(j in 1:3)\n {\n rho <- penalty_matrix(est, alpha)\n est <- glasso(empvar, rho=rho)$wi\n }\n return(est)\n}\n\n#' Computes the graphical lasso with power law regularization and regularization parameter tuned via adaptive validation sf_glasso (AV).\n#' \n#' @param data Data matrix of size n x d\n#' @param C Constant C used to tune the thAV. Default value is 1.5\n#' @return Graphical lasso with power law regularization and regularization parameter tuned via adaptive validation\n#' @export \nav_sf_glasso <- function(data, C=1.5)\n{\n empvar <- var(data)\n max_r <- 0.8#max(abs(empvar[upper.tri(empvar)]))\n seq_r <- seq(0.01, max_r, length.out = 40)\n #initialization\n r <- max(seq_r)\n estimates <- list()\n \n estimates[[length(seq_r)]] <- normalize_theta(sf_glasso(data, r))\n \n counter_r <- length(seq_r) #used to fill the list estimates with corresponding estimates\n while(r != min(seq_r))\n {\n counter_r <- counter_r - 1\n r <- seq_r[counter_r]\n estimates[[counter_r]] <- normalize_theta(sf_glasso(data, r))\n \n counter_r_dash <- length(seq_r)\n r_dash <- seq_r[counter_r_dash]\n while(r_dash > r)\n {\n #if l(...) > Cr_dash + Cr\n if(avtest(estimates, seq_r, counter_r, counter_r_dash, C))\n {\n return(list(TuningParameter=seq_r[counter_r + 1], Thetahat=estimates[[counter_r + 1]]))\n }\n counter_r_dash <- counter_r_dash - 1\n r_dash <- seq_r[counter_r_dash]\n }\n }\n return(list(TuningParameter=seq_r[1], Thetahat=estimates[[1]]))\n}\n", "meta": {"hexsha": "05fe579baf9228b1e68a4006ba4b1abc4b69f642", "size": 12207, "ext": "r", "lang": "R", "max_stars_repo_path": "R/av_estimation.r", "max_stars_repo_name": "MikeLasz/thav", "max_stars_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/av_estimation.r", "max_issues_repo_name": "MikeLasz/thav", "max_issues_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/av_estimation.r", "max_forks_repo_name": "MikeLasz/thav", "max_forks_repo_head_hexsha": "cc533ef7bb7ba6b2968e8955567059129506828e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4654255319, "max_line_length": 210, "alphanum_fraction": 0.6702711559, "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6352017944283969}} {"text": "# Generates artificial threads with models of Gomez 2010 and Gomez 2013\n# author: Alberto Lumbreras\n################################\n\nlibrary(igraph)\nlibrary(dplyr)\nsource('R/plotting.r')\n\ngen.thread.Gomez2011 <- function(n=100, alpha.root=1, alpha.c = 1, beta.root = 1){\n # Generate synthetic thread according to Gomez 2011\n # Args:\n # n: number of posts\n # alpha: preferential attachement exponent\n # beta: root bias\n g <- graph.empty(n=1)\n \n # First post has no choice\n g <- add_vertices(g, 1)\n g <- add_edges(g, c(2,1))\n \n for (i in 3:n){\n alphas <- c(alpha.root, rep(alpha.c, i-2))\n betas <- c(beta.root, rep(1, i-2))\n popularities <- 1 + degree(g, mode=\"in\")\n \n # Probability of choosing every node (only one is chosen)\n probs <- (betas*popularities)^alphas\n probs <- probs/sum(probs)\n j <- sample(1:length(probs), 1, prob=probs)\n \n # Add new vertex attached to the chosen node\n g <- add_vertices(g, 1)\n g <- add_edges(g, c(i,j))\n } \n g\n}\n\n\ngen.thread.Gomez2013 <- function(n=100, alpha=1, beta = 1, tau=0.75){\n # Generate synthetic thread according to Gomez 2011\n # Args:\n # n: number of posts\n # alpha: preferential attachement exponent\n # beta: root bias\n g <- graph.empty(n=1)\n \n # First post has no choice\n g <- add_vertices(g, 1)\n g <- add_edges(g, c(2,1))\n \n for (i in 3:n){\n betas <- c(beta, rep(0, i-2))\n lags <- (i-1):1\n popularities <- 1 + degree(g, mode=\"in\") # even root starts with degree 1\n \n # Probability of choosing every node (only one is chosen)\n probs <- alpha*popularities + betas + tau^lags\n probs <- probs/sum(probs)\n j <- sample(1:length(probs), 1, prob=probs)\n \n # Add new vertex attached to the chosen node\n g <- add_vertices(g, 1)\n g <- add_edges(g, c(i,j))\n }\n V(g)$user <- 1 # for compatibility with Lumbreras\n g\n}\n\ngen.thread.Lumbreras2016 <- function(n=100, z=c(1,2,3), alphas = c(1,2,3), betas = c(1,2,3), taus = c(0.25, 0.5, 0.75)){\n # Generate threads like in Gomez 2013 but from a mixture model where users\n # in one component have different parameters (alpha, beta, tau) than users in the\n # other component\n # then for each post chose a random user and then pick the parameters of its group\n # Args:\n # n: number of posts\n # alpha: preferential attachement exponent\n # beta: root bias\n nusers <- length(z)\n g <- graph.empty(n=1)\n \n # First post has no choice\n g <- add_vertices(g, 1)\n g <- add_edges(g, c(2,1))\n \n # the user of the two first posts is irrelevant for us\n V(g)$user <- 1 \n \n for (i in 3:n){\n # choose random user\n u <- sample(nusers, 1)\n cluster <- z[u]\n alpha <- alphas[cluster]\n beta <- betas[cluster]\n tau <- taus[cluster]\n \n bs <- c(beta, rep(0, i-2))\n lags <- (i-1):1\n popularities <- 1 + degree(g, mode=\"in\") # even root starts with degree 1\n \n # Probability of choosing every node (only one is chosen)\n probs <- alpha*popularities + bs + tau^lags\n probs <- probs/sum(probs)\n \n j <- sample(1:length(probs), 1, prob=probs)\n \n # Add new vertex attached to the chosen node\n g <- add_vertices(g, 1, attr=list('user'= u))\n g <- add_edges(g, c(i,j))\n } \n g\n}\n\ntree.to.data <- function(g, thread=0){\n # Creates a dataframe with a row per post\n # and columns \"degree of parent\", \"is_parent_root\", \"lag to parent\", and \"t\"\n # With the model parameters, the three first columns are used to compute the numerator the likelihood\n # and 't' to compute the denominator of the likelihood\n parents <- get.edgelist(g)[,2] # parents vector without the first two posts\n authors <- V(g)$user[-1] # remove first post\n popularities <- c(1,sapply(2:length(parents), function(t) 1 + sum(parents[1:(t-1)]==parents[t])))\n #popularities[parents==1] <- popularities[parents==1]-1 # the root node has no parent\n posts <- 2:(length(parents)+1)\n data <- data.frame(thread = rep(thread, length(posts)),\n user = authors,\n post = posts,\n t = 1:(length(parents)),\n parent = parents,\n popularity = popularities)\n \n data <- mutate(data, lag=t-parent+1)\n data\n}\n\n\n# Generate a synthetic dataset of trees\n#######################################\nif(FALSE){\n n <- 100\n \n alpha.root <- 0.734\n alpha.c <- 0.683\n beta.root <- 1.302\n trees <- replicate(n, gen.thread.Gomez2011(n=20, alpha.root=alpha.root, alpha.c=alpha.c, beta.root=beta.root), simplify = FALSE)\n \n alpha <- 1\n beta <- 0.68\n tau <- 0.75\n trees <- replicate(100, gen.thread.Gomez2013(n=100, alpha=alpha, beta=beta, tau=tau), simplify = FALSE)\n \n # Synthetic trees for Lumbreras 2016\n set.seed(1)\n alphas <- c(1,2,3)\n betas <- c(1,2,3)\n taus <- c(0.25, 0.5, 0.75)\n z <- c(1,2,3,1,2,3,1,2,3,1,2,3)\n trees <- replicate(1000, gen.thread.Lumbreras2016(n=100, z=z, alphas=alphas, betas=betas, taus=taus), simplify = FALSE)\n \n # Very simple synthetic trees for Lumbreras 2016\n set.seed(1)\n alphas <- c(0.1,0.5)\n betas <- c(0.1,0.5)\n taus <- c(0.1, 0.5)\n z <- c(1,2)\n \n set.seed(1)\n alphas <- c(0.1, 0.5, 1)\n betas <- c(1, 5, 10)\n taus <- c(0.1, 0.5, 0.99)\n z <- do.call(c, lapply(1:length(alphas), function(x) rep(x,10000)))\n \n # the parallel way\n library(parallel)\n cl <- makeCluster(detectCores()-2) \n clusterEvalQ(cl, {library(igraph); source('thread_generator.r')})\n clusterExport(cl, c(\"alphas\", \"betas\", \"taus\", \"z\"))\n trees <- parLapply(cl, 1:20000, function(i) gen.thread.Lumbreras2016(n=25, z=z, alphas=alphas, betas=betas, taus=taus) )\n stopCluster(cl)\n \n save(trees, file='trees.Rda')\n \n \n # Create dataframe from a set of trees\n ############################################################\n # Prepare all the information needed into a nice dataframe\n library(parallel)\n ncores <- detectCores() - 2\n cl<-makeCluster(ncores, outfile=\"\", port=11439)\n clusterEvalQ(cl, {library(igraph); library(dplyr)})\n data.parlapply <- parLapply(cl, trees, tree.to.data)\n stopCluster(cl)\n \n # join results adding thread id\n for (i in 1:length(data.parlapply)){\n data.parlapply[[i]]$thread <- i\n }\n data.parlapply <- rbindlist(data.parlapply)\n df.trees <- data.frame(thread = data.parlapply$thread, \n user = data.parlapply$user,\n post = data.parlapply$post,\n t = data.parlapply$t,\n parent = data.parlapply$parent,\n popularity = data.parlapply$popularity,\n lag = data.parlapply$lag)\n \n save(df.trees, file='df.trees.Rda')\n \n}\n\n# Generate and plot some synthetic tree\n########################################\nTEST <- FALSE\nif(TEST){\n # Values reported in Gomze 2010 (Table 2)\n # Slashdot: \n alpha.root <- 0.734\n alpha.c <- 0.683\n beta.root <- 1.302\n \n # Barrapunto\n alpha.root <- 0.665\n alpha.c <- -0.116\n beta.root <- 0.781\n \n # Meneame\n alpha.root <- 0.856\n alpha.c <- 0.196\n beta.root <- 1.588\n \n # Wikipedia\n alpha.root <- 0.884\n alpha.c <- -1.684\n beta.root <- 0.794\n \n trees <- replicate(4, gen.thread.Gomez2011(n=100, alpha.root=alpha.root, alpha.c=alpha.c, beta.root=beta.root), simplify = FALSE)\n \n \n alpha <- 1\n beta <- 0.68\n tau <- 0.75\n trees <- replicate(4, gen.thread.Gomez2013(n=100, alpha=alpha, beta=beta, tau=tau), simplify = FALSE)\n \n trees <- replicate(4, gen.thread.Lumbreras2016(n=100), simplify = FALSE)\n \n par(mfrow=c(2,2))\n for (i in 1:length(trees)){\n g <- trees[[i]]\n root = which(degree(g, mode='out')==0)\n V(g)$color <- 'black'\n V(g)$color[root] <- 'red'\n V(g)$size <- 1\n V(g)$size[root] <- 3\n g.un <- as.undirected(g)\n la = layout_with_fr(g.un)\n plot(g.un, layout = la, vertex.label = NA, edge.arrow.size=0.6)\n }\n}", "meta": {"hexsha": "f046ae381cb5eaca93e4d2e45226ec908a39a8f8", "size": 7816, "ext": "r", "lang": "R", "max_stars_repo_path": "R/thread_generators.r", "max_stars_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_stars_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_stars_repo_licenses": ["MIT"], "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/thread_generators.r", "max_issues_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_issues_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_issues_repo_licenses": ["MIT"], "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/thread_generators.r", "max_forks_repo_name": "alumbreras/dynamic-thread-stochastic-model", "max_forks_repo_head_hexsha": "96b7943754bcdba688391244f4fc8251a60a36ce", "max_forks_repo_licenses": ["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.53125, "max_line_length": 132, "alphanum_fraction": 0.5972364381, "num_tokens": 2496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6351778991971618}} {"text": "### The idea is to get score residuals from the score vector ###\n\n# a function to get score residiuals from the fitted model\n# (the code are taking directly from `orm.fit`)\nfunc_score <- function(fit){\n \n # coefficients\n coef <- fit$coefficients\n \n # convert y to ordered category\n y <- match(fit$y, fit$yunique)\n # x\n x <- fit$x\n \n # some useful numbers\n kint <- length(fit$yunique) - 1L\n nx <- dim(x)[2L]\n n <- length(y)\n p <- as.integer(kint + nx)\n \n # store results - matrix\n u <- matrix(0, nrow = n, ncol=p)\n \n # functions\n f <- fit$trans$cumprob\n fp <- fit$trans$deriv\n \n \n xb <- fit$x %*% coef[-(1L : kint)]\n ints <- c(1e100, coef[1:kint], -1e100)\n xby <- xb + ints[y]; xby1 <- xb + ints[y + 1L]\n fa <- f(xby)\n fb <- f(xby1)\n P <- fa - fb\n fpa <- fp(xby, fa)\n fpb <- fp(xby1, fb)\n \n # score for alpha\n for(m in 1:kint){\n for(j in 1:n){\n u[j, m] <- (fpa[j]*(y[j]-1==m) - fpb[j]*(y[j]==m)) / P[j]\n }\n }\n \n # score for beta\n for(m in (kint+1):p){\n for(j in 1:n){\n u[j, m] <- (fpa[j] - fpb[j]) * x[j,m-kint] / P[j]\n }\n }\n \n return(u)\n \n}\n\n\nfunc_robcov <- function(fit, cluster){\n var <- vcov(fit, intercepts='all')\n vname <- dimnames(var)[[1]]\n \n # X <- as.matrix(residuals(fit, type=\"score\"))\n X <- func_score(fit) # get score residuals\n \n n <- nrow(X)\n \n cluster <- as.factor(cluster)\n \n p <- ncol(var)\n j <- is.na(X %*% rep(1, ncol(X)))\n if(any(j)) {\n X <- X[! j,, drop=FALSE]\n cluster <- cluster[! j, drop=TRUE]\n n <- length(cluster)\n }\n \n j <- order(cluster)\n X <- X[j, , drop=FALSE]\n clus.size <- table(cluster)\n # if(length(clusterInfo)) clusterInfo$n <- length(clus.size)\n clus.start <- c(1, 1 + cumsum(clus.size))\n nc <- length(levels(cluster))\n clus.start <- clus.start[- (nc + 1)]\n storage.mode(clus.start) <- \"integer\"\n \n # dyn.load(\"robcovf.so\")\n W <- matrix(.Fortran(\"robcovf\", n, p, nc, clus.start, clus.size, X, \n double(p), double(p * p), w=double(p * p))$w, nrow=p)\n \n ##The following has a small bug but comes close to reproducing what robcovf does\n # W <- tapply(X,list(cluster[row(X)],col(X)),sum)\n # W <- t(W) %*% W\n \n #The following logic will also do it, also at great cost in CPU time\n # W <- matrix(0, p, p)\n # for(j in levels(cluster)){\n # s <- cluster==j\n # if(sum(s)==1){\n # sx <- X[s,,drop=F]\n # }else {sx <- apply(X[s,,drop=F], 2, sum); dim(sx) <- c(1,p)}\n # W <- W + t(sx) %*% sx\n # }\n \n adjvar <- var %*% W %*% var\n \n return(adjvar)\n}\n\n\n\n### test ###\nif(FALSE) {\n# generate longitudinal data\nlibrary(mvtnorm)\nlibrary(rms)\ndata_gen <- function(n=100, m=10, b=beta, a0=0.7){\n # correlation matrix - exchangeable structure\n G <- matrix(rep(a0, m*m), nrow=m)\n diag(G) <- 1\n \n stdevs <- rep(1,m)\n e <- rmvnorm(n, mean = rep(0,m), \n sigma = G * matrix(outer(stdevs, stdevs), nrow=m, byrow=TRUE))\n\n # x1: gender (0: female, 1: male)\n x1 <- rep(c(rep(0,round(n/2)), rep(1,n-round(n/2))), m)\n \n # x2: time\n x2 <- rep(c(1:m), each=n)\n \n y <- b[1] + b[2] * x1 + b[3] * x2 + e\n \n dat <- data.frame(y=c(y), \n x1=c(x1), \n x2=c(x2), \n id=rep(1:n, m))\n \n return(dat)\n}\n\n# data\ndat <- data_gen(n=50, m=10, b=beta, a0=0.7)\n# model\nmod_orm <- orm(y ~ x1 + x2,\n data = dat,\n x=T, y=T)\n# robcov\nrob.cov <- robcov(fit = mod_orm,\n cluster = dat$id)\nrob.cov\n}\n", "meta": {"hexsha": "34ab5e0fef68e9b4048f1ffcd95a7eb2fd85ff08", "size": 3480, "ext": "r", "lang": "R", "max_stars_repo_path": "SilveR/R/library/rms/tests/robcov_Yuqi.r", "max_stars_repo_name": "robalexclark/SilveR-Dev", "max_stars_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SilveR/R/library/rms/tests/robcov_Yuqi.r", "max_issues_repo_name": "robalexclark/SilveR-Dev", "max_issues_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SilveR/R/library/rms/tests/robcov_Yuqi.r", "max_forks_repo_name": "robalexclark/SilveR-Dev", "max_forks_repo_head_hexsha": "263008fdb9dc3fdd22bfc6f71b7c092867631563", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-31T18:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T18:42:06.000Z", "avg_line_length": 23.0463576159, "max_line_length": 82, "alphanum_fraction": 0.524137931, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6350474568712555}} {"text": "closestPair<-function(x,y)\n {\n distancev <- function(pointsv)\n {\n x1 <- pointsv[1]\n y1 <- pointsv[2]\n x2 <- pointsv[3]\n y2 <- pointsv[4]\n sqrt((x1 - x2)^2 + (y1 - y2)^2)\n }\n pairstocompare <- t(combn(length(x),2))\n pointsv <- cbind(x[pairstocompare[,1]],y[pairstocompare[,1]],x[pairstocompare[,2]],y[pairstocompare[,2]])\n pairstocompare <- cbind(pairstocompare,apply(pointsv,1,distancev))\n minrow <- pairstocompare[pairstocompare[,3] == min(pairstocompare[,3])]\n if (!is.null(nrow(minrow))) {print(\"More than one point at this distance!\"); minrow <- minrow[1,]}\n cat(\"The closest pair is:\\n\\tPoint 1: \",x[minrow[1]],\", \",y[minrow[1]],\n \"\\n\\tPoint 2: \",x[minrow[2]],\", \",y[minrow[2]],\n \"\\n\\tDistance: \",minrow[3],\"\\n\",sep=\"\")\n c(distance=minrow[3],x1.x=x[minrow[1]],y1.y=y[minrow[1]],x2.x=x[minrow[2]],y2.y=y[minrow[2]])\n }\n", "meta": {"hexsha": "76870ff90b3733510472e41801df23962f4d85d2", "size": 904, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-2.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Closest-pair-problem/R/closest-pair-problem-2.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 43.0476190476, "max_line_length": 107, "alphanum_fraction": 0.5807522124, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6347274522650832}} {"text": "conv <- function(a, b) {\n\tp <- length(a)\n\tq <- length(b)\n\tn <- p + q - 1\n\tr <- nextn(n, f=2)\n\ty <- fft(fft(c(a, rep(0, r-p))) * fft(c(b, rep(0, r-q))), inverse=TRUE)/r\n\ty[1:n]\n}\n\ndeconv <- function(a, b) {\n\tp <- length(a)\n\tq <- length(b)\n\tn <- p - q + 1\n\tr <- nextn(max(p, q), f=2)\n\ty <- fft(fft(c(a, rep(0, r-p))) / fft(c(b, rep(0, r-q))), inverse=TRUE)/r\n\treturn(y[1:n])\n}\n", "meta": {"hexsha": "f84997524fd0be0391f1f501da689428c0fd9179", "size": 375, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Deconvolution-1D/R/deconvolution-1d-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/Deconvolution-1D/R/deconvolution-1d-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/Deconvolution-1D/R/deconvolution-1d-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": 20.8333333333, "max_line_length": 74, "alphanum_fraction": 0.48, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896671963207, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.6347054777224233}} {"text": "#' Bootstrap Methods\n#'\n#' @param x numeric vector.\n#' @param weights numeric vector of weight\n#' @param boot how many bootstrap sample is generated?\n#' @param alpha significant value to construct confidential interval\n#' @param seed seed value\n#' @param bca logical. use bias corrected and accelerated (BCa) bootstrap\n#' to construct confidential intervals.\n#'\n#' @importFrom stats na.omit\n#' @importFrom stats sd\n#' @importFrom stats quantile\n#' @importFrom stats qnorm\n#' @importFrom stats pnorm\n#' @examples\n#' \\dontrun{\n#' x <- rnorm(100)\n#' bootstrap(x, boot = 1000)\n#' }\n#' \nbootstrap <- function(x,\n weights,\n boot = 100,\n alpha = 0.05,\n seed = 120511,\n bca = FALSE) {\n # output list\n output <- list()\n # observation information\n x <- na.omit(x)\n n <- length(x)\n output$n <- n\n if (missing(weights)) weights <- rep(1, n)\n output$mu <- mean(x * weights) / mean(weights)\n\n # bootstrap\n set.seed(seed)\n bootmu <- lapply(seq_len(boot), function(i) {\n pick <- sample(seq_len(n), size = n, replace = TRUE)\n bx <- x[pick]\n bw <- weights[pick]\n mean(bx * bw) / mean(bw)\n })\n bootmu <- unlist(bootmu)\n output$boot$distribution <- bootmu\n\n # bootstrap standard error\n output$boot$se <- sd(bootmu)\n\n # bootstrap CI\n output$boot$ci$alpha <- alpha\n if (!bca) {\n # quantile bootstrap\n output$boot$ci$method <- \"quantile\"\n output$boot$ci$interval <- quantile(\n bootmu, probs = c(alpha / 2, 1 - alpha / 2)\n )\n } else {\n # Bias corrected and accelerated (BCa) bootstrap\n # reference: https://www.erikdrysdale.com/bca_python/\n output$boot$ci$method <- \"BCa\"\n\n # bias-correction factor\n z0 <- qnorm(mean(bootmu < output$mu), lower.tail = TRUE)\n\n # acceleration factor by jackknife\n jack <- lapply(seq_len(n), function(i) mean(x[-i]))\n jack <- unlist(jack)\n jack_mean <- mean(jack)\n a <- sum((jack_mean - jack)^3) / (6 * sum((jack_mean - jack)^2)^(3 / 2))\n\n # quantile point of normal distribution\n za1 <- qnorm(alpha, lower.tail = TRUE)\n za2 <- qnorm(1 - alpha, lower.tail = TRUE)\n # bias corrected quantile point\n a1 <- pnorm(\n z0 + (z0 + za1) / (1 - a * (z0 + za1))\n )\n a2 <- pnorm(\n z0 + (z0 + za2) / (1 - a * (z0 + za2))\n )\n\n output$boot$ci$correction.factor <- z0\n output$boot$ci$acceleration.factor <- a\n output$boot$ci$interval <- quantile(bootmu, probs = c(a1, a2))\n }\n output\n}\n\n#' Permutation test\n#'\n#' @param y numeric vector of outcome\n#' @param d numeric vector of treatment indicator (contain 1 and 0 only)\n#' @param weights numeric vector of weights\n#' @param boot how many re-randomization are generated\n#' @param seed seed value\n#'\n#' @examples\n#' \\dontrun{\n#' y1 <- 2 + rnorm(20, sd = 4)\n#' y0 <- rnorm(20, sd = 4)\n#' d <- sample(c(1, 0), replace = TRUE, size = 40)\n#' y <- ifelse(d == 1, y1, y0)\n#' permutation(y, d, boot = 200)\n#' }\n#'\npermutation <- function(y,\n d,\n weights,\n boot = 100,\n seed = 120511) {\n # check same length of outcome and treatment vector\n if (length(y) != length(d)) stop(\"Same length of y and d\")\n\n # check binary treatment indicator\n if (!(all(unique(d) %in% c(1, 0)))) {\n stop(\"d must be binary indicator of treated.\")\n }\n\n # create weight vector if missing\n weights <- rep(1, length(y))\n\n # check missing values\n na_y <- !is.na(y)\n na_d <- !is.na(d)\n na_w <- !is.na(weights)\n keep <- na_y & na_d & na_w\n\n # use vector\n y <- y[keep]\n w <- weights[keep]\n d <- d[keep]\n\n y1 <- y[d == 1]\n y0 <- y[d == 0]\n w1 <- w[d == 1]\n w0 <- w[d == 0]\n\n # output list\n output <- list()\n\n # information\n n1 <- sum(d == 1)\n n0 <- sum(d == 0)\n output$treat$N <- n1\n output$control$N <- n0\n\n mean_y1 <- mean(y1 * w1) / mean(w1)\n mean_y0 <- mean(y0 * w0) / mean(w0)\n obs_diff_mean <- mean_y1 - mean_y0\n\n output$treat$mean <- mean_y1\n output$control$mean <- mean_y0\n output$ate$estimate <- obs_diff_mean\n\n # re-randomization\n output$ate$method <- \"permutation test\"\n set.seed(seed)\n bootdiff <- lapply(seq_len(boot), function(i) {\n sim_treated <- sample(seq_len(n1 + n0), size = n1)\n simd <- rep(0, n1 + n0)\n simd[sim_treated] <- 1\n\n simy1 <- y[simd == 1]\n simy0 <- y[simd == 0]\n simw1 <- w[simd == 1]\n simw0 <- w[simd == 0]\n\n sim_mean_y1 <- mean(simy1 * simw1) / mean(simw1)\n sim_mean_y0 <- mean(simy0 * simw0) / mean(simw0)\n sim_mean_y1 - sim_mean_y0\n })\n bootdiff <- unlist(bootdiff)\n output$ate$re.random <- bootdiff\n\n # exact test\n pval <- mean(abs(bootdiff) >= abs(obs_diff_mean))\n output$ate$p.value <- pval\n\n output\n}\n", "meta": {"hexsha": "0a3e1a4e2d4f162d91a1a9601bb325ebbbf8b405", "size": 4740, "ext": "r", "lang": "R", "max_stars_repo_path": "R/internal-bootstrap.r", "max_stars_repo_name": "KatoPachi/discreteRD", "max_stars_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/internal-bootstrap.r", "max_issues_repo_name": "KatoPachi/discreteRD", "max_issues_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/internal-bootstrap.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": 25.9016393443, "max_line_length": 76, "alphanum_fraction": 0.5879746835, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6346013324829963}} {"text": "# ......................................................................................\n# ................Cvičení 6 - Vybraná rozdělení spojité náhodné veličiny................\n# ..................Martina Litschmannová, Adéla Vrtková, Michal Béreš..................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Přehled rozdělení a jejich funkcí ####\n# * Úvod: Hustota pravděpodobnosti, Distribuční funkce a Kvantilová funkce ####\n# ** Hustota pravděpodobnosti ####\n# - začíná písmenkem **d**: p = d...(x, ...)\n# \n# ** Distribuční funkce ####\n# - začíná písmenkem **p**: $p = P(X < x)$: p = p...(x, ...)\n# \n# ** Kvantilová funkce ####\n# - začíná písmenkem **q**: najdi x pro zadané p: $p = F(x) \\rightarrow x = F^{-1}(p)$:\n# x = q...(p, ...)\n\n\n# * Rovnoměrné rozdělení: $X \\sim Ro(a, b)$ ####\n# - náhodná veličina nabývá pouze hodnot větších než a a menších než b\n# - všechny hodnoty mají stejnou hustotu výskytu -> hustota pravděpodobnosti je\n# konstantní mezi a a b, jinde nulová\n\n\n# Hustota pravděpodobnosti f(x)\na = 2 # odkud \nb = 4 # kam\nx = 3 \ndunif(x, a, b)\n\n# vykreslíme si Hustotu pravděpodobnosti\nx = seq(from = 0, to = 6, by = 0.01)\nf_x = dunif(x, a, b)\nplot(x, f_x, cex = 0.1) # cex je velikost markerů\ngrid()\n\n# Distribuční funkce F(x) = P(X < x)\na = 2 # odkud \nb = 4 # kam\nx = 3 \npunif(x, a, b)\n\n# vykreslíme si Distribuční funkci\nx = seq(from = 0, to = 6, by = 0.01)\nF_x = punif(x, a, b)\nplot(x, F_x, type = 'l')\ngrid()\n\n# kvantilová funkce F^(-1)(p) = x: P(X exponenciální rozdělení\nx = 5\ndweibull(x,shape=beta, scale=theta)\n\n# vykreslíme si Hustotu pravděpodobnosti\nx = seq(from = 0, to = 6, by = 0.01)\nf_x = dweibull(x,shape=beta, scale=theta)\nplot(x, f_x, type='l')\ngrid()\n\n# Distribuční funkce F(x) = P(X < x)\ntheta = 3 # ekvivalent 1/lambda u exp. rozdělení\nbeta = 2 # beta = 1 -> exponenciální rozdělení\nx = 5\npweibull(x,shape=beta, scale=theta)\n\n# vykreslíme si Distribuční funkci\nx = seq(from = 0, to = 6, by = 0.01)\nF_x = pweibull(x,shape=beta, scale=theta)\nplot(x, F_x, type = 'l')\ngrid()\n\n# kvantilová funkce F^(-1)(p) = x: P(X exponenciální rozdělení\np = 0.5\nqweibull(p,shape=beta, scale=theta)\n\n# vykreslení - kvantilová funkce F^(-1)(p) = x\np = seq(from=0, to=1, by=0.01) \nx = qweibull(p,shape=beta, scale=theta)\nplot(p, x, type = 'l')\ngrid()\n\n# * Normální rozdělení: $X \\sim N(\\mu,\\sigma^2)$ ####\n# - rozdělení modelující např. chyby měření, chování součtu/průměru mnoha jiných\n# náhodných veličin\n# - viz. Centrální limitní věta\n# - $\\mu$ je přímo střední hodnota rozdělení: $E(X)=\\mu$\n# - $\\sigma$ je přímo směrodatná odchyla rozdělení: $D(X)=\\sigma^2$ \n# - s parametry $\\mu=0,\\sigma=1$ se nazývá normované Normální rozdělení\n\n\n# Hustota pravděpodobnosti f(x)\nmu = 2\nsigma = 3\nx = 4\ndnorm(x, mean=mu, sd=sigma)\n\n# vykreslíme si Hustotu pravděpodobnosti\nx = seq(from = -5, to = 10, by = 0.01)\nf_x = dnorm(x, mean=mu, sd=sigma)\nplot(x, f_x, type='l')\ngrid()\n\n# Distribuční funkce F(x) = P(X < x)\nmu = 2\nsigma = 3\nx = 4\npnorm(x, mean=mu, sd=sigma)\n\n# vykreslíme si Distribuční funkci\nx = seq(from = -5, to = 10, by = 0.01)\nF_x = pnorm(x, mean=mu, sd=sigma)\nplot(x, F_x, type = 'l')\ngrid()\n\n# kvantilová funkce F^(-1)(p) = x: P(X35000)=1-F(35000)\n1 - pexp(35000, lambda)\n\n# ** c) ####\n# dobu, do níž se porouchá 95 % součástek.\n\n\n#c) P(X F(t)=0,95 -> t… 95% kvantil\nqexp(0.95, lambda)\n\n# * Příklad 3. ####\n# Výrobní zařízení má poruchu v průměru jednou za 2000 hodin. Veličina Y představující\n# dobu čekání na poruchu má exponenciální rozdělení. Určete dobu T0 tak, aby\n# pravděpodobnost, že přístroj bude pracovat delší dobu než T0, byla 0,99.\n\n\n# X ... doba čekání na poruchu (h)\n# X ~ Exp(lambda), kde E(X)=1/lambda\nlambda = 1/2000\n\n#P(X>t)=0,99 -> 1-F(t)=0,99 -> F(t)=0,01 -> t… 1% kvant.\nqexp(0.01, lambda)\n\n# * Příklad 4. ####\n# Výsledky měření jsou zatíženy jen normálně rozdělenou chybou s nulovou střední\n# hodnotou a se směrodatnou odchylkou 3 mm. Jaká je pravděpodobnost, že při 3 měřeních\n# bude alespoň jednou chyba v intervalu (0 mm; 2,4mm)?\n\n\n# Y… velikost chyby měření (mm)\n# Y ~ N(mu = 0,sigma = 3)\n\nmu = 0\nsigma = 3\n\n# pp… pravd., že chyba měření bude v int. 0,0-2,4mm\npp = pnorm(2.4,mean=mu,sd=sigma) - pnorm(0,mean=mu,sd=sigma)\npp\n\n# X … počet chyb měření v int. 0 mm -2,4 mm ve 3 měř.\n# X ~ Bi(n = 3,p = pp)\nn = 3\np = pp\n\n# P(X>=1)=1-P(X=0)\n1 - dbinom(0, n, p)\n\n# * Příklad 5. ####\n# Ve velké počítačové síti se průměrně přihlašuje 25 uživatelů za hodinu. Určete\n# pravděpodobnost,\n# že:\n# ** a) ####\n# se nikdo nepřihlásí během 14:30 - 14:36,\n\n\n# X … počet uživatelů přihlášených za 6 minut\n# X ~ Po(lt = 2.5)\n\nlambda = 25/60\nt = 6\nlt = lambda*t\n\n# P(X=0)\ndpois(0, lt)\n\n# ** b) ####\n# do dalšího přihlášení uběhnou 2-3 minuty.\n\n\n# Y … doba do dalšího přihlášení\n# Y ~ Exp(lambda = 25/60), kde E(X)=1/lambda\nlambda = 25/60 \n\n# P(2t)=0,90 -> 1-F(t)=0,90 -> F(t)=0,10 -> t…10% kv.\n\nqexp(0.10, lambda)*60\n\n# * Příklad 6. ####\n# Náhodná veličina X má normální rozdělení N(µ; σ). Určete:\n# ** a) ####\n# P(µ − 2σ < X < µ + 2σ),\n\n\n# P(µ − 2σ < X < µ + 2σ) = F(µ + 2σ) - F(µ - 2σ)\n# X~N(µ,σ)\n# je jedno jaké hodnoty zvolíme\nmu = -105.5447 \nsigma = 2.654\n\npnorm(mu + 2*sigma, mean=mu, sd=sigma) - \npnorm(mu - 2*sigma, mean=mu, sd=sigma)\n\n# ** b) ####\n# nejmenší k ∈ Z, tak, aby P(µ − kσ < X < µ + kσ) > 0,99.\n\n\n# normální rozdělení je symetrické \n# P(µ − kσ < X < µ + kσ) = \n# = 1 - (P(X < µ − kσ ) + P(X > µ + kσ)) = \n# = 1 - 2*P(X > µ + kσ) = 0.99 -> P(X > µ + kσ) = 0.005\n# -> P(X < µ + kσ) = 0.995\n\n# x = µ + kσ\nx = qnorm(0.995, mean=mu, sd=sigma)\n(x - mu)/sigma\n\nfor(k in 1:5){\n p = pnorm(mu + k*sigma, mean=mu, sd=sigma) - \n pnorm(mu - k*sigma, mean=mu, sd=sigma)\n print(paste0(k,\":\",p))\n}\n\n# * Příklad 7. ####\n# Na prohlídce výstavy je promítán doprovodný film o životě autora vystavovaných děl.\n# Jeho projekce začíná každých 20 minut. Určete pravděpodobnost, že pokud náhodně\n# přijdete do promítacího sálu,\n\n\n# Y … doba do začátku další projekce\n# Y ~ Ro(a=0, b=20)\n\na = 0\nb = 20\n\n# ** a) ####\n# nebudete na začátek filmu čekat víc než 5 minut,\n\n\n# P(X<5)\npunif(5, a, b)\n\n# ** b) ####\n# budete čekat mezi 5 a 10 minutami,\n\n\n# P(5700)=1-F(700)\nP.J = 1-pnorm(700,mean=mu_J,sd=sigma_J)\nP.J\n\n# P(A)=P(SA>700)=1-F(700)\nP.A = 1-pnorm(700,mean=mu_A, sd=sigma_A)\nP.A\n\n# KJ … Jakub se kvalifikuje na závody, \n# P(KJ) = 1-(1-P(J))(1-P(J))\nP.KJ=1-(1-P.J)*(1-P.J)\nP.KJ\n\n# KA … Aleš se kvalifikuje na závody, \n# P(KA) = 1-(1-P(A))(1-P(A))\nP.KA=1-(1-P.A)*(1-P.A)\nP.KA\n\n# ** a) ####\n# S jakou pravděpodobností se oba dva kvalifikují na závody?\n\n\n# ada)\nP.KJ*P.KA\n\n# ** b) ####\n# S jakou pravděpodobností se kvalifikuje Aleš, ale Jakub ne?\n\n\n# adb)\n(1-P.KJ)*P.KA\n\n\n\n", "meta": {"hexsha": "fd0e08de558f00c491a29350f79c69615eae4ffb", "size": 10908, "ext": "r", "lang": "R", "max_stars_repo_path": "CV6/cv6.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": "CV6/cv6.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": "CV6/cv6.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": 23.6616052061, "max_line_length": 88, "alphanum_fraction": 0.613953062, "num_tokens": 5148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6345864250451192}} {"text": "queens <- function(n) {\n a <- seq(n)\n u <- rep(T, 2 * n - 1)\n v <- rep(T, 2 * n - 1)\n m <- NULL\n aux <- function(i) {\n if (i > n) {\n m <<- cbind(m, a)\n } else {\n for (j in seq(i, n)) {\n k <- a[[j]]\n p <- i - k + n\n q <- i + k - 1\n if (u[[p]] && v[[q]]) {\n u[[p]] <<- v[[q]] <<- F\n a[[j]] <<- a[[i]]\n a[[i]] <<- k\n aux(i + 1)\n u[[p]] <<- v[[q]] <<- T\n a[[i]] <<- a[[j]]\n a[[j]] <<- k\n }\n }\n }\n }\n aux(1)\n m\n}\n", "meta": {"hexsha": "3332e6a59544d7460d32f376c1069b8757c09f60", "size": 538, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/N-queens-problem/R/n-queens-problem-1.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/N-queens-problem/R/n-queens-problem-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/N-queens-problem/R/n-queens-problem-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5517241379, "max_line_length": 33, "alphanum_fraction": 0.2434944238, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.6345182218829304}} {"text": "#######################################################################\n#######################################################################\n#######################################################################\n###### ######\n###### Routines for simulation of high-dimensionsal ######\n###### multivariate normals ######\n###### ######\n#######################################################################\n#######################################################################\nrbigmvn.setup <- function(mu,covfunc,covpars,Sigmalist,coords,\n groups,neighbours,nNN,MaxDist,coord.type,\n method=\"Gibbs\",vars.to.monitor) {\n#######################################################################\n#\n# To set up the quantities required to simulate from a \n# high-dimensional multivariate normal distribution using\n# routine rbigmvnorm. Arguments:\n#\n# mu mean vector of the distribution\n# covfunc Name of a function to compute covariances between\n# pairs of points. This function itself should have\n# two arguments: the first a vector of parameters,\n# and the second a matrix of \"co-ordinates\" or \n# covariates. Denoting the parameter vector by theta,\n# and the co-ordinates for variable i by x[i], the \n# covariance between variables i and j can be\n# computed as f(x[i],x[j],theta). It should return a\n# matrix of covariances. Note that the argument\n# \"Sigmalist\" (see below) offers an alternative\n# way to define the covariance structure. \n# covpars Vector of parameters for the covariance function\n# coords Matrix giving the \"coordinates\" or covariate values\n# for each variable, for use when evaluating the \n# covariance function. Row i corresponds to variable \n# i; the number of rows should match the length of mu.\n# groups A numeric vector, the same length as mu, containing group\n# numbers. Variables in the same group will be simulated\n# as a block within each Gibbs sampler iteration. If \n# there are M groups then they must be numbered from \n# 1 to M.\n# neighbours A list of M vectors, where M is the number of groups.\n# The jth element of this list should be a vector of \n# indices for the variables that are not in group j but\n# are in its neighbourhood. This argument should not\n# be supplied if either nNN or MaxDist is provided;\n# but it must be supplied if neither of these is provided.\n# nNN Optional scalar, giving the number of nearest neighbours\n# to include in the neighbourhood of each group. If supplied,\n# then distfunc must also be supplied; and neither \n# neighbours nor MaxDist should be supplied. Conversely,\n# if this is not supplied then either neighbours or \n# MaxDist must be supplied\n# MaxDist Optional scalar, or vector of length M (number of groups)\n# giving the maximum distance to consider as being within \n# the neighbourhood of each group. A variable will be \n# considered as in the neighbourhood of a group if it is\n# within MaxDist of at least one site in the group, but \n# not otherwise. If this argument is supplied, then\n# distfunc must also be supplied; and neither neighbours \n# nor nNN should be supplied. Conversely, if this is not \n# supplied then either neighbours or nNN must be supplied\n# Sigmalist An optional list of covariance matrices, with length M\n# where M is the total number of groups. This should not\n# be used if cov.func is supplied. If provided, its jth \n# element should be the covariance matrix of all pairs of \n# variables within both group j and its neighbours (as defined \n# via the \"neighbours\" argument, which must therefore be \n# provided in this case). The ordering of variables in \n# this matrix must correspond with that in the full joint\n# distribution (i.e. it consists of the rows and columns\n# of the full covariance matrix corresponding to the \n# current group and its neighbours).\n# Note that the routine does *not* check that the elements\n# of the list are in mutual agreement (for example, that\n# the supplied covariance between any pair of sites is the\n# same for all groups where that pair appears). It is the\n# user's responsibility to check this, therefore.\n# coord.type Either \"geographical\" (if coords is a two-column\n# matrix containing latitudes and longitudes - NB in \n# this case the first column should be latitude) or\n# \"euclidean\". This controls how distances between \n# variables are calculated.\n# method Either \"Gibbs\" or \"factorize\". If \"Gibbs\", the routine\n# will set things up for a Gibbs sampler; if \"factorize\"\n# then it will set things up so that simulation is done\n# in a single pass (no iteration) using factorisation of\n# the full joint distribution into products of conditionals.\n# The latter is potentially quicker, but this increase in\n# speed may be offset by the need to specify considerably\n# larger neighbourhoods in order to achieve the same \n# level of accuracy.\n# vars.to.monitor An optional vector of indices in the range\n# 1:length(mu). If provided, the routine will \n# calculate the quantities needed to produce a trace \n# plot of the logarithm of the joint density of the \n# corresponding variables during random variate \n# generation when method=\"Gibbs\". This allows \n# convergence monitoring. \n#\n# Note that if neighbourhoods are defined using nNN or MaxDist, it\n# becomes necessary to calculate all of the pairwise intersite distances,\n# which has a computational cost quadratic in the number of sites ...\n#\n#######################################################################\n#\n# Checks on inputs and set up storage for results\n#\n p <- length(mu)\n if (!is.matrix(coords)) stop(\"coords must be a matrix\")\n if (nrow(coords) != p) {\n stop(\"coords has wrong number of rows - should be length(mu)\")\n }\n if (length(groups) != p) stop(\"groups should have same length as mu\")\n M <- max(groups)\n if (!all(sort(unique(groups))==1:M)) {\n stop(\"groups should be numbered from 1 to M where M is total number of groups\")\n }\n if (missing(covfunc)) {\n if (missing(Sigmalist)) stop(\"Either covfunc or Sigmalist must be supplied\")\n } else {\n if (!is.function(covfunc)) stop(\"covfunc should be the name of a function\")\n }\n if (as.numeric(missing(neighbours))+as.numeric(missing(nNN))+\n as.numeric(missing(MaxDist)) != 2) {\n stop(\"You must provide exactly one of neighbours, nNN and MaxDist\")\n }\n if (!missing(neighbours)) {\n if (!is.list(neighbours)) stop(\"neighbours must be a list\")\n if (length(neighbours) != M) {\n stop(\"neighbours must have a list element for each group\")\n }\n }\n if (!missing(nNN)) {\n if (!(length(nNN) %in% c(1,M))) {\n stop(\"nNN must be either a scalar, or a vector with an element for each group\")\n }\n }\n if (!missing(MaxDist)) {\n if (!(length(MaxDist) %in% c(1,M))) {\n stop(\"MaxDist must be either a scalar, or a vector with an element for each group\")\n }\n }\n if (!missing(Sigmalist)) {\n if (!missing(covfunc)) stop(\"Only one of covfunc and Sigmalist can be specified\")\n if (missing(neighbours)) stop(\"'neighbours' must be specified when using 'Sigmalist'\")\n if (length(Sigmalist) != M) stop(\"Length of Sigmalist doesn't match number of groups\")\n }\n if (coord.type==\"geographical\") {\n distfunc <- howfar\n } else if (coord.type==\"euclidean\") {\n distfunc <- function(coords1,coords2) {\n sqrt(outer(coords1[,1],coords2[,1],\"-\")^2 +\n outer(coords1[,2],coords2[,2],\"-\")^2)\n }\n } else {\n stop(\"coord.type must be either 'geographical' or 'euclidean'\")\n }\n cat(paste(\"Tested all inputs and these are ok\\n\"))\n \n group.details <- matrix(0,nrow=M,ncol=p)\n Sig12.Sig22Inv <- CondCovChol <- vector(\"list\",M)\n#\n# Set up neighbourhood structures for each group\n#\n for (i in 1:M) {\n cat(paste(\"Working on block\",i,\"of\",M,\"... \\n\"))\n group.details[i,groups==i] <- 1 # in network stations=1\n if (!missing(neighbours)) {\n tmp <- neighbours[[i]]\n tmp <- tmp[!(tmp %in% (1:p)[groups==i])] # double check no neighbours are actual stations?\n group.details[i,tmp] <- 2 # network neighbours =2? \n }\n if (!missing(nNN)) {\n nNN.cur <- nNN\n if (length(nNN) > 1) nNN.cur <- nNN[i]\n dist.cur <- distfunc(coords[groups==i,],coords[groups!=i,])\n min.dist <- apply(dist.cur,MARGIN=2,FUN=min)\n wanted.sites <- order(min.dist)[1:nNN.cur]\n tmp <- (1:p)[groups!=i]\n group.details[i,tmp[wanted.sites]] <- 2\n }\n if (!missing(MaxDist)) {\n MD.cur <- MaxDist\n if (length(MaxDist) > 1) MD.cur <- MaxDist[i]\n dist.cur <- distfunc(coords[groups==i,],coords[groups!=i,])\n wanted.sites <- (dist.cur <= MD.cur)\n tmp <- (1:p)[groups!=i]\n group.details[i,tmp[wanted.sites]] <- 2\n }\n#\n# Now set up the components of the partitioned covariance matrix, and \n# required Choleski factors. The variables to condition on are the ones\n# that are in the neighbourhood of the current group and, if method\n# method=\"factorize\", that are also in lower-numbered groups (because \n# these will already have been allocated by the time we get to the \n# current group).\n#\n\n# Use this whereever you want to stop with access to variables\n# browser()\n\n if (method==\"Gibbs\") {\n wanted.vars <- (group.details[i,]>0)\n } else if (method==\"factorize\") {\n wanted.vars <- (group.details[i,]>0 & groups <= i)\n } else {\n stop(\"method must be either 'Gibbs' or 'factorize'\")\n }\n if (missing(Sigmalist)) {\n Sigma <- covfunc(covpars,coords[wanted.vars,])\n } else {\n Sigma <- Sigmalist[[i]]\n \n if (nrow(Sigma) != sum(group.details[i,]>0)) {\n stop(paste(\"Dimensions of Sigmalist[[\",i,\n \"]] don't match required number of variables\",sep=\"\"))\n }\n if (method==\"factorize\") { # Get rid of elements for \n tmp <- (groups[group.details[i,]>0] <= i) # groups that haven't been \n Sigma <- matrix(Sigma[tmp,tmp],\n\t nrow=length(which(tmp==TRUE)),\n\t\t ncol=length(which(tmp==TRUE))) # done yet\n }\n }\n# cat(paste(\"Now in the block and working on Sigma\",i,\"\\n\",sep=\"\"))\n\n tmp <- group.details[i,wanted.vars]\n# Sig11 <- matrix(Sigma[tmp==1,tmp==1],nrow=length(which(tmp==1)),ncol=length(which(tmp==1)))\n# Sig12 <- matrix(Sigma[tmp==1,tmp==2],nrow=length(which(tmp==1)),ncol=length(which(tmp==1)))\n# Sig22 <- matrix(Sigma[tmp==2,tmp==2],nrow=length(which(tmp==1)),ncol=length(which(tmp==1)))\n Sig11 <- Sigma[tmp==1,tmp==1]\n Sig12 <- Sigma[tmp==1,tmp==2]\n Sig22 <- Sigma[tmp==2,tmp==2]\n \t# for first few there may be no neighbours\n# print(tmp)\n #print(length(tmp))\n# if (nrow(Sig22)>0) {\n if (length(which(tmp==2))>0) {\n Sig12.Sig22Inv[[i]] <- Sig12 %*% solve(Sig22)\n CondCovChol[[i]] <- chol(Sig11 - tcrossprod(Sig12.Sig22Inv[[i]],Sig12))\n } else {\n CondCovChol[[i]] <- chol(Sig11)\n }\n }\n#\n# Choleski factor of inverse of covariance matrix for monitoring \n# locations\n#\n if (!missing(vars.to.monitor)) {\n if (!(method == \"Gibbs\")) {\n warning(\"argument vars.to.monitor is only used when method='Gibbs'\")\n SigInvChol <- NULL\n vtm <- NULL\n } else {\n Sigma <- covfunc(covpars,coords[vars.to.monitor,])\n SigInvChol <- solve(chol(Sigma))\n vtm <- vars.to.monitor\n }\n } else {\n SigInvChol <- NULL\n vtm <- NULL\n }\n invisible(list(mu=mu,groups=groups,group.details=group.details,\n Sig12.Sig22Inv=Sig12.Sig22Inv,CondCovChol=CondCovChol,\n SigInvChol=SigInvChol,method=method,vars.to.monitor=vtm))\n}\n#######################################################################\n#######################################################################\n#######################################################################\nrbigmvnorm <- function(n,setup,nburnin=0,nthin=1,init,monitor=FALSE) {\n#######################################################################\n#\n# To simulate from a high-dimensional multivariate normal \n# distribution. Arguments:\n#\n# n Number of realisations required\n# setup A list object containing all of the information\n# required to carry out the simulation. This \n# should be produced via a call to rbigmvn.setup\n# nburnin Number of Gibbs Sampler iterations to use as \"burnin\".\n# Only used if setup$method=\"Gibbs\".\n# nthin Thinning rate for the sampler after the burnin period:\n# the n returned values will correspong to iterations\n# nburnin+nthin, nburnin+(2*nthin), ... , nburnin+(n*nthin)\n# Only used if setup$method=\"Gibbs\".\n# init Starting value for the Gibbs sampler. If supplied, \n# this can be used (for example) to generate further \n# draws from a chain that is already known to have \n# converged to its limiting distribution, thereby\n# eliinating the need for any further burnin.\n# Only used if setup$method=\"Gibbs\".\n# monitor A logical scale indicated whether to produce a \n# trace plot of the logarithm of the joint density \n# for the variables defined by setup$vars.to.monitor.\n# The purpose is to assess convergence of the Gibbs \n# sampler. To produce the plot *does* slow down the \n# iterations, however. Only used if setup$method=\"Gibbs\".\n#\n#######################################################################\n p <- length(setup$mu)\n M <- nrow(setup$group.details)\n if (!missing(init)) {\n if (length(init) != p) stop(\"Lengths of 'init' and 'mu' don't match\")\n }\n if (monitor & is.null(setup$vars.to.monitor)) {\n warning(\"No monitoring variables defined - trace plot will not be produced\")\n monitor <- FALSE\n }\n sim <- matrix(nrow=n,ncol=p)\n#\n# Initialisation if we're using a Gibbs sampler\n#\n if (setup$method==\"Gibbs\") {\n logL <- rep(0,nburnin+(n*nthin))\n ntt <- nthin\n if (missing(init)) {\n cat(\"Initialising Gibbs sampler ... \\r\")\n z <- rep(NA,p)\n for (i in 1:M) {\n wanted <- (setup$groups==i)\n e <- rnorm(sum(wanted))\n z[wanted] <- setup$mu[wanted] + (setup$CondCovChol[[i]] %*% e)\n }\n } else {\n z <- init\n }\n#\n# Burnin for Gibbs sampler\n#\n for (iter in (if (nburnin < 1) NULL else 1:nburnin)) {\n cat(paste(\"Gibbs sampler burnin period: iteration\",iter,\"of\",nburnin,\"...\\r\"))\n for (i in 1:M) {\n wanted <- (setup$groups==i)\n mu1 <- setup$mu[wanted]\n y2 <- z[setup$group.details[i,]==2]\n mu2 <- setup$mu[setup$group.details[i,]==2]\n e <- rnorm(length(mu1))\n z[wanted] <- mu1 + (setup$Sig12.Sig22Inv[[i]] %*% (y2-mu2)) + \n t(setup$CondCovChol[[i]]) %*% e\n } \n if (monitor) {\n logL[iter] <- -sum((t(setup$SigInvChol) %*% \n (z[setup$vars.to.monitor]-\n setup$mu[setup$vars.to.monitor]))^2)/2\n }\n }\n if (monitor) {\n pp <- 1/(nburnin+(nthin*n))\n ylim <- -0.5*qchisq(c(pp,1-pp),df=length(setup$vars.to.monitor))\n if (nburnin > 0) ylim <- c(ylim,logL[1:nburnin])\n ylim <- extendrange(ylim)\n plot(1:(nburnin+(nthin*n)),type=\"n\",xlab=\"Iteration\",ylab=\"Score\",\n main=\"Gibbs sampler iterations: log-density score for monitoring variables\",\n ylim=ylim)\n abline(v=nburnin,col=\"red\")\n if (nburnin > 0) lines(1:nburnin,logL[1:nburnin])\n } else {\n ntt <- 1\n }\n }\n\n for (cur.sim in 1:n) {\n cat(paste(\"Generating sample\",cur.sim,\"of\",n,\"... \\r\"))\n if (setup$method == \"factorize\") z <- rep(NA,p)\n for (iter in 1:nthin) {\n for (i in 1:M) {\n wanted <- (setup$groups==i)\n mu1 <- setup$mu[wanted]\n e <- rnorm(length(mu1))\n if (setup$method==\"Gibbs\") {\n cond.vars <- (setup$group.details[i,]==2)\n } else if (setup$method==\"factorize\") {\n cond.vars <- (setup$group.details[i,]==2) & (setup$groups < i)\n }\n if (sum(cond.vars) > 0) {\n y2 <- z[cond.vars]\n mu2 <- setup$mu[cond.vars]\n z[wanted] <- mu1 + (setup$Sig12.Sig22Inv[[i]] %*% (y2-mu2)) + \n t(setup$CondCovChol[[i]]) %*% e\n } else {\n z[wanted] <- mu1 + t(setup$CondCovChol[[i]]) %*% e\n }\n } \n if (monitor & setup$method==\"Gibbs\") {\n cur.idx <- nburnin + ((cur.sim-1)*ntt) + iter\n logL[cur.idx] <- -sum((t(setup$SigInvChol) %*% \n (z[setup$vars.to.monitor]-\n setup$mu[setup$vars.to.monitor]))^2)/2\n if (cur.idx > 1) lines(c(cur.idx-1,cur.idx),logL[c(cur.idx-1,cur.idx)])\n }\n }\n sim[cur.sim,] <- z\n }\n sim\n}\n######################################################################\n######################################################################\n######################################################################\nhowfar <- function(sites1,sites2,units=\"km\") {\n######################################################################\n#\n# Function to calculate the distance between sets of points on the \n# earth's surface, with co-ordinates given in latitude and longitude.\n# Arguments:\n#\n# sites1 A matrix with 2 columns, indicating the (lat, long)\n#\t\tcoordinates of each site in the first set (in \n#\t\tdegrees!)\n# sites2\tThe same for the second set of sites\n# units\t\tEither \"km\" (the default) or \"nm\" for distances in \n#\t\tnautical miles (*not* nanometers!)\n#\n# Value:\tA matrix of distances, with rows corresponding to \n#\t\tthe sites in sites1 and columns corresponding to \n#\t\tthose in sites2. If sites1 and sites2 have row names,\n#\t\tthese are copied over as appropriate\n######################################################################\n n1 <- dim(sites1)[1]; n2 <- dim(sites2)[1]\n z <- matrix(nrow=n1,ncol=n2)\n rownames(z) <- rownames(sites1) \n colnames(z) <- rownames(sites2) \n pi180 <- pi/180\n for (i in 1:n1) {\n lat1 <- sites1[i,1]\n long1 <- sites1[i,2]\n lat2 <- sites2[,1]\n long2 <- sites2[,2]\n z[i,] <- sin(sites1[i,1]*pi180)*sin(sites2[,1]*pi180) + \n cos(sites1[i,1]*pi180)*cos(sites2[,1]*pi180) * \n cos((sites2[,2]-sites1[i,2])*pi180)\n#\n# Next line deals with rounding errors that take the previous\n# line slightly outside the range (-1,1)\n#\n z[i,] <- (60*180/pi)*acos(pmax(pmin(z[i,],1),-1))\n }\n if (units == \"km\") {\n z <- 1.852*z\n } else if (units != \"nm\") {\n stop(\"units must be either 'km' or 'nm'\")\n }\n z\n}\n", "meta": {"hexsha": "5eb675b232c79af8871efd8416622001596c05dd", "size": 19577, "ext": "r", "lang": "R", "max_stars_repo_path": "BigMVNgen.r", "max_stars_repo_name": "ISTI-Benchmarking/ISTI_Clean_Worlds", "max_stars_repo_head_hexsha": "139f9eac04e9af87e94402814f1201adac290372", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BigMVNgen.r", "max_issues_repo_name": "ISTI-Benchmarking/ISTI_Clean_Worlds", "max_issues_repo_head_hexsha": "139f9eac04e9af87e94402814f1201adac290372", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BigMVNgen.r", "max_forks_repo_name": "ISTI-Benchmarking/ISTI_Clean_Worlds", "max_forks_repo_head_hexsha": "139f9eac04e9af87e94402814f1201adac290372", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0923423423, "max_line_length": 96, "alphanum_fraction": 0.55994279, "num_tokens": 4950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6345182104561867}} {"text": "# Name: Barnabas Forgo\n# Email: psybf@nottingham.ac.uk\n# Student ID: 4211949\n\nrequire(FuzzyToolkitUoN);\nrequire(rgl);\n\nfis1 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, trapMF( \"low\", c(0:10), c(0, 0, 1, 3, 1)));\n fis= addMF(fis, \"input\", 2, trapMF( \"mild\", c(0:10), c(1, 4, 6, 9, 1)));\n fis= addMF(fis, \"input\", 2, trapMF(\"severe\", c(0:10), c(7, 9, 10, 10, 1))); \n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(15, 0, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(15, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(15, 100, 1)));\n\n rulelist = rbind(\n c(1,4,3,1,1), # IF temperature is very low THEN urgency is emergency\n c(2,4,2,1,1), # IF temperature is low THEN urgency is medium\n c(3,4,1,1,1), # IF temperature is normal THEN urgency is very low\n c(4,4,2,1,1), # IF temperature is high THEN urgency is medium\n c(5,4,3,1,1) # IF temperature is very high THEN urgency is emergency \n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\nfis2 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, trapMF( \"low\", c(0:10), c(0, 0, 1, 3, 1)));\n fis= addMF(fis, \"input\", 2, trapMF( \"mild\", c(0:10), c(1, 4, 6, 9, 1)));\n fis= addMF(fis, \"input\", 2, trapMF(\"severe\", c(0:10), c(7, 9, 10, 10, 1))); \n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(15, 0, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(15, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(15, 100, 1)));\n\n rulelist = rbind(\n c(1,4,3,1,1),\n \n c(2,1,1,1,1),\n c(2,2,2,1,1),\n c(2,3,3,1,1),\n \n c(3,1,1,1,1),\n c(3,2,1,1,1),\n c(3,3,2,1,1),\n \n c(4,1,1,1,1),\n c(4,2,2,1,1),\n c(4,3,3,1,1),\n \n c(5,4,3,1,1)\n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\nfis3 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"medium\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"severe\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF(\"very severe\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(15, 0, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(15, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(15, 100, 1)));\n\n rulelist = rbind(\n c(1,6,3,1,1),\n \n c(2,1,1,1,1),\n c(2,2,1,1,1),\n c(2,3,2,1,1),\n c(2,4,2,1,1),\n c(2,5,3,1,1),\n \n c(3,1,1,1,1),\n c(3,2,1,1,1),\n c(3,3,1,1,1),\n c(3,4,2,1,1),\n c(3,5,2,1,1),\n \n c(4,1,1,1,1),\n c(4,2,1,1,1),\n c(4,3,2,1,1),\n c(4,4,2,1,1),\n c(4,5,3,1,1),\n \n c(5,6,3,1,1)\n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\nfis4 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, gaussMF( \"very low\", c(0:10), c(1, 0, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"low\", c(0:10), c(1, 2.5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"medium\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF( \"severe\", c(0:10), c(1, 7.5, 1)));\n fis= addMF(fis, \"input\", 2, gaussMF(\"very severe\", c(0:10), c(1, 10, 1)));\n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"very low\", c(0:100), c(10, 0, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(10, 25, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(10, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"high\", c(0:100), c(10, 75, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(10, 100, 1)));\n\n rulelist = rbind(\n c(1,6,5,1,1),\n \n c(2,1,1,1,1),\n c(2,2,1,1,1),\n c(2,3,2,1,1),\n c(2,4,3,1,1),\n c(2,5,4,1,1),\n \n c(3,1,1,1,1),\n c(3,2,1,1,1),\n c(3,3,1,1,1),\n c(3,4,2,1,1),\n c(3,5,4,1,1),\n \n c(4,1,1,1,1),\n c(4,2,1,1,1),\n c(4,3,2,1,1),\n c(4,4,3,1,1),\n c(4,5,4,1,1),\n \n c(5,6,5,1,1)\n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\nfis5 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, -1, 1.5)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 8, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 11, 1.5)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, triMF( \"very low\", seq(0, 10, by=0.1), c(0,0,2.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"low\", seq(0, 10, by=0.1), c(0,2.5,5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"mild\", seq(0, 10, by=0.1), c(2.5,5,7.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"severe\", seq(0, 10, by=0.1), c(5,7.5,10,1)));\n fis= addMF(fis, \"input\", 2, triMF(\"very severe\", seq(0, 10, by=0.1), c(7.5,10,10,1)));\n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"very low\", c(0:100), c(10, -15, 3)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(10, 25, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(10, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"high\", c(0:100), c(10, 75, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(10, 115, 3)));\n\n rulelist = rbind(\n c(1,6,5,1,1),\n \n c(2,1,1,1,1),\n c(2,2,1,1,1),\n c(2,3,2,1,1),\n c(2,4,3,1,1),\n c(2,5,4,1,1),\n \n c(3,1,1,1,1),\n c(3,2,1,1,1),\n c(3,3,1,1,1),\n c(3,4,2,1,1),\n c(3,5,4,1,1),\n \n c(4,1,1,1,1),\n c(4,2,1,1,1),\n c(4,3,2,1,1),\n c(4,4,3,1,1),\n c(4,5,4,1,1),\n \n c(5,6,5,1,1)\n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\nfis6 <- function() {\n fis= newFIS(\"emergency\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, -1, 1.5)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 8, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 11, 1.5)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, triMF( \"very low\", seq(0, 10, by=0.1), c(0,0,2.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"low\", seq(0, 10, by=0.1), c(0,2.5,5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"mild\", seq(0, 10, by=0.1), c(2.5,5,7.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"severe\", seq(0, 10, by=0.1), c(5,7.5,10,1)));\n fis= addMF(fis, \"input\", 2, triMF(\"very severe\", seq(0, 10, by=0.1), c(7.5,10,10,1)));\n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n \n fis= addMF(fis, \"output\", 1, gaussMF( \"very low\", c(0:100), c(10, -15, 3)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(10, 25, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(10, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"high\", c(0:100), c(10, 75, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(10, 115, 3)));\n\n rulelist = rbind(\n c(1,6,5,3,1),\n\n c(2,1,1,1,1),\n c(2,2,2,1,1),\n c(2,3,3,1,1),\n c(2,4,4,1,1),\n c(2,5,4,1,1),\n\n c(3,1,1,1,1),\n c(3,2,1,1,1),\n c(3,3,2,1,1),\n c(3,4,3,1,1),\n c(3,5,4,1,1),\n\n c(4,1,1,1,1),\n c(4,2,2,1,1),\n c(4,3,3,1,1),\n c(4,4,4,1,1),\n c(4,5,4,1,1),\n\n c(5,6,5,3,1) \n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\n\nfisFinal <- function() {\n fis= newFIS(\"emergency\", defuzzMethod=\"bisector\", impMethod=\"prod\")\n \n fis= addVar(fis,\"input\", \"temperature\", c(0, 10));\n \n fis= addMF(fis, \"input\", 1, gaussMF( \"very low\", c(0:10), c(1, -1, 1.5)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"low\", c(0:10), c(1, 2, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"normal\", c(0:10), c(1, 5, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF( \"high\", c(0:10), c(1, 8, 1)));\n fis= addMF(fis, \"input\", 1, gaussMF(\"very high\", c(0:10), c(1, 11, 1.5)));\n \n fis= addMF(fis, \"input\", 1, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n fis= addVar(fis,\"input\", \"headache\", c(0, 10));\n \n fis= addMF(fis, \"input\", 2, triMF( \"very low\", seq(0, 10, by=0.1), c(0,0,2.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"low\", seq(0, 10, by=0.1), c(0,2.5,5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"mild\", seq(0, 10, by=0.1), c(2.5,5,7.5,1)));\n fis= addMF(fis, \"input\", 2, triMF( \"severe\", seq(0, 10, by=0.1), c(5,7.5,10,1)));\n fis= addMF(fis, \"input\", 2, triMF(\"very severe\", seq(0, 10, by=0.1), c(7.5,10,10,1)));\n \n \n fis= addMF(fis, \"input\", 2, trapMF(\"undefined\", c(0:10), c(0,0,10,10, 1)));\n \n \n fis= addVar(fis, \"output\", \"urgency\", 0:100);\n fis= addMF(fis, \"output\", 1, gaussMF( \"very low\", c(0:100), c(10, -15, 3)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"low\", c(0:100), c(10, 25, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"medium\", c(0:100), c(10, 50, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF( \"high\", c(0:100), c(10, 75, 1)));\n fis= addMF(fis, \"output\", 1, gaussMF(\"emergency\", c(0:100), c(10, 115, 3)));\n \n \n rulelist = rbind(\n c(1,6,5,3,1), # IF temperature is very low THEN urgency is emergency\n \n c(2,1,1,1,1), # IF temperature is low AND headache is very low THEN urgenc#y is very low\n c(2,2,2,1,1), # IF temperature is low AND headache is low THEN urgency is low\n c(2,3,3,1,1), # IF temperature is low AND headache is mild THEN urgency is medium\n c(2,4,4,1,1), # IF temperature is low AND headache is severe THEN urgency is high\n c(2,5,4,1,1), # IF temperature is low AND headache is very severe THEN urgency is high\n \n c(3,1,1,1,1), # IF temperature is normal AND headache is very low THEN urgency is very low\n c(3,2,1,1,1), # IF temperature is normal AND headache is low THEN urgency is very low\n c(3,3,2,1,1), # IF temperature is normal AND headache is mild THEN urgency is low\n c(3,4,3,1,1), # IF temperature is normal AND headache is severe THEN urgency is medium\n c(3,5,4,1,1), # IF temperature is normal AND headache is very severe THEN urgency is high\n \n c(4,1,1,1,1), # IF temperature is high AND headache is very low THEN urgency is very low\n c(4,2,2,1,1), # IF temperature is high AND headache is low THEN urgency is low\n c(4,3,3,1,1), # IF temperature is high AND headache is mild THEN urgency is medium\n c(4,4,4,1,1), # IF temperature is high AND headache is severe THEN urgency is high\n c(4,5,4,1,1), # IF temperature is high AND headache is very severe THEN urgency is high\n \n c(5,6,5,3,1) # IF temperature is very high THEN urgency is emergency\n );\n fis= addRule(fis, rulelist);\n \n return(fis);\n}\n\nshowMFS <- function(fis) {\n par(mfrow=c(3,1));\n plotMF(fis,\"input\",1);\n plotMF(fis,\"input\",2);\n plotMF(fis,\"output\",1);\n}\n\nintsurf <- function(fis, ix1=1, ix2=2, ox1=1, accuracy=15) {\n\trequire(rgl);\n \n\ti1 = fis$inputList[[ix1]]\n\ti2 = fis$inputList[[ix2]]\n\to1 = fis$outputList[[ox1]]\n\n\ti1b = i1$inputBounds\n\ti2b = i2$inputBounds\n\n\ti1_min = i1b[1]\n\ti1_max = i1b[length(i1b)]\n\n\ti2_min = i2b[1]\n\ti2_max = i2b[length(i2b)]\n \n\tx_values = seq(i1_min, i1_max, length = accuracy)\n\ty_values = seq(i2_min, i2_max, length = accuracy)\n\t\n\tm_values = meshgrid(x_values, y_values)\n\n\to_values = evalFIS(cbind(c(m_values$x), c(m_values$y)), fis)\n\n\n\tz_values = matrix(o_values[,ox1], accuracy, accuracy, byrow=TRUE)\n\n plot3d(i1b, i2b, o1$outputBounds,\n xlab=i1$inputName, ylab=i2$inputName, zlab=o1$outputName,\n type='n'\n );\n \n zlim <- range(o1$outputBounds)\n zlen <- zlim[2] - zlim[1] + 1\n\n colorlut <- rainbow(zlen, start=2/6, end=0)\n\n col <- colorlut[ z_values-zlim[1]+1 ]\n \n surface3d(x_values, y_values, z_values, color=col, lit=T, smooth=F, shininess=128)\n # persp3d(x_values, y_values, z_values, color=col, lit=T, smooth=F, shininess=128)\n}\n\nprojectPng <- function(projectName, dir, ...) {\n # get a list of existing plots for the project\n plots <- list.files(path=dir, pattern=glob2rx(paste0(projectName, \"*.png\")))\n # pull out numeric component of the plot files\n nums <- as.numeric(gsub(paste(projectName, \".png\", sep=\"|\"), \"\", plots))\n last <- max(nums)\n if (last == -Inf) last <- 0;\n # Create a new file name with an incremented counter.\n newFile <- paste0(projectName, sprintf(\"%03d\", last + 1), \".png\")\n # now call png\n png(file.path(dir, newFile), ...)\n}\n\nfis= fisFinal();\n\n# projectPng(\"cw\", \"C:\\\\work\\\\fuz\", width=1000, height=1000, pointsize=20)\n# intsurf(fis, accuracy=20);\n# dev.off()\n# intsurf(fis, accuracy=100);\n# rgl.snapshot(\"C:\\\\work\\\\fuz\\\\lastfis.png\")\n# projectPng(\"cw\", \"C:\\\\work\\\\fuz\", width=800, height=1000, pointsize=20)\n# showMFS(fis);\n# dev.off()\n\n\nvalues= rbind(\n c(5,0), # 1\n c(3,0), # 2\n c(7,0), # 3\n c(5,3), # 4\n c(5,5), # 5\n c(5,7), # 6\n c(5,10), # 7\n c(0,5), # 8\n c(0,0), # 9\n c(10,5), #10\n c(0,10), #11\n c(10,0), #12\n c(10,10) #13\n )\n\nexpected= rbind(\n 0, # 1\n 0, # 2\n 0, # 3\n 15, # 4\n 25, # 5\n 50, # 6\n 75, # 7\n 100, # 8\n 100, # 9\n 100, #10\n 100, #11\n 100, #12\n 100 #13\n )\n\nrmse <- function(actual, expected) {\n return(sqrt(mean((actual - expected)^2)))\n}\n\n\nprint(rmse(evalFIS(values, fis1()), expected))\nprint(rmse(evalFIS(values, fis2()), expected))\nprint(rmse(evalFIS(values, fis3()), expected))\nprint(rmse(evalFIS(values, fis4()), expected))\nprint(rmse(evalFIS(values, fis5()), expected))\nprint(rmse(evalFIS(values, fis6()), expected))\nprint(rmse(evalFIS(values, fisFinal()), expected))\n", "meta": {"hexsha": "d35d26a20a7a662f5be484cf3f9ffc64c6ca02c7", "size": 17138, "ext": "r", "lang": "R", "max_stars_repo_path": "coursework/fis.r", "max_stars_repo_name": "SpeedoDevo/G53FUZ", "max_stars_repo_head_hexsha": "dba2176082fbb2c11b4191ee1df0d51cbf74cdca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-15T07:17:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T07:17:00.000Z", "max_issues_repo_path": "coursework/fis.r", "max_issues_repo_name": "SpeedoDevo/G53FUZ", "max_issues_repo_head_hexsha": "dba2176082fbb2c11b4191ee1df0d51cbf74cdca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coursework/fis.r", "max_forks_repo_name": "SpeedoDevo/G53FUZ", "max_forks_repo_head_hexsha": "dba2176082fbb2c11b4191ee1df0d51cbf74cdca", "max_forks_repo_licenses": ["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.3969754253, "max_line_length": 94, "alphanum_fraction": 0.5372272144, "num_tokens": 7841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6344420763806078}} {"text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\r\nwrite(round(pnorm(9800, 205 * 49, sqrt( 49 * (15 ^ 2) )), 4), stdout())", "meta": {"hexsha": "e1aabc95101118876994611ef1a11067044363e7", "size": 142, "ext": "r", "lang": "R", "max_stars_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849829.r", "max_stars_repo_name": "hermes-jr/my-hackerrank-solutions", "max_stars_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849829.r", "max_issues_repo_name": "hermes-jr/my-hackerrank-solutions", "max_issues_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849829.r", "max_forks_repo_name": "hermes-jr/my-hackerrank-solutions", "max_forks_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.0, "max_line_length": 71, "alphanum_fraction": 0.661971831, "num_tokens": 49, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6344228471404734}} {"text": "a <- 5.0\nl <- 2.0\n\nN <- 10000\ncentX <- a/2 * runif(N)\ncentY <- a/2 * runif(N)\nalpha <- runif(N, min=0, max=pi/2)\n\nif (l < a) {\n\tifx <- centX < l*cos(alpha)/2 \n\tify <- centY < l*sin(alpha)/2\n\tp <- mean(ifx | ify)\n\tprint(p)\n\tnewPi <- l^2 / (a^2 * p)\n\tprint(newPi)\n}\n", "meta": {"hexsha": "3916bb1594f16f3016d590c112ed200495411fac", "size": 264, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK1/sem1/needleCells.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TASK1/sem1/needleCells.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK1/sem1/needleCells.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.5294117647, "max_line_length": 34, "alphanum_fraction": 0.5151515152, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6344116013425789}} {"text": "a <- 5\nl <- 3\n\nN <- 100000\ncent_x <- a * runif(N)\nalpha <- runif(N, min=0, max=pi/2)\n\nmn <- mean(cent_x < l*cos(alpha))\nprint(mn)\nnew_pi <- 2 * l / (mn * a)\nprint(new_pi)\n", "meta": {"hexsha": "3ea83eb08438dd466a975f63a8bb16ae2eddfe51", "size": 171, "ext": "r", "lang": "R", "max_stars_repo_path": "needle.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "needle.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "needle.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.25, "max_line_length": 34, "alphanum_fraction": 0.5555555556, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.6342424643514039}} {"text": "## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n## population genetics\n## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nGset <- c(\"GG\",\"GT\",\"TT\")\nG_table <- expand.grid(Gf=Gset,Gm=Gset,GG=NA,GT=NA,TT=NA)\nG_table[1,Gset] <- c(1 , 0, 0)\nG_table[2,Gset] <- c(1/2, 1/2, 0)\nG_table[3,Gset] <- c(0 , 1, 0)\nG_table[4,Gset] <- c(1/2, 1/2, 0)\nG_table[5,Gset] <- c(1/4, 1/2, 1/4)\nG_table[6,Gset] <- c(0 , 1/2, 1/2)\nG_table[7,Gset] <- c(0 , 1, 0)\nG_table[8,Gset] <- c(0 , 1/2, 1/2)\nG_table[9,Gset] <- c(0 , 0, 1)\n\npGenoOffCond <- vector(\"list\",3)\nnames(pGenoOffCond) <- Gset\nfor (i in Gset) pGenoOffCond[[i]] <- t(subset(G_table, Gf==i)[,Gset])\n\np.offgenotype <- function(G_, Gf, pGm) {\n ## Look up the probability of an offspring genotype, given the maternal genotype and\n ## proportions of offspring sired by each paternal genotype.\n\n ## Args:\n ## G_: Offspring genotype.\n ## Gf: Maternal genotype.\n ## pGm: Relative fecundities of different male genotypes.\n\n ## Returns:\n ## The probability of offspring genotype G_.\n\n ## expect Gf to have length=1\n if (length(Gf) != 1)\n stop(\"offspring genotype function not vectorised for maternal genotype\")\n ## return the required probability\n return((pGenoOffCond[[Gf]] %*% pGm)[G_,1])\n}\n", "meta": {"hexsha": "0b1e8f633ac4d4753648f72f1a7c88146e45ee30", "size": 1402, "ext": "r", "lang": "R", "max_stars_repo_path": "code_r/imported/popgen_fun.r", "max_stars_repo_name": "tdjames1/soay_ibm", "max_stars_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_stars_repo_licenses": ["MIT"], "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/imported/popgen_fun.r", "max_issues_repo_name": "tdjames1/soay_ibm", "max_issues_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_issues_repo_licenses": ["MIT"], "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/imported/popgen_fun.r", "max_forks_repo_name": "tdjames1/soay_ibm", "max_forks_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_forks_repo_licenses": ["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.9487179487, "max_line_length": 100, "alphanum_fraction": 0.5228245364, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6341077104902498}} {"text": "###############################################################################\n# Copyright (C) 1994 - 2009, Performance Dynamics Company #\n# #\n# This software is licensed as described in the file COPYING, which #\n# you should have received as part of this distribution. The terms #\n# are also available at http://www.perfdynamics.com/Tools/copyright.html. #\n# #\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell #\n# copies of the Software, and permit persons to whom the Software is #\n# furnished to do so, under the terms of the COPYING file. #\n# #\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY #\n# KIND, either express or implied. #\n###############################################################################\n\n# Load the library\nlibrary(\"pdq\")\n#\n# Thruput bounds for closed tandem QNM with fixed Z\n# Created by NJG on Fri Feb 27, 2009\nclients = 200\nthink = 8 * 10^(-3) # ms as seconds\nstime = 500 * 10^(-3) # ms as seconds\nwork = \"w\"\nfor(k in list(1,20,50)) {\n xc<-0 # prudent to reset these\n yc<-0\n for (i in 1:clients) {\n Init(\"\")\n CreateClosed(work, TERM, as.double(i), think) \n # create k queueing nodes in PDQ\n for (j in 1:k) {\n \t nname = paste(\"n\",sep=\"\",j) # concat j to node name\n CreateNode(nname,CEN,FCFS)\n SetDemand(nname,work,stime)\n }\n Solve(APPROX)\n # set up for plotting in R\n xc[i]<-as.double(i)\n yc[i]<-GetThruput(TERM,work)\n nopt<-(k*stime+think)/stime\n }\n if (k==1) {\n \t# establish plot frame and first curve\n plot(xc, yc, type=\"l\", ylim=c(0,1/stime), lwd=2, xlab=\"N Clients\", \n ylab=\"Throughput X(N)\")\n title(\"Increasing Number (K) of Queues\")\n \tabline(0, 1/(nopt*stime), lty=\"dashed\", col=\"blue\")\n \tabline(1/stime, 0, lty=\"dashed\", col = \"red\")\n \tabline(v=nopt, lty=\"dashed\", col=\"gray50\") # grid line\n text(150,1.95,paste(\"K =\", k))\n \ttext(5+k,1.4,paste(\"N* =\",nopt),adj=c(0,0)) \n } else {\n \t# add the other curves\n \tpoints(xc, yc, type=\"l\", lwd=2)\n \tabline(0,1/(nopt*stime), lty=\"dashed\", col=\"blue\")\n \tabline(v=nopt, lty=\"dashed\", col=\"gray50\")\n \ttext(150,1.85-0.085*k/10, paste(\"K =\", k))\n \ttext(k+5,0.5-0.1*k/10,paste(\"N* =\",nopt),adj=c(0,0))\n }\n}\n\n\n", "meta": {"hexsha": "3d78729c8d3e12c2c14eed78b5cb34ed09918f7a", "size": 2722, "ext": "r", "lang": "R", "max_stars_repo_path": "R/moreq.r", "max_stars_repo_name": "peterlharding/PDQ", "max_stars_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:22:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T05:57:35.000Z", "max_issues_repo_path": "R/moreq.r", "max_issues_repo_name": "peterlharding/PDQ", "max_issues_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/moreq.r", "max_forks_repo_name": "peterlharding/PDQ", "max_forks_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-03-12T12:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-05T05:57:44.000Z", "avg_line_length": 42.53125, "max_line_length": 79, "alphanum_fraction": 0.4757531227, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6339277692889059}} {"text": "## Assignment 2 i.e Quiz 2 of R class##\n## Quiz 1##\ncube <- function(x, n) {\n x^3\n}\ncube(3)\n\n# Since no use of n in the function enviroments, so it is evaluated i.e function \n# does not depends on n, so there is no error at all.\n\n## Quiz 2 ##\n\nx<- 1:10\nif(x >5) {\n x <- 0\n}\n\n# since the value of x is vector and it could evaluate for first value only\n# Warning message:\n# In if (x > 5) { :\n# the condition has length > 1 and only the first element will be used\n\n\n\n#### Question 3 ####\nf <- function(x) {\n g <- function(y) {\n y + z\n }\n z <- 4\n x + g(x)\n}\n\nz <- 10\nf(3) # will call function g <- function(y) {y +z} in the function enviroment, \n# z <- 4; 3 + g(3), now function g called in function enviroment i.e 3 + 4 = 7\n# so, g (3) will return 7 and hence 3 + 7 = 10\n\n\n#### Question 4 ####\n\nx <- 5\ny <- if (x < 3) {\n NA\n} else {\n 10\n}\n\n\n### Programming Assignement 2###\n\n\nmakeVector <- function(x = numeric()) {\n m <- NULL\n set <- function(y) {\n x <<- y\n m <<- NULL\n }\n get <- function() x\n setmean <- function(mean) m <<- mean\n getmean <- function() m\n list(set = set, \n get = get,\n setmean = setmean,\n getmean = getmean)\n}\n\ncachemean <- function(x, ...) {\n m <- x$getmean()\n if(!is.null(m)) {\n message(\"getting cached data\")\n return(m)\n }\n data <- x$get()\n m <- mean(data, ...)\n x$setmean(m)\n m\n}\n\nmakeCacheMatrix <- function(x = matrix()) {\n ## Initialise the matrix.\n inverseMatrix <- NULL\n # set the given matrix\n set <- function(matrix) {\n m <<- matrix\n inverseMatrix <<- NULL\n }\n \n # Get the given matrix\n get <- function() {\n m\n }\n \n # find and set the inverse of the matrix\n setInverse <- function(solve) {\n inverseMatrix <<- solve\n }\n \n # Get the inverted matrix\n getInverse <- function() {\n inverseMatrix\n }\n \n # Return the list\n list(set = set,\n get = get,\n setInverse = setInverse,\n getInverse = getInverse\n )\n}\n\ncacheSolve <- function(x, ...) {\n ## Return a matrix that is the inverse of 'x'\n inverseMatrix <- x$getInverse()\n if(!is.null(inverseMatrix)) {\n message(\"getting cached inverse matrix\")\n return(inverseMatrix)\n }\n \n originalMatrix <- x$get()\n inverseMatrix <- solve(originalMatrix, ...)\n x$setInverse(inverseMatrix)\n inverseMatrix\n}\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "e624e72735dbd7a024aa74ac3201b5d3f6c6ceda", "size": 2824, "ext": "r", "lang": "R", "max_stars_repo_path": "quiz2.r", "max_stars_repo_name": "krishnaiitd/Rprogramming", "max_stars_repo_head_hexsha": "801097a2bb8f9b6672fd79a94f0be3b1b0f9fc6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-08-06T18:25:27.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-06T18:25:27.000Z", "max_issues_repo_path": "quiz2.r", "max_issues_repo_name": "krishnaiitd/Rprogramming", "max_issues_repo_head_hexsha": "801097a2bb8f9b6672fd79a94f0be3b1b0f9fc6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quiz2.r", "max_forks_repo_name": "krishnaiitd/Rprogramming", "max_forks_repo_head_hexsha": "801097a2bb8f9b6672fd79a94f0be3b1b0f9fc6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3939393939, "max_line_length": 101, "alphanum_fraction": 0.4723796034, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.8670357649558007, "lm_q1q2_score": 0.6338539237891879}} {"text": "#' rsq_1.1 - generate r-squared for observations relative to 1:1 line\n#'\n#' @param observed observed values of dependent variable.\n#' @param predicted predicted values of dependent variable.\n#'\n#' @return returns r-squared value for observed vs. predicted. Can be negative.\n#' @export\n#'\n#' @examples\nrsq_1.1 <- function(observed, predicted){\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 #calculate residual sums of squares relative to actual prediction (i.e. \"1:1 line\")\n SS.res <- sum((observed - predicted)^2)\n #calculate total sum of squares.\n SS.tot <- sum((observed - mean(observed))^2)\n #calculate rsq and return.\n rsq.1 <- 1 - SS.res/SS.tot\n return(rsq.1)\n}\n", "meta": {"hexsha": "f9802d16156aaa70d54f6eff55c50f411651e580", "size": 778, "ext": "r", "lang": "R", "max_stars_repo_path": "NEFI_functions/rsq_1.1.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/rsq_1.1.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/rsq_1.1.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": 37.0476190476, "max_line_length": 85, "alphanum_fraction": 0.6915167095, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.633698814428562}} {"text": "'\n\nsummaryw -> Return Heteroskedastic robust standard errors for \"model\".\n\nclx -> Return clustered-standard errors for \"fm\".\n\nwald.ci -> Return Wald Confidenceintervall for second \"coef\" of \"reg\"\n\nanderson.rubin.ci -> Return \"Anderson Rubin CI\" for \"ivmodel\" with sig. niveau \n \"conflevel\". Default is \"conflevel=.95\"\n\n'\n\n\nsummaryw = function(model) { \n '\n Return Heteroskedastic robust standard errors for \"model\"\n '\n \n s = summary(model)\n X = model.matrix(model)\n u2 = residuals(model)^2\n XDX = 0\n\n ## Here one needs to calculate X'DX. But due to the fact that\n ## D is huge (NxN), it is better to do it with a cycle.\n for (i in 1:nrow(X)) {\n XDX = XDX + u2[i] * X[i,] %*% t(X[i,])\n }\n\n # inverse(X'X)\n XX1 = solve(t(X)%*%X)\n\n # Variance calculation (Bread x meat x Bread)\n varcovar = XX1 %*% XDX %*% XX1\n\n # degrees of freedom adjustment\n dfc = sqrt(nrow(X)) / sqrt(nrow(X) - ncol(X))\n\n # Standard errors of the coefficient estimates are the\n # square roots of the diagonal elements\n stdh = dfc*sqrt(diag(varcovar))\n\n t = model$coefficients / stdh\n p = 2 * pt(\n -abs(t),nrow(X)-ncol(X)\n )\n results = cbind(\n model$coefficients, stdh, t, p\n )\n dimnames(results) = dimnames(s$coefficients)\n list(results, dfc^2 * varcovar)\n}\n\nclx = function(fm, dfcw, cluster) {\n # Return clustered-standard errors for \"fm\". \n # Mahmood Arai, Jan 26, 2008.\n\n # The arguments of the function are:\n # fitted model, cluster1 and cluster2\n # You need to install libraries `sandwich' and `lmtest'\n\n # reweighting the var-cov matrix for the within model\n library(sandwich)\n library(lmtest)\n M = length(\n unique(cluster)\n ) \n N = length(cluster) \n K = fm$rank \n dfc = ( M / (M-1) ) * ( (N-1) / (N-K) ) \n uj = apply(\n estfun(fm),2, function(x) tapply(x, cluster, sum) \n )\n vcovCL = dfc * sandwich(fm, meat=crossprod(uj) / N) * dfcw\n list(coeftest(fm, vcovCL), vcovCL) \n}\n\nwald.ci = function (reg , alpha, cluster){\n # Return Wald Confidenceintervall for second \"coef\" of\n # \"reg\" \n df = summary(reg)$df[2]\n c = summary(reg)$df[1]\n h = clx(fm = reg, dfcw = 1, cluster = cluster)[[1]][c + 2] * qt(1 - alpha/2,df)\n est = reg$coef[2]\n paste(\n \"$[\", round(est - h,2), \", \" , round(est + h,2), \"]$\",\n sep=\"\"\n )\n}\n\nanderson.rubin.ci = function(ivmodel, conflevel=.95){\n ## Return \"Anderson Rubin CI\" for \"ivmodel\" with sig. niveau \n ## \"conflevel\". Default is \"conflevel=.95\"\n \n y = ivmodel$y\n n = length(y)\n \n if( is.null(ivmodel$x)==TRUE ){\n print(\"Refit ivmodel with x=TRUE option in the ivreg function.\")\n stop()\n }\n \n regressors = ivmodel$x$regressors\n instruments = ivmodel$x$instruments\n \n # Use notation in Davidson and MacKinnon, 2011\n # Figure out based on ivmodel fit from ivreg, the elements in Davidson and MacKinnon \n W = instruments;\n # Figure out which columns in regressors and instruments are the same\n regressors.same.vec = rep(0,ncol(regressors))\n instruments.columns.same = rep(0,ncol(regressors)-1)\n count = 1\n for (i in 1:ncol(regressors)) {\n tempmat = regressors[,i] - instruments\n tempsum = apply(abs(tempmat),2,sum)\n regressors.same.vec[i] = sum(tempsum==0) > 0\n\n if (sum(tempsum==0)>0) {\n instruments.columns.same[count] = i\n count = count + 1\n } \n }\n \n y2column = which(regressors.same.vec==0)\n y2 = regressors[,y2column]\n Z = regressors[,-y2column]\n W2 = instruments[,-instruments.columns.same]\n \n l = ncol(W)\n \n if ( is.null(ncol(Z)) ){\n Z = matrix(Z)\n k = ncol(Z)\n } else {\n k = ncol(Z)\n }\n \n q = qf( conflevel, l-k, n-l )\n cval = q * (l-k) / (n-l)\n y1 = matrix(y, ncol=1)\n \n y2hat.given.W = fitted( lm(y2 ~ W - 1) )\n y2hat.given.Z = fitted( lm(y2 ~ Z) )\n y1hat.given.W = fitted( lm(y1 ~ W-1) )\n y1hat.given.Z = fitted( lm(y1 ~ Z) )\n \n coef.beta0sq = cval * sum(y2^2) - (cval+1) * sum(y2 * y2hat.given.W) + sum(y2 * y2hat.given.Z)\n \n a = sum( y1 * y2hat.given.Z)\n coef.beta0 = -2 * cval * sum(y1*y2) + 2 * (cval+1) * sum(y1 * y2hat.given.W) - 2 * a\n \n coef.constant = cval * sum(y1^2) - (cval + 1) * sum(y1 * y1hat.given.W) + sum(y1 * y1hat.given.Z)\n \n D = coef.beta0^2 - 4 * coef.constant * coef.beta0sq\n \n if(coef.beta0sq==0){\n if (coef.beta0>0) {\n ci=c(\n \"[\",\n round(-coef.constant / coef.beta0, 2),\n \",Infinity)\"\n )\n }\n if (coef.beta0<0) {\n ci=c(\n \"(-Infinity,\",\n round(-coef.constant / coef.beta0, 2),\n \"]\"\n )\n }\n if (coef.beta0==0) {\n \n if (coef.constant>=0) {\n ci=\"\\\\text{Whole Real Line}\"\n }\n if (coef.constant<0) {\n ci=\"\\\\text{Empty Set}\"\n }\n }\n } \n \n if (coef.beta0sq!=0) {\n if (D<0) {\n if (coef.beta0sq>0) {\n ci=\"\\\\text{Whole Real Line}\"\n }\n if (coef.beta0sq<0) {\n ci=\"\\\\text{Empty Set}\"\n }\n }\n if (D>0) {\n # Roots of quadratic equation\n # Roots of quadratic equation\n root1 = ( -coef.beta0 + sqrt(D) ) / (2 * coef.beta0sq)\n root2=( -coef.beta0 - sqrt(D) ) / (2 * coef.beta0sq)\n upper.root = round( max(root1,root2), 2)\n lower.root = round( min(root1,root2), 2)\n \n if (coef.beta0sq<0) {\n ci = paste(\n \"[\",\n lower.root,\",\",\n upper.root,\"]\",\n sep=\"\"\n )\n }\n if (coef.beta0sq>0) {\n ci = c(\n paste(\n \"($-\\\\infty$,\",\n \"$\",\n lower.root,\n \"$]U\",\n sep=\"\"\n ),\n paste(\n \"[$\",\n upper.root,\n \"$\",\n \",$\\\\infty$)\",\n sep=\"\"\n )\n )\n }\n }\n if (D==0) {\n ci=\"\\\\text{Whole Real Line}\"\n }\n }\n return(confidence.interval = ci)\n}\n", "meta": {"hexsha": "2429ae489b027fef55808665b626c211b185c2f0", "size": 6863, "ext": "r", "lang": "R", "max_stars_repo_path": "{{cookiecutter.project_slug}}/src_r/model_code/functions.r", "max_stars_repo_name": "roecla/econ-project-templates", "max_stars_repo_head_hexsha": "7625f6938094dd02bb863a67d4d5912c584df14d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "{{cookiecutter.project_slug}}/src_r/model_code/functions.r", "max_issues_repo_name": "roecla/econ-project-templates", "max_issues_repo_head_hexsha": "7625f6938094dd02bb863a67d4d5912c584df14d", "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": "{{cookiecutter.project_slug}}/src_r/model_code/functions.r", "max_forks_repo_name": "roecla/econ-project-templates", "max_forks_repo_head_hexsha": "7625f6938094dd02bb863a67d4d5912c584df14d", "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": 29.4549356223, "max_line_length": 101, "alphanum_fraction": 0.462479965, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6335926120489787}} {"text": "####\n###UMR_Trib Data. Si Woodstoich Working Group\n#5.19.19\n\n##====================================\n#What's diff from before?\n##Now using TP and TN instead of the inorganic constituents\n#and put Si in numerator of ratios, like Paul did\n\nlibrary(plyr)\nlibrary(dplyr)\n\nsetwd(\"~/Woodstoich/RawData_5.14.19\")\n\n#importing data\nData<-read.table(file=\"UMR_Tribs_jcc_5.14.19.csv\", header=TRUE, sep=',')\nnames(Data)\n\n#Helper variables from Paul\nN.mw=14.0067\nP.mw=30.973762\nC.mw=12.0107\nSi.mw=28.0855\n\n#Adding new colums with data in moles so to calc molar ratios\nData$uMSi<-(Data$SI/Si.mw*1000)\nData$uMNOX<-(Data$NOX/N.mw*1000)\nData$uMNHX<-(Data$NHX/N.mw*1000)\nData$uMSRP<-(Data$SRP/P.mw*1000)\nData$uMDIN<-(Data$uMNOX+Data$uMNHX)\nData$Si_DIN<-(Data$uMSi/Data$uMDIN)\nData$Si_SRP<-(Data$uMSi/Data$uMSRP)\n\nData$uMTP<-(Data$TP/P.mw*1000)\nData$uMTN<-(Data$TN/N.mw*1000)\nData$Si_TP<-(Data$uMSi/Data$uMTP)\nData$Si_TN<-(Data$uMSi/Data$uMTN)\n\nrange(Data$uMSi, na.rm=T)\n\n#subsetting to remove negatives\nData<-subset(Data, uMSi>0 & uMNOX>0 & uMSRP>0 & uMNHX>0 & uMTP>0 & uMTN>0)\n\n#Fixing dates and adding year as a column\nData$DATE2=as.Date(Data$DATE, c(\"%m/%d/%Y\"))\nData$YEAR=as.numeric(format(Data$DATE2,c(\"%Y\")))\n\n#making each site name into a unique number\nunique(Data$LOCATCD)\nData$SiteNum<-as.numeric(as.factor(Data$LOCATCD))\nhead(Data$SiteNum)\nunique(Data$SiteNum)\n\n#Calc min and max dates for each site\nSiteDates<-ddply(Data, c(\"LOCATCD\"), summarise, min.date=min(YEAR), max.date=max(YEAR))\nSiteDates$YrsData<-with(SiteDates, as.numeric(max.date-min.date))\nLongTermSites<-subset(SiteDates, SiteDates$YrsData>20)\n\n#Now merge these sites with >20 yrs data with larger dataset\nData3<-merge(LongTermSites, Data, by=c(\"LOCATCD\"))\nhead(Data3)\n\n#calc avg vaues by year at each site\nAvgByYr<-aggregate(cbind(Data3$uMSi, Data3$uMNHX, Data3$uMSRP, Data3$uMNOX, Data3$uMDIN, \n Data3$Si_TN, Data3$Si_TP, Data3$uMTP, Data3$uMTN) ~ Data3$LOCATCD + Data3$YEAR, FUN=mean)\nnames(AvgByYr)\ncolnames(AvgByYr) <- c(\"LOCATCD\", \"Year\", \"AvguMSi\", \"AvgNH4\", \"AvgSRP\", \"AvgNOX\", \n \"AvgDIN\", \"AvgSi_TNRatio\", \"AvgSi_TPRatio\", \"AvgTP\", \"AvgTN\")\nData4<-AvgByYr[order(AvgByYr$LOCATCD),]\nrange(Data4$AvgSi_TNRatio)\n\n\n##==============================================\n##plotting avg annual values over time for each site with >20yrs data \n##exported the results of simple linear regression\n##=============================================\n\nlibrary(broom)\n#glace in the broom package give R2 (and apparently pvalues). tidy gives p values and slopes\n\n#making new datafram of site IDs\nLocatID<-data.frame(unique(Data4$LOCATCD))\n\n\n#Average Si:TN molar ratios over time. y axis range: 0.124 to 6.38\n#these plots have y axis that includes all values but hard to see trends so zooming in on next plot\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgSiTN_Plot.jpeg\"), width=7, height=5, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.8,2,1.3))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"],\n xlim=c(1990, 2020), ylim=c(0,6.5), main=paste(\"Site\", i), ylab=\"Si:TN\", \n mgp=c(1.8,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\")\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,2,4,6), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\ndf2<-cbind(LocatID, df)\nwrite.csv(df2, file=\"R2_Si_TNRatiosvsTime_5.15.19_wNames.csv\", row.names=TRUE, na = \"NA\")\n\n#these margins work for exporting graphs to file folders but use above graphics if want to display the plots in panel in R Studio\n#Si:TN plots more zoomed in\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgSiTN_Plot_zoomed_in.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2,2,1.2))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"],\n xlim=c(1990, 2020), ylim=c(0,3), main=paste(\"Site\", i), ylab=\"Si:TN\", \n mgp=c(1.1,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main=0.8, cex.lab=0.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,1,2,3), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TNRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\n\n\nrange(Data4$AvgSi_TPRatio) #3 to 285\n#these margins work for exporting graphs to file folders but use above graphics if want to display the plots in panel in R Studio\n#Si:TP plots \nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgSiTP_Plot.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,0.9))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"],\n xlim=c(1990, 2020), ylim=c(0,290), main=paste(\"Site\", i), ylab=\"Si:TP\", \n mgp=c(1.7,.1,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main=0.8, cex.lab=0.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,100, 200,300), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\n\n##Same as above except y axis is zoomed in \n#more Si_TP plots\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgSiTP_Plot_ZoomedIn.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,0.9))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"],\n xlim=c(1990, 2020), ylim=c(0,150), main=paste(\"Site\", i), ylab=\"Si:TP\", \n mgp=c(1.7,.1,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main=0.8, cex.lab=0.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,50, 100, 150), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgSi_TPRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\ndf2<-cbind(LocatID, df)\nwrite.csv(df2, file=\"R2_Si_TPRatiosvsTime_wNames.csv\", row.names=TRUE, na = \"NA\")\n\n\n\n#Average DSi values over time\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgDSivsTime.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.3,2,0.9))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvguMSi\"],\n xlim=c(1990, 2020), ylim=range(Data4$AvguMSi), main=paste(\"Site\", i), ylab=\"DSi uM\", \n mgp=c(1.6,1.1,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main=0.8, cex.lab=0.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.3, cex.axis=.8, mgp=c(0,0.3,0), font.axis=1)\n axis(side=2, at = c(0,50,100,150,200, 250), tcl=-.3, cex.axis=.8, mgp=c(0,0.3,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvguMSi\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvguMSi\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n }\ndev.off()\n\ndf2<-cbind(LocatID, df)\nwrite.csv(df2, file=\"R2_DSivsTime_wNames.csv\", row.names=TRUE, na = \"NA\")\n\n\n\n#Average TP values over time\nrange(Data4$AvgTP) #1.7 to 44\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgTP_Plot.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,1.3))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgTP\"],\n xlim=c(1990, 2020), ylim=range(Data4$AvgTP), main=paste(\"Site\", i), ylab=\"TP uM\", \n mgp=c(1.6,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main =0.8, cex.lab=.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,20,40), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgTP\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgTP\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\nLocatID<-data.frame(unique(Data4$LOCATCD))\ndf2<-cbind(LocatID, df)\nwrite.csv(df2, file=\"R2_TPvsTime_5.19.19c.csv\", row.names=TRUE, na = \"NA\")\n\n\n#zooming in\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgTP_Plot_ZoomedIn.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,1.3))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgTP\"],\n xlim=c(1990, 2020), ylim=c(0,15), main=paste(\"Site\", i), ylab=\"TP uM\", \n mgp=c(1.3,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main =0.8, cex.lab=.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,5, 10, 15), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgTP\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgTP\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\n\n\n#Average TN values over time\nrange(Data4$AvgTN) #134 to 1153\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgTN_Plot.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,1))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgTN\"],\n xlim=c(1990, 2020), ylim=range(Data4$AvgTN), main=paste(\"Site\", i), ylab=\"TN uM\", \n mgp=c(1.8,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main =0.8, cex.lab=.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,250, 500, 750, 1000), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgTN\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgTN\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\ndf2<-cbind(LocatID, df)\nwrite.csv(df2, file=\"R2_TNvsTime_wNames.csv\", row.names=TRUE, na = \"NA\")\n\n#Average TN values over time - zoomed in\nrange(Data4$AvgTN) #134 to 1153\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgTN_Plot_zoomedIn.jpeg\"), width=7, height=4, units=\"in\", res=200)\npar(mfrow=c(4,7), mar=c(2,2.5,2,1))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgTN\"],\n xlim=c(1990, 2020), ylim=c(0,700), main=paste(\"Site\", i), ylab=\"TN uM\", \n mgp=c(1.8,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\", cex.main =0.8, cex.lab=.8)\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,300, 600), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgTN\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgTN\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\n##==============================================\n##playing with Chl data 5.16.19\n##==============================================\nData5<-subset(Data3, CHLcal>0 & VSS>0)\n\n\n#calculating average annual values with smaller dataset that excludes negatives for VSS and Chl a (n=~6000 now)\n#this still includes all sites with >20 yrs data\nAvgByYr_withChlVSS<-aggregate(cbind(Data5$uMSi, Data5$uMNHX, Data5$uMSRP, Data5$uMNOX, Data5$uMDIN, \n Data5$DINSi, Data5$PSi, Data5$VSS, Data5$CHLcal) ~ Data5$LOCATCD + Data5$YEAR, FUN=mean)\nnames(AvgByYr_withChlVSS)\ncolnames(AvgByYr_withChlVSS) <- c(\"LOCATCD\", \"Year\", \"AvguMSi\", \"AvgNH4\", \"AvgSRP\", \"AvgNOX\", \n \"AvgDIN\", \"AvgDIN_SiRatio\", \"AvgP_SiRatio\", \"AvgVSS\", \"AvgChl\")\nData6<-AvgByYr_withChlVSS[order(AvgByYr_withChlVSS$LOCATCD),]\n\n\n###===================================\n# looping Chl a vs. consitutents at each site\n##====================================\nrange(Data6$AvgChl, na.rm=T)\nrange(Data6$AvguMSi)\nnames(Data6)\nrange(Data5$VSS, na.rm=T)\n\n#Average Chl a vs. DSi at each site\ndf=NULL\nplot.path=paste0(getwd(),\"/img/\")\njpeg(filename=paste0(plot.path, \"AvgDSivsChl_5.16.19b.jpeg\"), width=7, height=7, units=\"in\", res=200)\n\npar(mfrow=c(4,7), mar=c(2.9,2.8,2,1.7))\nfor(i in unique(Data6$LOCATCD)){\n plot(Data6[Data6$LOCATCD==i, \"AvgChl\"], Data6[Data6$LOCATCD==i, \"AvguMSi\"],\n xlim=c(0, 35), ylim=c(0,300), main=paste(\"Site\", i), ylab=\"DSi uM\", \n mgp=c(1.6,.1,0), las=1, xlab=\"Chl a\", xaxt=\"n\", yaxt=\"n\", cex.main=.9)\n axis(side=1, at = c(0, 10, 20, 30), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,100, 200, 300), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data6[Data6$LOCATCD==i, \"AvguMSi\"]~ Data6[Data6$LOCATCD==i, \"AvgChl\"]))\n df=rbind(df,data.frame(glance(lm(Data6[Data6$LOCATCD==i, \"AvguMSi\"]~ Data6[Data6$LOCATCD==i, \"AvgChl\"]))))\n}\ndev.off()\n\nwrite.csv(df, file=\"R2_DIN_SiRatiosvsTime_5.15.19.csv\", row.names=TRUE, na = \"NA\")\n\n\n\n\n\n\n\n\n##=======================================================\n##below is me f-ing around...\n##=======================================================\n\n#couldn't figure this out - to define the path inside the loop:\nmypath<-file.path(~\"Woodstoich\",\"RawData_5.14.19\", \"img\")\njpeg(file=mypath)\n\n#if use below, i have to change site num to locatcd bc got rid of misc numbers:\n\n#testing out the loop here - works! just going into wrong folder and these are each plot individually, not multi-panel:\n#so putting in diff folder:\nsetwd(\"~/Woodstoich/RawData_5.14.19/img\")\nfor(i in unique(Data4$SiteNumber)){\n jpeg(paste(\"plot_\", i, \".jpeg\", sep=\"\"))\n plot(Data4[Data4$SiteNumber==i, \"Year\"], Data4[Data4$SiteNumber==i, \"AvguMSi\"],\n xlim=range(Data4$Year), ylim=range(Data4$AvguMSi), main=paste(\"Site\", i), ylab=\"DSi uM\", xlab=\"\")\n dev.off()\n}\n\n#couldn't figure out matrix so using mfrow instead\nlayout(matrix(1:3, ncol=3))\nlayout(matrix(1:28,7,4,byrow=F))\n\n#Test code for saving plot to folder\njpeg(file = \"~/Woodstoich/RawData_5.14.19/img/plot2.jpeg\")\nplot(Data4$Year, Data4$AvgP_SiRatio)\ndev.off()\n\n#lets add trend line to plot\n#practice plot not in loop:\nplot(Data4$Year, Data4$AvguMSi, ylim=c(5,250), xlim=c(1990,2020), ylab=\"DSi uM\", xlab=\"\", las=1)\ntitle(\"DSi uM concentrations over time, LOCATCD==WPO2.6M \", line=2, cex.main=.8)\nabline(lm(Data4$AvguMSi ~ Data4$Year))\nfit1<-lm(Data4$AvguMSi ~ Data4$Year)\nfit2<-lm(Data4$AvguMSi ~ Data4$Year)\n\n#this loop works - just need to save the files to a folder\nfor(i in unique(Data4$SiteNumber)){\n plot(Data4[Data4$SiteNumber==i, \"Year\"], Data4[Data4$SiteNumber==i, \"AvguMSi\"],\n xlim=range(Data4$Year), ylim=range(Data4$AvguMSi), main=paste(\"Site\", i), ylab=\"DSi uM\", xlab=\"\")\n }\ndev.off()\n\n#this works but ignore\nplot(Data4$Year[which(Data4$SiteNumber==1)], Data4$AvguMSi [which(Data4$SiteNumber==1)], ylim=c(5,250), xlim=c(1990,2020), ylab=\"DSi uM\", xlab=\"\", las=1)\ntitle(\"DSi uM concentrations over time, Site \", line=2, cex.main=.8)\n\n\n\n#Average DIN:DSi molar ratios over time\ndf=NULL\npar(mfrow=c(4,7), mar=c(2,2.8,2,1.3))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgDIN_SiRatio\"],\n xlim=c(1990, 2020), ylim=c(0,16), main=paste(\"Site\", i), ylab=\"DIN:DSi\", \n mgp=c(1.8,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\")\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,5,10,15), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgDIN_SiRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgDIN_SiRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\nwrite.csv(df, file=\"R2_DIN_SiRatiosvsTime_5.15.19.csv\", row.names=TRUE, na = \"NA\")\n\n\n\n##Switched ratios around - not using these any longer\n#Average DIP:Si molar ratios over time\ndf=NULL\npar(mfrow=c(4,7), mar=c(2,2.8,2,1.3))\nfor(i in unique(Data4$LOCATCD)){\n plot(Data4[Data4$LOCATCD==i, \"Year\"], Data4[Data4$LOCATCD==i, \"AvgP_SiRatio\"],\n xlim=c(1990, 2020), ylim=c(0,.1), main=paste(\"Site\", i), ylab=\"SRP:DSi\", \n mgp=c(1.8,.2,0), las=1, xlab=\"\", xaxt=\"n\", yaxt=\"n\")\n axis(side=1, at = c(1990, 2000, 2010, 2020), tcl=-.4, cex.axis=.8, mgp=c(0,.3,0), font.axis=1)\n axis(side=2, at = c(0,0.05, 0.1), tcl=-.3, cex.axis=.8, mgp=c(0, .5,0), font.axis=1, las=1)\n abline(lm(Data4[Data4$LOCATCD==i, \"AvgP_SiRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))\n df=rbind(df,data.frame(glance(lm(Data4[Data4$LOCATCD==i, \"AvgP_SiRatio\"]~ Data4[Data4$LOCATCD==i, \"Year\"]))))\n}\ndev.off()\n\nwrite.csv(df, file=\"R2_P_SiRatiosvsTime_5.15.19.csv\", row.names=TRUE, na = \"NA\")\n\n\n\n\n\n##not using but kept for maybe later\n#calc avg vaues by year at each site\nAvgByYr<-aggregate(Data$uMSi~ Data$SiteNum + Data$YEAR, FUN=mean)\ncolnames(AvgByYr) <- c(\"SiteNumber\", \"Year\", \"AvguMSi\")\nData3<-AvgByYr[order(AvgByYr$SiteNumber),]\n\n\n#these are 'or' not 'and' statements\nData5<-subset(Data,subset=uMSi>0 | uMNOX>0 | uMNHX>0 | uMSRP>0)\nData9<-Data[ !is.na(Data$uMSi | Data$uMNOX| Data$uMSRP | Data$NHX) & (Data$uMSi>0 | Data$uMNOX>0 |Data$uMNHX>0 | Data$uMSRP>0) ,]\n\n#Does same thing as above but uses the 'which', which some pple don't like\nData8<-Data[ which(Data$uMSi>0 | Data$uMNOX>0 |Data$uMNHX>0 | Data$uMSRP>0) ,]\n\n", "meta": {"hexsha": "5935f9e68b738fdd1ea1c7061820714affd2f387", "size": 18028, "ext": "r", "lang": "R", "max_stars_repo_path": "JCC/TrendsThruTime/UMR_Trib_5.19.19.r", "max_stars_repo_name": "SwampThingPaul/Woodstoich4_SiWG", "max_stars_repo_head_hexsha": "b957cb4636ace6c2a40b53c2e43fbff97e9db54c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JCC/TrendsThruTime/UMR_Trib_5.19.19.r", "max_issues_repo_name": "SwampThingPaul/Woodstoich4_SiWG", "max_issues_repo_head_hexsha": "b957cb4636ace6c2a40b53c2e43fbff97e9db54c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JCC/TrendsThruTime/UMR_Trib_5.19.19.r", "max_forks_repo_name": "SwampThingPaul/Woodstoich4_SiWG", "max_forks_repo_head_hexsha": "b957cb4636ace6c2a40b53c2e43fbff97e9db54c", "max_forks_repo_licenses": ["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.5458937198, "max_line_length": 153, "alphanum_fraction": 0.6461615265, "num_tokens": 7392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6334790739854441}} {"text": "############## CELL CYCLE DISTRIBUTION ESTIMATION FROM DAPI INTENSITIES ################\n# \n# licensed under the MIT License:\n# \n# Copyright (c) 2016 Andreas Stengl, David Hoerl, Heinrich Leonhardt and Jonas Helma\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify, merge,\n# publish, distribute, sublicense, and/or sell copies of the Software, and to permit \n# persons to whom the Software is furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be \n# included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULARPURPOSE AND NONINFRINGEMENT. IN NO EVENT\n# SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLEFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n# \n########################################################################################\n\n\nlibrary(GenSA)\n\n################################## Function Defs ###############################\n\n# sum of three Gaussian functions\nthreegauss = function(x, params) {\n res = (params[3]*exp(-1/2*(x-params[1])^2/params[2]^2) +\n params[6]*exp(-1/2*(x-params[4])^2/params[5]^2) +\n params[9]*exp(-1/2*(x-params[7])^2/params[8]^2))\n res \n}\n\n# single Gaussian\nagauss = function(x, params) {\n res = (params[3]*exp(-1/2*(x-params[1])^2/params[2]^2))\n res\n}\n\n# plateau with Gaussian fade-out\ngaussline = function(x, params){\n res = c()\n for(xi in x){\n if (xi < params[1]){\n y = (params[3]*exp(-1/2*(xi-params[1])^2/params[4]^2))\n }\n else if (xi > params[2]) {\n y= (params[3]*exp(-1/2*(xi-params[2])^2/params[4]^2))\n }\n else{\n y =( params[3])\n }\n res = c(res, y)\n }\n res\n}\n\n# sum of two Gaussian peaks plus a constant plateau with Gaussian fade-out\ntwogaussplusbroadendgauss = function(x, params) {\n res = (params[3]*exp(-1/2*(x-params[1])^2/params[2]^2) +\n params[6]*exp(-1/2*(x-params[4])^2/params[5]^2) +\n gaussline(x, params[7:10]))\n res\n}\n\n# guess plataeu height as minimum of vals between indices x1 and x2\nguessplateau = function(vals, x1,x2) {\n pg = vals[x1-1 + which.min(vals[c(x1):c(x2)])]\n dif = vals[x2] - pg\n \n # x2 is the minimum, take a slightly lower value as the guess\n if(dif <= 0){\n pg = vals[x2]*0.99999999\n }\n pg\n}\n\n# integrate peak area of G1, S, G2 and sum of them\nintegratepeaks = function(xs, params){\n G1 = integrate(function(x) {agauss(x, params[1:3])}, lower=min(xs), upper=max(xs))\n G2 = integrate(function(x) {agauss(x, params[4:6])}, lower=min(xs), upper=max(xs))\n S = integrate(function(x) {gaussline(x, params[7:10])}, lower=min(xs), upper=,max(xs))\n Pop = G1$value+S$value+G2$value\n res = c(G1$value,S$value,G2$value,Pop)\n res\n}\n\n\n\n################ Fitting script #########################\n\n# for saving the results of multiple runs\n# do not re-initialize every time\ncurveareas = data.frame()\n\n\n########### START ##################\n\n## 1) the integrated DAPI intensities per cell should be assigned to DAPIIntensities\n\nDAPIIntensities = c()\n\n## in our case:\n# platerow = 3\n# platecolumn = 3\n# DAPIIntensities = subset(SKBR3,Row %in% platerow & Column == platecolumn)$IDapiAbs\n\n\n## 2) get xs and ys\n# xs = histogram bin mids\n# ys = density curve\nh = hist(DAPIIntensities, breaks = 100, probability = T)\nxs = h$mids\nys = h$density\n\n\n\n# 3) Guess parameters\n# Guesses for peak positions\nxG1 = xs[which.max(smooth(ys))]\nxp1g = which.max(ys)\npgxg = xp1g - 1 + which.min(ys[xp1g:(which.max(ys)*2.5)])\nxp2g = pgxg - 1 + which.max(ys[pgxg:100])\nxG2 = xs[xp2g]\n\n# Guesses for peak and plateau heights\npeak1guess = ys[which.max(smooth(ys))]\nplateauguess <- guessplateau(ys,xp1g,xp2g)\npeak2guess = ys[xp2g]\n\n# Guess for all 10 params\nguess = c(xG1, xG1/6, (peak1guess-plateauguess),\n xG2, xG1/6, (peak2guess-plateauguess),\n xG1, xG2, plateauguess, xG1/6)\n\n# lower and upper bounds\nguessupper = guess + guess*c(0.5, 0.9, 0.05,\n 0.1, 0.5, 0.5,\n 0.25, 0.15, 0.1, 0.9)\nguesslower = guess - guess*c(0.5, 0.1, 0.3,\n 0.05, 0.5, 0.1,\n 0.5, 0.05, 0.9, 0.1)\n\n\n## 4) do optimization\nres = GenSA(NULL,function(guess) {sum((ys-twogaussplusbroadendgauss(xs, guess))^2)},\n upper = guessupper, lower = guesslower )\n\n\n## 5) plot histogram + fitted curves\n\nplot(xs, ys, type = \"h\")\n lines(xs, agauss(xs, res$par[1:3]), col=\"red\")\n lines(xs, agauss(xs, res$par[4:6]), col=\"green\")\n lines(xs, gaussline(xs, res$par[7:10]), col=\"blue\")\n lines(xs, twogaussplusbroadendgauss(xs, res$par), col=\"cyan\")\n \n # plot guesses\n abline(v = xG1, col='red')\n abline(v = xG2,col ='green')\n abline(h = peak1guess, col='red')\n abline(h = plateauguess, col='blue')\n abline(h = peak2guess, col='green')\n \n\n\n## 6) append resulting areas under curves to accumulated results\n\n### name for the condition of the histogram\n# e.g.\n \ncondition = '16nM Trastuzumab'\n\ncurveareas = rbind.data.frame(curveareas, c(condition, as.numeric(integratepeaks(xs, res$par))), stringsAsFactors = FALSE)\ncolnames(curveareas) = c('condition', 'G1', 'S', 'G2', 'total')\n\n\n################ Accumulated results plot/saving ###################\n\n# normalize to area=1\nnormIntegrals = apply(curveareas[,2:5], 2, function(x){as.numeric(as.character(x))}) /\n as.numeric(as.character(curveareas[,5]))\n# plot stacked bars\nbarplot(t(normIntegrals[,1:3]), names.arg = curveareas$condition)\n\n# save cell cycle fractions\nwrite.table(normIntegrals, \"Z:/normIntegrals.txt\", sep=\"\\t\") \n\n\n", "meta": {"hexsha": "be6155aa27463d1cbe2c160efa021791db7ebe92", "size": 6082, "ext": "r", "lang": "R", "max_stars_repo_path": "DAPI_CellCycle_Fit.r", "max_stars_repo_name": "hoerldavid/CellCycleFit", "max_stars_repo_head_hexsha": "17a55ded5f7aaade8a2fba8a619bf099ee3d03ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DAPI_CellCycle_Fit.r", "max_issues_repo_name": "hoerldavid/CellCycleFit", "max_issues_repo_head_hexsha": "17a55ded5f7aaade8a2fba8a619bf099ee3d03ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DAPI_CellCycle_Fit.r", "max_forks_repo_name": "hoerldavid/CellCycleFit", "max_forks_repo_head_hexsha": "17a55ded5f7aaade8a2fba8a619bf099ee3d03ac", "max_forks_repo_licenses": ["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.5129533679, "max_line_length": 122, "alphanum_fraction": 0.6251233147, "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6333734612827305}} {"text": "#' f_newton\n#'\n#' The newton algorithm to minimize the criteria\n#'\n#' @param v_y vector of y\n#' @param v_x vector of x\n#' @param v_k0 vector of internal knots for covariates\n#' @param v_m vector of orders for covariates\n#'\n#' @param init initialization for $\\beta$\n#' @param alpha threshold $\\alpha$, within $(0, 0.5)$.\n#' @param bet shrinkage rate $\\bet$, within $(0, 1)$.\n#' @param v_smooth vector of smoothing parameters\n#' @param maxit maximum number of iterations\n#' @param thresh stopping critria threshhold\n#' @param trace indicator whether to plot trace\n#'\n#' @import MASS\n#'\n#' @return the estimated $\\beta$\n#'\nf_newton <- function(v_y, v_x, v_k0, v_m, init,\n alpha = 0.2, bet = 0.1, v_smooth = rep(1, 3),\n maxit = 1e4, thresh = 1e-3, trace = NULL) {\n\n#-------------------------------------------------------\n##### set up #####\n#-------------------------------------------------------\n function_call <- match.call()\n x_ord <- order(v_x)\n v_x <- v_x[x_ord]\n v_y <- v_y[x_ord]\n iter <- 0L\n #Define dimensions\n k1 <- v_k0[1]; k2 <- v_k0[2]; m1 <- v_m[1]; m2 <- v_m[2]\n #Require\n m_n1 <- f_n1(v_x, k1, m1)\n m_g1 <- f_g1(k2, m2)\n m_g2 <- f_g2(k2, m2)\n m_sigmatau <- f_sigmatau(k2 + m2)\n m_sigma <- f_sigma(k1 + m1, k2 + m2)\n m_s <- f_mats(k1 + m1, k2 + m2, v_smooth)\n n_m2 <- rep(0, k2 + m2); n_m2[k2 + m2] <- 1\n\n #Precalculate\n m_h1 <- f_h1(m_n1, m_g1, m_g2, m_sigmatau, n_m2)\n\n #Initialization\n if (is.null(init)) {\n init <- f_init(v_y, v_x, m_sigma, m_n1, v_k0, v_m, m_s)\n }\n til_beta <- init\n v_beta <- og_beta(til_beta, k1 + m1, k2 + m2)\n\n #Calculate H2\n v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, k2, m2)\n m_ntau <- f_ntau(v_taustar, k2, m2)\n m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau)\n\n #Loss\n s_loss <- f_loss(v_beta, til_beta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n ##trace\n if (!is.null(trace)) {\n plot(v_x, v_y,\n type = \"p\", pch = 16, cex = 0.8, col = \"grey\",\n xlim = grDevices::extendrange(v_x, f = .5),\n ylim = grDevices::extendrange(v_y, f = .5),\n xlab = \"\", ylab = \"\",\n sub = paste(\"Iter:\", iter, \", Error=\", round(Inf, 3))\n )\n for (i in seq_along(trace)) {\n v_med <- f_qscop(trace[i], m_n1, til_beta, m_sigma, k2, m2)\n lines(v_x, v_med, col = i + 1)\n }\n }\n\n\n #Repeat\n while (maxit > iter) {\n iter <- iter + 1\n\n #Calculate gradient\n v_deriv <- f_lossderiv(til_beta, v_k0 + v_m, m_sigma, m_h1, m_h2)\n v_grad <- f_grad(v_beta, v_deriv, m_s)\n #Calculate Hessian\n m_hess <- f_hess(v_deriv, v_k0 + v_m, m_s)\n\n ##Loss\n t <- 1\n #Line search\n step_size <- c(MASS::ginv(m_hess) %*% v_grad)\n grad_size <- alpha * crossprod(v_grad, step_size)\n repeat{\n new_beta <- v_beta - t * step_size\n new_tilbeta <- tilde_beta(new_beta, k1 + m1, k2 + m2)\n new_loss <- f_loss(new_beta, new_tilbeta, v_taustar, v_y, m_sigma, m_h1, m_h2, m_s)\n t <- bet * t\n if (new_loss <= (s_loss - t * grad_size)) {\n break\n }\n }\n\n #Update v_beta\n v_beta <- new_beta\n til_beta <- new_tilbeta\n\n #Update H2 (most time consuming)\n#ptm <- proc.time()# Start the clock!\n v_taustar <- f_tausearch(v_y, m_n1, til_beta, m_sigma, k2, m2)\n#print(proc.time() - ptm)# Stop the clock\n m_ntau <- f_ntau(v_taustar, k2, m2)\n m_h2 <- f_h2(m_n1, m_ntau, m_g1, m_sigmatau)\n\n ##trace\n if (!is.null(trace)) {\n plot(v_x, v_y,\n type = \"p\", pch = 16, cex = 0.8, col = \"grey\",\n xlim = grDevices::extendrange(v_x, f = .5),\n ylim = grDevices::extendrange(v_y, f = .5),\n xlab = \"\", ylab = \"\",\n sub = paste(\"Iter:\", iter, \"Error=\", round(s_loss, 3))\n )\n for (i in seq_along(trace)) {\n v_med <- f_qscop(trace[i], m_n1, til_beta, m_sigma, k2, m2)\n lines(v_x, v_med, col = i + 1)\n }\n }\n #Check stop criterion\n converge <- (abs(new_loss - s_loss) <= thresh * s_loss)\n s_loss <- new_loss\n if (converge) break\n\n }\n\n#-------------------------------------------------------\n##### Output #####\n#-------------------------------------------------------\n out <- list(\n beta = v_beta,\n til_beta = til_beta,\n converge = converge,\n iter = iter,\n loss = s_loss,\n tau = v_taustar,\n x = v_x,\n y = v_y,\n n1 = m_n1,\n m_sigma = m_sigma,\n mat_s = m_s,\n call = function_call)\n\n return(out)\n}", "meta": {"hexsha": "e526519d63415aea37893b31dd0a3f474ab84c90", "size": 4819, "ext": "r", "lang": "R", "max_stars_repo_path": "R/newton.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/newton.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/newton.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": 31.4967320261, "max_line_length": 95, "alphanum_fraction": 0.5013488276, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6332573467198377}} {"text": "#' Rank difference test\n#'\n#' Performs Kornbrot's rank difference test. It's a modified Wilcoxon signed-rank\n#' test which produces consistent and meaningful results for ordinal or monotonically\n#' transformed data.\n#'\n#' For ordinal scale data, the Wilcoxon signed-rank test results in subtraction\n#' of those ordinal scale values. However, this subtraction is not meaningful on\n#' the ordinal scale. In addition, any monotone transformation of the data will\n#' result in different signed ranks, thus different p-values. However, ranking\n#' the original data allows for meaningful addition and subtraction of ranks and\n#' preserves ranks over monotonic transformation. Kornbrot described the rank\n#' difference test for this reason.\n#'\n#' Kornbrot recommends that the rank difference procedure be used in preference\n#' to the Wilcoxon signed-rank test in all paired comparison designs where the data\n#' are not both of interval scale type and of known distribution type. The rank\n#' difference test preserves good power compared to Wilcoxon's signed-rank test,\n#' is more powerful than the sign test, and has the benefit of being a true\n#' distribution-free test.\n#'\n#' The procedure for Wilcoxon's signed-rank test is as follows:\n#'\n#' 1. Calculate differences for each paired observation.\n#' 2. Remove differences equal to zero.\n#' 3. Order the absolute differences from smallest to largest.\n#' 4. Assign ranks \\eqn{1, \\dots, n} with average rank for ties.\n#' 5. Calculate W+ = sum of the ranks for positive differences. The sum of W+ and\n#' W- is \\eqn{n(n+1)/2}, so either can be calculated from the other.\n#' 6. Choose the smaller of W+ and W- as the test statistic W.\n#' 7. Since the test statistic is the smaller of W+ and W-, the critical region\n#' is the left tail of the distribution. W is distributed approximately normal\n#' with mean \\eqn{mu = (n(n+1))/4} and variance\n#' \\eqn{sigma^2 = (Tn(n+1)(2n+1))/24}, where T is a correction for ties and\n#' \\eqn{T = 1-(sum(t^3-t)/(N^3-N))}, summed over all ties, where t is the\n#' length of a tie. The continuity corrected mean \\eqn{mu = ((n(n+1))/4)+0.5}.\n#'\n#' The procedure for Kornbrot's rank difference test is as follows:\n#'\n#' 1. Combine all 2n observations.\n#' 2. Assign ranks \\eqn{1, \\dots, 2n} with average rank for ties.\n#' 3. Perform the Wilcoxon signed-rank test using the paired ranks.\n#'\n#' The test statistic for the rank difference test (D) is not exactly equal to the\n#' test statistic (W) of the naive rank-transformed Wilcoxon signed-rank test\n#' (the latter being implemented in `rdt()`). Using W should result in a\n#' conservative estimate for D, and they approach in distribution as the sample\n#' size increases. \\insertCite{kornbrot1990;textual}{rankdifferencetest}\n#' discusses methods for calculating D when n<7 and 8 0) {\n stop(paste0(\n \"Check the formula argument in rdt(). Variables not found in the data: \",\n paste0(shQuote(missing_vars), collapse = \", \")\n ))\n }\n if(!length(formula_vars) %in% 2:3) {\n stop(\"Check the formula argument in rdt(). It must be of form y ~ x or y ~ x | block.\")\n }\n zero.method <- match.arg(zero.method)\n distribution <- match.arg(distribution)\n alternative <- match.arg(alternative)\n return <- match.arg(return)\n\n #-----------------------------------------------------------------------------\n # Perform test\n #-----------------------------------------------------------------------------\n ## Step 1: Generate model data\n md <- model2data(formula = formula, data = data)\n\n ## Step 2: Rank order data and prepare for coin::wilcoxsign_test()\n if(is.null(md$block)) {\n # Intermediate argument check: if no block, must only have two variables.\n if(!all(lengths(md) == c(1, 1, 0))) {\n stop(\"Check the formula used in rdt(). It must correspond with a pairwise comparison as y ~ x.\")\n }\n # Note: Kornbrot orders opposite direction: rank(-xtfrm(data)).\n ranks <- rank(c(md$y[[1]], md$x[[1]]), na.last = \"keep\")\n coin_data <- data.frame(\n y = ranks[seq_along(md$y[[1]])],\n x = ranks[seq_along(md$x[[1]]) + length(md$y[[1]])]\n )\n coin_formula <- as.formula(\"y ~ x\")\n } else {\n # Intermediate argument check: must be a balanced pairwise comparison.\n if(length(unique(md$x[[1]])) != 2) {\n stop(paste0(\n \"Check the data and/or formula used in rdt(). The variable \",\n shQuote(names(md$x)),\n \" must be a balanced 2 level factor.\"\n ))\n }\n coin_data <- data.frame(\n y = rank(md$y[[1]], na.last = \"keep\"),\n x = as.factor(md$x[[1]]),\n block = as.factor(md$block[[1]])\n )\n coin_formula <- as.formula(\"y ~ x | block\")\n }\n\n ## Step 3: Run Wilcoxon signed-rank test\n coin <- wilcoxsign_test(\n formula = coin_formula,\n data = coin_data,\n zero.method = zero.method,\n distribution = distribution,\n alternative = alternative,\n ...\n )\n\n #-----------------------------------------------------------------------------\n # Prepare results\n #-----------------------------------------------------------------------------\n diff <- if(is.null(md$block)) {\n paste0(names(md$y), \" - \", names(md$x))\n } else {\n paste0(levels(coin_data$x)[1], \" - \", levels(coin_data$x)[2])\n }\n\n alternative <- paste0(\n \"True location shift of ranks (\",\n diff,\n \") is \",\n ifelse(\n test = identical(coin@statistic@alternative, \"two.sided\"),\n yes = \"not equal to \",\n no = paste0(coin@statistic@alternative, \" than \")\n ),\n coin@nullvalue\n )\n\n method <- paste(\n \"Kornbrot's Rank Difference Test using the\",\n paste0(\n toupper(substring(distribution, 1,1)),\n substring(distribution, 2)\n ),\n coin@method,\n sep = \" \"\n )\n\n df <- data.frame(\n p.value = as.numeric(pvalue(coin)),\n z.statistic = coin@statistic@teststatistic,\n formula = deparse(formula),\n alternative = alternative,\n method = method\n )\n\n #-----------------------------------------------------------------------------\n # Return\n #-----------------------------------------------------------------------------\n if(identical(x = return, y = \"data.frame\")) {\n df\n } else {\n coin\n }\n}\n", "meta": {"hexsha": "73997ee16cbc29f6773f2f1f75ac1e9a8b1af086", "size": 11827, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rdt.r", "max_stars_repo_name": "cran/rankdifferencetest", "max_stars_repo_head_hexsha": "f83ee1e13233b0fcd9f72939ceec0b65f95862b3", "max_stars_repo_licenses": ["MIT"], "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/rdt.r", "max_issues_repo_name": "cran/rankdifferencetest", "max_issues_repo_head_hexsha": "f83ee1e13233b0fcd9f72939ceec0b65f95862b3", "max_issues_repo_licenses": ["MIT"], "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/rdt.r", "max_forks_repo_name": "cran/rankdifferencetest", "max_forks_repo_head_hexsha": "f83ee1e13233b0fcd9f72939ceec0b65f95862b3", "max_forks_repo_licenses": ["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.2750809061, "max_line_length": 102, "alphanum_fraction": 0.6108057834, "num_tokens": 3087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6330634593049818}} {"text": "powerset <- function(set){\n\tps <- list()\n\tps[[1]] <- numeric()\t\t\t\t\t\t#Start with the empty set.\n\tfor(element in set){\t\t\t\t\t\t#For each element in the set, take all subsets\n\t\ttemp <- vector(mode=\"list\",length=length(ps))\t\t#currently in \"ps\" and create new subsets (in \"temp\")\n\t\tfor(subset in 1:length(ps)){\t\t\t\t#by adding \"element\" to each of them.\n\t\t\ttemp[[subset]] = c(ps[[subset]],element)\n\t\t}\n\t\tps <- c(ps,temp)\t\t\t\t\t\t#Add the additional subsets (\"temp\") to \"ps\".\n\t}\n\tps\n}\n\npowerset(1:4)\n", "meta": {"hexsha": "37eed500062d3664da44051789fcb336f95b1fa8", "size": 486, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Power-set/R/power-set-2.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Power-set/R/power-set-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Power-set/R/power-set-2.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": 32.4, "max_line_length": 102, "alphanum_fraction": 0.6193415638, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.8198933381139646, "lm_q1q2_score": 0.6328293419448375}} {"text": "#' GLS confidence intervals\n#'\n#' Computes confidence intervals for a GLS regression. When the variance covariance matrix is based on a phylogeny, this computes the confidence intervals for a phylogenetic regression (PGLS).\n#' @param Y Dependent variable.\n#' @param X Independent variable.\n#' @param Sigma Matrix describing the covariance among data points. For the phylogenetic regression, this is based on a phylogeny (vcv(tree)).\n#' @return GLS results.\n#' @return Confidence intervals of the estimates ('CI').\n#' @return Confidence intervals of unobserved values of Y ('CI.plot').\n#' @references Smaers & Rohlf (2016) Testing species' deviations from allometric preductions using the phylogenetic regression. Evolution. 70 (5): 1145-1149.\n#' @examples see https://smaerslab.com/software/ \n#' @export\ngls.ci<-function(Y,X,Sigma){\n n<-length(X)\n#Standardize sigma to reduce rounding errors\n tr<-sum(diag(Sigma))\n Sigma<-n*Sigma/tr\n#Input\n invSigma<-solve(Sigma)\n#pgls mean and variance\n X1<-rep(1,n)\n q<-2 # adjust if multivariate!!\n C1<-solve(t(X1)%*%invSigma%*%X1)\n Y_PGLSmean<-c(C1%*%t(X1)%*%invSigma%*%Y)\n Y_PGLSdeviations = Y - Y_PGLSmean\n Y_PGLSvariance = (t(Y_PGLSdeviations)%*%invSigma%*%Y_PGLSdeviations)/(n-1)\n SE_Y_mean = sqrt(Y_PGLSvariance/n)\n#Regression\n XX<-cbind(rep(1,n),X)\n C<-solve(t(XX)%*%invSigma%*%XX)\n w<-C%*%t(XX)%*%invSigma\n B<-w%*%Y\n Yhat<-XX%*%B\n Yresid=Y-Yhat\n Y_MSEresid<-c((t(Yresid)%*%invSigma%*%Yresid)/(n-q))\n a<-B[1]\n b<-B[2]\n#SE of statistics\n SEa<-sqrt(diag(C)*Y_MSEresid)[1]\n SEb<-sqrt(diag(C)*Y_MSEresid)[2]\n#Save model\n intercept<-cbind(a,SEa)\n slope<-cbind(b,SEb)\n model<-rbind(intercept,slope)\n colnames(model)<-c(\"Estimate\",\"Std.Error\")\n rownames(model)<-c(\"intercept\",\"slope\")\n#confint\n SEYhat<-sqrt(diag(XX%*%C%*%t(XX))%*%((t(Yresid)%*%invSigma%*%Yresid)/(n-q)))\n CI<-cbind(X,Yhat,SEYhat)\n Lower2.5<-Yhat-qt(0.975,n)*SEYhat\n Lower5<-Yhat-qt(0.95,n)*SEYhat\n Upper5<-Yhat+qt(0.95,n)*SEYhat\n Upper2.5<-Yhat+qt(0.975,n)*SEYhat\n CI<-cbind(CI,Lower2.5)\n CI<-cbind(CI,Lower5)\n CI<-cbind(CI,Upper5)\n CI<-cbind(CI,Upper2.5)\n CI<-CI[order(CI[,1]),]\n colnames(CI)<-c(\"X\",\"Yhat\",\"SEYhat\",\"Lower2.5\",\"Lower5\",\"Upper5\",\"Upper2.5\")\n CI<-as.data.frame(CI)\n#confint extrapolated\n Xi<-seq(c(min(X)-abs(max(X))),to=c(abs(max(X))*5),length.out=100)\n Z<-c(Xi)\n ZZ<-cbind(rep(1,length(Z)),Z)\n SEYhat.Xi<-sqrt(diag(ZZ%*%C%*%t(ZZ))%*%((t(Yresid)%*%invSigma%*%Yresid)/(n-q)))\n Yhat.Xi<-a+b*Xi\n Lower2.5.Yhat.Xi<-Yhat.Xi-qt(0.975,n)*SEYhat.Xi\n Lower5.Yhat.Xi<-Yhat.Xi-qt(0.95,n)*SEYhat.Xi\n Upper5.Yhat.Xi<-Yhat.Xi+qt(0.95,n)*SEYhat.Xi\n Upper2.5.Yhat.Xi<-Yhat.Xi+qt(0.975,n)*SEYhat.Xi\n CI.plot<-cbind(Xi,Yhat.Xi,SEYhat.Xi,Lower2.5.Yhat.Xi,Lower5.Yhat.Xi,Upper5.Yhat.Xi,Upper2.5.Yhat.Xi)\n colnames(CI.plot)<-c(\"X\",\"Yhat\",\"SEYhat\",\"Lower2.5\",\"Lower5\",\"Upper5\",\"Upper2.5\")\n CI.plot<-as.data.frame(CI.plot)\nresults<-list(model,CI,CI.plot)\nnames(results)<-c(\"model\",\"CI\",\"CI.plot\")\nreturn(results)\n}\n\n", "meta": {"hexsha": "b1b42a0852381e55a5a4a36e55917b1b065a9840", "size": 3232, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gls.ci.r", "max_stars_repo_name": "JeroenSmaers/evomap", "max_stars_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-01-07T04:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-15T19:42:12.000Z", "max_issues_repo_path": "R/gls.ci.r", "max_issues_repo_name": "JeroenSmaers/evomap", "max_issues_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/gls.ci.r", "max_forks_repo_name": "JeroenSmaers/evomap", "max_forks_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-10-14T18:26:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-10T04:57:55.000Z", "avg_line_length": 40.9113924051, "max_line_length": 192, "alphanum_fraction": 0.6237623762, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6326492441852116}} {"text": "# Random Walk for Brownian Motion\n# S_0 = 0\n# For all n >= 1, S_n = Epsilons_1 + ... Epsilons_n\n# ie S_n = S_(n-1) + Epsilons_n\n# 23-04-2015\n# Killian Martin--Horgassan\n\nrandomWalk = function(n, Epsilons) {\n\t\n\t# The vector of the Epsilon_i, they are uniformly distributed on {-1,+1}\n\tvect <- Epsilons\n\t\n\toutput <- rep(0,n+1)\n\t\n\tfor (i in 2:(n+1)) {\n\t\toutput[i] <- output[i-1]+vect[i-1]\n\t}\n\t\n\treturn(output)\n}\n", "meta": {"hexsha": "5c73077c4929e2b9f3476cd806d14c40550dde34", "size": 409, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_buildingBM/randomWalk.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_files_buildingBM/randomWalk.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_files_buildingBM/randomWalk.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4761904762, "max_line_length": 73, "alphanum_fraction": 0.630806846, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6325808769175707}} {"text": "## Function to do Wright-Fisher simulation with selection and a finite sample size\n# using set Ne, s, and initial allele frequency\n# Sample each generation\n\n# f1: the initial allele frequency uniform prior\n# s: the selection coefficient uniform prior\n# cnt: the size of the samples (in # chromosomes)\n# gen: the number of generations\n# ne: Ne value\n# h: dominance effect\n\nwfs_ts <- function(f1=0, s=0, cnt=50, gen=20, ne=100, h=0.5){ \n\tp <- rep(NA, gen)\n\tfsamp <- p\n\n\tp[1] <- f1 # current allele frequency\n\tfsamp[1] <- rbinom(1,cnt,p[1])/cnt # first sample allele frequency\n\twaa <- 1+s # relative fitness of genotype AA\n\twab <- 1+s*h\n\twbb <- 1\n\tfor(i in 2:gen){\n\t\tx <- (waa*p[i-1]^2 + wab*p[i-1]*(1-p[i-1]))/(waa*p[i-1]^2 + wab*2*p[i-1]*(1-p[i-1]) + wbb*(1-p[i-1])^2) # probability of sampling allele A, given selection\n\t\tp[i] <- rbinom(1,ne,x)/ne\n\t\tfsamp[i] <- rbinom(1,cnt,p[i])/cnt # first sample allele frequency\n#\t\tprint(paste(x,p))\n\t}\n\n\t\n\t# return values\n\tout <- list(gen=1:gen, p=p, fsamp=fsamp)\n\treturn(out)\n}\n", "meta": {"hexsha": "d40c992d02441accf27125d5237f8d718a3cce7c", "size": 1018, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/wfs_ts.r", "max_stars_repo_name": "pinskylab/codEvol", "max_stars_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/wfs_ts.r", "max_issues_repo_name": "pinskylab/codEvol", "max_issues_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-04-11T11:14:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T19:57:31.000Z", "max_forks_repo_path": "scripts/wfs_ts.r", "max_forks_repo_name": "pinskylab/codEvol", "max_forks_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_forks_repo_licenses": ["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.8484848485, "max_line_length": 157, "alphanum_fraction": 0.6542239686, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6323601959381006}} {"text": "do_summary_simple_mean <- function (x, target_var){\n\n\t# calculates simple (i.e., not stratified) mean statistics\n\t# Nuno Prista, SLU Aqua, Sweden\n\t# Developed @ KustMonitoring Review 2019\n\n\t#x is a dataframe or data.table with\n\t\t# # target values in target_var variable\n\n\n\t# 2019-05-06: added clow_mean and chigh_mean (confidence intervals)\n\n\t\t\n# ==========================\n# Non-stratified (Nst) results\n# ==========================\n\n\tvalues<-x[[target_var]]\n\t# simple mean\n\t\tNst_mean<-mean(values)\n\t# simple_var_mean\n\t\tNst_var_mean<-var(values)/length(values)\n\t# simple se of the mean\n\t\tNst_se_mean<-sd(values)/sqrt(length(values))\n\t# simple cv/rse of the mean \n\t\t\tNst_rse_mean<-round(Nst_se_mean/Nst_mean*100,1)\n\n\tlist(pop_res = data.frame(type = \"simple\", variable = target_var, n_tot = length(values), n_strata = NA, mean = Nst_mean, var_mean = Nst_var_mean, se_mean = Nst_se_mean, rse_mean = Nst_rse_mean, clow_mean=Nst_mean-2*Nst_se_mean, chigh_mean=Nst_mean+2*Nst_se_mean), stratum_res = NULL, type=\"stratified\")\n\n}\n", "meta": {"hexsha": "0641b082b7faa5b460e45c73bd924b1ec45691d8", "size": 1025, "ext": "r", "lang": "R", "max_stars_repo_path": "000_Funs/func_do_summary_simple_mean.r", "max_stars_repo_name": "nmprista/KustMonitorOptim", "max_stars_repo_head_hexsha": "cfcf327060013f24013350e1e6591b40bc672b3b", "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": "000_Funs/func_do_summary_simple_mean.r", "max_issues_repo_name": "nmprista/KustMonitorOptim", "max_issues_repo_head_hexsha": "cfcf327060013f24013350e1e6591b40bc672b3b", "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": "000_Funs/func_do_summary_simple_mean.r", "max_forks_repo_name": "nmprista/KustMonitorOptim", "max_forks_repo_head_hexsha": "cfcf327060013f24013350e1e6591b40bc672b3b", "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.064516129, "max_line_length": 305, "alphanum_fraction": 0.6995121951, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6323601879226206}} {"text": "## estimate effect sizes from association tests of features\n## se standard errors of the coefficients\n## mat input data matrix (features x samples)\nivwfe.stats <- function(estimate, se, mat=NULL, rho=NULL) {\n ## http://onlinelibrary.wiley.com/doi/10.1002/sim.6835/full\n ## calculate rho\n if (is.null(rho)) {\n stopifnot(!is.null(mat))\n rho <- ivwfe.rho(mat) \n } \n ## remove missing values\n na <- is.na(estimate) | is.na(se)\n if (sum(na) > 0) {\n if (sum(na) == length(estimate))\n return(c(B=NA, S=NA))\n\n estimate <- estimate[!na]\n se <- se[!na]\n rho <- rho[!na,!na,drop=F]\n }\n ## calculate statistics\n ivwfe.stats0 <- function(estimate, se, rho) {\n tryCatch({\n omega <- (se%*%t(se))*rho\n omega.inv <- solve(omega)\n one <- matrix(1,nrow=nrow(omega.inv), ncol=1)\n S2 <- 1/(t(one) %*% omega.inv %*% one)\n c(B=S2 * (t(one) %*% omega.inv) %*% estimate,\n S=sqrt(S2))\n }, error=function(e) {\n c(B=NA,S=NA)\n })\n }\n return(ivwfe.stats0(estimate, se, rho))\n}\n\nivwfe.getz <- function(estimate, se, mat=NULL, rho=NULL) {\n stats <- ivwfe.stats(estimate, se, mat, rho)\n as.vector(stats[\"B\"]/stats[\"S\"])\n}\n\n\n\nivwfe.rho <- function(mat) {\n mat <- t(mat)\n ## correlation matrix + nudge (to ensure invertible)\n rho <- cor(mat, use=\"p\") + diag(x=0.05,ncol(mat),ncol(mat))\n}\n\nivwfe.ma <- function(estimates, se) {\n weights <- 1/se^2\n se <- sqrt(1/rowSums(weights, na.rm=T))\n estimates <- rowSums(estimates * weights, na.rm=T)/rowSums(weights, na.rm=T)\n z <- estimates/se\n p <- 2*pnorm(-abs(z), lower.tail=T)\n data.frame(estimate=estimates,\n se=se,\n z=z,\n p.value=p)\n}\n\n", "meta": {"hexsha": "0418f8f3b1245e416db52fea55756baabf1aa48f", "size": 1821, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ivwfe.r", "max_stars_repo_name": "perishky/dmrff", "max_stars_repo_head_hexsha": "7b9443d0e89b4e22c742377582bc9067c32c2c0d", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-12-31T18:14:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T06:13:38.000Z", "max_issues_repo_path": "R/ivwfe.r", "max_issues_repo_name": "perishky/dmrff", "max_issues_repo_head_hexsha": "7b9443d0e89b4e22c742377582bc9067c32c2c0d", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2018-12-06T16:17:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T14:30:05.000Z", "max_forks_repo_path": "R/ivwfe.r", "max_forks_repo_name": "perishky/dmrff", "max_forks_repo_head_hexsha": "7b9443d0e89b4e22c742377582bc9067c32c2c0d", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-08-19T20:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T04:35:11.000Z", "avg_line_length": 29.3709677419, "max_line_length": 80, "alphanum_fraction": 0.5398132894, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6323110798921963}} {"text": "#' Estimating the inverse first-order reliability method (IFORM) environmental contours\r\n#'\r\n#' @description\r\n#' This function estimates the Invserse FORM (IFORM) environmental contours, as proposed in Winterstein et al. (1993)\r\n#' for a given sample data set or a fitted joint distribution of class \\code{ht} or \\code{wln}.\r\n#' \r\n#' @param object either a fitted joint distribution of class \\code{wln} or \\code{ht}, or an existing sample data\r\n#' set containing \\code{hs} and \\code{tp} as columns. See details.\r\n#' \r\n#' @param output_rp the required return periods (in years) for the estimated contours.\r\n#' \r\n#' @param npy the (optional) number of data points per year. This argument is only needed if the input\r\n#' \\code{object} is a sample data set.\r\n#' \r\n#' @param n_point the number of points to output around each contour. The default value is 100.\r\n#' \r\n#' @param alpha0 the omission factor for the IFORM contours. The default value is 0, meaning no\r\n#' inflation to the estimated contours.\r\n#' \r\n#' @details\r\n#' The IFORM contour is constructed based on the first-order reliability method (FORM) and \r\n#' it searches a hypersphere of constant radius to find the maximum response.\r\n#' \r\n#' The function can be applied to an existing sample set, which can be generated by function \\code{\\link{sample_jdistr}}\r\n#' or otherwise by importing a CSV file using function \\code{\\link[data.table]{fread}}. The input sample data\r\n#' object must contain \\code{hs} and \\code{tp} as columns. The user must also specify the number of points per year\r\n#' \\code{npy} and a valid \\code{output_rp}, i.e. the maximum \\code{output_rp} must be shorter than the total\r\n#' duration of the data set.\r\n#' \r\n#' Alternatively this function can be applied to a fitted joint distribution object\r\n#' generated by function \\code{\\link{fit_ht}} or \\code{\\link{fit_wln}}. When applied to a \\code{ht} object,\r\n#' the estimated contour is a blending between the two conditional models \\eqn{Hs|Tp>tp} and \\eqn{Tp|Hs>hs} above\r\n#' high thresholds \\eqn{tp} and \\eqn{hs}, as specified in Heffernan and Tawn (2004).\r\n#' \r\n#' @return A set of estimated IFORM contours with the specified return periods in the format\r\n#' of a \\code{data.table} with \\code{rp}, \\code{hs}, and \\code{tp} as columns.\r\n#'\r\n#' @examples\r\n#' # Estimating IFORM contours based on a fitted model\r\n#' data(ww3_pk)\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 50, dep_thresh_count = 500)\r\n#' ec_ht = estimate_iform(object = ht, output_rp = c(10,100,1000,10000))\r\n#' plot_ec(ec = ec_ht, raw_data = ww3_pk)\r\n#' \r\n#' # Estimating IFORM contours based on a sample data set\r\n#' data(ww3_ts)\r\n#' ec_data = estimate_iform(object = ww3_ts, output_rp = c(.5, 1, 2), npy = ww3_ts[, .N/10])\r\n#' plot_ec(ec = ec_data, raw_data = ww3_ts)\r\n#' \r\n#' @references\r\n#' Winterstein, S. R., Ude, T. C., Cornell, C. A., Bjerager, P., Haver, S., 1993. Environmental parameters\r\n#' for extreme variable: Inverse Form with omission factors. In: Proc. 6th Int. Conf. on\r\n#' Structural Safety and Reliability, Innsbruck, Austria.\r\n#' \r\n#' Heffernan, Janet & A. Tawn, Jonathan. (2004). A Conditional Approach for Multivariate Extreme Values.\r\n#' Journal of the Royal Statistical Society Series B. 66. 497-546. 10.1111/j.1467-9868.2004.02050.x. \r\n#' \r\n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}, \\code{\\link{sample_jdistr}}, \\code{\\link{plot_ec}}\r\n#' \r\n#' @export\r\nestimate_iform = function(\r\n object, output_rp, npy = NULL, n_point=100, alpha0=0){\r\n \r\n if(\"wln\" %in% class(object)){\r\n \r\n res = .estimate_iform_from_wln(wln = object, output_rp = output_rp, n_point = n_point, alpha0 = alpha0)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"ht\" %in% class(object)){\r\n \r\n res = .estimate_iform_from_ht(ht = object, output_rp = output_rp, n_point = n_point, alpha0 = alpha0)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"data.table\" %in% class(object)){\r\n \r\n if(is.null(npy)){\r\n stop(\"Argument npy must be provided for estimating contours from sample data.\")\r\n }else{\r\n invalid_rp = output_rp[output_rp>object[, .N/npy]]\r\n if(length(invalid_rp)==length(output_rp)){\r\n stop(\"All output_rp values are invalid as they require extrapolation. Consider fitting a joint distribution first.\")\r\n }else if(length(invalid_rp)>=1 & length(invalid_rp)ht$dep$p_dep_thresh]\r\n calc_hs[, hs:=.convert_unif_to_origin(\r\n unif = p1, p_thresh = p_thresh, gpd_par = ht$margin$hs$par, emp = ht$margin$hs$emp)]\r\n\r\n # Estimate tp based on tp|hs HT model for large hs\r\n calc_hs[, lap1:=.convert_unif_to_lap(p1)]\r\n calc_hs[, resid_q:=quantile(ht$dep$hs$resid, p2)]\r\n calc_hs[,lap2:=ht$dep$hs$par[1]*lap1+resid_q*lap1^ht$dep$hs$par[2]]\r\n calc_hs[, p_tp:=.convert_lap_to_unif(lap2)]\r\n calc_hs[, tp:=.convert_unif_to_origin(\r\n unif = p_tp, p_thresh = p_thresh, gpd_par = ht$margin$tp$par, emp = ht$margin$tp$emp)]\r\n\r\n # Estimate tp based on tp model\r\n calc_tp = calc[p2>ht$dep$p_dep_thresh]\r\n calc_tp[, tp:=.convert_unif_to_origin(\r\n unif = p2, p_thresh = p_thresh, gpd_par = ht$margin$tp$par, emp = ht$margin$tp$emp)]\r\n \r\n # Estimate hs based on hs|tp HT model for large tp\r\n calc_tp[, lap2:=.convert_unif_to_lap(p2)]\r\n calc_tp[, resid_q:=quantile(ht$dep$tp$resid, p1)]\r\n calc_tp[,lap1:=ht$dep$tp$par[1]*lap2+resid_q*lap2^ht$dep$tp$par[2]]\r\n calc_tp[, p_hs:=.convert_lap_to_unif(lap1)]\r\n calc_tp[, hs:=.convert_unif_to_origin(\r\n unif = p_hs, p_thresh = p_thresh, gpd_par = ht$margin$hs$par, emp = ht$margin$hs$emp)]\r\n \r\n # Return\r\n res = merge(\r\n x = calc_hs[, .(rp, angle, hs, tp)], y = calc_tp[, .(rp, angle, hs, tp)],\r\n by=c(\"rp\", \"angle\"), all=T)\r\n res[is.na(hs.x), hs:=hs.y]\r\n res[is.na(tp.x), tp:=tp.y]\r\n res[is.na(hs.y), hs:=hs.x]\r\n res[is.na(tp.y), tp:=tp.x]\r\n res[!is.na(hs.x+hs.y), hs:=hs.x*cos(angle)^2+hs.y*sin(angle)^2]\r\n res[!is.na(hs.x+hs.y), tp:=tp.x*cos(angle)^2+tp.y*sin(angle)^2]\r\n setkey(res, rp, angle)\r\n return(res[, .(rp, hs, tp)])\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ebf4a9582e4ef4020322d4b14fb18a55fff10e37", "size": 9434, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/estimate_iform.r", "max_stars_repo_name": "ECSADES/ecsades-r", "max_stars_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-09-17T00:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T08:13:22.000Z", "max_issues_repo_path": "ecsades/R/estimate_iform.r", "max_issues_repo_name": "ECSADES/ecsades-r", "max_issues_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2019-01-22T13:00:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-04T16:45:59.000Z", "max_forks_repo_path": "ecsades/R/estimate_iform.r", "max_forks_repo_name": "ECSADES/ecsades-r", "max_forks_repo_head_hexsha": "47ea50385c48030729d8227031a8ca73ab6a30b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3049327354, "max_line_length": 134, "alphanum_fraction": 0.6552893788, "num_tokens": 2953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6320933265490468}} {"text": "\n\n#' @name MGB2\n#' @rdname MGB2\n#' @aliases dMGB2 pMGB2 hMGB2\n#' @title Bivarite MGB2 copula\n#' @description Density, distribution function, and h-functions for the bivariate MGB2 copula proposed in Yang et al.,(2011).\n#' @param u1,u2 numeric vectors of equal length with values in \\eqn{[0,1]}.\n#' @param pars1,pars2,pars3 copula parameters, denoted by \\eqn{p_1, p_2, q}.\n#' @importFrom stats qbeta\n#' @importFrom stats pbeta\n#' @references Xipei Yang, Edward W Frees, and Zhengjun Zhang. A generalized beta copula with applications in\n#' modeling multivariate long-tailed data. Insurance: Mathematics and Economics, 49(2):265-284, 2011.\n#' @details\n#' The MGB2 copula with parameters (p1, p2, q) has joint density\n#' \t\t\\deqn{c(u_1,u_2;p_1,p_2,q)=\\frac{\\Gamma(q)\\Gamma(\\sum_{i=1}^2 p_i + q)}{\\prod_{i=1}^2\\Gamma(p_i+q)}\\frac{\\prod_{i=1}^2 (1 + x(u_i;p_i,q))^{p_i+q}}{(1 + \\sum_{i=1}^{2}x(u_i;p_i,q))^{\\sum_{i=1}^{2}p_i+q}},}\n#' for \\eqn{p_1, p_2>0, q>0}.\n#' (Here Gamma(a) is the function implemented by R's \\code{\\link[base]{gamma}} and defined in its help.\n#'\n#'\n#' The joint cdf of the MGB2 copula is\n#'\n#' \\deqn{C(u_1,u_2;p_1,p_2,q)=\\int_{0}^{+\\infty}\\prod_{i=1}^{2}G_p(\\frac{I_{p_i,q}^{-1}(u_i)}{(1-I_{p_i,q}^{-1}(u_i))\\theta})\\times \\frac{\\theta^{-(q+1)}e^{-1/\\theta}}{\\Gamma(q)}d\\theta, }\n#' where \\eqn{I_{m,n}^{-1}()} denotes the inverse of the beta cumulative distribution function (or regularized incomplete beta function)\n#' with parameters shape1 = m and shape2 = n\n#' implemented by R's \\code{\\link[stats]{qbeta}}.\n#'\n#' The h-function is defined as the conditional distribution function of a bivariate copula, i.e.,\n#' \\deqn{h_1(u_2|u_1,p_1,p_2,q) := P(U_2 \\leq u_2 | U_1 = u_1) = \\partial C(u_1,u_2) / \\partial u_1,}\n#'\n#' \\deqn{h_2(u_1|u_2,p_1,p_2,q) := P(U_1 \\leq u_1 | U_2 = u_2) := \\partial C(u_1,u_2) / \\partial u_2,}\n#'\n#' where \\eqn{(U_1, U_2) \\sim C}, and \\eqn{C} is a bivariate copula distribution function with parameter(s) \\eqn{p_1,p_2,q}.\n#'\n#'\n#' @return\n#' \\code{dcMGB2.bivar} gives the density\n#'\n#' \\code{pcMGB2.bivar} gives the distribution function\n#'\n#' \\code{hcMGB2.bivar} gives the h-functions (hfunc1, hfunc2).\nNULL\n\n#' @rdname MGB2\n#' @export\n#' @examples\n#' dcMGB2.bivar(u1 = c(0.2, 0.5), u2 = c(0.9, 0.2), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)\ndcMGB2.bivar <- function(u1, u2, pars1, pars2, pars3) {\n dim <- 2\n p1 <- pars1\n p2 <- pars2\n q <- pars3\n\n x1 <- qbeta(u1, shape1 = p1, shape2 = q) / (1 - qbeta(u1, shape1 = p1, shape2 = q))\n x2 <- qbeta(u2, shape1 = p2, shape2 = q) / (1 - qbeta(u2, shape1 = p2, shape2 = q))\n\n if (u1 == 0 | u2 == 0) {\n dc <- 0\n } else {\n dc <- gamma(q)^(dim - 1) * gamma(p1 + p2 + q) / (gamma(p1 + q) * gamma(p2 + q)) * (1 + x1)^(p1 + q) * (1 + x2)^(p2 + q) / (1 + x1 + x2)^(p1 + p2 + q)\n }\n dc\n}\ndcMGB2.bivar <- Vectorize(dcMGB2.bivar)\n\n\n\n#' @rdname MGB2\n#' @export\n#' @examples\n#' pcMGB2.bivar(u1 = c(0.5, 0.1), u2 = c(0.9, 0.1), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)\npcMGB2.bivar <- function(u1, u2, pars1, pars2, pars3) {\n p1 <- pars1\n p2 <- pars2\n q <- pars3\n\n x1 <- qbeta(u1, shape1 = p1, shape2 = q) / (1 - qbeta(u1, shape1 = p1, shape2 = q))\n x2 <- qbeta(u2, shape1 = p2, shape2 = q) / (1 - qbeta(u2, shape1 = p2, shape2 = q))\n fin <- function(theta) { # rely on a\n m1 <- x1 / theta\n m2 <- x2 / theta\n z1 <- pgamma(m1, shape = p1, scale = 1) * pgamma(m2, shape = p2, scale = 1)\n out <- z1 * theta^(-(q + 1)) * exp(-1 / theta) / gamma(q)\n out\n }\n if (u1 == 0 | u2 == 0) {\n z <- 0\n } else {\n z <- as.numeric(pracma::integral(fun = fin, xmin = 0, xmax = Inf, method = \"Clenshaw\"))\n # z <- as.numeric(integrate(f = fin, lower = 0, upper = Inf, rel.tol = 1e-4)$value)\n }\n return(z) # rely on k\n}\npcMGB2.bivar <- Vectorize(pcMGB2.bivar)\n\n\n#' @rdname MGB2\n#' @export\n#' @examples\n#' hcMGB2.bivar(u1 = c(0.5, 0.1), u2 = c(0.9, 0.1), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)$hfunc1\n#' hcMGB2.bivar(u1 = c(0.5, 0.1), u2 = c(0.9, 0.1), pars1 = 0.5, pars2 = 0.5, pars3 = 1.5)$hfunc2\nhcMGB2.bivar <- function(u1, u2, pars1, pars2, pars3) {\n p1 <- pars1\n p2 <- pars2\n q <- pars3\n\n x1 <- qbeta(u1, shape1 = p1, shape2 = q) / (1 - qbeta(u1, shape1 = p1, shape2 = q))\n x2 <- qbeta(u2, shape1 = p2, shape2 = q) / (1 - qbeta(u2, shape1 = p2, shape2 = q))\n\n index1 <- u1 == 1 & u2 != 1\n index2 <- u1 != 1 & u2 == 1\n index3 <- u1 == 1 & u2 == 1\n z1 <- x2 / (x1 + x2 + 1)\n z2 <- x1 / (x2 + x1 + 1)\n z1[index1] <- 0\n z2[index1] <- 1\n z1[index2] <- 1\n z2[index2] <- 0\n z1[index3] <- 1\n z2[index3] <- 1\n hfunc1 <- pbeta(z1, shape1 = p2, shape2 = p1 + q)\n hfunc2 <- pbeta(z2, shape1 = p1, shape2 = p2 + q)\n list(hfunc1 = hfunc1, hfunc2 = hfunc2)\n}\n", "meta": {"hexsha": "b52fc8c0da3ca33d6b8044fbda4e5f6db0ec2cf3", "size": 4672, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MGB2-bivariate.r", "max_stars_repo_name": "lizhengxiao/rMGLReg", "max_stars_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/MGB2-bivariate.r", "max_issues_repo_name": "lizhengxiao/rMGLReg", "max_issues_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-10T13:04:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T11:13:27.000Z", "max_forks_repo_path": "R/MGB2-bivariate.r", "max_forks_repo_name": "lizhengxiao/rMGLReg", "max_forks_repo_head_hexsha": "8823d8a0409616ddb3bb75cdba436865dd979604", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.376, "max_line_length": 209, "alphanum_fraction": 0.5898972603, "num_tokens": 2076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6314795128218015}} {"text": "# Chapter 8 Lab: Decision Trees\n\n# Fitting Classification Trees\n\nlibrary(tree)\nlibrary(ISLR)\nattach(Carseats)\nHigh=ifelse(Sales<=8,\"No\",\"Yes\")\nCarseats=data.frame(Carseats,High)\ntree.carseats=tree(High~.-Sales,Carseats)\nsummary(tree.carseats)\nplot(tree.carseats)\ntext(tree.carseats,pretty=0)\ntree.carseats\nset.seed(2)\ntrain=sample(1:nrow(Carseats), 200)\nCarseats.test=Carseats[-train,]\nHigh.test=High[-train]\ntree.carseats=tree(High~.-Sales,Carseats,subset=train)\ntree.pred=predict(tree.carseats,Carseats.test,type=\"class\")\ntable(tree.pred,High.test)\n(86+57)/200\nset.seed(3)\ncv.carseats=cv.tree(tree.carseats,FUN=prune.misclass)\nnames(cv.carseats)\ncv.carseats\npar(mfrow=c(1,2))\nplot(cv.carseats$size,cv.carseats$dev,type=\"b\")\nplot(cv.carseats$k,cv.carseats$dev,type=\"b\")\nprune.carseats=prune.misclass(tree.carseats,best=9)\nplot(prune.carseats)\ntext(prune.carseats,pretty=0)\ntree.pred=predict(prune.carseats,Carseats.test,type=\"class\")\ntable(tree.pred,High.test)\n(94+60)/200\nprune.carseats=prune.misclass(tree.carseats,best=15)\nplot(prune.carseats)\ntext(prune.carseats,pretty=0)\ntree.pred=predict(prune.carseats,Carseats.test,type=\"class\")\ntable(tree.pred,High.test)\n(86+62)/200\n\n# Fitting Regression Trees\n\nlibrary(MASS)\nset.seed(1)\ntrain = sample(1:nrow(Boston), nrow(Boston)/2)\ntree.boston=tree(medv~.,Boston,subset=train)\nsummary(tree.boston)\nplot(tree.boston)\ntext(tree.boston,pretty=0)\ncv.boston=cv.tree(tree.boston)\nplot(cv.boston$size,cv.boston$dev,type='b')\nprune.boston=prune.tree(tree.boston,best=5)\nplot(prune.boston)\ntext(prune.boston,pretty=0)\nyhat=predict(tree.boston,newdata=Boston[-train,])\nboston.test=Boston[-train,\"medv\"]\nplot(yhat,boston.test)\nabline(0,1)\nmean((yhat-boston.test)^2)\n\n# Bagging and Random Forests\n\nlibrary(randomForest)\nset.seed(1)\nbag.boston=randomForest(medv~.,data=Boston,subset=train,mtry=13,importance=TRUE)\nbag.boston\nyhat.bag = predict(bag.boston,newdata=Boston[-train,])\nplot(yhat.bag, boston.test)\nabline(0,1)\nmean((yhat.bag-boston.test)^2)\nbag.boston=randomForest(medv~.,data=Boston,subset=train,mtry=13,ntree=25)\nyhat.bag = predict(bag.boston,newdata=Boston[-train,])\nmean((yhat.bag-boston.test)^2)\nset.seed(1)\nrf.boston=randomForest(medv~.,data=Boston,subset=train,mtry=6,importance=TRUE)\nyhat.rf = predict(rf.boston,newdata=Boston[-train,])\nmean((yhat.rf-boston.test)^2)\nimportance(rf.boston)\nvarImpPlot(rf.boston)\n\n# Boosting\n\nlibrary(gbm)\nset.seed(1)\nboost.boston=gbm(medv~.,data=Boston[train,],distribution=\"gaussian\",n.trees=5000,interaction.depth=4)\nsummary(boost.boston)\npar(mfrow=c(1,2))\nplot(boost.boston,i=\"rm\")\nplot(boost.boston,i=\"lstat\")\nyhat.boost=predict(boost.boston,newdata=Boston[-train,],n.trees=5000)\nmean((yhat.boost-boston.test)^2)\nboost.boston=gbm(medv~.,data=Boston[train,],distribution=\"gaussian\",n.trees=5000,interaction.depth=4,shrinkage=0.2,verbose=F)\nyhat.boost=predict(boost.boston,newdata=Boston[-train,],n.trees=5000)\nmean((yhat.boost-boston.test)^2)\n\n", "meta": {"hexsha": "60d0cca70b5569911ab06c6d359b3f242815cc89", "size": 2932, "ext": "r", "lang": "R", "max_stars_repo_path": "islr/r_code/chap8.r", "max_stars_repo_name": "AtmaMani/pyChakras", "max_stars_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "islr/r_code/chap8.r", "max_issues_repo_name": "AtmaMani/pyChakras", "max_issues_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-03-12T01:01:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:01:42.000Z", "max_forks_repo_path": "islr/r_code/chap8.r", "max_forks_repo_name": "AtmaMani/pyChakras", "max_forks_repo_head_hexsha": "e58a4e244d65858049914cf98dcb454ef009362a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-09T02:11:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T19:34:32.000Z", "avg_line_length": 29.9183673469, "max_line_length": 125, "alphanum_fraction": 0.7680763984, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6311906451518623}} {"text": "library(gridExtra)\nlibrary(tidyverse)\nlibrary(deSolve)\nlibrary(ggplot2)\nlibrary(plotly)\nlibrary(shinythemes)\nlibrary(shinyjs)\n#library(covdata)\n\n## Configuration\ntheme_set(theme_minimal(base_size = 12))\n\n## CONSTANTS\n\n# Population size \nN <- 1394000\n\n# Rate at which person stays in the infectious compartment (disease specific and tracing specific)\ngamma <- 0.14\n\n# Initial number of infected people\nn_init <- 1\n\nx_max = 365\nmax_time <- 365\n# # Grid where to evaluate\n# max_time <- 365 # 150\n# times <- seq(0, max_time, by = 0.1)\n\n# R0 for the beta and gamma values\n# R0 <- beta*N/gamma\n\n# calculate beta\n# Infectious contact rate - beta = R0/N*gamma and when R0 ~2.25 then 2.25/N*gamma\n# beta <- 4.5e-07 \n\n# Function to compute the derivative of the ODE system\n# -----------------------------------------------------------\n# t - time\n# y - current state vector of the ODE at time t\n# parms - Parameter vector used by the ODE system (beta, gamma)\n\ndiffsdp<-function(sdp)\n{\n # Compute the square of integer `n`\n dif <- as.numeric(as.Date(sdp) - as.Date(\"2020-03-03\"))\n return(dif)\n}\n\n\nsir <- function(t, y, parms, \n social_dist_period, \n reduction) {\n \n beta0 <- parms[1]\n gamma <- parms[2]\n\n #print(social_dist_period)\n \n if (t <= social_dist_period[1]) {\n beta_t = beta0;\n #cat('1. This is loop number',t)\n }\n else if (t >=social_dist_period[1] && t <= social_dist_period[2]) {\n beta_t = beta0 * reduction[1];\n #cat('2. This is loop number',t)\n }\n else if (t >=social_dist_period[2] && t <= social_dist_period[3]) {\n beta_t = beta0 * reduction[2];\n #cat('3. This is loop number',t)\n }\n else if (t >=social_dist_period[3] && t <= social_dist_period[4]) {\n beta_t = beta0 * reduction[3];\n #cat('3. This is loop number',t)\n }\n else {\n beta_t = beta0 * reduction[4];\n #cat('4. This is loop number',t)\n }\n \n # Reduce contact rate \n #beta_t <- if_else(t <= social_dist_period[1], \n # beta0,\n # if_else(t <= social_dist_period[2], \n # beta0 * reduction[1],\n # beta0 * reduction[2]\n # )\n #)\n \n S <- y[1]\n I <- y[2]\n R <- y[3]\n return(list(c(S = -beta_t * S * I, \n I = beta_t * S * I - gamma * I,\n R = gamma * I)))\n}\n\n## we assume that some globals exist...\nsolve_ode <- function(sdp, red, typ, beta, max_time) {\n \n # Grid where to evaluate\n times <- reactive({ seq(0, max_time, by = 0.1) })\n \n ode_solution <- lsoda(y = c(N - n_init, n_init, 0), \n times = times(), \n func = sir, \n parms = c(beta, gamma), \n social_dist_period = sdp,\n reduction = red) %>%\n as.data.frame() %>%\n setNames(c(\"t\", \"S\", \"I\", \"R\")) %>%\n mutate(beta = beta, \n gama = gamma,\n R0 = N * beta / gamma, \n s = S, \n i = I, \n type = typ)\n \n daily <- ode_solution %>%\n filter(t %in% seq(0, max_time, by = 1)) %>%\n mutate(C = if_else(row_number() == 1, 0, lag(S, k = 1) - S), \n c = C)\n \n daily\n}\n\n\n# add results with intervention and plot\nrun <- function(sdp, red, r0, max_time) {\n #print(sdp)\n #print(\"sdp\")\n #print(sdp2)\n #print(\"sdp2\")\n print(red)\n shinyjs::logjs(red)\n #print(\"red\")\n \n beta <- r0 / N * gamma\n \n ode_solution_daily <- solve_ode(\n sdp = c(0, max_time,max_time,max_time), # social_dist_period\n red = c(1, 1, 1, 1), # reduction\n typ = \"If there was no Lockdown\", \n beta = beta, \n max_time\n )\n \n # solve with interventions\n ode_solution2_daily <- solve_ode(\n sdp = sdp,\n red = red,\n typ = \"with Lockdown\", \n beta = beta, \n max_time\n )\n \n # solve with interventions\n #ode_solution3_daily <- solve_ode(\n # sdp = sdp2,\n # red = c(0.66, 0.8),\n # typ = \"with Lockdown2\", \n # beta = beta, \n # max_time\n #) \n \n # Combine the two solutions into one dataset\n ode_df <- rbind(ode_solution_daily, ode_solution2_daily)\n \n}\n\nplot_lockdown <- function(ode_df, sdp) { \n #print(\"Plot Result\")\n #print(sdp)\n #print(ode_df)\n #write.csv(x=ode_df, file=\"ode_df\")\n max_time = 365\n # The final size in the two cases:\n final_sizes <- ode_df %>%\n group_by(type) %>%\n filter(row_number() == n()) %>%\n mutate(\"Proportion Infected\" = scales::percent(1 - s, accuracy = 1)) %>%\n select(\"Proportion Infected\", interventions = type) %>% \n arrange(desc(interventions))\n \n # Plot\n y_axis_fixed = FALSE\n if (y_axis_fixed) {\n y_max <- 0.09\n } else {\n y_max <- max(ode_df$c, na.rm = TRUE) * 1.05\n }\n y_arrow <- y_max * 0.975\n y_text <- y_arrow + y_max * 0.01 \n col_sdp <- \"deeppink4\"\n \n x_labs <- sort(c(0, 150, 200, 300, 365, sdp))\n start = as.Date(\"2020-03-03\")\n ode_df$date <- as.Date(ode_df$t+start)\n \n pp <-ggplotly(\n ggplot(ode_df, \n aes(x = t, \n y = 0, \n xend = t, \n yend = c, \n color = type,\n name = date)) + \n geom_segment(alpha = 0.7) + \n geom_line(aes(x = t, y = c)) + \n labs(\n x = \"Days from first known case\", \n y = \"Forecasts for Infected Daily\", \n subtitle = \"Daily new cases\", \n caption = \"SIQ: Separate, Isolate and Quarantine period\") +\n scale_x_continuous(labels = x_labs, \n breaks = x_labs) +\n scale_y_continuous(limits = c(0, y_max), labels = scales::comma) + \n #scale_color_brewer(name = \"Key\", \n # type = \"qual\", \n # palette = 6, \n # guide = guide_legend(reverse = TRUE)) +\n # sdp \n #geom_hline(yintercept = 10900, color = \"deeppink4\") +\n geom_vline(xintercept = sdp, lty = 2, color = \"gray30\") +\n geom_text(aes(x = 10 + sdp[1] + (sdp[2] - sdp[1])/2, \n y = y_text, \n label = \"With No Lockdown\"),\n vjust = 0,\n color = col_sdp) + \n geom_text(aes(x = sdp[2] + 100, \n y = y_text, \n label = \"With Lockdowns\"),\n vjust = 0,\n color = \"springgreen3\") + \n geom_segment(aes(\n x = sdp[1],\n y = y_arrow, \n xend = sdp[2] * 0.99, # shorten\n yend = y_arrow\n ),\n size = 0.3, \n color = col_sdp,\n arrow = arrow(length = unit(2, \"mm\"))) +\n geom_segment(aes(\n x = sdp[2]*1.01, # shorten\n y = y_arrow, \n xend = max_time,\n yend = y_arrow\n ),\n size = 0.3, \n color = col_sdp,\n arrow = arrow(length = unit(2, \"mm\"))) +\n # Add final size as table\n annotation_custom(tableGrob(final_sizes, \n rows = NULL,\n theme = ttheme_minimal(\n core = list(fg_params = list(hjust = 0, x = 0.1)),\n rowhead = list(fg_params = list(hjust = 0, x = 0))\n )),\n xmin = max_time * 0.4,\n xmax = max_time,\n ymin = y_max * 0.8,\n ymax = y_max * 0.8\n )\n )\n ggplotly(pp, tooltip=\"c\")\n}\n\nplot_predict <- function(ode_df, sdp) { \n print(sdp)\n max_time = 365\n \n x_labs <- sort(c(0, 200, 300, 365, sdp))\n start = as.Date(\"2020-03-03\")\n ends = as.Date(\"2020-03-03\")\n ode_df$date <- as.Date(ode_df$t+start)\n #filtered <- subset(ode_df, type == \"with SIQ\")\n result <- filter(ode_df, type == \"with Lockdown\")\n result$Dead <-result$C * 0.005\n total_deaths = sum(result$Dead)\n total_cases = sum(result$C)\n total_detected_cases = sum(result$C) * 0.2\n y_max <- max(result$c, na.rm = TRUE) * 1.05\n y_arrow <- y_max * 0.975\n y_text <- y_arrow + y_max * 0.01 \n col_sdp <- \"deeppink4\"\n \n result = head(result, 365)\n names(result)[names(result) == \"C\"] <- \"daily_infections\"\n result$CumulativeCases <-cumsum(result$daily_infections)\n #print(result)\n \n pp1 <-ggplotly(\n ggplot(result, aes(date, daily_infections)) +\n geom_bar(stat=\"identity\", na.rm = TRUE, fill = \"darkturquoise\") + \n labs(\n x = \"Date\", \n y = \"Infected Daily\") + #ggtitle(\"Predicted Daily Infections with Lockdown Interventions\") + \n #title = \"Predicted Daily Infections with Lockdown Interventions\") + \n geom_vline(xintercept=as.numeric(ode_df$date[sdp]), colour=\"gray30\",linetype=\"dotted\") +\n scale_x_date(date_breaks = \"1 month\", date_minor_breaks = \"1 week\",\n date_labels = \"%B\") + theme(axis.text.x = element_text(angle = 60, hjust = 1)) + \n theme(axis.text=element_text(size=8),\n axis.title=element_text(size=8)) +\n annotate(geom=\"text\",x=start + 45,\n y=y_max, label=\"Full Lockdown\",fontface=\"bold\", color = \"deeppink4\") + \n annotate(geom=\"text\",x=ends + sdp[2] + 4,\n y=y_max,label=\"Ph 1\",fontface=\"bold\",color = \"deeppink4\") + \n annotate(geom=\"text\",x=ends + sdp[3] + 4,\n y=y_max,label=\"Ph 2\",fontface=\"bold\",color = \"deeppink4\") +\n annotate(geom=\"text\",x=ends + sdp[4] + 4,\n y=y_max,label=\"Ph 3\",fontface=\"bold\",color = \"deeppink4\") +\n annotate(geom=\"text\",x=ends + 300,\n y=y_max, label=sprintf(\"Total Cases = %s\",toString(ceiling(total_cases))),fontface=\"bold\",color = \"red\") +\n annotate(geom=\"text\",x=ends + 300,\n y=y_max * .9, label=sprintf(\"Total Detected Cases = %s\",toString(ceiling(total_detected_cases))),fontface=\"bold\",color = \"red\") +\n annotate(geom=\"text\",x=ends + 300,\n y=y_max * .8, label=sprintf(\"Total Dead = %s\",toString(ceiling(total_deaths))),fontface=\"bold\",color = \"red\")\n + scale_y_continuous(labels = scales::comma)\n \n )\n ggplotly(pp1, tooltip=\"daily_infections\")\n}\n\nmake_summary_table <- function(ode_df, sdp) {\n \n start = as.Date(\"2020-03-03\")\n ends = as.Date(\"2020-03-03\") + sdp[1]\n ode_df$date <- as.Date(ode_df$t+start)\n prediction <- filter(ode_df, type == \"with Lockdown\")\n \n prediction$Dead <-prediction$C * 0.005\n prediction$Detected_Cases <-prediction$C * 0.1\n \n summary <- prediction %>%mutate(Year_Month = format(date, \"%Y-%m\")) %>%\n group_by(Year_Month) %>%\n summarise(total_predicted_cases = ceiling(sum(C)), total_detected_cases = ceiling(sum(Detected_Cases)), total_predicted_deaths = ceiling(sum(Dead)))\n \n summary <- summary[order(summary$Year_Month),]\n \n return(summary)\n \n}\n\nplot_real <- function(ode_df, sdp) { \n guy <- read.csv(file = 'Trinidad.csv')\n guy$date <- as.Date(guy$date)\n pp3 <-ggplotly(\n ggplot(guy, aes(x=date)) +\n geom_line(aes(y = cu_cases, color = \"Cumulative Cases\")) + \n geom_line(aes(y = cu_deaths, color = \"Cumulative Deaths\")) +\n geom_point(aes(y = cases, color = \"Cases\", alpha=1/3), shape=1) +\n geom_point(aes(y = deaths, color = \"Deaths\",alpha=1/3), shape = 4) + \n scale_colour_manual(\"\", \n breaks = c(\"Cumulative Cases\", \"Cumulative Deaths\", \"Cases\",\"Deaths\"),\n values = c(\"turquoise3\", \"red\", \"turquoise3\",\"red\")) #+\n #scale_y_continuous(labels = scales::comma) + geom_vline(xintercept=as.numeric(ode_df$date[sdp]), colour=\"gray30\") +\n #annotate(geom=\"text\",x=start + 50,\n # y=top,label=\"Lockdown starts\",fontface=\"bold\", color = \"deeppink4\") + \n #annotate(geom=\"text\",x=ends + sdp[1] + 30,\n # y=top,label=\"Phase 1\",fontface=\"bold\",color = \"deeppink4\") + \n #annotate(geom=\"text\",x=ends + sdp[2] + 30,\n # y=top,label=\"Phase 2\",fontface=\"bold\",color = \"deeppink4\") \n )\n \n ggplotly(pp3)\n}\n\nplot_cum <- function(ode_df, sdp) { \n \n max_time = 365\n \n x_labs <- sort(c(0, 200, 300, 365, sdp))\n start = as.Date(\"2020-03-03\")\n ends = as.Date(\"2020-03-03\") + sdp[1]\n ode_df$date <- as.Date(ode_df$t+start)\n #filtered <- subset(ode_df, type == \"with SIQ\")\n result <- filter(ode_df, type == \"with Lockdown\")\n y_max <- max(result$c, na.rm = TRUE) * 1.05\n y_arrow <- y_max * 0.975\n y_text <- y_arrow + y_max * 0.01 \n \n col_sdp <- \"deeppink4\"\n \n result = head(result, 365)\n names(result)[names(result) == \"C\"] <- \"daily_infections\"\n result$CumulativeCases <-cumsum(result$daily_infections)\n result$Dead <-result$daily_infections * 0.005\n result$CumulativeSus <-result$S - result$Dead\n result$CumulativeDead <-cumsum(result$Dead)\n result$CumulativeRec <- result$S - result$CumulativeCases\n top = head(result$CumulativeSus, n=1) * 1.1\n #top = result[\"CumulativeCases\"].iloc[-1]\n #print(result)\n \n pp3 <-ggplotly(\n ggplot(result, aes(x=date)) +\n geom_line(aes(y = CumulativeCases, color = \"Cases\")) + \n geom_line(aes(y = CumulativeDead, color = \"Dead\")) +\n geom_line(aes(y = CumulativeSus, color = \"Susceptible\")) +\n geom_line(aes(y = R, color = \"Recovered\")) + \n scale_colour_manual(\"\", \n breaks = c(\"Cases\", \"Dead\", \"Susceptible\",\"Recovered\"),\n values = c(\"steelblue\", \"darkred\", \"goldenrod\", \"green\")) +\n #scale_color_discrete(name = \"Descriptions\", labels = c(\"CumulativeCases\", \"CumulativeDead\", \"CumulativeSus\", \"R\")) +\n scale_y_continuous(labels = scales::comma) + geom_vline(xintercept=as.numeric(ode_df$date[sdp]), colour=\"gray30\") +\n annotate(geom=\"text\",x=start + 40,\n y=top,label=\"Lockdown\",fontface=\"bold\", color = \"deeppink4\") + \n annotate(geom=\"text\",x=ends + sdp[2] - 26,\n y=top,label=\"Ph 1\",fontface=\"bold\",color = \"deeppink4\") + \n annotate(geom=\"text\",x=ends + sdp[3] - 26,\n y=top,label=\"Ph 2\",fontface=\"bold\",color = \"deeppink4\") +\n annotate(geom=\"text\",x=ends + sdp[4] - 26,\n y=top,label=\"Ph 3\",fontface=\"bold\",color = \"deeppink4\") \n )\n \n ggplotly(pp3, tooltip=\"CumulativeCases\")\n}\n\n\nui <- fluidPage(theme = shinytheme(\"flatly\"),\n titlePanel(\"What Happens When T&T Re-Opens? An Interactive Covid-19 SIR Policy Simulator\"),\n h4(\"Charts update in real-time, please allow ~5 seconds for charts to load\"),\n hr(),\n sidebarLayout(\n sidebarPanel(\n h3(\"Phase 1 of Lockdown Removal\"),\n br(),\n dateInput(\"end\",\n \"Set start date:\",\n value = \"2020-06-08\",\n format = \"dd/mm/yyyy\"),\n br(),\n h4(\"Select Policy Choices\"),\n checkboxInput(\"foo\", label = \"Food Establistments and related stores re-opened\", value = TRUE),\n checkboxInput(\"non\", label = \"Manufacturing & Public Section re-started\", value = TRUE),\n checkboxInput(\"bus\", label = \"Medium to low risk businesses and malls re-opened\", value = TRUE),\n checkboxInput(\"res\", label = \"Medium to high risk businesses re-openes (resturants, bars, cinemas, salons, offices & gyms)\", value = FALSE),\n checkboxInput(\"gat\", label = \"Mass Gatherings of 25+ allowed\", value = FALSE),\n checkboxInput(\"sch\", label = \"Schools re-opened\", value = FALSE),\n sliderInput(\"sda\",\n \"Control Social Distance/Mask Wearing/Hand Washing Adherance (100% is everyone follows)\",\n min = 1,\n max = 100,\n value = 60, \n step = 1), \n hr(),\n h3(\"Phase 2 of Lockdown Removal\"),\n br(),\n dateInput(\"end2\",\n \"Set start date:\",\n value = \"2020-06-22\",\n format = \"dd/mm/yyyy\"),\n br(),\n h4(\"Select Policy Choices\"),\n checkboxInput(\"foo2\", label = \"Food Establistments and related stores re-opened\", value = TRUE),\n checkboxInput(\"non2\", label = \"Manufacturing & Public Section re-started\", value = TRUE),\n checkboxInput(\"bus2\", label = \"Medium to low risk businesses and malls re-opened\", value = TRUE),\n checkboxInput(\"res2\", label = \"Medium to high risk businesses re-openes (resturants, bars, cinemas, offices, salons & gyms)\", value = TRUE),\n checkboxInput(\"gat2\", label = \"Mass Gatherings of 25+ allowed\", value = TRUE),\n checkboxInput(\"sch2\", label = \"Schools re-opened\", value = TRUE),\n sliderInput(\"sda2\",\n \"Control Social Distance/Mask Wearing/Hand Washing Adherance (100% is everyone follows)\",\n min = 1,\n max = 100,\n value = 50, \n step = 1), \n hr(),\n h3(\"Phase 3 of Lockdown Removal\"),\n br(),\n dateInput(\"end3\",\n \"Set start date:\",\n value = \"2020-08-17\",\n format = \"dd/mm/yyyy\"),\n br(),\n h4(\"Select Policy Choices\"),\n checkboxInput(\"foo3\", label = \"Food Establistments and related stores re-opened\", value = TRUE),\n checkboxInput(\"non3\", label = \"Manufacturing & Public Section re-started\", value = TRUE),\n checkboxInput(\"bus3\", label = \"Medium to low risk businesses and malls re-opened\", value = TRUE),\n checkboxInput(\"res3\", label = \"Medium to high risk businesses re-openes (resturants, bars, cinemas, offices, salons & gyms)\", value = FALSE),\n checkboxInput(\"gat3\", label = \"Mass Gatherings of 25+ allowed\", value = FALSE),\n checkboxInput(\"sch3\", label = \"Schools re-opened\", value = FALSE),\n sliderInput(\"sda3\",\n \"Control Social Distance/Mask Wearing/Hand Washing Adherance (100% is everyone follows)\",\n min = 1,\n max = 100,\n value = 70, \n step = 1), \n #radioButtons(\"sda\", label = h4(\"Control Social Distance Adherance (Mask Wearing etc)\"),\n # choices = list(\"0 to 30% People wear masks in public\" = 7,\n # \"30% to 70% People wear masks in public\" = 13,\n # \"70% to 100% People wear masks in public\" = 16),\n # selected = 13),\n #radioButtons(\"sdo\", label = h4(\"Social Distancing Obeyed\"),\n # choices = list(\"0 to 30% People object 6ft spacing\" = 7,\n # \"30% to 70% People object 6ft spacing\" = 13,\n # \"70% to 100% People object 6ft spacing\" = 15),\n # selected = 13),\n #radioButtons(\"hwh\", label = h4(\"Hand Washing and Basic Hygenine\"),\n # choices = list(\"0 to 30% People follow\" = 7,\n # \"30% to 70% People follow\" = 13,\n # \"70% to 100% People follow\" = 15),\n # selected = 13),\n br(),\n hr(), \n tags$div(\"Developed by Rajev Ratan\"), \n tags$div(\"Version 2.1, 16-May-2020\"), \n tags$a(href=\"https://caribbeandatafam.com/\",\"Caribbean Data Fam\"), \n \n br(),\n width = 3,\n ),\n \n mainPanel(\n \n # Output: Tabset w/ plot, summary, and table ----\n tabsetPanel(type = \"tabs\",\n tabPanel(\"Forecasted Cases\", plotlyOutput(\"chart1\", height = \"auto\", width = \"auto\"), \n DT::dataTableOutput('table', width = \"55%\", height = \"auto\")),\n tabPanel(\"Forecasted Cumulative Data\", plotlyOutput(\"chart3\", height = \"auto\",width = \"auto\")),\n tabPanel(\"Actual Data\", plotlyOutput(\"chart2\", height = \"auto\",width = \"100%\")),\n tabPanel(\"What if there were no Lockdowns?\", plotlyOutput(\"chart4\", height = \"auto\",width = \"auto\"))\n #tabPanel(\"Table\", tableOutput(\"table\"))\n ),\n \n \n \n #br(),\n #br(),\n #hr(),\n div(HTML(\"Parameters Used:\")), \n div(HTML(\"R0 of 2.25\")), \n div(HTML(\"Gamma = 0.2, beta <- 4.5e-07 \")), \n div(HTML(\"beta <- 4.5e-07 \")),\n div(HTML(\"Population = 1,394,000\")), \n div(HTML(\"Initial Infect People = 2\")),\n div(HTML(\"Day 0 is 3rd March 202\")),\n br(),\n width = 9\n )\n \n )\n)\n\n\nserver <- function(input, output) {\n \n res <- reactive({\n \n run(sdp = c(c(30, diffsdp(input$end)), diffsdp(input$end2), diffsdp(input$end3)),\n #sdp2 = c(c(diffsdp(input$end)),c(diffsdp(input$end2))),\n #red = c(0.4, (100-(input$red_two)/1.5)/100), \n #test = input$mask,\n red = c(0.3, (((100 - ((-13*as.integer(input$sch)) + (-13*as.integer(input$res)) + (-13*as.integer(input$gat)) +\n (-10*as.integer(input$bus))+ (-10*as.integer(input$foo)) + \n (-10*as.integer(input$non)) ))/100)- 0.7) * (1-(as.integer(input$sda)/300)), \n (((100 - ((-13*as.integer(input$sch2)) + (-13*as.integer(input$res2)) + (-13*as.integer(input$gat2)) +\n (-10*as.integer(input$bus2))+ (-10*as.integer(input$foo2)) + \n (-10*as.integer(input$non2)) ))/100)- 0.7) * (1-(as.integer(input$sda2)/300)),\n (((100 - ((-13*as.integer(input$sch3)) + (-13*as.integer(input$res3)) + (-13*as.integer(input$gat3)) +\n (-10*as.integer(input$bus3))+ (-10*as.integer(input$foo3)) + \n (-10*as.integer(input$non3)) ))/100)- 0.7) * (1-(as.integer(input$sda3)/300))),\n \n #(((100 - ((-5*as.integer(input$sch2)) + (-5*as.integer(input$res2)) + (-5*as.integer(input$gat2)) +\n # (-5*as.integer(input$bus2))+ (-5*as.integer(input$foo2))+ (-5*as.integer(input$non2)) + (-1*(10-(as.integer(input$sda2)/10) )) ))/100)- 0.4)), \n #red2 = c(0(((100 - ((-5*as.integer(input$sch)) + (-5*as.integer(input$res)) + (-4*as.integer(input$gat)) +\n # (-3*as.integer(input$bus))+ (-3*as.integer(input$foo))+ (-3*as.integer(input$non)) + (-1*(7-(as.integer(input$sda)/10) )) ))/100)- 0.4), \n # (((100 - ((-5*as.integer(input$sch2)) + (-5*as.integer(input$res2)) + (-4*as.integer(input$gat2)) +\n # (-3*as.integer(input$bus2))+ (-3*as.integer(input$foo2))+ (-3*as.integer(input$non2)) + (-1*(7-(as.integer(input$sda2)/10) )) ))/100)- 0.4)), \n r0 = 2.25,\n max_time = 365)\n #start = input$start,\n # \n #)\n })\n \n output$table <- DT::renderDataTable(make_summary_table(res(), c(c(30,diffsdp(input$end),diffsdp(input$end2),diffsdp(input$end3))) ), options=list(scrollX=T))\n \n output$chart1 <- renderPlotly({\n plot_predict(res(), c(c(30,diffsdp(input$end),diffsdp(input$end2)), diffsdp(input$end3)) )\n })\n \n output$chart2 <- renderPlotly({\n plot_real(res(), c(c(30,diffsdp(input$end),diffsdp(input$end2)), diffsdp(input$end3)) )\n })\n \n \n output$chart3 <- renderPlotly({\n plot_cum(res(), c(c(30,diffsdp(input$end),diffsdp(input$end2)), diffsdp(input$end3)) )\n })\n \n output$chart4 <- renderPlotly({\n plot_lockdown(res(), c(c(30,diffsdp(input$end),diffsdp(input$end2)), diffsdp(input$end3)) )\n }) \n \n \n \n \n}\n\n# Run the application \nshinyApp(ui = ui, server = server)", "meta": {"hexsha": "58dc6ba73a8c1ab6eb57f96971181022edd004e4", "size": 22925, "ext": "r", "lang": "R", "max_stars_repo_path": "app.r", "max_stars_repo_name": "rajeevratan84/Covid-19-Policy-Simulator", "max_stars_repo_head_hexsha": "df0c6b6525b3534e82684b2b746580855a8ec7db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app.r", "max_issues_repo_name": "rajeevratan84/Covid-19-Policy-Simulator", "max_issues_repo_head_hexsha": "df0c6b6525b3534e82684b2b746580855a8ec7db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app.r", "max_forks_repo_name": "rajeevratan84/Covid-19-Policy-Simulator", "max_forks_repo_head_hexsha": "df0c6b6525b3534e82684b2b746580855a8ec7db", "max_forks_repo_licenses": ["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.0813953488, "max_line_length": 172, "alphanum_fraction": 0.5494438386, "num_tokens": 6815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6310959452611558}} {"text": "# empirical likelihood for the mean\nmeanlike <- function(x){\n n<- length(x)\n\nf1<- function(lambda,x){\n x/(n-lambda*x)\n }\n\n sx<- sort(x)\n nt<- 40\n nlam<-40\n th<- seq(1.01*sx[1],(sx[n-1]+.99*(sx[n]-sx[n-1])),len=nt)\n theta<- NULL\n loglik<- NULL\n for (i in 1:nt){\n a<- x-th[i]\n lam <- seq(n/min(a),n/max(a),len=nlam)\n lam <- lam[c(-1,-nlam)]\n glam <-outer(lam,a,'f1')\n glam<- c(glam %*% rep(1,n))\n lam0<- approx(glam,lam,xout=0)$y\n if (is.na(lam0)==F) { # lam0 exists\n w <- 1/(n-lam0*a)\n if (min(w)>0 & max(w)<1){ # proper distribution\n ll<- sum(log(w))\n theta<- c(theta,th[i])\n loglik <- c(loglik,ll)\n }\n } # endif\n }# endfor\n\n loglik<- loglik - max(loglik)\n out <- list(theta= theta, loglik=loglik)\n return(out)\n} # end function\n", "meta": {"hexsha": "dc8aa675a5a302fed6394f0427f3a31f8ea4726c", "size": 790, "ext": "r", "lang": "R", "max_stars_repo_path": "R/LKPACK/meanlike.r", "max_stars_repo_name": "covuworie/in-all-likelihood", "max_stars_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_stars_repo_licenses": ["MIT"], "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/LKPACK/meanlike.r", "max_issues_repo_name": "covuworie/in-all-likelihood", "max_issues_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:53:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T20:16:17.000Z", "max_forks_repo_path": "R/LKPACK/meanlike.r", "max_forks_repo_name": "covuworie/in-all-likelihood", "max_forks_repo_head_hexsha": "6638bec8bb4dde7271adb5941d1c66e7fbe12526", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-21T10:24:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T10:24:59.000Z", "avg_line_length": 21.9444444444, "max_line_length": 58, "alphanum_fraction": 0.5367088608, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.63107008756442}} {"text": "#Example : 2 Chapter : 2.3 pageno : 58\n#Purpose of Elimination matrices\nI<-matrix(c(1,0,0,0,1,0,0,0,1),ncol=3)\nE31<-matrix(c(1,0,-4,0,1,0,0,0,1),ncol=3)\nb<-matrix(c(1,3,9),ncol=1)\nIb<-I%*%b\nprint(Ib)\nEb<-E31%*%b\nprint(Eb)\n", "meta": {"hexsha": "21725a986ad5dabc0da4a56b216708efd593b42f", "size": 229, "ext": "r", "lang": "R", "max_stars_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.2/Ex2.3_2.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.2/Ex2.3_2.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Introduction_To_Linear_Algebra_by_Gilbert_Strang/CH2/EX2.3.2/Ex2.3_2.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 22.9, "max_line_length": 45, "alphanum_fraction": 0.6069868996, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6310700820829415}} {"text": "# Synthetic Data Project\r\n# Differential private algorithm using beta, binomial, and Laplace probabilities\r\n\r\n# Authors:\r\n# Version: 5/14/2017\r\n\r\n# Copyright 2017\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and\r\n# associated documentation files (the \"Software\"), to deal in the Software without restriction, including\r\n# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the\r\n# following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all copies or substantial\r\n# portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\r\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n# import Laplace distribution functions\r\nsys.source(\"LaplaceDistribution.r\", env=environment())\r\n\r\n#####################################################################################\r\n#### DP algorithm\r\n#####################################################################################\r\n\r\nDP.threshold <- function (S, M, epsilon, alpha, nIter=250000) {\r\n\r\n ### add random Laplace noise to S\r\n ### note that this converts S to a real number\r\n ### since the Laplace distribution (double exponential) is symmetric about 0,\r\n ### nS maybe greater than or less than S\r\n ### also, nS can be negative or greater than M\r\n nS <- S + rlaplace(1, 0, 1/epsilon)\r\n\r\n ### Range of S\r\n RangeS <- 0:M\r\n\r\n ### Initial value of p\r\n ### shape parameters of (1, 1) correspond to the uniform(0, 1) distribution\r\n ### use supplied initial shape parameters\r\n ### p = rbeta(1, alpha[1], alpha[2])\r\n ### note that E[rbeta(n, shape1, shape2)] = shape1/(shape1+shape2)\r\n ### use of rbeta(1, S, M-S) would give a theoretical mean p of S/M,\r\n ### but S=0 requires rbeta() to return 0, in order to satisfy a mean value of 0.00\r\n ### once a supplied or randomly generated value of S becomes 0, all subsequent\r\n ### p and S values are 0\r\n ### similarly, S=50 requires rbeta() mean of 1.00, once supplied or generated S=50,\r\n ### all subsequent S values are 50\r\n ### adding initial beta parameters prevents expected value numerators of zero and\r\n ### gives mean of (S+alpha1)/(S+alpha1+alpha2) for S=M and should be unequal to 1.00\r\n p <- rbeta(1, S+alpha[1], M-S+alpha[2])\r\n\r\n ### generate Laplace density (using random nS) for each centrality value in 0:M\r\n dslap <- dlaplace(RangeS, nS, 1/epsilon)\r\n\r\n ### Gibbs interaction\r\n f.iter <- function(j) {\r\n # update S\r\n # product of binomial mass (using curent p) and Laplace density for each 0:M\r\n prob <- dbinom(RangeS, M, prob=p)*dslap\r\n # randomly select one S in 0:M\r\n # selection weights are probability products for each 0:M\r\n S <- sample(RangeS, 1, prob=prob)\r\n # update p\r\n # note that E(p) = (shape par 1)/(shape par 1 + shape par 2)\r\n # = (alpha[1]+S)/(alpha[1]+S + alpha[2]+M-S)\r\n # = (alpha[1]+S)/(alpha[1]+alpha[2]+M)\r\n # variance = ab/((a+b)^2*(a+b+1)), where a=shape par 1, b=shape par 2\r\n p <<- rbeta(1, S+alpha[1], M-S+alpha[2])\r\n }\r\n \r\n ### iterate MCMC and return all but first 1,000 generated values\r\n if(nIter<10000)\r\n nIter <- 10000\r\n sapply(1:nIter, f.iter)[1001:nIter]\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "e4e92e241a6dd1220f298fa39364db39efc0835a", "size": 3724, "ext": "r", "lang": "R", "max_stars_repo_path": "VerificationServer/BetaBinomialLaplacePosteriorDP.r", "max_stars_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_stars_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VerificationServer/BetaBinomialLaplacePosteriorDP.r", "max_issues_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_issues_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VerificationServer/BetaBinomialLaplacePosteriorDP.r", "max_forks_repo_name": "DukeSynthProj/DukeSynthJASA2017", "max_forks_repo_head_hexsha": "c6d93608df295e434fa6753447059c400b69fad3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8117647059, "max_line_length": 107, "alphanum_fraction": 0.6517185822, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6310700674806035}} {"text": "\n\n\n\n\n\n\n C\bCH\bHA\bAP\bPT\bTE\bER\bR 3\b3\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n\n\n\n This chapter describes FRANZ LISP's functions for doing\n arithmetic. Often the same function is known by many names.\n For example, _\ba_\bd_\bd is also _\bp_\bl_\bu_\bs, and _\bs_\bu_\bm. This is caused by\n our desire to be compatible with other Lisps. The FRANZ\n LISP user should avoid using functions with names such as +\n and * unless their arguments are fixnums. The Lisp compiler\n takes advantage of these implicit declarations.\n\n An attempt to divide or to generate a floating point\n result outside of the range of floating point numbers will\n cause a floating exception signal from the UNIX operating\n system. The user can catch and process this interrupt if\n desired (see the description of the _\bs_\bi_\bg_\bn_\ba_\bl function).\n\n\n\n 3\b3.\b.1\b1.\b. S\bSi\bim\bmp\bpl\ble\be A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n (\b(a\bad\bdd\bd ['n_arg1 ...])\b)\n (\b(p\bpl\blu\bus\bs ['n_arg1 ...])\b)\n (\b(s\bsu\bum\bm ['n_arg1 ...])\b)\n (\b(+\b+ ['x_arg1 ...])\b)\n\n RETURNS: the sum of the arguments. If no arguments are\n given, 0 is returned.\n\n NOTE: if the size of the partial sum exceeds the limit\n of a fixnum, the partial sum will be converted to\n a bignum. If any of the arguments are flonums,\n the partial sum will be converted to a flonum\n when that argument is processed and the result\n will thus be a flonum. Currently, if in the pro-\n cess of doing the addition a bignum must be con-\n verted into a flonum an error message will\n result.\n\n\n\n\n\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-1\b1\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-2\b2\n\n\n (\b(a\bad\bdd\bd1\b1 'n_arg)\b)\n (\b(1\b1+\b+ 'x_arg)\b)\n\n RETURNS: its argument plus 1.\n\n (\b(d\bdi\bif\bff\bf ['n_arg1 ... ])\b)\n (\b(d\bdi\bif\bff\bfe\ber\bre\ben\bnc\bce\be ['n_arg1 ... ])\b)\n (\b(-\b- ['x_arg1 ... ])\b)\n\n RETURNS: the result of subtracting from n_arg1 all sub-\n sequent arguments. If no arguments are given,\n 0 is returned.\n\n NOTE: See the description of add for details on data\n type conversions and restrictions.\n\n (\b(s\bsu\bub\bb1\b1 'n_arg)\b)\n (\b(1\b1-\b- 'x_arg)\b)\n\n RETURNS: its argument minus 1.\n\n (\b(m\bmi\bin\bnu\bus\bs 'n_arg)\b)\n\n RETURNS: zero minus n_arg.\n\n (\b(p\bpr\bro\bod\bdu\buc\bct\bt ['n_arg1 ... ])\b)\n (\b(t\bti\bim\bme\bes\bs ['n_arg1 ... ])\b)\n (\b(*\b* ['x_arg1 ... ])\b)\n\n RETURNS: the product of all of its arguments. It\n returns 1 if there are no arguments.\n\n NOTE: See the description of the function _\ba_\bd_\bd for\n details and restrictions to the automatic data\n type coercion.\n\n (\b(q\bqu\buo\bot\bti\bie\ben\bnt\bt ['n_arg1 ...])\b)\n (\b(/\b/ ['x_arg1 ...])\b)\n\n RETURNS: the result of dividing the first argument by\n succeeding ones.\n\n NOTE: If there are no arguments, 1 is returned. See\n the description of the function _\ba_\bd_\bd for details\n and restrictions of data type coercion. A divide\n by zero will cause a floating exception interrupt\n -- see the description of the _\bs_\bi_\bg_\bn_\ba_\bl function.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-3\b3\n\n\n (\b(*\b*q\bqu\buo\bo 'i_x 'i_y)\b)\n\n RETURNS: the integer part of i_x / i_y.\n\n (\b(D\bDi\biv\bvi\bid\bde\be 'i_dividend 'i_divisor)\b)\n\n RETURNS: a list whose car is the quotient and whose\n cadr is the remainder of the division of\n i_dividend by i_divisor.\n\n NOTE: this is restricted to integer division.\n\n (\b(E\bEm\bmu\bul\bld\bdi\biv\bv 'x_fact1 'x_fact2 'x_addn 'x_divisor)\b)\n\n RETURNS: a list of the quotient and remainder of this\n operation:\n ((x_fact1 * x_fact2) + (sign extended) x_addn) / x_divisor.\n\n NOTE: this is useful for creating a bignum arithmetic\n package in Lisp.\n\n\n\n 3\b3.\b.2\b2.\b. p\bpr\bre\bed\bdi\bic\bca\bat\bte\bes\bs\n\n (\b(n\bnu\bum\bmb\bbe\ber\brp\bp 'g_arg)\b)\n\n (\b(n\bnu\bum\bmb\bbp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a number (fixnum, flonum or\n bignum).\n\n (\b(f\bfi\bix\bxp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a fixnum or bignum.\n\n (\b(f\bfl\blo\boa\bat\btp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a flonum.\n\n (\b(e\bev\bve\ben\bnp\bp 'x_arg)\b)\n\n RETURNS: t iff x_arg is even.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-4\b4\n\n\n (\b(o\bod\bdd\bdp\bp 'x_arg)\b)\n\n RETURNS: t iff x_arg is odd.\n\n (\b(z\bze\ber\bro\bop\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a number equal to 0.\n\n (\b(o\bon\bne\bep\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a number equal to 1.\n\n (\b(p\bpl\blu\bus\bsp\bp 'n_arg)\b)\n\n RETURNS: t iff n_arg is greater than zero.\n\n (\b(m\bmi\bin\bnu\bus\bsp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a negative number.\n\n (\b(g\bgr\bre\bea\bat\bte\ber\brp\bp ['n_arg1 ...])\b)\n (\b(>\b> 'fx_arg1 'fx_arg2)\b)\n (\b(>\b>&\b& 'x_arg1 'x_arg2)\b)\n\n RETURNS: t iff the arguments are in a strictly decreas-\n ing order.\n\n NOTE: In functions _\bg_\br_\be_\ba_\bt_\be_\br_\bp and _\b> the function _\bd_\bi_\bf_\bf_\be_\br_\b-\n _\be_\bn_\bc_\be is used to compare adjacent values. If any\n of the arguments are non-numbers, the error mes-\n sage will come from the _\bd_\bi_\bf_\bf_\be_\br_\be_\bn_\bc_\be function. The\n arguments to _\b> must be fixnums or both flonums.\n The arguments to _\b>_\b& must both be fixnums.\n\n (\b(l\ble\bes\bss\bsp\bp ['n_arg1 ...])\b)\n (\b(<\b< 'fx_arg1 'fx_arg2)\b)\n (\b(<\b<&\b& 'x_arg1 'x_arg2)\b)\n\n RETURNS: t iff the arguments are in a strictly increas-\n ing order.\n\n NOTE: In functions _\bl_\be_\bs_\bs_\bp and _\b< the function _\bd_\bi_\bf_\bf_\be_\br_\be_\bn_\bc_\be\n is used to compare adjacent values. If any of\n the arguments are non numbers, the error message\n will come from the _\bd_\bi_\bf_\bf_\be_\br_\be_\bn_\bc_\be function. The\n arguments to _\b< may be either fixnums or flonums\n but must be the same type. The arguments to _\b<_\b&\n must be fixnums.\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-5\b5\n\n\n (\b(=\b= 'fx_arg1 'fx_arg2)\b)\n\n (\b(=\b=&\b& 'x_arg1 'x_arg2)\b)\n\n RETURNS: t iff the arguments have the same value. The\n arguments to = must be the either both fixnums\n or both flonums. The arguments to =& must be\n fixnums.\n\n\n\n 3\b3.\b.3\b3.\b. T\bTr\bri\big\bgn\bno\bom\bme\bet\btr\bri\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n Some of these funtcions are taken from the host\n math library, and we take no further responsibility\n for their accuracy.\n\n (\b(c\bco\bos\bs 'fx_angle)\b)\n\n RETURNS: the (flonum) cosine of fx_angle (which is\n assumed to be in radians).\n\n (\b(s\bsi\bin\bn 'fx_angle)\b)\n\n RETURNS: the sine of fx_angle (which is assumed to be\n in radians).\n\n (\b(a\bac\bco\bos\bs 'fx_arg)\b)\n\n RETURNS: the (flonum) arc cosine of fx_arg in the range\n 0 to -\bn.\n\n (\b(a\bas\bsi\bin\bn 'fx_arg)\b)\n\n RETURNS: the (flonum) arc sine of fx_arg in the range\n --\bn/2 to -\bn/2.\n\n (\b(a\bat\bta\ban\bn 'fx_arg1 'fx_arg2)\b)\n\n RETURNS: the (flonum) arc tangent of fx_arg1/fx_arg2 in\n the range --\bn to -\bn.\n\n\n\n 3\b3.\b.4\b4.\b. B\bBi\big\bgn\bnu\bum\bm/\b/F\bFi\bix\bxn\bnu\bum\bm M\bMa\ban\bni\bip\bpu\bul\bla\bat\bti\bio\bon\bn\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-6\b6\n\n\n (\b(h\bha\bai\bip\bpa\bar\brt\bt bx_number x_bits)\b)\n\n RETURNS: a fixnum (or bignum) which contains the x_bits\n high bits of _\b(_\ba_\bb_\bs _\bb_\bx_\b__\bn_\bu_\bm_\bb_\be_\br_\b) if x_bits is pos-\n itive, otherwise it returns the _\b(_\ba_\bb_\bs _\bx_\b__\bb_\bi_\bt_\bs_\b)\n low bits of _\b(_\ba_\bb_\bs _\bb_\bx_\b__\bn_\bu_\bm_\bb_\be_\br_\b).\n\n (\b(h\bha\bau\bul\blo\bon\bng\bg bx_number)\b)\n\n RETURNS: the number of significant bits in bx_number.\n\n NOTE: the result is equal to the least integer greater\n to or equal to the base two logarithm of one plus\n the absolute value of bx_number.\n\n (\b(b\bbi\big\bgn\bnu\bum\bm-\b-l\ble\bef\bft\bts\bsh\bhi\bif\bft\bt bx_arg x_amount)\b)\n\n RETURNS: bx_arg shifted left by x_amount. If x_amount\n is negative, bx_arg will be shifted right by\n the magnitude of x_amount.\n\n NOTE: If bx_arg is shifted right, it will be rounded to\n the nearest even number.\n\n (\b(s\bst\bti\bic\bck\bky\by-\b-b\bbi\big\bgn\bnu\bum\bm-\b-l\ble\bef\bft\bts\bsh\bhi\bif\bft\bt 'bx_arg 'x_amount)\b)\n\n RETURNS: bx_arg shifted left by x_amount. If x_amount\n is negative, bx_arg will be shifted right by\n the magnitude of x_amount and rounded.\n\n NOTE: sticky rounding is done this way: after shifting,\n the low order bit is changed to 1 if any 1's were\n shifted off to the right.\n\n\n\n 3\b3.\b.5\b5.\b. B\bBi\bit\bt M\bMa\ban\bni\bip\bpu\bul\bla\bat\bti\bio\bon\bn\n\n (\b(b\bbo\boo\bol\ble\be 'x_key 'x_v1 'x_v2 ...)\b)\n\n RETURNS: the result of the bitwise boolean operation as\n described in the following table.\n\n NOTE: If there are more than 3 arguments, then evalua-\n tion proceeds left to right with each partial\n result becoming the new value of x_v1. That is,\n _\b(_\bb_\bo_\bo_\bl_\be _\b'_\bk_\be_\by _\b'_\bv_\b1 _\b'_\bv_\b2 _\b'_\bv_\b3_\b) _\b=_\b= _\b(_\bb_\bo_\bo_\bl_\be _\b'_\bk_\be_\by _\b(_\bb_\bo_\bo_\bl_\be _\b'_\bk_\be_\by _\b'_\bv_\b1 _\b'_\bv_\b2_\b) _\b'_\bv_\b3_\b).\n In the following table, * represents bitwise and,\n + represents bitwise or, O\b+ represents bitwise xor\n and ~ represents bitwise negation and is the\n highest precedence operator.\n\n\n\n\n\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-7\b7\n\n\n +-------------------------------------------------------------------------------------------+\n | (boole 'key 'x 'y) |\n | |\n +-------------------------------------------------------------------------------------------+\n | key 0 1 2 3 4 5 6 7 |\n |result 0 x * y ~ x * y y x * ~ y x x O\b+ y x + y |\n | |\n |common |\n |names and bitclear xor or |\n | |\n +-------------------------------------------------------------------------------------------+\n | |\n | key 8 9 10 11 12 13 14 15 |\n |result ~ (x + y) ~(x O\b+ y) ~ x ~ x + y ~ y x + ~ y ~ x + ~ y -1 |\n |common |\n |names nor equiv implies nand |\n +-------------------------------------------------------------------------------------------+\n\n (\b(l\bls\bsh\bh 'x_val 'x_amt)\b)\n\n RETURNS: x_val shifted left by x_amt if x_amt is posi-\n tive. If x_amt is negative, then _\bl_\bs_\bh returns\n x_val shifted right by the magnitude if x_amt.\n\n NOTE: This always returns a fixnum even for those num-\n bers whose magnitude is so large that they would\n normally be represented as a bignum, i.e. shifter\n bits are lost. For more general bit shifters,\n see _\bb_\bi_\bg_\bn_\bu_\bm_\b-_\bl_\be_\bf_\bt_\bs_\bh_\bi_\bf_\bt and _\bs_\bt_\bi_\bc_\bk_\by_\b-_\bb_\bi_\bg_\bn_\bu_\bm_\b-_\bl_\be_\bf_\bt_\bs_\bh_\bi_\bf_\bt_\b.\n\n (\b(r\bro\bot\bt 'x_val 'x_amt)\b)\n\n RETURNS: x_val rotated left by x_amt if x_amt is posi-\n tive. If x_amt is negative, then x_val is\n rotated right by the magnitude of x_amt.\n\n\n\n 3\b3.\b.6\b6.\b. O\bOt\bth\bhe\ber\br F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n As noted above, some of the following functions\n are inherited from the host math library, with all\n their virtues and vices.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-8\b8\n\n\n (\b(a\bab\bbs\bs 'n_arg)\b)\n (\b(a\bab\bbs\bsv\bva\bal\bl 'n_arg)\b)\n\n RETURNS: the absolute value of n_arg.\n\n (\b(e\bex\bxp\bp 'fx_arg)\b)\n\n RETURNS: _\be raised to the fx_arg power (flonum) .\n\n (\b(e\bex\bxp\bpt\bt 'n_base 'n_power)\b)\n\n RETURNS: n_base raised to the n_power power.\n\n NOTE: if either of the arguments are flonums, the cal-\n culation will be done using _\bl_\bo_\bg and _\be_\bx_\bp.\n\n (\b(f\bfa\bac\bct\bt 'x_arg)\b)\n\n RETURNS: x_arg factorial. (fixnum or bignum)\n\n (\b(f\bfi\bix\bx 'n_arg)\b)\n\n RETURNS: a fixnum as close as we can get to n_arg.\n\n NOTE: _\bf_\bi_\bx will round down. Currently, if n_arg is a\n flonum larger than the size of a fixnum, this\n will fail.\n\n (\b(f\bfl\blo\boa\bat\bt 'n_arg)\b)\n\n RETURNS: a flonum as close as we can get to n_arg.\n\n NOTE: if n_arg is a bignum larger than the maximum size\n of a flonum, then a floating exception will\n occur.\n\n (\b(l\blo\bog\bg 'fx_arg)\b)\n\n RETURNS: the natural logarithm of fx_arg.\n\n (\b(m\bma\bax\bx 'n_arg1 ... )\b)\n\n RETURNS: the maximum value in the list of arguments.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n A\bAr\bri\bit\bth\bhm\bme\bet\bti\bic\bc F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs 3\b3-\b-9\b9\n\n\n (\b(m\bmi\bin\bn 'n_arg1 ... )\b)\n\n RETURNS: the minimum value in the list of arguments.\n\n (\b(m\bmo\bod\bd 'i_dividend 'i_divisor)\b)\n (\b(r\bre\bem\bma\bai\bin\bnd\bde\ber\br 'i_dividend 'i_divisor)\b)\n\n RETURNS: the remainder when i_dividend is divided by\n i_divisor.\n\n NOTE: The sign of the result will have the same sign as\n i_dividend.\n\n (\b(*\b*m\bmo\bod\bd 'x_dividend 'x_divisor)\b)\n\n RETURNS: the balanced representation of x_dividend mod-\n ulo x_divisor.\n\n NOTE: the range of the balanced representation is\n abs(x_divisor)/2 to (abs(x_divisor)/2) -\n x_divisor + 1.\n\n (\b(r\bra\ban\bnd\bdo\bom\bm ['x_limit])\b)\n\n RETURNS: a fixnum between 0 and x_limit - 1 if x_limit\n is given. If x_limit is not given, any\n fixnum, positive or negative, might be\n returned.\n\n (\b(s\bsq\bqr\brt\bt 'fx_arg)\b)\n\n RETURNS: the square root of fx_arg.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n", "meta": {"hexsha": "d40d594a1b1f03657fa10768b7745f5f850e6192", "size": 18292, "ext": "r", "lang": "R", "max_stars_repo_path": "lisplib/manual/ch3.r", "max_stars_repo_name": "krytarowski/franz-lisp-christos", "max_stars_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-17T08:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T08:07:14.000Z", "max_issues_repo_path": "lisplib/manual/ch3.r", "max_issues_repo_name": "krytarowski/franz-lisp-christos", "max_issues_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lisplib/manual/ch3.r", "max_forks_repo_name": "krytarowski/franz-lisp-christos", "max_forks_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-15T16:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-15T16:38:53.000Z", "avg_line_length": 30.7428571429, "max_line_length": 198, "alphanum_fraction": 0.4378416794, "num_tokens": 5460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6308976715763716}} {"text": "# Article submitted \n# Fusion of Evidences in Intensities Channels for Edge Detection in PolSAR Images \n# GRSL - IEEE Geoscience and Remote Sensing Letters \n# Anderson A. de Borba, Maurı́cio Marengoni, and Alejandro C Frery\n# Despriction (function)\n# Finds the l(L, mu) using log-likelihood, (internal side)\n# Input: L, mu > 0 \n# \n# Output: l(L, mu) - log-likelihood \nloglike <- function(param){\n\tL <- param[1]\n\tmu <- param[2]\n\taux1 <- L * log(L)\n \taux2 <- L * sum(log(z[1: j])) / j\n \taux3 <- L * log(mu) \n \taux4 <- log(gamma(L))\n \taux5 <- (L / mu) * sum(z[1: j]) / j \n \tll <- aux1 + aux2 - aux3 - aux4 - aux5 \n\treturn(ll)\n\t}\n\n", "meta": {"hexsha": "27132a28953b0826674efd14d96177bec378c58d", "size": 677, "ext": "r", "lang": "R", "max_stars_repo_path": "Code_r/loglike.r", "max_stars_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_stars_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2020-07-19T09:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T01:35:11.000Z", "max_issues_repo_path": "Code_r/loglike.r", "max_issues_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_issues_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code_r/loglike.r", "max_forks_repo_name": "lcbjrrr/Code_GRSL_2020_1_dockers", "max_forks_repo_head_hexsha": "e765e397df0b82737ede5befed3cdad64480386d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-07-31T02:35:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T08:12:58.000Z", "avg_line_length": 30.7727272727, "max_line_length": 82, "alphanum_fraction": 0.5834564254, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6308282975959586}} {"text": "#' @title calcOpenWaterEff\n#'\n#' @description Calculate the open water efficiency (\\code{openWaterEff})\n#' (dimensionless) using the Kristensen method with Harvald regressions.\n#'\n#' @param Rtot Total ship resistance (vector of numericals, kN) (see\n#' \\code{\\link{calcKristTotalRes}} or \\code{\\link{calcHMTotalRes}})\n#' @param thrustFactor Thrust deduction factor (vector of numericals,\n#' dimensionless) (see \\code{\\link{calcKristThrustFactor}} or\n#' \\code{\\link{calcHMThrustFactor}})\n#' @param nProp Number of propellers (vector of numericals, see\n#' \\code{\\link{calcPropNum}})\n#' @param wakeFraction Wake fraction coefficient (vector of numericals,\n#' dimensionless) (see \\code{\\link{calcKristWakeFrac}} or\n#' \\code{\\link{calcHMWakeFraction}})\n#' @param propDiam Propeller diameter (vector of numericals, m) (see\n#' \\code{\\link{calcPropDia}})\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#'\n#' @return \\code{openWaterEff} (vector of numericals, dimensionless)\n#'\n#'@references\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcKristTotalRes}}\n#'\\item \\code{\\link{calcHMTotalRes}}\n#'\\item \\code{\\link{calcKristThrustFactor}}\n#'\\item \\code{\\link{calcHMThrustFactor}}\n#'\\item \\code{\\link{calcPropNum}}\n#'\\item \\code{\\link{calcKristWakeFrac}}\n#'\\item \\code{\\link{calcHMWakeFraction}}\n#'\\item \\code{\\link{calcPropDia}}\n#'\\item \\code{\\link{calcSpeedUnitConversion}}}\n#'\n#' @examples\n#' calcOpenWaterEff(398.487,0.1894947,1,0.3199536,6.7,0,seawaterDensity=1.025)\n#'\n#' @export\n\n\n\ncalcOpenWaterEff<-function(Rtot,thrustFactor,nProp,wakeFraction,propDiam,shipSpeed,seawaterDensity=1.025){\n\n\n cth<- (8/pi)*Rtot/(1-thrustFactor)/nProp/seawaterDensity/((1-wakeFraction)*shipSpeed*propDiam)^2\n\n\nopenWaterEff<- ifelse(shipSpeed==0,\n 0,\n ((2/(1+sqrt((cth)+1)))*pmax(0.65, 0.81-0.014*(cth)))\n)\n\nreturn(openWaterEff)\n\n}\n", "meta": {"hexsha": "40c0414682547036d208922bbc99f10d23711132", "size": 2214, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcOpenWaterEff.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/calcOpenWaterEff.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/calcOpenWaterEff.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": 36.2950819672, "max_line_length": 106, "alphanum_fraction": 0.7186088528, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6307752412476723}} {"text": "## Inversion for bedform migration rates and sediment flux in the ancient\n## Eric Barefoot\n## May 2018\n\n## TODO\n# clean up documentation more.\n# complete the uncertainty routines.\n# add the ability to also account for variance in data.\n\n# This collection of functions provides functionality for calculating bedform migration rates using methods put out by Rob Mahon and Brandon McElroy in 2018\n\n# describe inputs and other stuff needed\n\n# Mahon et al. use a Bayesian approach for paleohydraulic inversion, meaning that the coefficients that they describe for the empirical fit each have a distribution. They provide uncertainties for the distribution in their Table 1.\n# In this way, we can ascribe ranges for the coefficients, and potentially provide a range of estimates of paleoslope accordingly. I think this means we can have confidence intervals, but I'm not sure about that.\n# Initially, the user is allowed to select a percentile, and that percentile will be chosen for each parameter.\n\n# In the future, users should be allowed to vary each parameter individually.\n\n# get libraries\n\nlibrary(tibble)\n\n## Set values and lookup table for empirical constants.\n\nparam_names = c('alpha0', 'alpha1', 'alpha2', 'beta0', 'beta1', 'gamma', 'delta0', 'delta1')\n\nparams_vals = c(-2.08, 0.254, -1.09, 0.6113, 1.305, 2.9, 0.0513, 0.7744)\n\nparams_uncert = c(0.036, 0.016, 0.044, 0.144, 0.0515, 0.7, 0.0017, 0.0123)\n\npars = tibble(name = param_names, vals = params_vals, uncert = params_uncert)\n\n## Define functions from Mahon et al. 2018\n\n# a function for table lookup. just feed it the name of the constant you want.\nfun_paramVal = function(pars_list, param_name, zscore = 0) {\n\n therow = pars_list[which(pars_list$name == param_name), ] # lookup the constant\n\n val = as.numeric(therow[2]) # extract the value\n dev = as.numeric(therow[3] * zscore) # extract the magnitude of deviation from mean at zscore.\n\n return(list(val = val, dev = dev))\n\n}\n\n# equation 1 from the paper.\n\n#' Bedform-bedload equation\n#'\n#' \\code{bedform_bedload} calculates the sediment flux through bedload in a river based on the height and migration rate of bedforms. From Simons et al. (1965), Implemented from Mahon et al. (2018)\n#' @param hd The mean height of bedforms in meters.\n#' @param V The dune migration rate in meters per second.\n#' @param phi The porosity of the riverbed material. Default is 0.36.\n#' @return Returns a vector \\code{qs}, the sediment flux in m^3/s.\n#' @export\n\nbedform_bedload = function(hd, V, phi = 0.36) {\n\n qs = (1 - phi) * (hd * V) / 2\n\n return(qs)\n\n}\n\n# equation 2 from the paper.\n\n#' Bedform velocity relation\n#'\n#' \\code{bedform_velocity} estimates the velocity of a migrating bedform using a power law fit for slope. Implemented from Mahon et al. (2018)\n#' @param S The dimensionless river slope.\n#' @param beta0 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @param beta1 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @return Returns a vector \\code{V}, the bedform migration rate in m/s.\n#' @export\n\nbedform_velocity = function(beta0, beta1, S) {\n\n logV = beta0 + beta1 * log10(S)\n\n V = 10^(logV)\n\n return(V)\n\n}\n\n# equation 3 from the paper\n\n#' Bedform length to height relation\n#'\n#' \\code{height_length} estimates the mean height of bedforms based on the mean bedform length. Implemented from Mahon et al. (2018)\n#' @param L The mean bedform length.\n#' @param delta0 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @param delta1 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @return Returns a vector \\code{hd}, the bedform migration rate in m/s.\n#' @export\n\nheight_length = function(delta0, delta1, L) {\n\n hd = delta0 * L ^ delta1\n\n return(hd)\n\n}\n\n# equation 4 from the paper\n\n#' Paleoslope relation\n#'\n#' \\code{paleo_slope} estimates the slope of an ancient river. Originally developed in Trmapush et al. 2014. Implemented from Mahon et al. (2018)\n#' @param D50 The median bedload grain size. Determined from samples.\n#' @param Hbf The mean bankfull flow depth. Determined from preserved barforms.\n#' @param alpha0 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @param alpha1 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @param alpha2 Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @return Returns a vector \\code{S}, the dimensionless paleoslope of the ancient river.\n#' @export\n\npaleo_slope = function(alpha0, alpha1, alpha2, D50, Hbf) {\n\n logS = alpha0 + alpha1 * log10(D50) + alpha2 * log10(Hbf)\n\n S = 10^logS\n\n return(S)\n\n}\n\n# equation 5 from the paper\n\n#' Dune height from cosets relation\n#'\n#' \\code{dune_height} estimates the height of dunes based on cross-stratification. Originally developed by Leclair and Bridge (2001). Implemented from Mahon et al. (2018)\n#' @param Tsm The mean thickness of cross-bedded cosets. (see publication for more information)\n#' @param gamma Empirical constant. Value and associated uncertainty from Table 1 in Mahon + McElroy 2018.\n#' @return Returns a vector \\code{hd}, the dune height in the ancient river.\n#' @export\n\ndune_height = function(gamma, Tsm) {\n\n hd = gamma * Tsm\n\n return(hd)\n\n}\n\n# self-contained function for calculating sediment flux rates from outcrops.\n# have to have grain size measurements and bankfull depth estimates\n\n#' Estimating sediment flux in ancient rivers.\n#'\n#' \\code{ancient_1} estimates the sediment flux (\\code{qs}) of ancient river deposits based on dune cross-stratification, bankfull depth reconstruction, and grain size. Implemented from Mahon et al. (2018). Original relations referenced therein.\n#' @param Tsm The mean thickness of cross-bedded cosets. (see publication for more information)\n#' @param D50 The median bedload grain size. Determined from samples.\n#' @param Hbf The mean bankfull flow depth. Determined from preserved barforms.\n#' @param uncert The uncertainty window for empirical parameters. The user should put in a confidence interval. A lower confidence interval will have a narrower error envelope, but will require more tenuous conclusion.\n#' @return Returns a list with elements:\n#' \\code{S}, the river slope (dimensionless).\n#' \\code{hd}, the dune height in the ancient river (m).\n#' \\code{V}, the dune migration rate in the ancient river (m/s).\n#' \\code{qs}, the bedload flux in the ancient river (m^3/s).\n#' If uncertainty is also requested, the output will include upper and lower bounds for confidence, \\code{V_env} and \\code{qs_env}\n#' @export\n\nancient_1 = function(Tsm, D50, Hbf, uncert = NULL) {\n\n S_est = paleo_slope(\n alpha0 = fun_paramVal(pars, 'alpha0')$val,\n alpha1 = fun_paramVal(pars, 'alpha1')$val,\n alpha2 = fun_paramVal(pars, 'alpha2')$val,\n D50 = D50,\n Hbf = Hbf\n )\n hd_est = dune_height(gamma = fun_paramVal(pars, 'gamma')$val, Tsm)\n V_est = bedform_velocity(beta0 = fun_paramVal(pars, 'beta0')$val, beta1 = fun_paramVal(pars, 'beta1')$val, S_est)\n qs_est = bedform_bedload(hd = hd_est, V = V_est)\n\n if (is.null(uncert)) {\n\n return(list(S = S_est, hd = hd_est, V = V_est, qs = qs_est))\n\n } else {\n\n zscore = abs(qnorm(uncert/2))\n env = c(-zscore, zscore)\n\n V_env = c(\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[1]), fun_paramVal(pars, 'beta1', zscore = env[1]), S),\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[2]), fun_paramVal(pars, 'beta1', zscore = env[2]), S)\n )\n\n qs_env = c(\n bedform_bedload(hd, V_env[1]),\n bedform_bedload(hd, V_env[2])\n )\n\n return(list(V = V_est, qs = qs_est, V_env = V_env, qs_env = qs_env))\n\n }\n\n}\n\n# self-contained function for calculating dune migration rates in the modern.\n# uses measured dune heights\n\n#' Estimating sediment flux in modern rivers if bedform height is known.\n#'\n#' \\code{modern_1} estimates the sediment flux (\\code{qs}) of modern rivers based on bedform height and river slope. Implemented from Mahon et al. (2018).\n#' @param hd The mean height of migrating bedforms.\n#' @param S The reach-average slope of the river.\n#' @param uncert The uncertainty window for empirical parameters. The user should put in a confidence interval. A lower confidence interval will have a narrower error envelope, but will require more tenuous conclusions.\n#' @return Returns a list with elements:\n#' \\code{V}, the dune migration rate in the river (m/s).\n#' \\code{qs}, the bedload flux in the river (m^3/s).\n#' If uncertainty is also requested, the output will include upper and lower bounds for confidence, \\code{V_env} and \\code{qs_env}\n#' @export\n\nmodern_1 = function(hd, S, uncert = NULL) { # if bedforme height is known\n\n V_est = bedform_velocity(beta0 = fun_paramVal(pars, 'beta0')$val, beta1 = fun_paramVal(pars, 'beta1')$val, S)\n qs_est = bedform_bedload(hd = hd, V = V_est)\n\n if (is.null(uncert)) {\n\n return(list(V = V_est, qs = qs_est))\n\n } else {\n\n zscore = abs(qnorm(uncert/2))\n env = c(-zscore, zscore)\n\n V_env = c(\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[1]), fun_paramVal(pars, 'beta1', zscore = env[1]), S),\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[2]), fun_paramVal(pars, 'beta1', zscore = env[2]), S)\n )\n\n qs_env = c(\n bedform_bedload(hd, V_env[1]),\n bedform_bedload(hd, V_env[2])\n )\n\n return(list(V = V_est, qs = qs_est, V_env = V_env, qs_env = qs_env))\n\n }\n\n}\n\n# self-contained function for calculating dune migration rates in the modern.\n# uses measured dune lengths\n#' Estimating sediment flux in modern rivers if bedform height is unknown, but bedform length is known.\n#'\n#' \\code{modern_2} estimates the sediment flux (\\code{qs}) of modern rivers based on bedform length and river slope. Implemented from Mahon et al. (2018).\n#' @param L The mean length of migrating bedforms.\n#' @param S The reach-average slope of the river.\n#' @param uncert The uncertainty window for empirical parameters. The user should put in a confidence interval. A lower confidence interval will have a narrower error envelope, but will require more tenuous conclusions.\n#' @return Returns a list with elements:\n#' \\code{V}, the dune migration rate in the river (m/s).\n#' \\code{qs}, the bedload flux in the river (m^3/s).\n#' If uncertainty is also requested, the output will include upper and lower bounds for confidence, \\code{V_env} and \\code{qs_env}\n#' @export\n\nmodern_2 = function(L, S, uncert = NULL) { # if bedforme height is unknown, but length is known\n\n V_est = bedform_velocity(beta0 = fun_paramVal(pars, 'beta0')$val, beta1 = fun_paramVal(pars, 'beta1')$val, S = S)\n hd_est = height_length(delta0 = fun_paramVal(pars, 'delta0')$val, delta1 = fun_paramVal(pars, 'delta1')$val, L = L)\n qs_est = bedform_bedload(hd = hd_est, V = V_est)\n\n if (is.null(uncert)) {\n\n return(list(V = V_est, qs = qs_est))\n\n } else {\n\n zscore = abs(qnorm(uncert/2))\n env = c(-zscore, zscore)\n\n V_env = c(\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[1]), fun_paramVal(pars, 'beta1', zscore = env[1]), S),\n bedform_velocity(fun_paramVal(pars, 'beta0', zscore = env[2]), fun_paramVal(pars, 'beta1', zscore = env[2]), S)\n )\n\n qs_env = c(\n bedform_bedload(hd, V_env[1]),\n bedform_bedload(hd, V_env[2])\n )\n\n return(list(V = V_est, qs = qs_est, V_env = V_env, qs_env = qs_env))\n\n }\n\n}\n", "meta": {"hexsha": "24c0cd92133609f96405d1f0f48ab0fdee302468", "size": 11522, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mahon_bedform_relations.r", "max_stars_repo_name": "ericbarefoot/paleohydror", "max_stars_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/mahon_bedform_relations.r", "max_issues_repo_name": "ericbarefoot/paleohydror", "max_issues_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-04-17T16:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-17T16:32:53.000Z", "max_forks_repo_path": "R/mahon_bedform_relations.r", "max_forks_repo_name": "ericbarefoot/paleohydror", "max_forks_repo_head_hexsha": "1870e634158b476121228f1d8fe82344af25dc9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3242320819, "max_line_length": 245, "alphanum_fraction": 0.7173233814, "num_tokens": 3238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6307190418626005}} {"text": "#install packages\ninstall.packages(\"minpack.lm\")\ninstall.packages(\"boot\")\nlibrary(minpack.lm)\nlibrary(boot)\n\n# Exsampledata of mortalitybase, absolute frequency of deaths in age x\ndx <- c(355,27,16,13,12,9,10,8,8,8,8,9,8,10,12,15,26,29,38,41,45,\n 44,45,46,48,48,47,52,51,57,57,68,69,70,79,87,87,92,103,107,\n 123,130,146,160,175,199,212,241,269,303,338,370,422,473,527,\n 578,638,699,777,844,908,983,1073,1143,1232,1307,1369,1479,\n 1513,1638,1742,1854,1939,2044,2170,2315,2473,2608,2803,3022,\n 3210,3432,3600,3778,3887,3966,3951,3853,3706,3478,3220,2978,\n 2631,2220,1883,1430,1116,830,588,399,260,381)\n \n# Data of mortalitybase, absolute frequency of survivers in age x\nlx <- rev(cumsum(rev(dx)))\n\n#qx = obserevd probability of death between the ages of x and age x+1\nqx <- dx/lx\nlogqx <- log(dx/lx)\n\n#w = limiting age of the mortality table/ database\nw <- length(dx)-1\nx<- 0:90\ndata <- data.frame(Y=rep(0:w, dx))\n\n#Models:\nin this example 4 models are used: \n\n#Gompertzfunction S(x)\nGompertzFuncS <- function(x, m, s) { \n return(exp(exp(-m/s)-exp((x-m)/s)))\n}\n#Inverse Gompertzfunction S(X)\nInvGompertzFuncS <- function(x, m, s) { \n return((1-exp(-exp(-(x-m)/s)))/(1-exp(-exp(m/s))))\n}\n#Weibullfunction S(X)\nWeibullFuncS <- function(x, m, s) {\n return(exp(-(x/m)^(m/s)))\n}\n#Inverse Weibullfunction S(X)\nInvWeibullFuncS <- function(x, m, s) {\n return(1-exp(-(x/m)^(-m/s)))\n}\n\n#Aggregation of models:\n#Function to combine all models in one S(X)\nS <- function(x, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4) {\n return(psi1 * GompertzFuncS(x, m1, s1) +\n psi2 * InvGompertzFuncS(x, m2, s2) +\n psi3 * WeibullFuncS(x, m3, s3) +\n psi4 * InvWeibullFuncS(x, m4, s4))\n}\nmyS <- function(x, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4) {\n return(psi1 * GompertzFuncS(x, m1, s1) +\n psi2 * InvGompertzFuncS(x, m2, s2) +\n psi3 * WeibullFuncS(x, m3, s3) +\n psi4 * InvWeibullFuncS(x, m4, s4))\n}\n#Function to define probability of death ages of x and age x+1 X as Q(X) = 1- S(X+1)/S(x)\nQ <- function(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4) {\n psi4 <- 1 - psi1 - psi2 - psi3\n return(1 - (S(x+1, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4)/\n S(x, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4)))\n}\n#Function to return the logarithmic probability of death ages of x and age x+1 as log(Q(X))\nlogQ <- function(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4) {\n psi4 <- 1 - psi1 - psi2 - psi3\n return(log(1 - (myS(x+1, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4)/\n myS(x, psi1, psi2, psi3, psi4, m1, m2, m3, m4, s1, s2, s3, s4))))\n}\n#fitting of parameters on the statistical values qx\nqx <- qx[0:91]\nPaperFit <- nlsLM(qx ~ Q(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4),\n start = list(psi1=0.97, psi2=0.01, psi3=0.01, \n m1=85, m2=42, m3=.26, m4=23, \n s1=11, s2=14, s3=1, s4=8),\n weights = 1/abs(qx) , control = nls.control(maxiter=1000))\n#fitting of parameters on the logarithmic statistical values qx using logQ\nlogqx <- logqx[0:91]\nlogPaperFit <- nlsLM(logqx ~ logQ(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4),\n start = list(psi1=0.97, psi2=0.01, psi3=0.01, \n m1=85, m2=42, m3=.26, m4=23, \n s1=11, s2=14, s3=1, s4=8), weights = 1/abs(logqx), control = nls.control(maxiter=1000))\nqxPaperFit <- predict(PaperFit, data=data.frame(x=0:90))\nlogqxPaperFit <- predict(logPaperFit, data=data.frame(x=0:90))\n##Visualization:\nplot(x, logSterbewahrscheinlichkeit)\nlines(x, logqxPaperFit, col=\"red\")\n#fitting of parameters on the logarithmic statistical values non parametric Bootstrap\nbootfit <- function(data, indices) {\n d <- data[indices, ]\n # Bestimme für d die logqx Werte\n dx <- as.numeric(table(d)) \n #lx = observed number of people alive, relative to an original cohort, at age x\n lx <- rev(cumsum(rev(dx)))\n #qx = obserevd probability of death between the ages of x and age x+1\n qx <- dx/lx\n #w = imiting age of the mortality table/ database\n w <- length(dx)-1\n #x= age \n x <- 0:90\n qx <- qx[0:91]\n PaperFit <- nlsLM(Sterbewahrscheinlichkeit ~ Q(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4),\n start = list(psi1=0.97, psi2=0.01, psi3=0.01, \n m1=85, m2=42, m3=.26, m4=23, \n s1=11, s2=14, s3=1, s4=8),\n weights = 1/abs(qx), control = nls.control(maxiter=1000))\n qxPaperFit <- predict(PaperFit, data=data.frame(x=0:90))\n return(PaperFit$m$getPars())\n}\nlogbootfit <- function(data, indices) {\n d <- data[indices, ]\n # Bestimme für d die logqx Werte\n dx <- as.numeric(table(d))\n #lx = observed number of people alive, relative to an original cohort, at age x\n lx <- rev(cumsum(rev(dx)))\n #qx = obserevd probability of death between the ages of x and age x+1\n qx <- dx/lx\n logqx <- log(dx/lx)\n #w = imiting age of the mortality table/ database\n w <- length(dx)-1\n #x= age \n x <- 0:90\n logqx<- logqx[0:91]\n logPaperFit <- nlsLM(logqx ~ logQ(x, psi1, psi2, psi3, m1, m2, m3, m4, s1, s2, s3, s4),\n start = list(psi1=0.97, psi2=0.01, psi3=0.01, \n m1=85, m2=42, m3=.26, m4=23, \n s1=11, s2=14, s3=1, s4=8),\n weights = 1/abs(logqx), control = nls.control(maxiter=1000))\n logqxPaperFit <- predict(logPaperFit, data=data.frame(x=0:90))\n return(logPaperFit$m$getPars())\n}\n#call non parametric bootstrap\nset.seed(2)\nnp_boot <- boot(data=data, statistic=bootfit, R=1000)\nset.seed(1)\nlognp_boot <- boot(data=data, statistic=logbootfit, R=1)\nset.seed(2)\n\n#plot results\nlines(x, logqxPaperFit, col=\"red\")\nlines(x, logQ(x,9.862212e-01, 2.189063e-03, 7.514800e-03, 8.311480e+01, 3.440280e+01, 2.878187e+01, 2.196682e+01, 9.342605e+00, 6.470701e+00, 2.004074e+02, 5.208513e+00) \n, col=\"blue\")\nlines(x, logQ(x, 0.917213634, 0.067941919, 0.004328894, 86.424663344, 57.935706039, 0.379915365, 34.177258127, 7.591399243, 4.847847541, 0.928726117, 4.373326151 ), col=\"red\")\n", "meta": {"hexsha": "e0f58ae16987eac112657154b52fa0616f75e0e5", "size": 6315, "ext": "r", "lang": "R", "max_stars_repo_path": "Bootstrapping.r", "max_stars_repo_name": "joshuakuepper/Bootstrapping-parametric-models-of-mortality", "max_stars_repo_head_hexsha": "aa3315533c453a84e0bd13af639dfd13647e7fbe", "max_stars_repo_licenses": ["MIT"], "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": "joshuakuepper/Bootstrapping-parametric-models-of-mortality", "max_issues_repo_head_hexsha": "aa3315533c453a84e0bd13af639dfd13647e7fbe", "max_issues_repo_licenses": ["MIT"], "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": "joshuakuepper/Bootstrapping-parametric-models-of-mortality", "max_forks_repo_head_hexsha": "aa3315533c453a84e0bd13af639dfd13647e7fbe", "max_forks_repo_licenses": ["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.6689189189, "max_line_length": 177, "alphanum_fraction": 0.6041171813, "num_tokens": 2485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6306720168206891}} {"text": "## Dati\r\nx1 <- 22.05 # (minore)\r\np1 <- 0.09\r\n\r\nx2 <- 25.84 # (maggiore)\r\np2 <- 0.08\r\n\r\nx3 <- 0.578\r\n\r\n## Svolgimento \r\n\r\nmat_a <- matrix(data = c(1,qnorm(p1),1,qnorm(1-p2)),\r\n nrow = 2, ncol = 2, byrow = TRUE)\r\nmat_b <- c(x1, x2)\r\ntmp <- solve(mat_a, mat_b)\r\nmi <- tmp[1]\r\nsigma <- tmp[2]\r\nrm(mat_a, mat_b, tmp)\r\n\r\nrisultato3 <- 1 - pnorm(x3) + pnorm(-x3)\r\n\r\nprint(mi)\r\nprint(sigma)\r\nprint(risultato3)\r\n", "meta": {"hexsha": "2eb9a6e2986255a6eeff4c16e207e039e2fbf406", "size": 416, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 43.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 43.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 43.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.64, "max_line_length": 53, "alphanum_fraction": 0.5384615385, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6304844055379911}} {"text": "\n# coding: utf-8\n\n# # Práctico 8 - Predecir información faltante en redes\n# \n# # 1. Ambientes de trabajo\n# \n# ## 1.a) Ambiente COLAB remoto\n# \n# 1. Abrir en navegador: https://colab.research.google.com/\n# 2. Abrir el notebook de la tarea:\n# File-> Open Notebook -> Github -> https://github.com/prbocca/na101_master -> homework_8_prediction\n# 3. Guardar el notebook en su Google Drive:\n# File -> Save a Copy in Drive... \n# 4. Renombrar el archivo `\"cedula ID\"_ar_hw8.ipynb`, por ejemplo *33484022_ar_hw8.ipynb*\n# 5. Al final usted deberá descargar el notebook. Asegurarse que se están guardando las salidas de ejecución en el notebook: File -> Download .ipynb\n# 6. Luego estos archivos deberán ser enviados a prbocca@fing.edu.uy \n# \n# ##1.b) Ambiente RSTUDIO local (opcional)\n# \n# Abrir el .r de la tarea en: https://github.com/prbocca/na101_master/tree/master/homework_8_prediction\n\n# ## 1.c) Cargar Librerias\n\n# In[ ]:\n\n# cargar librerias\nload_libs <- function(libraries = libs, install=TRUE){\n if (install){ # instalar librerias no instaladas\n new.packages <- libs[!(libs %in% installed.packages()[,\"Package\"])]\n if(length(new.packages)) install.packages(new.packages)\n }\n #cargo librerias \n for (lib in libraries){\n require(lib, character.only=TRUE, quietly = FALSE)\n } \n} \n\nlibs = c(\"ROCR\", #evaluacion de problemas de clasificacion\n \"rgexf\", #igraph to gephi\n \"vioplot\", \"cowplot\",\n # \"org.Sc.sgd.db\", \"GOstats\", \"GO.db\", #parecen no estar disponibles en el ambiente COLAB y los instalaremos luego de otra manera\n \"foreach\", \"doMC\", #procesamiento en paralelo\n \"sand\",\"igraph\", \"ggplot2\", \"reshape2\") #las basicas\n\nload_libs(libs)\n\n\n# ## 1.d) Descargar funciones auxiliares\n\n# In[ ]:\n\n#directorio donde se va a trabajar\ndata_path = \"/content/ar/hw8/\"\n\ndir.create(data_path, showWarnings = FALSE, recursive = TRUE)\nsetwd(data_path)\ngetwd()\nlist.files()\n\n# cargo funciones auxiliares\nsource(\"https://raw.githubusercontent.com/prbocca/na101_master/master/homeworks_common.r\")\n\n\n# # 2. Predicción de enlaces en `R`.\n# \n# Seguir las Secciones 7.1 y 7.2 del libro [SANDR], ejecutando el código fuente incluido.\n# \n\n# In[ ]:\n\n# Chapter 7 Network Topology Inference\n# 7.1 Introduction\n# 7.2 Link Prediction SANDR (esta es el tutorial de SANDR incluido como ejercicio)\n#########################################################\n# To illustrate the potential of simple scoring methods like this, recall the network\n# fblog of French political blogs. The number of nearest common neighbors for\n# each pair of vertices in this network, excluding—if incident to each other—the two\n# vertices themselves, may be computed in the following manner.\n#library(sand)\nfblog = upgrade_graph(fblog) #evita warnings por ser un grafo en version vieja\nnv <- vcount(fblog)\nncn <- numeric()\nA <- get.adjacency(fblog)\nfor(i in (1:(nv-1))){\n ni <- neighborhood(fblog, 1, i)\n nj <- neighborhood(fblog, 1, (i+1):nv)\n nbhd.ij <- mapply(intersect, ni, nj, SIMPLIFY=FALSE)\n temp <- unlist(lapply(nbhd.ij, length)) -\n 2 * A[i, (i+1):nv]\n ncn <- c(ncn, temp)\n}\n\n\n# In[ ]:\n\n# In Fig. 7.2 we compare the scores s(i, j) for those vertex pairs that are not incident\n# to each other (i.e., ‘no edge’), and those that are (i.e., ‘edge’), using so-called violin\n# plots.\n#library(vioplot)\nAvec <- A[lower.tri(A)]\nvioplot(ncn[Avec==0], ncn[Avec==1],\n names=c(\"No Edge\", \"Edge\"))\ntitle(ylab=\"Number of Common Neighbors\")\n\n\n# In[ ]:\n\n# It is evident from this comparison that there is a decided tendency towards larger\n# scores when there is in fact an edge present. Viewing the calculation we have done\n# here as a ‘leave-one-out’ cross-validation, and calculating the area under the curve\n# (AUC) of the corresponding ROC curve,\n#library(ROCR)\npred <- prediction(ncn, Avec)\nperf <- performance(pred, \"auc\")\nslot(perf, \"y.values\")\n\n#agrego el plot de la curva ROC\nroc.perf = performance(pred, measure = \"tpr\", x.measure = \"fpr\")\nplot(roc.perf, col=\"red\")\nabline(a=0, b= 1)\n\n\n# $\\def\\ccalN{{\\mathcal N}}$\n# \n# # 3. Predicción de aristas en redes reales.\n# \n# En este ejercicio veremos que tan bien funcionan los métodos informales de *score* para predecir enlaces en distintas redes. Este ejercicio fue originalmente propuesto por el Prof. Aaron Clauset, en su curso \"Network Analysis and Modeling\", CSCI 5352, del Santa Fe Institute.\n# \n# Como vimos, los métodos informales de predicción de enlaces basados en *score* definen una medida de enlace para todo par de vértices que no son aristas (es decir, definen el *score*, $s(i,j)$, para todo $(i,j) \\notin E^{obs}$), y predicen las aristas faltantes como aquellas parejas con mayor `score`.\n# Hay muchas funciones de `score` posibles, en este ejercicio probaremos tres:\n# * camino más corto: $s(i,j)= \\frac{1}{dist_{G^{obs}}(i,j)}$, siendo $dist_{G^{obs}}(i, j)$ la distancia geodésica observada entre los vértices $i$ y $j$ en el grafo observado;\n# \n# * vecinos en común: $s(i,j)=|\\ccalN_i^{obs}\\cap \\ccalN_j^{obs}|$; y\n# \n# * producto de grados observados: $s(i,j)= d_i d_j$.\n\n# ## 3.a) Descargar y cargar la red de la enfermedad de Malaria.\n# \n# Existen muchas representaciones en red de las relaciones entre los genes para la enfermedad de la Malaria. \n# Usaremos la red de: *D. B. Larremore, A. Clauset, and C. O. Buckee, \"A network approach to analyzing highly recombinant malaria parasite genes.\" PLOS Computational Biology 9(10), e1003268 (2013).* \n# \n# Esta red tiene $307$ vértices y $2684$ aristas.\n# Los vértices son genes, y dos genes están conectados si ellos comparten un substring cuyo largo es estadísticamente significativo. Se tiene una etiqueta en los vértices que clasifica los genes.\n# Visualizar la red en la siguiente Figura (el color de los vértices es la etiqueta de clasificación, y el tamaño representa el grado): ![alt text](https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/g_malaria.png)\n# \n# Descargar el grafo desde: https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/g_malaria.graphml.\n\n# In[ ]:\n\n# descargar y cargar datos\ng_malaria = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: -\n#\n#\n#\n##################################################################\nsummary(g_malaria)\n\n#plot\nset.seed(25)\nE(g_malaria)$color = \"gray\"\nplot(g_malaria, edge.color=\"gray\", edge.width=1, edge.lty=1, edge.arrow.size=.5, \n vertex.color=V(g_malaria)$label, vertex.size=3, vertex.label=NA,\n layout=layout_with_drl(g_malaria), main=\"Malaria\")\n\n\n# ## 3.b) Descargar y cargar la red de las relaciones entre directivos en empresas públicas de Noruega.\n# \n# Usaremos los datos del siguiente trabajo: *C. Seierstad and T. Opsahl, \"For the few not the many? The effects of affirmative action on presence, prominence, and social capital of women directors in Norway.\" Scand. J. Manag. 27(1), 44-54 (2011)*.\n# \n# Es una red de afiliaciones entre directores que comparten alguna junta directiva en las compañias públicas noruegas.\n# La red tiene una gran componente, con $854$ vértices (directivos) y $2745$ aristas (juntas directivas en común), y corresponde a la realidad de agosto de 2011.\n# Se incluyen algunos metadatos, como los nombres de directores y compañías, la ciudad y código postal para empresas, y el género de los directores. Visualizar la red en la siguiente Figura (el color de los vértices es el género (azul-hombre, rojo-mujer), y el tamaño representa el grado): ![alt text](https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/g_gcdirectores.png)\n# \n# Descargar el grafo desde: \n# https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/g_gcdirectores.graphml.\n# \n\n# In[ ]:\n\n# descargar y cargar datos\ng_gcdirectores = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: -\n#\n#\n#\n##################################################################\nsummary(g_gcdirectores)\n\n#plot\nset.seed(25)\nE(g_gcdirectores)$color = \"gray\"\nplot(g_gcdirectores, edge.color=\"gray\", edge.width=1, edge.lty=1, edge.arrow.size=.5, \n vertex.color=V(g_gcdirectores)$gender, vertex.size=3, vertex.label=NA,\n layout=layout_with_drl(g_gcdirectores), main=\"Red de afiliación de directores noruegos: componente gigante\")\n\n\n# ## 3.c) Predecir enlaces\n# \n# Para medir la calidad de predicción de cada método usaremos la métrica $AUC$ (*Area Under Curve*). Ver la página de Wikipedia sobre ROC: http://bit.ly/2ehXHrb. Un predictor aleatorio tiene $AUC=0.5$ y un predictor perfecto tiene $AUC=1.0$ por tanto los métodos serán mejores a mayor valor de $AUC$.\n# \n# Utilizando la métrica AUC, evaluar la capacidad predictiva del método de *score* de vecinos en común, sobre una subred observada con el $\\%80$ de las aristas de la red de Malaria.\n# \n# Se disponen de varias funciones auxiliares precargadas, incluyendo `score()` y `delete_edges_rand()`. \n# Es posible ver las funciones axiliares en: https://raw.githubusercontent.com/prbocca/na101_master/master/homeworks_common.r.\n# \n# El siguiente código resuelve el ejercicio y ejemplifica como usar las funciones auxiliares. Se obtiene una muy buena capacidad predictiva, con un $AUC=0.917$ y la curva ROC de la siguiente Figura: ![Curva ROC para el método de score de vecinos en común, sobre una subred con el %80 de las aristas de la red de Malaria.](https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/roc_malaria.png)\n# \n# \n\n# In[ ]:\n\n# computo las aristas reales y las pongo en un vector (triangular inferior, mismo orden que score())\nA_malaria <- get.adjacency(g_malaria)\nA_malaria_v <- A_malaria[lower.tri(A_malaria)]\n\n#creo una subred observada\nset.seed(42)\ng_malaria_obs = delete_edges_rand(g_malaria, p=0.2)\n\n# computo las aristas observadas y las pongo en un vector (triangular inferior, mismo orden que score())\nA_malaria_obs = get.adjacency(g_malaria_obs)\nA_malaria_obs_v <- A_malaria_obs[lower.tri(A_malaria_obs)]\ntrue_possibleedges_no_obs = A_malaria_v[A_malaria_obs_v==0] #vector real sobre aristas no observadas\n\n# computo aristas predichas \ns_cn = score(g_malaria_obs, type=\"common neighbors\")\npred_possibleedges_no_obs = s_cn$score[A_malaria_obs_v==0] #vector prediccho sobre aristas no observadas\n\n# computo la performance\npred_malaria <- prediction(pred_possibleedges_no_obs, true_possibleedges_no_obs)\nperf_malaria <- performance(pred_malaria, \"auc\")\nprintf(\"El método de score usando vecinos en cumún, tiene un AUC=%s\", slot(perf_malaria, \"y.values\"))\n# el valor de AUC es 0.9172444\n\n#plot de la curva ROC\nroc_malaria = performance(pred_malaria, measure = \"tpr\", x.measure = \"fpr\")\nplot(roc_malaria, col=\"red\")\ntitle(\"ROC para la red de Malaria y %20 de aristas no observadas\")\nabline(a=0, b=1)\n\n\n# ## 3.d) Estudio exahustivo de capacidad predictiva\n# \n# Realizar un estudio más exahustivo sobre la calidad predictiva del método de score, probando las tres funciones de score definidas anteriormente, variando el porcentaje de aristas observadas entre \\%99 y \\%20.\n# Buscando eliminar casuística, repetir la prueba sorteando distintos grafos observados.\n# Realizar este procedimiento para las siguientes redes:\n# * grafo aleatorio de Erdos Renyi con $100$ vértices y una probabilidad de arista de $0.20$;\n# \n# * modelo Barabási-Albert con $100$ vértices y $m=9$ aristias agregadas en cada paso;\n# \n# * red de Malaria; y \n# \n# * red de directores.\n# \n# \n# Es posible utilizar la función auxiliar cargada previamente `summary_predictions(g, n_sample, p, types=c(\"1/dist\",\"common neighbors\", \"degree product\"), metric=\"auc\", cores=1)`, que recibe un grafo $g$, crea un grafo observado para cada probabilidad de eliminación de arista del vector $p$, y prueba el métoodo de *score* para distintos tipos de medidas y para la métrica $AUC$. Repite cada caso `n_sample` y promedia resultados.\n# \n# \n\n# In[ ]:\n\n# defino los parámetros del experimento\n\n# para cada grafo, sorteo un subgrafo observado, calculo todos los tipos de score, predigo aristas faltantes y evaluo la metrica\np_v = c(0.01, 0.05, 0.10, 0.20, 0.50, 0.80) #las probabilidades de eliminacion de arista a evaluar\nn_sample = 5 #cantidad de sorteos de g_obs\ntypes = c(\"1/dist\",\"common neighbors\", \"degree product\")\nmetric=\"auc\" \nn_cores = 1 #la ejecución en COLAB solo permite 1 CPU\n\n\n# In[ ]:\n\n#realizo los cálculos para el grafo aleatorio\n\n# sorteo un grafo\ng_erdosrenyi = erdos.renyi.game(100,0.20)\nwrite.graph(g_erdosrenyi, file=\"g_erdosrenyi.graphml\", format= \"graphml\") \nplot(g_erdosrenyi, edge.color=\"gray\", edge.width=1, edge.lty=1, edge.arrow.size=.5, \n vertex.color=\"black\", vertex.size=3, vertex.label=NA,\n layout=layout_with_drl(g_erdosrenyi), main=\"Erdos-Renyi\")\n\n# evaluo la capacidad predictiva sobre ese grafo\nresults_erdosrenyi = summary_predictions(g_erdosrenyi, n_sample, p_v, types, metric, cores=n_cores)\nsaveRDS(results_erdosrenyi, \"results_erdosrenyi.RDS\")\n\n# imprimo resultados\nggplot(results_erdosrenyi$results_summary, aes(100*p, auc, colour = score)) + \n geom_line() + \n geom_point(data=results_erdosrenyi$results, aes(100*p, auc, colour = score), alpha=0.01) + \n labs(title = \"AUC para distintos scores y porcentaje de aristas no observadas\", \n subtitle = \"grafo Erdos Renyi\", x=\"% aristas no observadas\", y=\"AUC\")\n\n\n# In[ ]:\n\n#realizo los cálculos para el grafo Barabasi-Albert\n\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: similar a anterior\n#\n#\n#\n##################################################################\n\n\n\n# In[ ]:\n\n#realizo los cálculos para el grafo g_malaria\n\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: similar a anterior\n#\n#\n#\n##################################################################\n\n\n# In[ ]:\n\n#realizo los cálculos para el grafo g_gcdirectores\n\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: similar a anterior\n#\n#\n#\n##################################################################\n\n\n# ## 3.e) Interpretar resultados de sección anterior\n# \n# En la sección anterior debieron obtenerse resultados similares a los de la siguiente Figura: ![AUC de los métodos de score para predecir enlaces, usando distintos porcentajes de aristas no observadas y distintas redes.](https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/result_auc_p.png)\n# \n# Como es de esperar: \n# * no puede predecirse aristas en los grafos aleatorios;\n# * el *score* del producto de grado solo es útil en el modelo preferencial de Barabási-Albert debido a que en la construcción del grafo son más probables las aristas entre vértices más populares; y\n# * la capadidad predictiva en redes reales es bastante buena, inclusive para altos porcentajes de aristas no observadas.\n\n# # 4. Predicción de atributos de vértices en `R`\n# \n# Seguir las Secciones 8.1 y 8.2 del libro [SANDR], ejecutando el código fuente incluido.\n# \n\n# In[ ]:\n\n# Chapter 8 Modeling and Prediction for Processes on Network Graphs\n# 8.1 Introduction\n# 8.2 Nearest Neighbor Methods\n#############################################################\n\n# We illustrate through the problem of protein function prediction. \n# We saw examples of strong assortative mixing of protein function in\n# the underlying network of protein–protein interactions. While the gold standard for\n# establishing the functionality of proteins is through direct experimental validation\n# (or ‘assays’), results like these have been taken to suggest that, given the vast num-\n# ber of proteins yet to be annotated, it is natural to approach this problem from the\n# perspective of statistical prediction. Approaches to protein function prediction that\n# incorporate network-based information have become standard.\nset.seed(42)\n\ndata(ppi.CC)\nppi.CC = upgrade_graph(ppi.CC)\nsummary(ppi.CC)\n# IGRAPH 006c919 UN-- 134 241 -- \n# + attr: name (v/c), ICSC (v/n), IPR000198 (v/n), IPR000403 (v/n), IPR001806 (v/n), IPR001849 (v/n),\n# | IPR002041 (v/n), IPR003527 (v/n)\n# contains a network data object, called ppi.CC, that consists of a network of 241\n# interactions among 134 proteins, as well as various vertex attributes.\n#\n# The vertex attribute ICSC is a binary vector\nV(ppi.CC)$ICSC[1:10]\n\n# A visualization of this network is shown in Fig. 8.1.\nV(ppi.CC)[ICSC == 1]$color <- \"yellow\"\nV(ppi.CC)[ICSC == 0]$color <- \"blue\"\nplot(ppi.CC, vertex.size=5, vertex.label=NA)\n\n\n# In[ ]:\n\n# A simple, but often quite effective, method for producing local predictions is the\n# nearest-neighbor method. See Hastie, Tibshirani, and Friedman [71, Chap. 2.3.2],\n# for example, for general background on nearest-neighbor methods. For networks,\n# the nearest-neighbor method centers on the calculation, for a given vertex i ∈ V , of\n# the nearest-neighbor average\n# i.e., the average of the values of the vertex attribute vector X in the neighborhood\n# N i of i. Here |N i | denotes the number of neighbors of i in G. Calculation of these\n# averages over all vertices i ∈ V corresponds to a nearest-neighbor smoothing of X\n# across the network.\n\n# In the context of protein function prediction, X is a binary vector, with entries\n# indicating whether or not each protein is or is not annotated with a function of\n# interest (e.g., ICSC). In predicting binary vertex attributes, the nearest-neighbor av-\n# erages (8.1) typically are compared to some threshold. For example, a threshold\n# of 0.5 is commonly used, with a nearest-neighbor average greater than this value\n# meaning that a majority of neighbors have the characteristic indicated by X = 1,\n# resulting in a prediction for X i of 1 as well. Such methods are also known as ‘guilt-\n# by-association’ methods in some fields.\n\n# me quedo con la componente gigante\nclu <- clusters(ppi.CC)\nppi.CC.gc <- induced.subgraph(ppi.CC, clu$membership==which.max(clu$csize))\nplot(ppi.CC.gc, vertex.size=5, vertex.label=NA)\n\n# we can calculate the nearest-neighbor average\n# for each of the proteins in the giant connected component of our network.\nnn.ave <- sapply(V(ppi.CC.gc), function(x) mean(V(ppi.CC.gc)[nei(x)]$ICSC))\n\n# We then plot histograms of the resulting values, separated according to the status\n# of the vertex defining each neighborhood, i.e., according to the status of the ‘ego’\n# vertex, in the terminology of social networks.\n# The results, shown in Fig. 8.2, confirm that ICSC can be predicted with fairly\n# good accuracy. \npar(mfrow=c(2,1))\nhist(nn.ave[V(ppi.CC.gc)$ICSC == 1], col=\"yellow\",\n ylim=c(0, 30), xlab=\"Proportion Neighbors w/ ICSC\",\n main=\"Egos w/ ICSC\")\nhist(nn.ave[V(ppi.CC.gc)$ICSC == 0], col=\"blue\",\n ylim=c(0, 30), xlab=\"Proportion Neighbors w/ ICSC\",\n main=\"Egos w/out ICSC\")\n\n# In particular, using a threshold of 0.5 would yield an error rate\n# of roughly 25 %.\nnn.pred <- as.numeric(nn.ave > 0.5)\nmean(as.numeric(nn.pred != V(ppi.CC.gc)$ICSC))\n#[1] 0.2598425\n\n\n# In[ ]:\n\n# La siguiente sección requiere previamente instalar algunos paquetes especiales\n\nif (!requireNamespace(\"BiocManager\", quietly = TRUE))\n install.packages(\"BiocManager\")\nBiocManager::install()\nBiocManager::install(c(\"GOstats\", \"GO.db\", \"org.Sc.sgd.db\"))\n\n\n# In[ ]:\n\n# Interestingly, we can push this illustration a bit further by taking advantage of the\n# evolving nature of biological databases like GO. In particular, the proteins annotated\n# in GO as not having a given biological function include both (1) those that indeed are\n# known not to have that function, and (2) those whose status is simply unknown. As\n# a result, by comparing against more recent versions of GO, it is sometimes possible\n# to identify proteins whose status has changed for a given functional annotation,\n# indicating that in the interim it has been discovered to in fact have that function.\n# The R package GOstats, a part of the Bioconductor package, may be used to\n# manipulate and analyze Gene Ontology, as contained in the database GO.db.\nlibrary(GOstats)\nlibrary(GO.db)\n# And the annotations specific to the organism yeast can be obtained from the\n# org.Sc.sgd.db database.\nlibrary(org.Sc.sgd.db)\n# At the time of this writing, these annotations were last updated in September of\n# 2013, roughly six years after the data in ppi.CC were assembled.\n\n\n# In[ ]:\n\n# We extract those proteins with the function ICSC—now subsumed under the\n# term intercellular signaling transduction (ICST), or GO label 003556—and keep\n# only those that have been identified from direct experimental assay, as indicated by\n# the evidence code ‘IDA’.\nx <- as.list(org.Sc.sgdGO2ALLORFS)\ncurrent.icst <- x[names(x) == \"GO:0035556\"]\nev.code <- names(current.icst[[1]])\nicst.ida <- current.icst[[1]][ev.code == \"IDA\"]\n# We then separate out the names of those proteins that had ICSC in our original data\norig.icsc <- V(ppi.CC.gc)[ICSC == 1]$name\n# and similarly extract the names of those proteins under the new annotations that\n# were present in the giant connected component of our original network.\ncandidates <- intersect(icst.ida, V(ppi.CC.gc)$name)\n# Among these candidates, there are four that have been newly discovered to have\n# ICSC, with the following names.\nnew.icsc <- setdiff(candidates, orig.icsc)\nnew.icsc\n# [1] \"YDL159W\" \"YHL007C\" \"YIL033C\" \"YLR362W\"\n# And among these four, we find that two of them would have been correctly predicted\n# by comparing the value of their nearest-neighbor averages to a threshold of 0.5.\nnn.ave[V(ppi.CC.gc)$name %in% new.icsc]\n\n\n# # 5. Predicción de atributos de vértices en redes reales.\n# \n# Por lo general, los vértices de las redes reales tiene atributos, los cuales pueden ser categóricos, escalares o reales.\n# En muchos casos no se conocen estos atributos para algunos vértices, por ejemplo cuando solo se tiene una muestra de la red, cuando explicitamente el atributo es ocultado por el vértice, cuando el atributo aun no existe y se creará a futuro, etc.\n# \n# Un método sencillo para predecir los atributos faltantes es el método de los vecinos más cercanos (*NNM - nearest-neighbor method*), donde se estima el atributo faltante en el vértice $i$ como el promedio de los atributos en el vecindario de $i$. La idea de vecindario y promedio puede variar dependiendo del caso particular. Este método suele funcionar bien cuando existe una marcada homofilia entre los vértices participantes respecto a ese atributo.\n\n# ## 5.a) Cargar los datos\n# \n# Cargar la red de la enfermedad de Malaria y la red de relaciones entre directivos en empresas públicas de Noruega siguiendo el procedimiento del ejercicio anterior.\n# \n\n# In[ ]:\n\n# Cargar la red de Malaria\ng_malaria = read.graph(file=\"g_malaria.graphml\", format= \"graphml\")\nsummary(g_malaria)\n\n# Cargar la red de directores\ng_gcdirectores = read.graph(file=\"g_gcdirectores.graphml\", format= \"graphml\")\nsummary(g_gcdirectores)\n\n\n# ## 5.b) Predecir atributos en la red de Malaria\n# \n# Evaluar la precisión del método NNM, sobre una subred observada con el $\\%80$ de los atributos de vértice `label` de la red de Malaria.\n# El atributo `label`, disponible en la red, es un enumerado (variable categórica) y es representado en `igraph` como números. Por tal motivo, el promedio sobre los vecinos del método NNM se define como el enumerado de mayor frecuencia. \n# Para medir la calidad de predicción del método usaremos la exactitud (*accuracy* - fracción de predicciones correctas).\n# \n# Se disponen de varias funciones auxiliares, incluyendo `nnm()` y `delete_vertex_attr_rand()`. \n# Es posible ver las funciones axiliares en: https://github.com/prbocca/na101_master/raw/master/homeworks_common.r.\n# \n# El siguiente código resuelve el ejercicio y ejemplifica como usar las funciones auxiliares. Se obtiene una muy buena capacidad predictiva, con una exactitud de $acc=0.712$.\n# \n\n# In[ ]:\n\n#creo una subred observada\nset.seed(42)\ng_malaria_obs = delete_vertex_attr_rand(g_malaria,\"label\", p=0.2)\nvertex_attr_deleted = is.na(vertex_attr(g_malaria_obs, \"label\")) #vector booleando con los atributos borrados\n\n#computo vector con los atributos reales\nvertex_attr_actual = vertex_attr(g_malaria, \"label\")[vertex_attr_deleted] #vector con los atributos reales\nvertex_attr_actual = factor(vertex_attr_actual, levels=unique(vertex_attr(g_malaria, \"label\")))\n\n#computo vector con atributos predichos\nvertex_attr_pred = nnm(g_malaria_obs,\"label\", fun=\"freq\")[vertex_attr_deleted] #vector con los atributos predichos\nvertex_attr_pred = factor(vertex_attr_pred, levels=unique(vertex_attr(g_malaria, \"label\")))\n\n# computo la exactitud\ncm = as.matrix(table(pred=vertex_attr_pred, actual=vertex_attr_actual)) # create the confusion matrix\naccuracy = sum(diag(cm)) / sum(cm)\nprintf(\"La exactitud de NNM para la red de Malaria es %s\", accuracy) # [1] 0.7121212\n\n# otra forma corta de hacerlo\n# comparo con funcion de prediccion que hace todo\n#r = evaluate_predictions_vertexattr(g_malaria, g_malaria_obs, \"label\", fun=\"freq\", metric=\"acc\")\n#r$metrics\n\n\n# ## 5.c) Predecir atributos en la red de directores\n# \n# En la red de relaciones entre directivos se conoce el género de los directivos, como un atributo binario de vértice llamado `gender`.\n# Dado que el atributo es binario se puede utilizar tanto la métrica de exactitud como $AUC$ vista anteriormente. Además el método NNM puede realizarse usando el promedio entre los vecinos (y no la frecuencia más alta).\n# Repetir la parte anterior para esta red. \n# ¿Qué se puede concluir sobre la homofilia en esta red?\n# \n\n# In[ ]:\n\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: similar a anterior\n#\n#\n#\n##################################################################\n\n\n# ## 5.d) Estudio exahustivo de capacidad predictiva\n# \n# Realizar un estudio más exahustivo sobre la calidad predictiva del método NNM, variando el porcentaje de atributos `label` observados entre \\%99 y \\%20 para la red de Malaria.\n# Buscando eliminar casuística, repetir la prueba sorteando distintos grafos observados.\n# \n# Es posible utilizar la función auxiliar cargada previamente `summary_predictions_vertexattr(g, attr, n_sample, p, fun=\"mean\", metric=\"auc\", cores=1)`, que recibe un grafo `g`, crea un grafo observado para cada probabilidad de eliminación de arista del vector `p`, y prueba el método NNM promediando con la función `fun` y para la métrica `acc`. Repite cada caso `n_sample` y promedia resultados.\n# \n# Deben obtenerse resultados similares a los de la siguiente Figura: ![precisión del método NNM para predecir atributos de vértices, usando distintos porcentajes de atributos no observados](https://github.com/prbocca/na101_master/raw/master/homework_8_prediction/result_acc_p.png). Observar que en este caso, la capadidad predictiva no es muy buena, y existe gran variación en los resultados entre muestras.\n# \n# \n\n# In[ ]:\n\n# defino los parámetros del experimento\n\n# para cada grafo, sorteo un subgrafo observado, calculo todos los tipos de score, predigo aristas faltantes y evaluo la metrica\np_v = c(0.01, 0.05, 0.10, 0.20, 0.50, 0.80) #las probabilidades de eliminacion de arista a evaluar\nn_sample = 5 #cantidad de sorteos de g_obs\nmetric=\"acc\" #metric=\"auc\" #metric=\"f\"\nn_cores = 1 #la ejecución en COLAB solo permite 1 CPU\n\n\n# In[ ]:\n\n#realizo los calculos para el grafo g_malaria\n\nresults_malaria_vertexattr = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: ver funciones auxiliares\n#\n#\n#\n##################################################################\nstr(results_malaria_vertexattr)\n\n#imprimo resultados\nggplot(results_malaria_vertexattr$results_summary, aes(100*p, acc)) + \n geom_line() + \n geom_point(data=results_malaria_vertexattr$results, aes(100*p, acc), alpha=0.20) + \n labs(title = \"Precisión para distintos porcentajes de atributos no observados\", \n subtitle = \"grafo Malaria\", x=\"% atributos de vértices no observados\", y=\"precisión\")\n\n", "meta": {"hexsha": "b28d47bda57e8d9834249e10516238026dfb302e", "size": 28250, "ext": "r", "lang": "R", "max_stars_repo_path": "r_deprecated/homework_8_prediction/ar_hw8.r", "max_stars_repo_name": "prbocca/na101_master", "max_stars_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "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_deprecated/homework_8_prediction/ar_hw8.r", "max_issues_repo_name": "prbocca/na101_master", "max_issues_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "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_deprecated/homework_8_prediction/ar_hw8.r", "max_forks_repo_name": "prbocca/na101_master", "max_forks_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T19:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T19:06:12.000Z", "avg_line_length": 45.71197411, "max_line_length": 454, "alphanum_fraction": 0.7089557522, "num_tokens": 7790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.6300383079017399}} {"text": "#' @title pressure2Depth\n#' @description Unesco 1983. Algorithms for computation of fundamental properties of seawater, 1983\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\npressure2Depth <- function (pressure, lat = 45) {\n lat <- lat * 0.0174532925199433\n x <- sin(lat)^2\n gr <- 9.780318 * (1 + (0.0052788 + 2.36e-05 * x) * x) + 1.092e-06 * pressure\n d <- (((-1.82e-15 * pressure + 2.279e-10) * pressure - 2.2512e-05) * \n pressure + 9.72659) * pressure/gr\n \n return(d)\n}\n", "meta": {"hexsha": "bb816fb3590d7aca4d4f5213bd9f05eeab77688d", "size": 548, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pressure2Depth.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/pressure2Depth.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/pressure2Depth.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": 36.5333333333, "max_line_length": 99, "alphanum_fraction": 0.6259124088, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6300310169281985}} {"text": "# Day 7: The Treachery of Whales\n\nget_day7_input_path <- function() {\n paste(getwd(), \"/2021/Day 7/Day7_input.txt\", sep = \"\")\n}\n\npart1 <- function(fuel_type = \"standard\") {\n positions <- strtoi(unlist(strsplit(readLines(get_day7_input_path()), \",\")))\n\n unique_crab_pos <- sort(unique(positions))\n max_crab_pos <- unique_crab_pos[length(unique_crab_pos)]\n crabs <- matrix(ncol = 2)[-1, ]\n\n for (i in seq_len(length(unique_crab_pos))) {\n sum_crabs_in_pos <- sum(positions == unique_crab_pos[i])\n crabs <- rbind(crabs, c(unique_crab_pos[i], sum_crabs_in_pos))\n }\n\n optimal_pos <- 0\n optimal_fuel <- 2147483647\n\n for (i in 0:max_crab_pos) {\n fuel_used <- 0\n target_pos <- i\n for (c in seq_len(length(unique_crab_pos))) {\n if (fuel_type == \"standard\") {\n fuel_used <- fuel_used +\n calc_fuel_std(target_pos, crabs[c, 1], crabs[c, 2])\n } else {\n fuel_used <- fuel_used +\n calc_fuel_crab(target_pos, crabs[c, 1], crabs[c, 2])\n }\n }\n\n if (fuel_used < optimal_fuel) {\n optimal_fuel <- fuel_used\n optimal_pos <- target_pos\n }\n }\n\n cat(\"Optimal Position: \", optimal_pos, \"; Fuel Used: \", optimal_fuel, \"\\n\")\n}\n\npart2 <- function() {\n part1(\"crab\")\n}\n\ncalc_fuel_std <- function(tar_pos, cur_pos, num_crabs) {\n abs(tar_pos - cur_pos) * num_crabs\n}\n\ncalc_fuel_crab <- function(tar_pos, cur_pos, num_crabs) {\n delta <- abs(tar_pos - cur_pos)\n crab_adj <- 0\n\n if (delta > 0) {\n crab_adj <- sum(1:delta)\n }\n\n crab_adj * num_crabs\n}\n\npart1()\npart2()\n", "meta": {"hexsha": "194e3ba3f0c991cc0cbbe85b8ad163db060d7d3f", "size": 1674, "ext": "r", "lang": "R", "max_stars_repo_path": "2021/Day 07/Day7_TheTreacheryofWhales.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 07/Day7_TheTreacheryofWhales.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 07/Day7_TheTreacheryofWhales.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": 25.7538461538, "max_line_length": 80, "alphanum_fraction": 0.5818399044, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6299007369210782}} {"text": "library(epimdr)\nlibrary(bbmle)\nlibrary(statnet)\n\n\ndata(niamey)\nhead(niamey[, 1:5])\n\npar(mar = c(5,5,2,5))\nplot(niamey$absweek, niamey$tot_cases, type = \"b\", \n xlab = \"Week\", ylab = \"Incidence\")\npar(new = TRUE)\nplot(niamey$absweek, niamey$cum_cases, type = \"l\", \n col = \"red\", axes = FALSE, xlab = NA, ylab = NA, log = \"y\")\naxis(side = 4)\nmtext(side = 4, line = 4, \"Cumulative incidence\")\nlegend(\"topleft\", legend = c(\"Cases\", \"Cumulative\"),\n lty = c(1,1), pch = c(1,NA), col = c(\"black\", \"red\"))\n\nfit=lm(log(cum_cases)~absweek, subset=absweek<7, \n data=niamey)\nr=fit$coef[\"absweek\"]\nV=c(1.5, 1.8)\nV*r+1\n\nV = c(1.5, 1.8)\nf = (5/7)/V\nV * r + 1 + f * (1 - f) * (V * r)^2\n\nllik.cb = function(S0, beta, I) {\n n = length(I)\n S = floor(S0 - cumsum(I[-n]))\n p = 1 - exp(-beta * (I[-n])/S0)\n L = -sum(dbinom(I[-1], S, p, log = TRUE))\n return(L)\n}\n\ntwoweek = rep(1:15, each = 2)\ny = sapply(split(niamey$cases_1[1:30], twoweek), sum)\nsum(y)\n\nS0cand = 6500 \nbetacand = seq(0,10, by = .1)\nll = rep(NA, length(betacand))\nfor(i in 1:length(betacand)){\n ll[i] = llik.cb(S0 = S0cand, beta = betacand[i],\n I = y)}\nplot(ll ~ betacand, ylab = \"Neg log-lik\", \n xlab = expression(beta)) \nbetacand[which.min(ll)]\n\nbetacand = 2.3\nS0cand = seq(5920,8000, length = 101)\nll = rep(NA, length = 101)\nfor(i in 1:101){\n ll[i] = llik.cb(S0 = S0cand[i], beta = betacand, \n I = y)}\nplot(ll ~ S0cand, ylab = \"Neg log-lik\", \n xlab = expression(S[0]))\nS0cand[which.min(ll)]\n\nfit = mle2(llik.cb, start = list(S0 = 7085, beta = 2.3), \n method = \"Nelder-Mead\",data = list(I = y))\nsummary(fit)\nconfint(fit)\n\ncov2cor(vcov(fit))\n\nsim.cb=function(S0, beta, I0){\n I=I0\n S=S0\n i=1\n while(!any(I==0)){\n i=i+1\n I[i]=rbinom(1, size=S[i-1], prob=1-\n exp(-beta*I[i-1]/S0))\n S[i]=S[i-1]-I[i]\n }\n out=data.frame(S=S, I=I)\n return(out)\n}\n\nplot(y, type=\"n\", xlim=c(1,18), \n ylab=\"Predicted/observed\", xlab=\"Week\")\nfor(i in 1:100){\n sim=sim.cb(S0=floor(coef(fit)[\"S0\"]), \n beta=coef(fit)[\"beta\"], I0=11)\n lines(sim$I, col=grey(.5))\n}\npoints(y, type=\"b\", col=2)\n\ndata(flu)\nplot(flu$day, flu$cases, type=\"b\", xlab=\"Day\", \n ylab=\"In bed\", log=\"y\")\ntail(flu)\n\nfit=lm(log(cases)~day, subset=day<=5, \n data=flu)\nr=fit$coef[\"day\"]\nV=c(2,3)\nV*r+1\n\ndata(ebola)\npar(mar = c(5,5,2,5))\nplot(ebola$day, ebola$cases, type=\"b\", xlab=\"Week\", \n ylab=\"Incidence\")\npar(new=T)\nplot(ebola$day, ebola$cum_cases, type=\"l\", col=\"red\",\n axes=FALSE, xlab=NA, ylab=NA, log=\"y\")\naxis(side = 4)\nmtext(side = 4, line = 4, \"Cumulative incidence\")\nlegend(\"right\", legend=c(\"Cases\", \"Cumulative\"),\n lty=c(1,1), pch=c(1,NA), col=c(\"black\", \"red\"))\ntail(ebola)\n\nfit=lm(log(cum_cases)~day, subset=day<100, \n data=ebola)\nr=fit$coef[\"day\"]\nV=15\nf=.5\nV*r+1+f*(1-f)*(V*r)^2\n\n#Data aggregation\ncases=sapply(split(ebola$cases, \n floor((ebola$day-.1)/14)), sum)\nsum(cases)\n\n#Removal MLE\nfit = mle2(llik.cb, start = list(S0 = 20000, beta = 2), \n method = \"Nelder-Mead\",data = list(I = cases))\nsummary(fit)\n\nconfint(fit, std.err = c(100, 0.1))\n\nnames(ferrari)\nferrari$Ebolacases95\nsum(ferrari$Ebolacases95, na.rm = TRUE)\ny = c(na.omit(ferrari$Ebolacases95))\n\nfit = mle2(llik.cb, method = \"Nelder-Mead\", \n start = list(S0 = 300, beta = 2), \n data = list(I = y))\nfit\nconfint(fit, std.err = 2)\n\ndata(gonnet)\nnwt = network(gonnet, directed = TRUE)\nplot(nwt, vertex.col = c(0, rep(1, 17), rep(2, 71)))\n\nF1 = quote(beta * S * I/N)\nF2 = 0\n\nVm1 = quote(mu * E + sigma * E)\nVm2 = quote(mu * I + alpha * I + gamma * I)\n\nVp1 = 0\nVp2 = quote(sigma * E)\n\nV1 = substitute(a - b, list(a = Vm1, b = Vp1))\nV2 = substitute(a - b, list(a = Vm2, b = Vp2))\n\nf11 = D(F1, \"E\"); f12 = D(F1, \"I\")\nf21 = D(F2, \"E\"); f22 = D(F2, \"I\")\n\nv11 = D(V1, \"E\"); v12 = D(V1, \"I\")\nv21 = D(V2, \"E\"); v22 = D(V2, \"I\")\n\nparas = list(S = 1, E = 0, I = 0, R = 0, mu = 0, \n alpha = 0, beta = 5, gamma = .8, sigma = 1.2, N = 1)\nf = with(paras,\n matrix(c(eval(f11),eval(f12),eval(f21),\n eval(f22)), nrow = 2, byrow = TRUE))\nv=with(paras,\n matrix(c(eval(v11),eval(v12),eval(v21),\n eval(v22)), nrow=2, byrow=TRUE))\n\nmax(eigen(f %*% solve(v))$values)\n\nwith(paras,\nsigma/(sigma+mu)*beta/(gamma+mu+alpha))\n\nF1 = expression(betai * S * I / N + betah* S * H / N +\n betaf * S * F / N)\nF2=0\nF3=0\nF4=0\n\nVm1 = quote(sigma * E)\nVm2 = quote(Theta * gammah * I + (1 - Theta) * (1-\n Lambda) * gammar * I + (1 - Theta) * Lambda * \n gammaf * I)\nVm3 = quote(Lambda * etaf * H + (1 - Lambda) * etar * H)\nVm4 = quote(chi * F)\n\nVp1 = 0\nVp2 = quote(sigma * E)\nVp3 = quote(Theta * gammah * I)\nVp4 = quote((1 - Theta) * (1 - Lambda) * gammar * I+ \n Lambda * etaf * H)\n\nV1 = substitute(a - b, list(a = Vm1, b = Vp1))\nV2 = substitute(a - b, list(a = Vm2, b = Vp2))\nV3 = substitute(a - b, list(a = Vm3, b = Vp3))\nV4 = substitute(a - b, list(a = Vm4, b = Vp4))\n\nf11 = D(F1, \"E\"); f12 = D(F1, \"I\"); f13 = D(F1, \"H\") \n f14 = D(F1, \"F\")\nf21 = D(F2, \"E\"); f22 = D(F2, \"I\"); f23 = D(F2, \"H\") \n f24 = D(F2, \"F\")\nf31 = D(F3, \"E\"); f32 = D(F3, \"I\"); f33 = D(F3, \"H\") \n f34 = D(F3, \"F\")\nf41 = D(F4, \"E\"); f42 = D(F4, \"I\"); f43 = D(F4, \"H\") \n f44 = D(F4, \"F\")\n\nv11 = D(V1, \"E\"); v12 = D(V1, \"I\"); v13 = D(V1, \"H\")\n v14 = D(V1, \"F\")\nv21 = D(V2, \"E\"); v22 = D(V2, \"I\"); v23 = D(V2, \"H\")\n v24 = D(V2, \"F\")\nv31 = D(V3, \"E\"); v32 = D(V3, \"I\"); v33 = D(V3, \"H\")\n v34 = D(V3, \"F\")\nv41 = D(V4, \"E\"); v42 = D(V4, \"I\"); v43 = D(V4, \"H\")\n v44 = D(V4, \"F\")\n\ngammah = 1/5 * 7\ngammaf = 1/9.6 * 7\ngammar = 1/10 * 7\nchi = 1/2 * 7\netaf = 1/4.6 * 7\netar = 1/5 * 7\nparas = list(S = 1,E = 0, I = 0, H = 0, F = 0,R = 0,\n sigma = 1/7*7, Theta = 0.81, Lambda = 0.81, betai = 0.588, \n betah = 0.794, betaf = 7.653, N = 1, gammah = gammah,\n gammaf = gammaf, gammar = gammar, etaf = etaf, \n etar = etar, chi = chi)\n\nf = with(paras, \nmatrix(c(eval(f11), eval(f12), eval(f13), eval(f14),\n eval(f21), eval(f22), eval(f23), eval(f24),\n eval(f31), eval(f32), eval(f33), eval(f34),\n eval(f41), eval(f42), eval(f43), eval(f44)),\n nrow = 4, byrow = T))\n\nv = with(paras, \nmatrix(c(eval(v11), eval(v12), eval(v13), eval(v14),\n eval(v21), eval(v22), eval(v23), eval(v24),\n eval(v31), eval(v32), eval(v33), eval(v34),\n eval(v41), eval(v42), eval(v43), eval(v44)),\n nrow = 4, byrow = T))\n\nmax(eigen(f %*% solve(v))$values)\n", "meta": {"hexsha": "6c682b97ae18e5bbe6c090d7153db6afd2af81e8", "size": 6355, "ext": "r", "lang": "R", "max_stars_repo_path": "models/bjornstad_2018/chapter3_r0.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/bjornstad_2018/chapter3_r0.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/bjornstad_2018/chapter3_r0.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": 25.3187250996, "max_line_length": 64, "alphanum_fraction": 0.5477576711, "num_tokens": 2763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6298355107129221}} {"text": "#' Generate likelihood statistics (AIC, AICC, BIC, etc.)\n#'\n#' Generate likelihood statistics that include the Jacobian adjustment for transformations as done in the X-13ARIMA-SEATS program\n#'\n#' @param Y numeric vector, original time series.\n#' @param Lnlkhd numeric scalar, maximized log likelihood of model.\n#' @param Np Integer scalar, Number of parameters in model used. Default is 2.\n#' @param Nintvl Integer scalar, Number of differences in model used. Default is 2.\n#' @param Adj numeric vector, prior adjustment factor time series. Default is NULL, which indicates there is no prior adjustment.\n#' @param Logit logical scalar, if TRUE the logit transformation is used. Default is FALSE.\n#' @param Trans logical scalar, if TRUE a Box-Cox transform is used. Default is TRUE\n#' @param Lam numeric scalar, Box-Cox transformation parameter. Default is 0 (Log transform).\n#' @param Eick numeric scalar, weighting paramter for Empiracle Information Criterion. Default is NULL (EIC not computed).\n#' @return List of likelihood diagnostics and related estimates (ll = log likelihood, jacadj = jacobian transformation adjustment, \n#' lladj = adjusted likelihood, nobs = number of observations, neffective = effective number of observations,\n#' nparams = number of parameters, df = Nspobs - Nintvl - Np, aic = AIC, aicc = AICC, hannanquinn = Hannan Quinn,\n#' bic = BIC, bic2 = BIC2, EIC = Empiracle Information Criterion)\n#' @examples\n#' ic_default_log_est <- \n#' rjd3highfreq::fractionalAirlineEstimation(log(ic_obs), periods=c(365.25/7), \n#' x=ic_default_matrix)\n#' ic_default_log_lkhd_stat <- \n#' gen_likelihood_stats(ic_obs, \n#' Lnlkhd = ic_default_log_est$likelihood$ll, \n#' Nintvl = 2, \n#' Np = ic_default_log_est$likelihood$nparams)\n#' ic_default_log_aicc <- ic_default_log_lkhd_stat$aicc\n#' @import stats\n#' @export\ngen_likelihood_stats <- function(Y, Lnlkhd, Nintvl = 2, Np = 2, Adj = NULL, \n Logit = FALSE, Trans = TRUE, Lam = 0.0, \n Eick = NULL) {\n # Author: Brian C. Monsell (OEUS), Version 2.0, 2/2/2022\n\n # generate jacobian adjustment\n Nspobs <- length(Y)\n jacadj <- jacobian_trans_adj(Y, Nspobs, Nintvl, Adj = Adj, Logit = Logit, Trans = Trans, Lam = Lam) \n\n dnefob <- Nspobs - Nintvl\n TWO <- 2.0\n lladj <- Lnlkhd + jacadj\n \n # AIC\n Aic=-TWO*(lladj-Np)\n \n # AICC\n Aicc=-TWO*(lladj-dnefob*Np/(dnefob-(Np+1)))\n \n # Hannon-Quinn\n Hnquin=-TWO*(lladj-log(log(dnefob))*Np)\n \n # BIC\n Bic=-TWO*(lladj)+Np*log(dnefob)\n \n # BIC2\n Bic2=(-TWO*Lnlkhd+Np*log(dnefob))/dnefob\n \n # BICC\n \n # EIC (only produced if EICk is specified) and return a list of likelihood statistics\n if (!is.null(Eick)) {\n Eic=-TWO*(lladj)+Np*Eick\n return(list(ll = Lnlkhd, jacadj = jacadj, lladj = lladj, nobs = Nspobs, neffective = dnefob,\n nparams = Np, df = dnefob - Np, aic = Aic, aicc = Aicc, hannanquinn = Hnquin,\n bic = Bic, bic2 = Bic2, eic = Eic, eick = Eick))\n } else {\n return(list(ll = Lnlkhd, jacadj = jacadj, lladj = lladj, nobs = Nspobs, neffective = dnefob,\n nparams = Np, df = dnefob - Np, aic = Aic, aicc = Aicc, hannanquinn = Hnquin,\n bic = Bic, bic2 = Bic2))\n }\n \n}\n", "meta": {"hexsha": "9290a0bd669b9674a696e7c5ff6183f37c5f6d4a", "size": 3395, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gen_likelihood_stats.r", "max_stars_repo_name": "bcmonsell/airutilities", "max_stars_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_stars_repo_licenses": ["MIT"], "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/gen_likelihood_stats.r", "max_issues_repo_name": "bcmonsell/airutilities", "max_issues_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_issues_repo_licenses": ["MIT"], "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/gen_likelihood_stats.r", "max_forks_repo_name": "bcmonsell/airutilities", "max_forks_repo_head_hexsha": "278d52b6accf576fea1f21801564664e15d5f2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5068493151, "max_line_length": 131, "alphanum_fraction": 0.6424153166, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6298349038702687}} {"text": "# Compare means with Kruskal-Wallis test (nonparametric, because non-normal distribution)\n\ndata <- read.csv('../../results/caching/data_all.csv', sep = ';')\ndata_amf <- read.csv('../../results/client_algos/data_all.csv', sep = ';')\ndata_noamf <- read.csv('../../results/caching_none/data_all.csv', sep = ';')\n\n# Means\naggregate(data$time, list(data$combination), median)\n# HTTP+Filter 732.0\n# Filter 1126.0\n# HTTP 652.5\n# None 254672.5\naggregate(data_noamf$time, list(data_noamf$combination), median)\n# HTTP 2408.0\n# None 4156.5\n\n#boxplot(time ~ combination, data = data, ylab=\"Exec (ms)\", xlab=\"Combination\")\n\n# H0: No statistical difference between combinations\nkruskal.test(time ~ combination, data = data)\n# p: < 2.2e-16\n# => Reject H0, non-equal means => big statistical difference\n\n# H0: Filter == HTTP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_1' | data$combination=='combination_2'),])\n# p: 0.02255\n# => Reject H0, non-equal means => Filter > HTTP\n\n# H0: HTTP+Filter == HTTP\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_0' | data$combination=='combination_2'),])\n# p: 0.7694\n# => Accept H0, equal means => HTTP+Filter == HTTP\n\n# H0: AMF-nocache == noAMF-nocache\nkruskal.test(time ~ combination, data = data[which(data$combination=='combination_3' | data_noamf$combination=='combination_1'),])\n# p: < 2.2e-16\n# => Reject H0, non-equal means => AMF-nocache < noAMF-nocache\n\n# H0: AMF-cache == noAMF-cache\nkruskal.test(time ~ combination, data = data[which(data_amf$combination=='combination_3' | data_noamf$combination=='combination_0'),])\n# p: < 2.2e-16\n# => Reject H0, non-equal means => AMF-cache < noAMF-cache\n", "meta": {"hexsha": "84f7001e2abda2f000940f5b717a0685346741b2", "size": 1742, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/caching/tests.r", "max_stars_repo_name": "comunica/Experiments-AMF", "max_stars_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/caching/tests.r", "max_issues_repo_name": "comunica/Experiments-AMF", "max_issues_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-03-04T17:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T11:23:38.000Z", "max_forks_repo_path": "analysis/caching/tests.r", "max_forks_repo_name": "comunica/Experiments-AMF", "max_forks_repo_head_hexsha": "e133e5994d470f84ab923ca6ef8afa114ed21739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.511627907, "max_line_length": 134, "alphanum_fraction": 0.6865671642, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6297866976156498}} {"text": "for(j in 2:10) {\n r <- sprintf(\"%d: \", j)\n for(n in 1:j) {\n r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n0)\n\tif(!is.na(tau2)) \tstopifnot(tau2>0)\n\tif(!is.na(v)) \t\tstopifnot(v>0)\n\tif(!is.na(beta1)) \tstopifnot(beta1>0)\n\n\tif(sum(c((is.na(sigma2)||is.nan(sigma2)),\n\t\t\t (is.na((tau2)||is.nan(tau2))),\n\t\t\t (is.na((v)||is.nan(v))),\n\t\t\t (is.na((beta1)||is.nan(beta1))))) != 2)\n\t\tstop(\"please specifiy exacty two parameters out of 'sigma2','tau2','v', and 'beta'\")\n\t# beta1 / v specified\n\tif(is.na(tau2) & (!is.na(beta1))& (!is.na(v)))\n\t\ttau2 = beta1*v\n\tif(is.na(sigma2) & (!is.na(beta1))& (!is.na(v)))\n\t\tsigma2 = (1-beta1)*v\n\t# sigma2 /v specified\n\tif(is.na(sigma2) & (!is.na(tau2))& (!is.na(v)))\n\t\tsigma2 = v - tau2\n\t# tau2/v specified\n\tif(is.na(tau2) & (!is.na(sigma2))& (!is.na(v)))\n\t\ttau2 = v - sigma2\n\t# tau2 / V specified\n\tif(is.na(sigma2) & (!is.na(tau2))& (!is.na(beta1)))\n\t\tsigma2 = (tau2/beta1) - tau2\n\t# tau2 / V specified\n\tif(is.na(tau2) & (!is.na(sigma2))& (!is.na(beta1)))\n\t\ttau2 = (sigma2*beta1)/(1-beta1)\n\tif(is.na(sigma2) |is.na(tau2) )\n\t\tstop('Insufficient arguments: ')\n\tif(is.na(v))\n\t\tv = sigma2 + tau2\n\tif(is.na(beta1))\n\t\tbeta1 = tau2 / v\n\treturn(list(sigma2=sigma2,\n\t\t\t \ttau2=tau2,\n\t\t\t \tv=v,\n\t\t\t \tbeta1=beta1,\n\t\t\t\tmu=ARGS$mu,\n\t\t\t\tbn = function(n)tau2/((sigma2/n) + tau2)))\n}\n\n", "meta": {"hexsha": "1b1d2efdae0ef760aa5a6d67839a84c90edd7bb4", "size": 2800, "ext": "r", "lang": "R", "max_stars_repo_path": "R/peb-utils.r", "max_stars_repo_name": "jdthorpe/PEB", "max_stars_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_stars_repo_licenses": ["MIT"], "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/peb-utils.r", "max_issues_repo_name": "jdthorpe/PEB", "max_issues_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_issues_repo_licenses": ["MIT"], "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/peb-utils.r", "max_forks_repo_name": "jdthorpe/PEB", "max_forks_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 106, "alphanum_fraction": 0.6203571429, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6294632900202873}} {"text": "# Performing calculations in the Matrix\n\n# Construct star_wars_matrix\nbox_office <- c(460.998, 314.4, 290.475, 247.900, 309.306, 165.8)\nregion <- c(\"US\", \"non-US\")\ntitles <- c(\"A New Hope\", \n \"The Empire Strikes Back\", \n \"Return of the Jedi\")\n \nstar_wars_matrix <- matrix(box_office, \n nrow = 3, byrow = TRUE,\n dimnames = list(titles, region))\n\n# Calculate worldwide box office figures\nworldwide_vector <- rowSums(star_wars_matrix)\n", "meta": {"hexsha": "bc02624ac1281267c79b8ea5ed3c01ef48ec7e6e", "size": 520, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DataAnalyst/Basics/matrix-calcs.r", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/DataAnalyst/Basics/matrix-calcs.r", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/DataAnalyst/Basics/matrix-calcs.r", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5, "max_line_length": 65, "alphanum_fraction": 0.5923076923, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6288388682119543}} {"text": "## @knitr logistic-fun\nx <- seq(-4,4,by=.05)\np <- 1/(1 + exp(-x)) # Figure (*\\ref{fig:lrm-logistic-fun}*)\nplot(x, p, xlab=\"X\", ylab=\"P\", type=\"l\")\n\n\n## @knitr or-vs-diff\nplot(0, 0, type=\"n\", xlab=\"Risk for Subject Without Risk Factor\",\n ylab=\"Increase in Risk\",\n xlim=c(0,1), ylim=c(0,.6)) # Figure (*\\ref{fig:lrm-or-vs-diff}*)\ni <- 0\nor <- c(1.1,1.25,1.5,1.75,2,3,4,5,10)\nfor(h in or) {\n i <- i + 1\n p <- seq(.0001, .9999, length=200)\n logit <- log(p/(1 - p)) # same as qlogis(p)\n logit <- logit + log(h) # modify by odds ratio\n p2 <- 1/(1 + exp(-logit))# same as plogis(logit)\n d <- p2 - p\n lines(p, d, lty=i)\n maxd <- max(d)\n smax <- p[d==maxd]\n text(smax, maxd + .02, format(h), cex=.6)\n}\n\n\n## @knitr lrmodel\nrequire(rms)\ngetHdata(sex.age.response)\nd <- sex.age.response\ndd <- datadist(d); options(datadist='dd')\nf <- lrm(response ~ sex + age, data=d)\nfasr <- f # Save for later\nw <- function(...)\n with(d, {\n m <- sex=='male'\n f <- sex=='female'\n lpoints(age[f], response[f], pch=1)\n lpoints(age[m], response[m], pch=2)\n af <- cut2(age, c(45,55), levels.mean=TRUE)\n prop <- tapply(response, list(af, sex), mean,\n na.rm=TRUE)\n agem <- as.numeric(row.names(prop))\n lpoints(agem, prop[,'female'],\n pch=4, cex=1.3, col='green')\n lpoints(agem, prop[,'male'],\n pch=5, cex=1.3, col='green')\n x <- rep(62, 4); y <- seq(.25, .1, length=4)\n lpoints(x, y, pch=c(1, 2, 4, 5),\n col=rep(c('blue','green'),each=2))\n ltext(x+5, y,\n c('F Observed','M Observed',\n 'F Proportion','M Proportion'), cex=.8)\n } ) # Figure (*\\ref{fig:lrm-lrmodel}*)\n\nplot(Predict(f, age=seq(34, 70, length=200), sex, fun=plogis),\n ylab='Pr[response]', ylim=c(-.02, 1.02), addpanel=w)\nltx <- function(fit) latex(fit, inline=TRUE, columns=54,\n file='', after='$.', digits=3,\n size='Ssize', before='$X\\\\hat{\\\\beta}=')\nltx(f)\n\n\n## @knitr simerr\nsigmas <- c(.5, .75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4)\nns <- seq(25, 300, by=25)\nnsim <- 1000\nxs <- seq(-1.5, 1.5, length=200)\npactual <- plogis(xs)\n\ndn <- list(sigma=format(sigmas), n=format(ns))\nmaxerr <- N1 <- array(NA, c(length(sigmas), length(ns)), dn)\nrequire(rms)\n\ni <- 0\nfor(s in sigmas) {\n i <- i + 1\n j <- 0\n for(n in ns) {\n j <- j + 1\n n1 <- maxe <- 0\n for(k in 1:nsim) {\n x <- rnorm(n, 0, s)\n P <- plogis(x)\n y <- ifelse(runif(n) <= P, 1, 0)\n n1 <- n1 + sum(y)\n beta <- lrm.fit(x, y)$coefficients\n phat <- plogis(beta[1] + beta[2] * xs)\n maxe <- maxe + max(abs(phat - pactual))\n }\n n1 <- n1/nsim\n maxe <- maxe/nsim\n maxerr[i,j] <- maxe\n N1[i,j] <- n1\n }\n}\nxrange <- range(xs)\nsimerr <- llist(N1, maxerr, sigmas, ns, nsim, xrange)\n\nmaxe <- reShape(maxerr)\n# Figure (*\\ref{fig:lrm-simerr}*)\nxYplot(maxerr ~ n, groups=sigma, data=maxe,\n ylab=expression(paste('Average Maximum ',\n abs(hat(P) - P))),\n type='l', lty=rep(1:2, 5), label.curve=FALSE,\n abline=list(h=c(.15, .1, .05), col=gray(.85)))\nKey(.8, .68, other=list(cex=.7,\n title=expression(~~~~~~~~~~~sigma)))\n\n\n## @knitr assumptions\nplot(0:1, 0:1, xlab=expression(X[2]), ylab='logit{Y=1}',\n axes=FALSE, type='n')\naxis(1, at=0:1, labels=rep('',2))\naxis(2, at=0:1, labels=rep('',2))\nlines(c(.05, .8), c(.05, .5))\nlines(c(.05, .8), c(.30, .75))\ntext(.9, .5, expression(X[1]==0), adj=.5)\ntext(.9, .75,expression(X[1]==1), adj=.5)\n\n\n## @knitr emp-age-sex\ngetHdata(acath)\nacath$sex <- factor(acath$sex, 0:1, c('male','female'))\ndd <- datadist(acath); options(datadist='dd')\nf <- lrm(sigdz ~ rcs(age, 4) * sex, data=acath)\n\n## @knitr emp-age-sex-kn\nkn <- specs(f)$how.modeled['age','Parameters']\nkn <- setdiff(strsplit(kn, ' ')[[1]], '')\nkn[length(kn)] <- paste('and', kn[length(kn)])\nkn <- paste(kn, collapse=', ')\n\n## @knitr emp-age-sex-pl\nw <- function(...)\n with(acath, {\n plsmo(age, sigdz, group=sex, fun=qlogis, lty='dotted',\n add=TRUE, grid=TRUE)\n af <- cut2(age, g=10, levels.mean=TRUE)\n prop <- qlogis(tapply(sigdz, list(af, sex), mean,\n na.rm=TRUE))\n agem <- as.numeric(row.names(prop))\n lpoints(agem, prop[,'female'], pch=4, col='green')\n lpoints(agem, prop[,'male'], pch=2, col='green')\n } ) # Figure (*\\ref{fig:lrm-emp-age-sex-pl}*)\nplot(Predict(f, age, sex), ylim=c(-2,4), addpanel=w,\n label.curve=list(offset=unit(0.5, 'cm')))\n\n## @knitr emp-age-sex-plunused\nggplot(Predict(f, age, sex)) +\n stat_plsmo(aes(x=age, y=sigdz), data=acath, fun=qlogis)\n\n\n\n\n## @knitr lrtest\nlr <- function(formula)\n {\n f <- lrm(formula, data=acath)\n stats <- f$stats[c('Model L.R.', 'd.f.')]\n cat('L.R. Chi-square:', round(stats[1],1),\n ' d.f.:', stats[2],'\\n')\n f\n }\na <- lr(sigdz ~ sex + age)\nb <- lr(sigdz ~ sex * age)\nc <- lr(sigdz ~ sex + rcs(age,4))\nd <- lr(sigdz ~ sex * rcs(age,4))\nlrtest(a, b)\nlrtest(a, c)\nlrtest(a, d)\nlrtest(b, d)\nlrtest(c, d)\n\n\n## @knitr dur\ndz <- subset(acath, sigdz==1)\ndd <- datadist(dz)\nf <- lrm(tvdlm ~ rcs(cad.dur, 5), data=dz)\nw <- function(...)\n with(dz, {\n plsmo(cad.dur, tvdlm, fun=qlogis, add=TRUE,\n grid=TRUE, lty='dotted')\n x <- cut2(cad.dur, g=15, levels.mean=TRUE)\n prop <- qlogis(tapply(tvdlm, x, mean, na.rm=TRUE))\n xm <- as.numeric(names(prop))\n lpoints(xm, prop, pch=2, col='green')\n } ) # Figure (*\\ref{fig:lrm-dur}*)\nplot(Predict(f, cad.dur), addpanel=w)\n\n\n## @knitr problog\nf <- lrm(tvdlm ~ log10(cad.dur + 1), data=dz)\nw <- function(...)\n with(dz, {\n x <- cut2(cad.dur, m=150, levels.mean=TRUE)\n prop <- tapply(tvdlm, x, mean, na.rm=TRUE)\n xm <- as.numeric(names(prop))\n lpoints(xm, prop, pch=2, col='green')\n } )\n# Figure (*\\ref{fig:lrm-problog}*)\nplot(Predict(f, cad.dur, fun=plogis), ylab='P',\n ylim=c(.2, .8), addpanel=w)\n\n\n## @knitr acath\nacath <- transform(acath,\n cholesterol = choleste,\n age.tertile = cut2(age,g=3),\n sx = as.integer(acath$sex) - 1)\n# sx for loess, need to code as numeric\ndd <- datadist(acath); options(datadist='dd')\n\n# First model stratifies age into tertiles to get more\n# empirical estimates of age x cholesterol interaction\n\nf <- lrm(sigdz ~ age.tertile*(sex + rcs(cholesterol,4)),\n data=acath)\nf\nltx(f)\n\n## @knitr cholxage\nprint(anova(f), caption='Crudely categorizing age into tertiles',\n size='smaller')\nyl <- c(-1,5)\nplot(Predict(f, cholesterol, age.tertile),\n adj.subtitle=FALSE, ylim=yl) # Figure (*\\ref{fig:lrm-cholxage}*)\n\n\n## @knitr iacholxage-loess\n# Re-do model with continuous age\nf <- loess(sigdz ~ age * (sx + cholesterol), data=acath,\n parametric=\"sx\", drop.square=\"sx\")\nages <- seq(25, 75, length=40)\nchols <- seq(100, 400, length=40)\ng <- expand.grid(cholesterol=chols, age=ages, sx=0)\n# drop sex dimension of grid since held to 1 value\np <- drop(predict(f, g))\np[p < 0.001] <- 0.001\np[p > 0.999] <- 0.999\nzl <- c(-3, 6) # Figure (*\\ref{fig:lrm-iacholxage-loess}*)\nwireframe(qlogis(p) ~ cholesterol*age,\n xlab=list(rot=30), ylab=list(rot=-40),\n zlab=list(label='log odds', rot=90), zlim=zl,\n scales = list(arrows = FALSE), data=g)\n\n\n## @knitr iacholxage-lsp\nf <- lrm(sigdz ~ lsp(age,c(46,52,59)) *\n (sex + lsp(cholesterol,c(196,224,259))),\n data=acath)\nltx(f)\nprint(anova(f), caption='Linear spline surface',\n size='smaller')\nperim <- with(acath,\n perimeter(cholesterol, age, xinc=20, n=5))\nzl <- c(-2, 4) # Figure (*\\ref{fig:lrm-iacholxage-lsp}*)\nbplot(Predict(f, cholesterol, age, np=40), perim=perim,\n lfun=wireframe, zlim=zl, adj.subtitle=FALSE)\n\n\n## @knitr iacholxage-1\nf <- lrm(sigdz ~ rcs(age,4)*(sex + rcs(cholesterol,4)),\n data=acath, tol=1e-11)\nltx(f)\nprint(anova(f), caption='Cubic spline surface',\n size='smaller')\n# Figure (*\\ref{fig:lrm-iacholxage-1}*):\nbplot(Predict(f, cholesterol, age, np=40), perim=perim,\n lfun=wireframe, zlim=zl, adj.subtitle=FALSE)\n\n\n## @knitr iacholxage-2\nf <- lrm(sigdz ~ sex*rcs(age,4) + rcs(cholesterol,4) +\n rcs(age,4) %ia% rcs(cholesterol,4), data=acath)\nprint(anova(f), size='smaller',\n caption='Singly nonlinear cubic spline surface')\n# Figure (*\\ref{fig:lrm-iacholxage-2}*):\nbplot(Predict(f, cholesterol, age, np=40), perim=perim,\n lfun=wireframe, zlim=zl, adj.subtitle=FALSE)\nltx(f)\n\n\n## @knitr iacholxage-3\nf <- lrm(sigdz ~ rcs(age,4)*sex + rcs(cholesterol,4) +\n age %ia% cholesterol, data=acath)\nprint(anova(f), caption='Linear interaction surface',\n size='smaller')\n# Figure (*\\ref{fig:lrm-iacholxage-3}*):\nbplot(Predict(f, cholesterol, age, np=40), perim=perim,\n lfun=wireframe, zlim=zl, adj.subtitle=FALSE)\nf.linia <- f # save linear interaction fit for later\nltx(f)\n\n## @knitr cholxage-model\n# Make estimates of cholesterol effects for mean age in\n# tertiles corresponding to initial analysis\nmean.age <-\n with(acath,\n as.vector(tapply(age, age.tertile, mean, na.rm=TRUE)))\nplot(Predict(f, cholesterol, age=round(mean.age,2),\n sex=\"male\"),\n adj.subtitle=FALSE, ylim=yl) #3 curves, Figure (*\\ref{fig:lrm-cholxage-model}*)\n\n## @knitr dur-partial-resid\nf <- lrm(tvdlm ~ cad.dur, data=dz, x=TRUE, y=TRUE)\nresid(f, \"partial\", pl=\"loess\", xlim=c(0,250), ylim=c(-3,3))\nscat1d(dz$cad.dur)\nlog.cad.dur <- log10(dz$cad.dur + 1)\nf <- lrm(tvdlm ~ log.cad.dur, data=dz, x=TRUE, y=TRUE)\nresid(f, \"partial\", pl=\"loess\", ylim=c(-3,3))\nscat1d(log.cad.dur) # Figure (*\\ref{fig:lrm-dur-partial-resid}*)\n\n\n## @knitr asr-influence\nf <- update(fasr, x=TRUE, y=TRUE, data=sex.age.response)\n## Also try which.influence(f, .4)\nround(resid(f, 'dfbetas'), 1) # Table (*\\ref{table:dfbetas}*)\n\n\n## @knitr sex-age-response-boot\nd <- sex.age.response\ndd <- datadist(d); options(datadist='dd')\nf <- lrm(response ~ sex + age, data=d, x=TRUE, y=TRUE)\nset.seed(3) # for reproducibility\nv1 <- validate(f, B=150)\n\n## @knitr sex-age-response-booth\nap1 <- round(v1[,'index.orig'], 2)\nbc1 <- round(v1[,'index.corrected'], 2)\n\n## @knitr sex-age-response-bootp\nlatex(v1,\n caption='Bootstrap Validation, 2 Predictors Without Stepdown',\n insert.bottom='\\\\label{pg:lrm-sex-age-response-boot}',\n digits=2, size='Ssize', file='')\n\n\n## @knitr sex-age-response-bootsw\nv2 <- validate(f, B=150, bw=TRUE,\n rule='p', sls=.1, type='individual')\n\n## @knitr sex-age-response-bootswh\nap2 <- round(v2[,'index.orig'], 2)\nbc2 <- round(v2[,'index.corrected'], 2)\n\n## @knitr sex-age-response-bootswp\nlatex(v2,\n caption='Bootstrap Validation, 2 Predictors with Stepdown',\n digits=2, B=15, file='', size='Ssize')\n\n\n## @knitr sex-age-response-bootsw5\nset.seed(133)\nn <- nrow(d)\nx1 <- runif(n)\nx2 <- runif(n)\nx3 <- runif(n)\nx4 <- runif(n)\nx5 <- runif(n)\nf <- lrm(response ~ age + sex + x1 + x2 + x3 + x4 + x5,\n data=d, x=TRUE, y=TRUE)\nv3 <- validate(f, B=150, bw=TRUE,\n rule='p', sls=.1, type='individual')\n\n## @knitr sex-age-response-bootsw5v\nk <- attr(v3, 'kept')\n# Compute number of x1-x5 selected\nnx <- apply(k[,3:7], 1, sum)\n# Get selections of age and sex\nv <- colnames(k)\nas <- apply(k[,1:2], 1,\n function(x) paste(v[1:2][x], collapse=', '))\ntable(paste(as, ' ', nx, 'Xs'))\n\n\n## @knitr sex-age-response-bootsw5ph\nap3 <- round(v3[,'index.orig'], 2)\nbc3 <- round(v3[,'index.corrected'], 2)\n\n## @knitr sex-age-response-bootsw5p\nlatex(v3, # (*\\label{pg:lrm-sw5p}*)\n caption='Bootstrap Validation with 5 Noise Variables and Stepdown',\n digits=2, B=15, size='Ssize', file='')\n\n\n## @knitr sex-age-response-bootsw52\nv4 <- validate(f, B=150, bw=TRUE, rule='p', sls=.1,\n type='individual', force=1:2)\nap4 <- round(v4[,'index.orig'], 2)\nbc4 <- round(v4[,'index.corrected'], 2)\n\n## @knitr sex-age-response-bootsw52p\nlatex(v4,\n caption='Bootstrap Validation with 5 Noise Variables and Stepdown, Forced Inclusion of age and sex',\n digits=2, B=15, size='Ssize')\n\n\n## @knitr calibrations\ng <- function(v) v[c('Intercept','Slope'),'index.corrected']\nk <- rbind(g(v1), g(v2), g(v3))\nco <- c(2,5,4,1)\nplot(0, 0, ylim=c(0,1), xlim=c(0,1),\n xlab=\"Predicted Probability\",\n ylab=\"Estimated Actual Probability\", type=\"n\")\nlegend(.45,.35,c(\"age, sex\", \"age, sex stepdown\",\n \"age, sex, x1-x5\", \"ideal\"),\n lty=1, col=co, cex=.8, bty=\"n\")\nprobs <- seq(0, 1, length=200); L <- qlogis(probs)\nfor(i in 1:3) {\n P <- plogis(k[i,'Intercept'] + k[i,'Slope'] * L)\n lines(probs, P, col=co[i], lwd=1)\n}\nabline(a=0, b=1, col=co[4], lwd=1) # Figure (*\\ref{fig:lrm-calibrations}*)\n\n\n## @knitr cholxage-confbar\ns <- summary(f.linia)\nprint(s, size='Ssize')\nplot(s) # Figure (*\\ref{fig:lrm-cholxage-confbar}*)\n\n## @knitr iacholxage-3-nomogram\n# Draw a nomogram that shows examples of confidence intervals\nnom <- nomogram(f.linia, cholesterol=seq(150, 400, by=50),\n interact=list(age=seq(30, 70, by=10)),\n lp.at=seq(-2, 3.5, by=.5),\n conf.int=TRUE, conf.lp=\"all\",\n fun=function(x)1/(1+exp(-x)), # or plogis\n funlabel=\"Probability of CAD\",\n fun.at=c(seq(.1, .9, by=.1), .95, .99)\n ) # Figure (*\\ref{fig:lrm-iacholxage-3-nomogram}*)\nplot(nom, col.grid = gray(c(0.8, 0.95)),\n varname.label=FALSE, ia.space=1, xfrac=.46, lmgp=.2)\n\n\n## @knitr val-prob\nset.seed(13)\nn <- 200\nx1 <- runif(n)\nx2 <- runif(n)\nx3 <- runif(n)\nlogit <- 2*(x1-.5)\nP <- 1/(1+exp(-logit))\ny <- ifelse(runif(n) <= P, 1, 0)\nd <- data.frame(x1, x2, x3, y)\nf <- lrm(y ~ x1 + x2 + x3, subset=1:100)\nphat <- predict(f, d[101:200,], type='fitted')\n# Figure (*\\ref{fig:lrm-val-prob}*)\nv <- val.prob(phat, y[101:200], m=20, cex=.5)\n\n\n## Bayesian analysis\n\n## @knitr bayes-bin_mods\ndd <- datadist(sex.age.response)\noptions(datadist = 'dd')\nrequire(brms)\n\n# Frequentist model\nfit_lrm <- lrm(response ~ sex + age, data=sex.age.response)\n\n# Bayesian model\n# Distribute chains across cpu cores:\noptions(mc.cores=parallel::detectCores())\n\n# Set priors\n# Solve for SD such that sex effect has only a 0.025 chance of\n# being above 5 (or being below -5)\n\ns1 <- 5 / qnorm(0.975)\n\n# Solve for SD such that 10-year age effect has only 0.025 chance\n# of being above 20\n\ns2 <- (20 / qnorm(0.975)) / 10 # divide by 10 since ratio on 10b scale\n\nstanvars <- stanvar(s1, name='s1') + stanvar(s2, name='s2')\n\nprs <- c(prior(student_t(3,0,10), class='Intercept'),\n prior(normal(0, s1), class='b', coef='sexmale'),\n prior(normal(0, s2), class='b', coef='age'))\n\n# Full model\nfit_brms <- brm(response ~ sex + age, data=sex.age.response,\n family=bernoulli(\"logit\"), prior=prs, iter=5000,\n stanvars=stanvars)\n\n\n## @knitr bayes-bin_fits\n# Frequentist model output\nfit_lrm\n\nsummary(fit_lrm, age=20:21)\n\n\n## @knitr bayes-bin_fits2\n# Bayesian model output\npost_samps <- posterior_samples(fit_brms, c(\"age\",\"sex\")) \n\nfit_brms\nposterior_interval(fit_brms, c(\"age\",\"sex\"))\nprior_summary(fit_brms)\n\n\n## @knitr bayes-post_plt\n# display posterior densities for age and sex parameters\nplot(fit_brms, c(\"age\",\"sex\"), combo=c(\"dens\",\"trace\",\"hex\"))\n\n\n## @knitr bayes-margeff\n# Marginal effects plot\nplot(conditional_effects(fit_brms, \"age:sex\"))\n\n\n## @knitr bayes-biv\n# Frequentist\n# variance-covariance for sex and age parameters\nsex_age_vcov <- vcov(fit_lrm)[2:3,2:3]\n\n# Sampling based parameter estimate correlation coefficient\nf_cc <- sex_age_vcov[1,2] / (sqrt(sex_age_vcov[1,1]) * sqrt(sex_age_vcov[2,2]))\n\n# Bayesian\n# Linear correlation between params from posterior \nb_cc <- cor(post_samps)[1,2]\n\n\n## @knitr bayes-postprobs\n# Define P() as mean() just to provide a nice notation for\n# computing posterior probabilities\nP <- function(x) mean(x)\nb1 <- post_samps[, 'b_sexmale']\nb2 <- post_samps[, 'b_age']\n(p1 <- P(b1 > 0)) # post prob(sex has positive association with Y)\n(p2 <- P(b2 > 0))\n(p3 <- P(b1 > 0 & b2 > 0))\n(p4 <- P(b1 > 0 | b2 > 0))\n\n\n## @knitr bayes-bidens\nggplot(post_samps, aes(x=b_sexmale, y = b_age)) + \n geom_hex() + \n theme(legend.position=\"none\")\n\n\n## @knitr bayes-MAP\n# Calculate MAP interval\n# Code from http://www.sumsar.net/blog/2014/11/how-to-summarize-a-2d-posterior-using-a-highest-density-ellipse/\nsamples <- as.matrix(post_samps)\ncoverage = 0.95\nfit <- MASS::cov.mve(samples, quantile.used = round(nrow(samples) * coverage))\npoints_in_ellipse <- samples[fit$best,]\nellipse_boundary <- predict(cluster::ellipsoidhull(points_in_ellipse))\nmap <- data.frame(ellipse_boundary)\nnames(map) <- c(\"y\",\"x\")\n\nggplot(post_samps, aes(x=b_sexmale, y = b_age)) + \n geom_hex() + \n geom_polygon(data = map, aes(x=x,y=y), color = \"grey\", alpha = 0) +\n geom_point(aes(x = fixef(fit_brms)[,1][2], y = fixef(fit_brms)[,1][3]), color = \"grey\") + \n theme(legend.position=\"none\")\n\n\n## @knitr bayes-ellipse\n# Function takes in variance-covariance matrix (D), point estimates (d),\n# and a level of significance (alpha)\nEllipseDF <- function(D, d, alpha = 0.05) {\n delta = sqrt(eigen(D)$values)\n # Root eigenvalues correspond to the half-lengths of the ellipse \n V = eigen(D)$vectors\n # Eigenvectors give the axes of the confidence ellipse\n R = sqrt(qchisq(1-alpha, df = length(delta)))\n # Scaling factor to get to 0.95 confidence\n a = R*delta[1] # scale the ellipse axes\n b = R*delta[2]\n t <- seq(0, 2*pi, length.out=200)\n # Generate radian measures from 0 to 2pi\n points.proj = V %*% t(cbind(a * cos(t), b * sin(t)))\n # Transform circle into ellipse\n return(data.frame(x = (points.proj)[1, ] + d[1],\n y = (points.proj)[2, ] + d[2]))\n}\n\nD <- vcov(fit_lrm)[-1,-1]\nbeta <- coef(fit_lrm)[-1]\nci_ellipse <- EllipseDF(D, beta, alpha = 0.05)\n\nggplot(post_samps, aes(x=b_sexmale, y = b_age)) + \n geom_hex() + \n geom_polygon(data = map, aes(x=x,y=y), color = \"grey\", alpha = 0) +\n geom_polygon(data = ci_ellipse, aes(x = x,y = y), color = \"red\", alpha = 0) +\n geom_point(aes(x = fixef(fit_brms)[,1][2], y = fixef(fit_brms)[,1][3]), color = \"grey\") + \n geom_point(aes(x = coef(fit_lrm)[2], y = coef(fit_lrm)[3]), color = \"red\") + \n theme(legend.position=\"none\")\n", "meta": {"hexsha": "f7c85d7ceebd6e201f5e79f6bb9c2622a9525c2d", "size": 18103, "ext": "r", "lang": "R", "max_stars_repo_path": "RMScode/10_logistic_regression_theory.r", "max_stars_repo_name": "fabarrios/Regression", "max_stars_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-01T18:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T18:27:09.000Z", "max_issues_repo_path": "RMScode/10_logistic_regression_theory.r", "max_issues_repo_name": "fabarrios/Regression", "max_issues_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-23T23:59:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T23:59:10.000Z", "max_forks_repo_path": "RMScode/10_logistic_regression_theory.r", "max_forks_repo_name": "fabarrios/Regression", "max_forks_repo_head_hexsha": "a16af97ccc82d32982b33ab38a2956e64b8b67e7", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-24T03:43:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T03:43:53.000Z", "avg_line_length": 30.425210084, "max_line_length": 111, "alphanum_fraction": 0.6077998122, "num_tokens": 6444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6287903004707038}} {"text": "##### 医学統計勉強会18第6回ロジスティック回帰分析 R code #####\n\n### Low Infant Birth Weightデータの準備 ###\n\nlibrary(MASS)\ndata(birthwt)\nhead(birthwt, n=2)\n\nbirthwt2 <- birthwt[, -10]\t\t# bwt: 出生体重を除く\nbirthwt2$race <- factor(birthwt2$race, label=c(\"white\", \"black\", \"other\"))\t# 因子型に変換し、水準のラベルを1, 2, 3から、white, black, otherに変更する。\nbirthwt2$ptl[birthwt2$ptl >= 1] <- \"1+\"\t\t# ptl: 1以上の値を \"1+\" とする。\nbirthwt2$ftv[birthwt2$ftv >= 1] <- \"1+\"\t\t# ftv: 1以上の値を \"1+\" とする。\nhead(birthwt2, n=2)\n\nattach(birthwt2)\t# birthwt2に含まれる変数を、個別に扱えるようにする。\n\n### 連続説明変数の要約 ###\nsummary(age)\nsummary(lwt)\n\nsd(age); IQR(age)\nsd(lwt); IQR(lwt)\n\n## boxplot ##\nboxplot(age ~ low)\np <- t.test(age ~ low)$p.value\t# Welch's t-test p-value\np <- round(p, 3)\t\t\t\t# 小数点以下第3位まで四捨五入\nboxplot(age ~ low, main=\"age\", sub=paste(\"Welch's t-test p =\", p))\n\nboxplot(lwt ~ low)\np <- t.test(lwt ~ low)$p.value\t# Welch's t-test p-value\np <- round(p, 3)\t\t\t\t# 小数点以下第3位まで四捨五入\nboxplot(lwt ~ low, main=\"lwt\", sub=paste(\"Welch's t-test p =\", p))\n\n## scatter plot ##\nplot(age, lwt)\nx1 <- cov(age, lwt); x1 <- round(x1, 3)\t\t# 共分散\nx2 <- cor(age, lwt); x2 <- round(x2, 3)\t\t# 相関係数\nplot(age, lwt, pch = 16, sub=paste(\"cov =\", x1, \": cor =\", x2))\n\n### 離散説明変数の要約 ###\ntbl <- table(low, race)\nprint(tbl)\nfisher.test(tbl)\n\ntbl <- table(low, smoke)\nprint(tbl)\nfisher.test(tbl)\n\ntbl <- table(low, ptl)\nprint(tbl)\nfisher.test(tbl)\n\ntbl <- table(low, ht)\nprint(tbl)\nfisher.test(tbl)\n\ntbl <- table(low, ui)\nprint(tbl)\nfisher.test(tbl)\n\ntbl <- table(low, ftv)\nprint(tbl)\nfisher.test(tbl)\n\n\n\n### logistic regression ###\n\nfit <- glm(low ~ age + lwt + race + smoke + ptl + ht + ui + ftv, family=binomial, data=birthwt2)\nsummary(fit)\n\n## 係数の信頼区間 ##\nconfint(fit)\n\n## オッズ比の信頼区間 ##\nexp(confint(fit))\n\n## イベントの予測確率 ##\nfit$fitted\n\n\n\n### goodness of fit test for logistic regression ###\n\n## Hosmer-Lemeshow検定 ##\ninstall.packages(\"ResourceSelection\")\t# 初回のみ \nlibrary(ResourceSelection)\nhl <- hoslem.test(low, fit$fitted, g=10)\n\n## ROC曲線とAUC ##\nlibrary(pROC)\ntbl.roc <- roc(low, fit$fitted)\nplot(tbl.roc, print.auc=TRUE, print.thres=TRUE)\t\t\t\t# ROC曲線の描画\nopt.sp <- tbl.roc$sp[which.max(tbl.roc$se+tbl.roc$sp)]\t\t# 最適な特異度\nopt.se <- tbl.roc$se[which.max(tbl.roc$se+tbl.roc$sp)]\t\t# 最適な感度\nabline((opt.sp+opt.se), -1)\t\t# 最適なカットポイントを通る45度線\n\n\n\n## 変数選択 ##\nlibrary(MASS)\nfit.aic1 <- stepAIC(fit, direction=\"backward\")\t\t\t# backward elimination #\nsummary(fit.aic1)\n\nfit0 <- glm(low ~ 1, family=binomial, data=birthwt2)\t# forward selection #\nfit.aic2 <- stepAIC(fit0, direction=\"forward\", scope=list(upper=fit, lower=fit0))\nsummary(fit.aic2)\n\nfit.aic3 <- stepAIC(fit0, direction=\"both\", scope=list(upper=fit, lower=fit0))\t# both #\nsummary(fit.aic3)\n\n\n\n### Generalized Additive Model ###\ninstall.packages(\"mgcv\")\t# 初回のみ \nlibrary(mgcv)\nfit.gam <- gam(low ~ s(age) + s(lwt) + race + smoke + ptl + ht + ui, family=binomial, data=birthwt2)\nsummary(fit.gam)\n\npar(mfrow=c(1,2))\nplot(fit.gam)\n\n\n## additive model ##\nfit.gam2 <- gam(lwt ~ s(age), family=gaussian, data=birthwt2)\n\nsummary(fit.gam2)\n\nplot(age, lwt)\n\nord <- order(age)\n\nlines(age[ord], fit.gam2$fitted[ord], col=\"red\", lwd=2)\n\nfit.lm <- lm(lwt ~ age, data=birthwt2)\n\nsummary(fit.lm)\n\nlines(age[ord], fit.lm$fitted[ord], col=\"green\", lwd=2)", "meta": {"hexsha": "e49ce53fc39b1e9b24bc81b3d80974e2035fbaaa", "size": 3162, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/6/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2019/6/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2019/6/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5857142857, "max_line_length": 127, "alphanum_fraction": 0.6540164453, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924674, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6286773497977551}} {"text": "#\n# # modified to get quantile function\n# # this code is not efficient but should be OK for case of\n# # pair-copulas all permutation symmetric\n#\n# # Different copula family for each edge\n# # nsim = #replications or sample size\n# # parvec = vector of parameters to be optimized in nllk\n# # A = dxd vine array with 1:d on diagonal\n# # ntrunc = truncated level, assume >=1\n# # pcondmat = matrix of names of conditional cdfs for trees 1,...,ntrunc\n# # (assuming only one needed for permutation symmetric pair-copulas)\n# # qcondmat = matrix of names of conditional quantile functions for\n# # trees 1,...,ntrunc\n# # pcondmat and qcondmat are empty for diagonal and lower triangle,\n# # and could have ntrunc rows or be empty for rows ntrunc+1 to d-1\n# # np = dxd where np[ell,j] is #parameters for parameter th[ell,j]\n# # for pair-copula in tree ell, variables j and A[ell,j]\n# # np=0 on and below diagonal\n# # iinv=T to check that this is inverse of rvinepcond()\n# # in this case, columns of pmat come from rvinepcond()\n# # iinv=F, get quantiles C_{d|1:(d-1)}(p|u[1:(d-1)]) based on last column of\n# # pmat[,d] where u[1],..,u[d-1] have been previously converted to\n# # u[1], C_{2|1}(u[2]|u[1]), ... C_{d-1|1:(d-2)}(u[d-1]|u[1:(d-2)])\n# # via rvinepcond()\n# ## Output: nsim x d matrix with values in (0,1) or\n# # quantile C_{d|1...d-1}(p| u1,...,u[d-1])\n# #rvinesimvec2=function(nsim,A,ntrunc,parvec,np,qcondmat,pcondmat,iprint=F)\n# temrvineqcond=function(pmat,A,ntrunc,parvec,np,qcondmat,pcondmat,iinv=F)\n# { d=ncol(A)\n# # get matrix ip1,ip2 of indices\n# ii=0\n# ip1=matrix(0,d,d); ip2=matrix(0,d,d)\n# for(ell in 1:ntrunc)\n# { for(j in (ell+1):d)\n# { ip1[ell,j]=ii+1; ip2[ell,j]=ii+np[ell,j]\n# ii=ii+np[ell,j]\n# }\n# }\n# #if(iprint) { print(ip1); print(ip2) }\n# out=varray2M(A)\n# M=out$mxarray\n# icomp=out$icomp\n# #p=matrix(runif(nsim*d),nsim,d)\n# p=pmat\n# nsim=nrow(p)\n# qq=array(0,c(nsim,d,d)); v=array(0,c(nsim,d,d))\n# u=matrix(0,nsim,d)\n# u[,1]=p[,1]; qq[,1,1]=p[,1]; qq[,2,2]=p[,2];\n# qcond=match.fun(qcondmat[1,2])\n# u[,2]=qcond(p[,2],p[,1],parvec[ip1[1,2]:ip2[1,2]])\n# qq[,1,2]=u[,2]\n# if(icomp[1,2]==1)\n# { #pcond=match.fun(pcondnames[1])\n# pcond=match.fun(pcondmat[1,2])\n# v[,1,2]=pcond(u[,1],u[,2],parvec[ip1[1,2]:ip2[1,2]])\n# }\n# # the main loop\n# for(j in 3:d) # variable\n# { tt=min(ntrunc,j-1)\n# qq[,tt+1,j]=p[,j]\n# if(tt>1)\n# { for(ell in seq(tt,2)) # tree\n# { if(A[ell,j]==M[ell,j]) { s= qq[,ell,A[ell,j]] }\n# else { s=v[,ell-1,M[ell,j]] }\n# #qcond=match.fun(qcondnames[ell])\n# qcond=match.fun(qcondmat[ell,j])\n# qq[,ell,j]=qcond(qq[,ell+1,j], s, parvec[ip1[ell,j]:ip2[ell,j]]);\n# }\n# }\n# #qcond=match.fun(qcondnames[1])\n# qcond=match.fun(qcondmat[1,j])\n# qq[,1,j]=qcond(qq[,2,j],u[,A[1,j]], parvec[ip1[1,j]:ip2[1,j]])\n# u[,j]=qq[,1,j]\n# # set up for next iteration (not needed for last j=d)\n# #pcond=match.fun(pcondnames[1])\n# pcond=match.fun(pcondmat[1,j])\n# v[,1,j]=pcond(u[,A[1,j]],u[,j],parvec[ip1[1,j]:ip2[1,j]])\n# if(tt>1)\n# { for(ell in 2:tt)\n# { if(A[ell,j]==M[ell,j]) { s=qq[,ell,A[ell,j]] }\n# else { s=v[,ell-1,M[ell,j]] }\n# if(icomp[ell,j]==1)\n# { #pcond=match.fun(pcondnames[ell])\n# pcond=match.fun(pcondmat[ell,j])\n# v[,ell,j]=pcond(s, qq[,ell,j], parvec[ip1[ell,j]:ip2[ell,j]]);\n# }\n# }\n# }\n# }\n# if(iinv) u=u[,d]\n# u\n# }\n#\n# #============================================================\n#\n# library(CopulaModel)\n# source(\"hjcondvine.R\")\n# d=5\n# np=matrix(1,d,d)\n# ntrunc=4\n# udat=matrix(c(.1,.2,.3,.4,.5, .6,.7,.8,.9,.5),2,5,byrow=T)\n# parvec=c(2,2,2,2,1.5,1.5,1.5,1.2,1.2,1.1)\n# D5=Dvinearray(d)\n# pcondmat=matrix(\"pcondgum\",d,d)\n# qcondmat=matrix(\"qcondgum\",d,d)\n#\n# pmatd=rvinepcond(parvec,udat,D5,ntrunc,pcondmat,np)\n# print(pmatd)\n#\n# #rvineqcond=function(pmat,A,ntrunc,parvec,np,qcondmat,pcondmat,iprint=F)\n#\n# qmatd=temrvineqcond(pmatd,D5,ntrunc,parvec,np,qcondmat,pcondmat,iinv=F)\n# print(qmatd) # same as udat\n#\n# q5=temrvineqcond(pmatd,D5,ntrunc,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q5)\n# # [1] 0.5 0.5\n# pnewd=pmatd; pnewd[,d]=0.9\n# q5b=temrvineqcond(pnewd,D5,ntrunc,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q5b)\n# # [1] 0.5227173 0.8994989\n#\n# # direct approach\n# ntrunc=4\n# pcond=pcondgum\n# qcond=qcondgum\n# parm=matrix(0,d,d) # format of parameter for vine\n# ii=0;\n# for(ell in 1:ntrunc)\n# { for(j in (ell+1):d)\n# { parm[ell,j]=parvec[ii+1]\n# ii=ii+1\n# }\n# }\n#\n# # compared with specific case for dvine\n# pdchk=udat\n# pdchk[,2]=pcond(udat[,2],udat[,1],parm[1,2])\n# tem12=pcond(udat[,1],udat[,2],parm[1,2])\n# tem32=pcond(udat[,3],udat[,2],parm[1,3])\n# pdchk[,3]=pcond(tem32,tem12,parm[2,3])\n# tem1g23=pcond(tem12,tem32,parm[2,3])\n# tem23=pcond(udat[,2],udat[,3],parm[1,3])\n# tem43=pcond(udat[,4],udat[,3],parm[1,4])\n# tem4g23=pcond(tem43,tem23,parm[2,4])\n# pdchk[,4]=pcond(tem4g23,tem1g23,parm[3,4])\n# tem1g234=pcond(tem1g23,tem4g23,parm[3,4])\n# tem34=pcond(udat[,3],udat[,4],parm[1,4])\n# tem54=pcond(udat[,5],udat[,4],parm[1,5])\n# tem5g34=pcond(tem54,tem34,parm[2,5])\n# tem2g34=pcond(tem23,tem43,parm[2,4])\n# tem5g234=pcond(tem5g34,tem2g34,parm[3,5])\n# pdchk[,5]=pcond(tem5g234,tem1g234,parm[4,5])\n# # quantiles at .9\n# p=rep(.9,2)\n# s2=qcond(p,tem1g234,parm[4,5])\n# s3=qcond(s2,tem2g34,parm[3,5])\n# s4=qcond(s3,tem34,parm[2,5])\n# s5=qcond(s4,udat[,4],parm[1,5])\n# print(s5)\n# # 1] 0.5227173 0.8994989\n#\n# #============================================================\n#\n# # truncated vines\n#\n# # ntrunc=2\n# pmatd2=rvinepcond(parvec,udat,D5,2,pcondmat,np)\n# # [,1] [,2] [,3] [,4] [,5]\n# #[1,] 0.1 0.4938008 0.7385935 0.7430672 0.76377507\n# #[2,] 0.6 0.7328919 0.8830648 0.9508236 0.08757126\n# qmatd2=temrvineqcond(pmatd2,D5,2,parvec,np,qcondmat,pcondmat,iinv=F)\n# print(qmatd2) # same as udat\n# q52=temrvineqcond(pmatd2,D5,2,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q52)\n# # [1] 0.5 0.5\n# pnewd=pmatd2; pnewd[,d]=0.9\n# q52b=temrvineqcond(pnewd,D5,2,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q52b)\n# # [1] 0.6190225 0.9281953\n#\n# # ntrunc=1\n# pmatd1=rvinepcond(parvec,udat,D5,1,pcondmat,np)\n# # [,1] [,2] [,3] [,4] [,5]\n# #[1,] 0.1 0.4938008 0.5364857 0.5842195 0.63198274\n# #[2,] 0.6 0.7328919 0.7951641 0.8831572 0.08282512\n# qmatd1=temrvineqcond(pmatd1,D5,1,parvec,np,qcondmat,pcondmat,iinv=F)\n# print(qmatd1) # same as udat\n# q51=temrvineqcond(pmatd1,D5,1,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q51)\n# # [1] 0.5 0.5\n# pnewd=pmatd1; pnewd[,d]=0.9\n# q51b=temrvineqcond(pnewd,D5,1,parvec,np,qcondmat,pcondmat,iinv=T)\n# print(q51b)\n# # [1] 0.7332716 0.9529803\n#\n", "meta": {"hexsha": "5ba472ad3af4e85eab24507a44b487a5f29b1834", "size": 6773, "ext": "r", "lang": "R", "max_stars_repo_path": "qcond_pcond_vine-original/qcondvine.r", "max_stars_repo_name": "vincenzocoia/copsupp", "max_stars_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-11-29T23:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-29T23:25:20.000Z", "max_issues_repo_path": "qcond_pcond_vine-original/qcondvine.r", "max_issues_repo_name": "vincenzocoia/copsupp", "max_issues_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qcond_pcond_vine-original/qcondvine.r", "max_forks_repo_name": "vincenzocoia/copsupp", "max_forks_repo_head_hexsha": "9b92e11670aff9a7b6ef8365fc2c9b3a8c904923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2070707071, "max_line_length": 77, "alphanum_fraction": 0.597667208, "num_tokens": 2960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6284645748788176}} {"text": "=begin\n[(())] \n\n= AlgebraicExtensionField\n((*(代数拡大体)*))\n\n代数拡大体を表現するクラス\n\n== ファイル名:\n* ((|algebraic-Extension-feild.rb|))\n\n== スーパークラス:\n\n* ((|ResidueClassRing|))\n\n== インクルードしているモジュール:\n\nなし。\n\n== 関連するメソッド:\n\n--- Algebra.AlgebraicExtensionField(field, obj){|x| ... }\n ((<::create>)) と同じ。\n\n== クラスメソッド:\n\n--- ::create(k, obj){|x| p(x) }\n 体 ((|k|)) を、((|obj|)) で表される変数 ((|x|)) の多項式\n ((|p(x)|)) で拡大した環 ((|k[x]/(p(x))|))を返します。\n この環には、クラスメソッド ((<::var>))、((<::def_polys>))、\n ((<::env_ring>)) が定義されます。\n\n \n 例: 有理数を方程式 (({x**2 + x + 1 == 0})) で拡大した体 F を作る。\n require \"rational\"\n require \"algebraic-extension-field\"\n F = Algebra::AlgebraicExtensionField.create(Rational, \"x\") {|x| x**2 + x + 1}\n x = F.var\n p( (x-1)** 3 / (x**2 - 1) ) #=> -3x - 3\n\n--- ::to_ary\n (({[self, var]})) を返します。\n\n 例: 代数拡大体と添加元を同時に定義する\n require \"rational\"\n require \"algebraic-extension-field\"\n F, a = Algebra.AlgebraicExtensionField(Rational, \"a\") {|a| a**2 + a + 1}\n\n--- ::var\n ((<::create>)) の返り値 ((|k[x]/(p(x))|)) に定義され、\n この剰余環における ((|x|)) で\n 代表される剰余類を返します。\n\n--- ::modulus\n ((<::create>)) の返り値 ((|k[x]/(p(x))|)) に定義され、((|k[x]|)) \n の要素 ((|p(x)|)) を返します。\n\n--- ::def_polys\n ((<::create>)) の返り値 ((|k[x]/(p(x))|)) に定義され、\n 長さ ((|n|)) の各 ((<::modulus>)) の配列を返します。\n ここで、自身は、基礎体 ((|k0|)) 上高さ ((|n|)) の\n 再帰的な ((|AlgebraicExtensionField|)) であるとします。\n\n\n 例: 基礎体を有理数とし、2, 3, 5 の立方根による拡大体を作る\n require \"algebra\"\n # K0 == Rational\n K1 = AlgebraicExtensionField(Rational, \"x1\") { |x|\n x ** 3 - 2\n }\n K2 = AlgebraicExtensionField(K1, \"x2\") { |y|\n y ** 3 - 3\n }\n K3 = AlgebraicExtensionField(K2, \"x3\") { |z|\n z ** 3 - 5\n }\n\n p K3.def_polys #=> [x1^3 - 2, x2^3 - 3, x3^3 - 5]\n\n x1, x2, x3 = K1.var, K2.var, K3.var\n f = x1**2 + 2*x2**2 + 3*x3**2\n f0 = f.abs_lift\n\n p f0.type #=> (Polynomial/(Polynomial/(Polynomial/Rational)))\n p f0.type == K3.env_ring #=> true\n\n p f #=> 3x3^2 + 2x2^2 + x1^2\n p f0.evaluate(x3.abs_lift, x2.abs_lift, x1.abs_lift)\n #=> x3^2 + 2x2^2 + 3x3^2\n\n\n--- ::env_ring\n ((<::create>)) の返り値 ((|k[x]/(p(x))|)) に定義され、\n 多変数多項式環 ((|k0[x1, x2,.., xn]|)) を返します。\n ここで、自身は、基礎体 ((|k0|)) 上高さ ((|n|)) の\n 再帰的な ((|AlgebraicExtensionField|)) であるとします。\n\n--- ::ground\n 剰余環のもとになる多項式環 ((|k[x]|)) を返します。\n\n\n== メソッド\n--- abs_lift\n ((<::env_ring>)) すなわち基礎体 ((|k0|)) 上\n の多変数多項式環 ((|k0[x1, x2,.., xn]|))\n へのリフトを返します。\n\n--- [](n)\n (()) 次の係数を返します。(({lift[n]})) と同じです。\n\n 例: Fibonacci 数列\n require \"algebra\"\n t = AlgebraicExtensionField(Integral, \"t\"){|x| x**2-x-1}.var\n (0..10).each do |n|\n p( (t**n)[1] ) #=> 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55\n end\n\n=end\n", "meta": {"hexsha": "308c769c53afabfb481c49e89d4b6415d005f2e7", "size": 2778, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/algebraic-extension-field-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/algebraic-extension-field-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/algebraic-extension-field-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3445378151, "max_line_length": 83, "alphanum_fraction": 0.4989200864, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6280239642938804}} {"text": "\r\n# Pvec if the vector of probabilities predicted by your model\r\n# Cvec is the vector of 0's and 1's indicating the realized\r\n# classifications of each observation.\r\n\r\n\r\nROCPlot <- function(Pvec,Cvec,Plot=T,Add=F) {\r\n NHam <- sum(Cvec==0)\r\n NSpam <- sum(Cvec==1)\r\n PvecS <- unique(sort(Pvec))\r\n x <- rep(NA,length(PvecS))\r\n y <- rep(NA,length(PvecS))\r\n for(i in 1:length(PvecS)) {\r\n x[i] <- sum(Pvec>=PvecS[i]&Cvec==0)/NHam\r\n y[i] <- sum(Pvec>=PvecS[i]&Cvec==1)/NSpam\r\n }\r\n x <- c(0,x,1)\r\n y <- c(0,y,1)\r\n ord <- order(x)\r\n x <- x[ord]\r\n y <- y[ord]\r\n \r\n AUC <- sum((x[2:length(x)]-x[1:(length(x)-1)])*(y[2:length(y)]+y[1:(length(y)-1)])/2)\r\n \r\n if(Add) {\r\n plot(x,y,type=\"l\",xlim=c(0,1),ylim=c(0,1),xlab=\"P( classified + | Is - )\",ylab=\"P( classified + | Is + )\")\r\n title(\"ROC Curve\")\r\n mtext(paste(\"AUC =\",round(AUC,3)),side=3,line=0.5)\r\n abline(0,1)\r\n par(pty=\"m\")\r\n } else {\r\n if(Plot) {\r\n par(pty=\"s\")\r\n plot(x,y,type=\"l\",xlim=c(0,1),ylim=c(0,1),xlab=\"P( classified + | Is - )\",ylab=\"P( classified + | Is + )\")\r\n title(\"ROC Curve\")\r\n mtext(paste(\"AUC =\",round(AUC,3)),side=3,line=0.5)\r\n abline(0,1)\r\n par(pty=\"m\")\r\n }\r\n }\r\n \r\n \r\n invisible(list(x=c(0,x,1),y=c(0,y,1),AUC=AUC))\r\n}\r\n", "meta": {"hexsha": "56eb02b851206c823124450cc76c6262cd2b9ccb", "size": 1264, "ext": "r", "lang": "R", "max_stars_repo_path": "ROCPlot.r", "max_stars_repo_name": "ZiHG/Spam-prediction", "max_stars_repo_head_hexsha": "d2597dd1dff1cf678ba0612af5e4df5f8645b3ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ROCPlot.r", "max_issues_repo_name": "ZiHG/Spam-prediction", "max_issues_repo_head_hexsha": "d2597dd1dff1cf678ba0612af5e4df5f8645b3ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ROCPlot.r", "max_forks_repo_name": "ZiHG/Spam-prediction", "max_forks_repo_head_hexsha": "d2597dd1dff1cf678ba0612af5e4df5f8645b3ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0888888889, "max_line_length": 113, "alphanum_fraction": 0.5292721519, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6280239510615733}} {"text": "john_z <- function(x, parms) {\r\n ## transform x values to z which is normally distributed if Johnson distribution\r\n ## x can be one value or a set of values\r\n ## parms is the set of parameters from SuppDists::JohnsonFit on the entire dataset\r\n u <- (x - parms$xi) / parms$lambda\r\n type <- parms$type\r\n if (type == 'SU') {\r\n ## unbounded distribution\r\n fu <- u + (1 + u^2)^0.5\r\n } else if (type == 'SL') {\r\n ## log normal\r\n fu <- u\r\n } else if (type == 'SB') {\r\n ## bounded distribution\r\n fu <- u / (1-u)\r\n } else if (type == 'SN') {\r\n ## normal distribution\r\n fu <- exp(u)\r\n } else {\r\n cat('\\n')\r\n cat('#####################################\\n')\r\n cat(' ERROR IN JOHNSON_TOL \\n')\r\n cat(' no type returned from fit attempt \\n')\r\n cat('#####################################\\n')\r\n print(jparms)\r\n ## stop()\r\n }\r\n ## z is normally distributed\r\n z <- parms$gamma + parms$delta * log(fu)\r\n return(z)\r\n}\r\n", "meta": {"hexsha": "f1de8fe24f5bdb70d2122eccbbfeb3ba8bf1fb8e", "size": 1058, "ext": "r", "lang": "R", "max_stars_repo_path": "modules/john_z.r", "max_stars_repo_name": "TECComputing/R-setup", "max_stars_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/john_z.r", "max_issues_repo_name": "TECComputing/R-setup", "max_issues_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/john_z.r", "max_forks_repo_name": "TECComputing/R-setup", "max_forks_repo_head_hexsha": "f4b5e45c6e2e55fcc6f58f804bb50cea3a697fe0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0625, "max_line_length": 87, "alphanum_fraction": 0.4593572779, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6279296658647335}} {"text": "### Illustrates the piece-wise linear approximation of the cumulative distribution using constant size bins\nfade = rgb(0,0,0,alpha=0.5)\ndot.size = 0.7\nn = 10000\nset.seed(5)\n\npdf(\"linear-interpolation.pdf\", width=6, height=2.7, pointsize=10)\nlayout(matrix(c(1,2),byrow=T, ncol=2), widths=c(1.1,1))\nu = sort(runif(n))\nx = log(1-u)\nx = sort(x)\nF = ((0:(n-1))+0.5)/n\npar(mar=c(2.5,3,0.5,1))\nplot(x, F, cex=dot.size, pch=21, bg=fade, col=NA, type='b', xlim=c(-9,-4.5), ylim=c(0,0.01), xaxt='n', ylab=NA, mgp=c(1,0.5,0), xlab=NA)\n\naxis(side=1, at=-10:-1, labels=NA)\ntitle(xlab='x', line=0.8, cex.lab=1.5)\ntitle(ylab='q', line=1.5, cex.lab=1.5)\n\nleft.end = x[1] - (x[2]-x[1])\n\nlines(c(left.end, x[100]), c(0, 0.01), lwd=2)\nlines(c(left.end, left.end), c(-0.0005, 0.0005), lt=1, col='black', lwd=0.5)\nlines(c(x[100], x[100]), c(0.0085, 0.015), lt=1, col='black', lwd=0.5)\ntext(-7, 0.006, \"100\")\n\n###text(-5, 0.4, adj=0, \"Constant size bins result in large\")\n###text(-5, 0.35, adj=0, \"errors at extreme quantiles\")\n\npar(mar=c(2.5,1.5,0.5,1))\n\nplot(x, F, cex=dot.size, pch=21, bg=fade, col=NA, type='b', xlim=c(-9,-4.5), ylim=c(0,0.01), yaxt='n', xaxt='n')\naxis(side=1, at=-10:-1, labels=NA)\naxis(side=2, at=(0:6)/10, labels=NA)\ntitle(xlab='x', line=0.8, cex.lab=1.5)\ntitle(ylab='q', line=2, cex.lab=1.5)\n\nq.to.k = function(q) {\n (asin(2*q-1)/pi + 1/2)\n}\n\nk.to.q = function(k,compression) {\n sin(k/compression*pi - pi/2)/2 + 0.5\n}\n\nweights = c(2, 8, 19, 35, 56, 81, 111)\nq.bin = cumsum(c(0, weights)/n)\n\ni.bin = c(1, cumsum(weights)+1)\ni.right = i.bin-1\ni.right = i.right[i.right > 0]\nm = length(i.right)\ni.bin = i.bin[1:m]\n\nx.bin = c(left.end, (x[i.right[1:(m-1)]] + x[i.bin[2:m]])/2)\nF.bin = (i.bin-1) / n\nlines(x.bin, F.bin, lwd=2)\ndy = 0.0005\nfor (i in 1:m) {\n x.text = (x[i.bin[i]] + x[i.right[i]])/2\n y.text = (F.bin[i] + F.bin[i+1])/2\n x.offset = 0.3 * y.text\n y.offset = dy * (1 + 500*y.text)\n x.pos = x.text - x.offset\n y.pos = y.text + y.offset\n lines(c(x.bin[i],x.bin[i]), c(F.bin[i]-dy+0.000, F.bin[i]+dy+y.offset*0.6-0.0005), lt=1, lwd=0.5, col='black')\n text(x.text - x.offset, y.text + y.offset, i.right[i]-i.bin[i]+1)\n}\n###text(-5, 0.35, adj=0, \"Variable size bins keep errors\")\n###text(-5, 0.3, adj=0, \"small at extreme quantiles\")\n\ndev.off()\n", "meta": {"hexsha": "75153944fa59eae91a0e996dee12e356e532d0ef", "size": 2280, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/t-digest-paper/linear-interpolation.r", "max_stars_repo_name": "ajwerner/t-digest", "max_stars_repo_head_hexsha": "fce13b0cee5daa1a98b84e8ca49cdf8f7ccff6b7", "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": "docs/t-digest-paper/linear-interpolation.r", "max_issues_repo_name": "ajwerner/t-digest", "max_issues_repo_head_hexsha": "fce13b0cee5daa1a98b84e8ca49cdf8f7ccff6b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/t-digest-paper/linear-interpolation.r", "max_forks_repo_name": "ajwerner/t-digest", "max_forks_repo_head_hexsha": "fce13b0cee5daa1a98b84e8ca49cdf8f7ccff6b7", "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": 31.2328767123, "max_line_length": 136, "alphanum_fraction": 0.5850877193, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6277834987463949}} {"text": "\n#' Simulate variable based on the influences of other variables\n#'\n#' I need a function that takes some variables, and an effect size for each of them, and this creates a new variable where y = Xb + e, where X is the matrix of independent variables, b is their effect sizes, and e is a noise term. By default it's easier if b relates to the variance explained by each vector in X, and e has variance of 1 - sum(b).\n#'\n#' @param effs An array of effect sizes that the variables in indep have on the variable that you are simulating\n#' @param indep A matrix of variables, rows = Samples and columns = variables that have an influence on the variable that you are simulating\n#' @param vy What variance the output should have. Default = 1, meaning effs relate to the signed rsq of the influence of the indep variables on the outcome\n#' @param vx What variance the indep variables should have. Default is to set to 1, meaning that the effects are the signed variance explained\n#' @param my mean value of y to be output\n#'\n#' @export\n#' @return Vector of y values\nmake_phen <- function(effs, indep, vy=1, vx=rep(1, length(effs)), my=0)\n{\n\tif(is.null(dim(indep))) indep <- cbind(indep)\n\tstopifnot(ncol(indep) == length(effs))\n\tstopifnot(length(vx) == length(effs))\n\tcors <- effs * vx / sqrt(vx) / sqrt(vy)\n\tsc <- sum(cors^2)\n\tif(sc >= 1)\n\t{\n\t\tprint(sc)\n\t\tstop(\"effects explain more than 100% of variance\")\n\t}\n\tcors <- c(cors, sqrt(1-sum(cors^2)))\n\tindep <- t(t(scale(cbind(indep, stats::rnorm(nrow(indep))))) * cors * c(vx, 1))\n\ty <- drop(scale(rowSums(indep)) * sqrt(vy)) + my\n\treturn(y)\n}\n\n#' Create genotype matrix\n#'\n#' @param nid Number of samples\n#' @param nsnp Number of SNPs\n#' @param af Allele frequency of all SNPs (all SNPs have the same allele frequency) \n#'\n#' @export\n#' @return Matrix of genotypes, rows = individuals, columns = snps\nmake_geno <- function(nid, nsnp, af)\n{\n\treturn(matrix(rbinom(nid * nsnp, 2, af), nid, nsnp))\n}\n\n#' Get vector of effects that explain some amount of variance\n#'\n#' @param nsnp Number of SNPs\n#' @param totvar Total variance explained by all SNPs\n#' @param sqrt Output effect sizes in terms of standard deviations. Default=TRUE\n#' @param mua Constant term to be added to effects. Default = 0\n#'\n#' @export\n#' @return Vector of effects\nchoose_effects <- function(nsnp, totvar, sqrt=TRUE, mua=0)\n{\n\teff <- stats::rnorm(nsnp)\n\teff <- sign(eff) * eff^2\n\taeff <- abs(eff)\n\tsc <- sum(aeff) / totvar\n\tout <- eff / sc\n\tif(sqrt)\n\t{\n\t\tout <- sqrt(abs(out)) * sign(out)\n\t}\n\treturn(out + mua)\n}\n\n#' Convert continuous trait to binary \n#'\n#' @param y Phenotype vector\n#' @param prevalence Disease prevalence. Default = NULL\n#' @param threshold Disease threshold Default = NULL\n#'\n#' @export\n#' @return Vector of binary trait\ny_to_binary <- function(y, prevalence=NULL, threshold=NULL)\n{\n\tif(is.null(prevalence) & is.null(threshold)) stop(\"Prevalence or threshold needs to be non-null\")\n\tif(!is.null(prevalence))\n\t{\n\t\td <- y\n\t\tt <- quantile(d, 1-prevalence)\n\t\td[y >= t] <- 1\n\t\td[y < t] <- 0\n\t\treturn(d)\n\t}\n\tif(!is.null(threshold))\n\t{\n\t\td <- y\n\t\td[y >= threshold] <- 1\n\t\td[y < threshold] <- 0\n\t\treturn(d)\n\t}\n}\n\n\n#' Ascertain some proportion of cases and controls from binary phenotype\n#'\n#' @param d Vector of 1/0\n#' @param prop_cases Proportion of 1s to retain\n#'\n#' @export\n#' @return Array of IDs\nascertain_samples <- function(d, prop_cases)\n{\n\td <- d[!is.na(d)]\n\td <- d[d %in% c(0,1)]\n\tx1 <- sum(d==1)\n\tx0 <- sum(d==0)\n\texp_cases <- x1\n\texp_controls <- (x1 - prop_cases * x1) / prop_cases\n\tif(round(exp_controls) > x0)\n\t{\n\t\texp_controls <- x0\n\t\texp_cases <- (x0 - (1 - prop_cases) * x0) / (1 - prop_cases)\n\t}\n\ti0 <- which(d == 0)\n\ti0 <- sample(i0, exp_controls, replace=FALSE)\n\ti1 <- which(d == 1)\n\ti1 <- sample(i1, exp_cases, replace=FALSE)\n\n\treturn(sort(c(i0, i1)))\n}\n\n", "meta": {"hexsha": "439d6bd536f398477dce6c825ed37b40bc10f0b5", "size": 3801, "ext": "r", "lang": "R", "max_stars_repo_path": "R/generate_individuals.r", "max_stars_repo_name": "explodecomputer/simulateGP", "max_stars_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T16:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T16:58:46.000Z", "max_issues_repo_path": "R/generate_individuals.r", "max_issues_repo_name": "aeaswar81/simulateGP", "max_issues_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T16:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:14:15.000Z", "max_forks_repo_path": "R/generate_individuals.r", "max_forks_repo_name": "aeaswar81/simulateGP", "max_forks_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T19:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T16:59:02.000Z", "avg_line_length": 30.408, "max_line_length": 347, "alphanum_fraction": 0.6771902131, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6276440099947699}} {"text": "LISP Interpreter Run\n\n[[[[ Omega in the limit from below! ]]]]\n \ndefine (all-bit-strings-of-size k)\n if = 0 k '(())\n (extend-by-one-bit (all-bit-strings-of-size - k 1))\n\ndefine all-bit-strings-of-size\nvalue (lambda (k) (if (= 0 k) (' (())) (extend-by-one-bi\n t (all-bit-strings-of-size (- k 1)))))\n\ndefine (extend-by-one-bit x)\n if atom x nil\n cons append car x '(0)\n cons append car x '(1)\n (extend-by-one-bit cdr x)\n\ndefine extend-by-one-bit\nvalue (lambda (x) (if (atom x) nil (cons (append (car x)\n (' (0))) (cons (append (car x) (' (1))) (extend-b\n y-one-bit (cdr x))))))\n\ndefine (count-halt p)\n if atom p 0\n +\n if = success car try t 'eval read-exp car p\n 1 0\n (count-halt cdr p)\n\ndefine count-halt\nvalue (lambda (p) (if (atom p) 0 (+ (if (= success (car \n (try t (' (eval (read-exp))) (car p)))) 1 0) (coun\n t-halt (cdr p)))))\n\ndefine (omega t) cons (count-halt (all-bit-strings-of-size t))\n cons /\n cons ^ 2 t\n nil\n\ndefine omega\nvalue (lambda (t) (cons (count-halt (all-bit-strings-of-\n size t)) (cons / (cons (^ 2 t) nil))))\n\n(omega 0)\n\nexpression (omega 0)\nvalue (0 / 1)\n\n(omega 1)\n\nexpression (omega 1)\nvalue (0 / 2)\n\n(omega 2)\n\nexpression (omega 2)\nvalue (0 / 4)\n\n(omega 3)\n\nexpression (omega 3)\nvalue (0 / 8)\n\n(omega 8)\n\nexpression (omega 8)\nvalue (1 / 256)\n\nEnd of LISP Run\n\nElapsed time is 0 seconds.\n", "meta": {"hexsha": "7773c1a5b710ea9cfb2d6f5d93613c388a3e4433", "size": 1550, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/omega.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/omega.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/omega.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 21.2328767123, "max_line_length": 62, "alphanum_fraction": 0.5225806452, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6275767162888787}} {"text": "#--------Reference Point helper functions-------\r\n\r\n#-------Spawners per recruit -----------------------------\r\ns.per.recr<-function(nages,fec.age,mat.age,M.age, F.mult, sel.age, spawn.time ) {\r\n \r\n spr=0.0\r\n cum.survive=1.0\r\n z=0.0\r\n for (i in 1:(nages-1) ) {\r\n z=M.age[i] + F.mult*sel.age[i]\r\n z.ts=(M.age[i]+F.mult*sel.age[i])*spawn.time\r\n spr=spr+cum.survive*fec.age[i]*mat.age[i]*exp(-z.ts)\r\n cum.survive=cum.survive*exp(-z )\r\n \r\n }\r\n \r\n z= M.age[nages] + F.mult*sel.age[nages]\r\n z.ts=(M.age[nages]+F.mult*sel.age[nages])*spawn.time\r\n spr=spr + fec.age[nages]*mat.age[nages]*cum.survive*exp(-z.ts)/( 1- exp(-z ) )\r\n \r\n return(spr)\r\n \r\n}\r\n\r\n#-------Yield per recruit -----------------------------\r\nypr<-function(nages, wgt.age, M.age, F.mult, sel.age ) {\r\n \r\n yield=0.0\r\n cum.survive=1.0\r\n z=0.0\r\n \r\n for (i in 1:(nages-1) ) {\r\n z=M.age[i] + F.mult*sel.age[i]\r\n yield=yield + wgt.age[i]*F.mult*sel.age[i]*(1-exp(-z) )*cum.survive/z\r\n cum.survive=cum.survive*exp(-z)\r\n }\r\n \r\n z= M.age[nages] + F.mult*sel.age[nages]\r\n yield=yield + wgt.age[nages]*F.mult*sel.age[nages]*cum.survive/z\r\n \r\n return(yield)\r\n \r\n}\r\n\r\n#-------Equilibrium SSB ------------------------\r\nssb.eq<-function(recr.par, R0.BH, spr, spr0, is.steepness=T ) {\r\n \r\n if (is.steepness==T) alpha.BH <- 4*recr.par/(1-recr.par)\r\n if (is.steepness==F) alpha.BH <- recr.par\r\n sprF=spr/spr0\r\n \r\n ssb=spr0*R0.BH*(sprF*alpha.BH - 1.0)/(alpha.BH-1.0)\r\n \r\n \r\n return(ssb)\r\n \r\n}\r\n#------Beverton-Holt alpha----------------------- \r\nbev.holt.alpha<-function(S,R0,recr.par,spr0, is.steepness=T){\r\n \r\n if (is.steepness==T) alpha.BH <- 4*recr.par/(1-recr.par)\r\n if (is.steepness==F) alpha.BH <- recr.par\r\n \r\n \r\n y=rep(0,length(S))\r\n y=R0*S*alpha.BH/(R0*spr0 +(alpha.BH-1.0)*S)\r\n return(y)\r\n \r\n} \r\n", "meta": {"hexsha": "bcfa20f4fa2c5d7acf1b34cdbe2649fea46792f7", "size": 1824, "ext": "r", "lang": "R", "max_stars_repo_path": "R/helper_functions_for_reference_points.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/helper_functions_for_reference_points.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/helper_functions_for_reference_points.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": 26.0571428571, "max_line_length": 82, "alphanum_fraction": 0.5334429825, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6275265898802385}} {"text": "###############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n###############################################################################\n# Black-Litterman model Functions\n# Copyright (C) 2011 Michael Kapler\n#\n# For more information please visit my blog at www.SystematicInvestor.wordpress.com\n# or drop me a line at TheSystematicInvestor at gmail\n###############################################################################\n\n\n###############################################################################\n# Black-Litterman model Functions\n###############################################################################\n# He & Litterman: The intuition Behind Black- Litterman Model Portfolios\n# T. Idzorek: A STEP-BY-STEP GUIDE TO THE BLACK-LITTERMAN MODEL\n# note (5)\n#\n#' @export \nbl.compute.risk.aversion <- function(bench, risk.free = 0)\n{\n\t# The implied risk aversion coefficient can be estimated by dividing\n\t# the expected excess return by the variance of the portfolio\n\tlambda = mean(coredata(bench) - coredata(risk.free)) / var(coredata(bench))\n\treturn( as.double(lambda) )\n}\n\n# He & Litterman: The intuition Behind Black- Litterman Model Portfolios\n# formulas (2)\n#\n# T. Idzorek: A STEP-BY-STEP GUIDE TO THE BLACK-LITTERMAN MODEL\n# formulas (1)\n#\n# use reverse optimization to compute the vector of equilibrium returns\n#' @export \nbl.compute.eqret <- function\n(\n\trisk.aversion, \t# Risk Aversion\n\tcov, \t\t\t# Covariance matrix\n\tcap.weight, \t# Market Capitalization Weights\n\trisk.free = 0\t# Rsik Free Interest Rate\n)\n{\n\treturn( risk.aversion * cov %*% as.vector(cap.weight) + as.double(risk.free))\t\n}\n\n# He & Litterman: The intuition Behind Black- Litterman Model Portfolios\n# formulas (8), (9), (10)\n# compute the posterior estimate of the returns and covariance\n#' @export \nbl.compute.posterior <- function\n(\n\tmu, \t\t# Equilibrium returns\n\tcov, \t\t# Covariance matrix\n\tpmat=NULL, \t# Views pick matrix\n\tqmat=NULL, \t# View mean vector\n\ttau=0.025, \t# Measure of uncertainty of the prior estimate of the mean returns\n\tconfidences=NULL # Confidence of each view\n)\n{\n\tout = list()\t\n\n\tif( !is.null(pmat) ) {\n\t\tif( is.null(confidences) ) {\n\t\t# The Black-Litterman Model In Detail by Jay Walters\n\t\t# Assume that the variance of the views will be proportional to the variance of the asset\n\t\t# returns, just as the variance of the prior distribution is. He and Litterman (1999)\n\t\t# This specification of the variance, or uncertainty, of the views essentially equally weights the investor's\n\t\t# views and the market equilibrium weights. By including tau in the expression, the final solution becomes\n\t\t# independent of tau as well.\n\t\t\t\t\n\t\t# contactenate 1 and remove first row, col ([-1,-1]) to work properly with single view\n\t\tomega = diag(c(1,diag(tau * pmat %*% cov %*% t(pmat))))[-1,-1]\n\t\t} else {\n\t\tomega = diag(c(1,confidences))[-1,-1]\n\t\t}\n\t\t\n\t\ttemp = solve(solve(tau * cov) + t(pmat) %*% solve(omega) %*% pmat)\n\t\n\t\tout$cov = cov + temp\n\t\n\t\tout$expected.return = temp %*% (solve(tau * cov) %*% mu + t(pmat) %*% solve(omega) %*% qmat)\n\t} else {\t# no views\t\n\t\ttemp = tau * cov\n\t\n\t\tout$cov = cov + temp\n\t\n\t\tout$expected.return = temp %*% (solve(tau * cov) %*% mu )\n\t\n\t}\n\treturn(out)\n}\n\n\n# He & Litterman: The intuition Behind Black- Litterman Model Portfolios\n# formulas (13)\n#\n# T. Idzorek: A STEP-BY-STEP GUIDE TO THE BLACK-LITTERMAN MODEL\n# formulas (2)\n#\n# compute the portfolio weights for the optimal portfolio on the unconstrained efficient frontier\n#' @export \nbl.compute.optimal <- function(risk.aversion, mu, cov)\n{\n\treturn( (1/risk.aversion) * solve(cov) %*% mu )\n}\n\n\t\n\naa.black.litterman.examples <- function()\n{\n\t# He & Litterman: The intuition Behind Black- Litterman Model Portfolios. \n\n\tdata =\n '1,0.4880,0.4780,0.5150,0.4390,0.5120,0.4910\n 0.4880,1,0.6640,0.6550,0.3100,0.6080,0.7790\n 0.4780,0.6640,1,0.8610,0.3550,0.7830,0.6680\n 0.5150,0.6550,0.8610,1,0.3540,0.7770,0.6530\n 0.4390,0.3100,0.3550,0.3540,1,0.4050,0.3060\n 0.5120,0.6080,0.7830,0.7770,0.4050,1,0.6520\n 0.4910,0.7790,0.6680,0.6530,0.3060,0.6520,1'\n\t\n\tCorrmat = matrix( as.double(spl( gsub('\\n', ',', data), ',')), \n\t\t\t\tnrow = len(spl(data, '\\n')), byrow=TRUE)\n\t\n\tRiskAversion = 2.5\n\n\tstdevs = c(16.0, 20.3, 24.8, 27.1, 21.0, 20.0, 18.7)/100\n\n\tMktWeight = c(1.6, 2.2, 5.2, 5.5, 11.6, 12.4, 61.5)/100\n\n\ttau = 0.05\n\n\tCovmat = Corrmat * (stdevs %*% t(stdevs))\n\t\n\tEqRiskPrem = RiskAversion * Covmat %*% MktWeight\nEqRiskPrem = bl.compute.eqret(RiskAversion, Covmat, MktWeight)\n\n\tAssetNames = c('Australia','Canada','France','Germany','Japan','UK','USA')\n\n\tTable2 = cbind(AssetNames, round(cbind(stdevs, MktWeight, EqRiskPrem) * 100,1))\n\t\tcolnames(Table2) = c('Assets','Std Dev','Weq','PI')\n\t\tTable2\n\t\t\n\t#View1 is The German Equity Market Will Outperform the rest of European Markets by 5% a year.\n\tP = matrix(c(0, 0, -29.5, 100, 0, -70.5, 0)/100, nrow=1)\n\tQ = 5/100\n\t\t\n\tOmega = diag(c(1,diag(tau * P %*% Covmat %*% t(P))))[-1,-1]\n\n\tPostCov = solve(solve(tau*Covmat) + (t(P) %*% solve(Omega) %*% P))\n\n\tSigmaP = Covmat + PostCov\n\n\tExpRet = PostCov %*% (solve(tau * Covmat) %*% EqRiskPrem + t(P) %*% solve(Omega) %*% Q)\n\t\npost = bl.compute.posterior(EqRiskPrem, Covmat, P, Q, tau)\t\t\n\tExpRet = post$expected.return\n\tSigmaP = post$cov\n\t\n\tOptimalWeights = (1/RiskAversion) * solve(SigmaP) %*% ExpRet\nOptimalWeights = bl.compute.optimal(RiskAversion, ExpRet, SigmaP)\t\n\t\n\tTab4Col4 = OptimalWeights - (MktWeight)/(1+tau)\n\t\t\n\tTable4 = cbind(AssetNames, round(cbind(t(P), ExpRet, OptimalWeights, round(Tab4Col4 * 1000)/1000)*100,1))\n\t\tcolnames(Table4) = c('Assets', 'P', 'MU', 'W','W - Weq/1+tau')\n\t\tTable4 \n\n\n\t# example from Thomas M. Idzorek's paper \"A STEP-BY-STEP GUIDE TO THE BLACK-LITTERMAN MODEL\"\n\tx = \n\tc(0.001005,0.001328,-0.000579,-0.000675,0.000121,0.000128,-0.000445,-0.000437 ,\n 0.001328,0.007277,-0.001307,-0.000610,-0.002237,-0.000989,0.001442,-0.001535 ,\n -0.000579,-0.001307,0.059852,0.027588,0.063497,0.023036,0.032967,0.048039 ,\n -0.000675,-0.000610,0.027588,0.029609,0.026572,0.021465,0.020697,0.029854 ,\n 0.000121,-0.002237,0.063497,0.026572,0.102488,0.042744,0.039943,0.065994 ,\n 0.000128,-0.000989,0.023036,0.021465,0.042744,0.032056,0.019881,0.032235 ,\n -0.000445,0.001442,0.032967,0.020697,0.039943,0.019881,0.028355,0.035064 ,\n -0.000437,-0.001535,0.048039,0.029854,0.065994,0.032235,0.035064,0.079958 )\n\n varCov <- matrix(x, ncol = 8, nrow = 8)\n mu <- c(0.08, 0.67,6.41, 4.08, 7.43, 3.70, 4.80, 6.60) / 100\n pick <- matrix(0, ncol = 8, nrow = 3, dimnames = list(NULL, letters[1:8]))\n pick[1,7] <- 1\n pick[2,1] <- -1; pick[2,2] <- 1\n pick[3, 3:6] <- c(0.9, -0.9, .1, -.1)\n \npost = bl.compute.posterior(mu, varCov, pick, c(0.0525, 0.0025, 0.02), tau = 0.025)\t\t \n \n\tlibrary(BLCOP)\n confidences <- 1 / c(0.000709, 0.000141, 0.000866)\n myViews <- BLViews(pick, c(0.0525, 0.0025, 0.02), confidences, letters[1:8])\n myPosterior <- posteriorEst(myViews, tau = 0.025, mu, varCov )\n myPosterior\n\n \n myPosterior@posteriorMean - post$expected.return\n myPosterior@posteriorCovar - post$cov\n \n \n\t\t\t\n}\n", "meta": {"hexsha": "e39e8da08874094fd953b2ad8c9e8e87acc700b5", "size": 7700, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/aa.bl.r", "max_stars_repo_name": "wisonhang/Shiny_report", "max_stars_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patterns.matching/SIT/aa.bl.r", "max_issues_repo_name": "wisonhang/Shiny_report", "max_issues_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patterns.matching/SIT/aa.bl.r", "max_forks_repo_name": "wisonhang/Shiny_report", "max_forks_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_forks_repo_licenses": ["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.8139534884, "max_line_length": 111, "alphanum_fraction": 0.6442857143, "num_tokens": 2677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6274423321611855}} {"text": "# A simple 2-layer neural network uses Perceptron as the activation function.\n#\n# x - Descriptive features, multi-column table later converted to mxn matrix\n# y - Target feature, single column table later converted to 1D matrix\n# yhat_train - zero matrix of same dimensions as y\n# w1 - first weight matrix with number of rows matching column \n# number of x and w1 column number equal to the number of nodes.\n# Initialized with unseeded random variable between 0 and 1\n# w2 - second weight matrix, 1D array with number of rows matching\n# node number\n# Initialized with unseeded random variable between 0 and 1\n# h1 - layer 1 of the heural network. Same number of rows as input \n# and column number equal to the number of nodes. Initialized with\n# zeros for all elements\n# dw1 - first weight gradient, dimensions match w1. Initialized with\n# zeros for all elements\n# dw2 - first weight gradient, dimensions match w2. Initialized with\n# zeros for all elements\n\nperceptron <- function(input, output, n){\n nnclass <- setClass(\n \"neural_net\", \n slots = c(\n x = \"matrix\",\n y = \"matrix\",\n yhat_train = \"matrix\",\n w1 =\"matrix\", \n w2 =\"matrix\",\n h1 =\"matrix\",\n dw1 =\"matrix\", \n dw2 =\"matrix\"\n )\n )\n \n neural_net <- nnclass(\n x = as.matrix(input),\n y = as.matrix(output),\n yhat_train = matrix(0L, \n nrow = dim(as.matrix(output))[1], \n ncol = dim(as.matrix(output))[2]),\n w1 = matrix(runif(ncol(input)*n, 0, 1), nrow = ncol(input), ncol = n),\n w2 = matrix(runif(n, 0, 1), nrow = n, ncol=1),\n h1 = matrix(0L, nrow = nrow(input), ncol = n),\n dw1 = matrix(0L, nrow = ncol(input), ncol = n),\n dw2 = matrix(0L, nrow = n, ncol = 1)\n )\n \n setGeneric(\"feedforward\", function(neural_net) \n standardGeneric(\"feedforward\"))\n \n setGeneric(\"backprop\", function(neural_net) \n standardGeneric(\"backprop\"))\n \n # Feedfoward method updates h1 and yhat_train matrices \n setMethod(f = \"feedforward\", signature = \"neural_net\",\n function(neural_net){\n neural_net@h1 <- activation(dot(neural_net@x, neural_net@w1))\n neural_net@yhat_train <- activation(dot(neural_net@h1, neural_net@w2))\n return(neural_net)\n })\n \n # Backprop method updates weights and weight gradient matrices\n setMethod(f = \"backprop\", signature = \"neural_net\",\n function(neural_net){\n neural_net@dw1 <- dot(t(neural_net@x), \n dot(2*(neural_net@y - neural_net@yhat_train) * \n activation_der(neural_net@yhat_train), t(neural_net@w2)) * \n activation_der(neural_net@h1))\n neural_net@dw2 <- dot(t(neural_net@h1), \n 2*(neural_net@y-neural_net@yhat_train) *\n activation_der(neural_net@yhat_train))\n neural_net@w1 = neural_net@w1 + neural_net@dw1\n neural_net@w2 = neural_net@w2 + neural_net@dw2\n return(neural_net)\n })\n\n return(neural_net)\n}\n\n# functions\n\ndot <- function(a, b){\n c <- a %*% b\n return(c)\n}\n\n# sigmoid function\nactivation <- function(z){\n sigmoid <- 1/ (1 + exp(-z))\n return(sigmoid)\n}\n\n# Derivative of sigmoid function\nactivation_der <- function(z){\n sigmoid_der <- (activation(z)) * (1 - activation(z))\n return(sigmoid_der)\n}\n\n# Threshold function with binay output of 0 or 1 based on a threshold value f\n# Kept separate from neural network classes as this can be used on test and train data\nthreshold <- function(yhat_thresh, f){\n yhat_thresh <- as.matrix(yhat_thresh)\n for(i in 1:nrow(yhat_thresh)){\n if (yhat_thresh[i,] < f){\n yhat_thresh[i,] <- 0L\n } else {\n yhat_thresh[i,] <- 1L\n }\n }\n return(yhat_thresh)\n}\n \nresult <- function(result_x, result_w1, result_w2){\n result_x = as.matrix(result_x)\n result_h1 <- activation(dot(result_x, result_w1))\n yhat_test <- activation(dot(result_h1, result_w2))\n return(yhat_test)\n}\n \n\n\n \n\n", "meta": {"hexsha": "7c76dd163525793a9cfdb0aa1fc3888e5b96aeec", "size": 4234, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/perceptron.r", "max_stars_repo_name": "Fergal-Stapleton/perceptron", "max_stars_repo_head_hexsha": "168bc279e4fe32671cc9fa619e192af8f66bd8fd", "max_stars_repo_licenses": ["MIT"], "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/perceptron.r", "max_issues_repo_name": "Fergal-Stapleton/perceptron", "max_issues_repo_head_hexsha": "168bc279e4fe32671cc9fa619e192af8f66bd8fd", "max_issues_repo_licenses": ["MIT"], "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/perceptron.r", "max_forks_repo_name": "Fergal-Stapleton/perceptron", "max_forks_repo_head_hexsha": "168bc279e4fe32671cc9fa619e192af8f66bd8fd", "max_forks_repo_licenses": ["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.1451612903, "max_line_length": 95, "alphanum_fraction": 0.6022673595, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.6266792699448509}} {"text": " ZTGSEN Example Program Results\n\n Reordered Schur matrix A\n 1 2 3 4\n 1 ( 4.6904, 2.3452) (-2.1563, 0.1192) ( 1.9599,-0.5174) ( 1.8091,-1.2060)\n 2 ( 0.0000, 0.0000) ( 2.0084,-1.0042) ( 0.9161,-0.2762) ( 1.8574,-0.5326)\n 3 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 1.6985, 1.6985) ( 0.1270, 0.7231)\n 4 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 6.0000,-2.0000)\n\n Reordered Schur matrix B\n 1 2 3 4\n 1 ( 2.3452, 0.0000) (-0.6181, 1.8237) ( 0.9290, 0.5409) ( 2.7136,-1.5076)\n 2 ( 0.0000, 0.0000) ( 1.0042, 0.0000) ( 1.2251,-1.1857) ( 1.8541,-0.2929)\n 3 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.8492, 0.0000) ( 0.1435, 0.9053)\n 4 ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 0.0000, 0.0000) ( 2.0000, 0.0000)\n\n Basis of left deflating invariant subspace\n 1 2\n 1 ( 0.9045, 0.3015) (-0.0033,-0.2397)\n 2 ( 0.3015, 0.0000) ( 0.2497, 0.7157)\n 3 ( 0.0000, 0.0000) ( 0.0549, 0.6042)\n 4 ( 0.0000, 0.0000) ( 0.0000, 0.0000)\n\n Basis of right deflating invariant subspace\n 1 2\n 1 ( 0.7071, 0.0000) (-0.5607, 0.0000)\n 2 ( 0.7071, 0.0000) ( 0.5607, 0.0000)\n 3 ( 0.0000, 0.0000) ( 0.0552, 0.6067)\n 4 ( 0.0000, 0.0000) ( 0.0000, 0.0000)\n\n Norm estimate of projection onto left eigenspace for selected cluster\n 8.90E+00\n\n Norm estimate of projection onto right eigenspace for selected cluster\n 7.02E+00\n\n F-norm based upper bound on Difu\n 2.18E-01\n\n F-norm based upper bound on Difl\n 2.62E-01\n", "meta": {"hexsha": "7a662ebf4cfef68a644806f042b49084ae0c282c", "size": 1601, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/ztgsen_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/ztgsen_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/ztgsen_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 38.119047619, "max_line_length": 75, "alphanum_fraction": 0.5302935665, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6266705690664638}} {"text": "#' Percent Change Without Div by 0 Error\n#' \n#' Calculates the percent change of two numbers or vectors, if prior = 0 then percent change is 100%\n#' \n#' @param prior A numeric object\n#' @param current A numeric object\n#' @param format If TRUE (default) then output is converted to a percentage with formattable, otherwise proportion\n#' @param ... Any arguments passed to formattable::percent, most likely digits\n#' \n#' @export\n#' \n#' @examples\n#' pct_change(0, 1) returns 100.00%\n#' pct_change(2, 3, format = F) returns 0.5\n#' \n\n\n\npct_change <- function(prior, current, format = T, ...){\n \n out <- ifelse(prior == 0, sign(current), (current/prior) - 1)\n \n if(format == T){\n formattable::percent(out, ...)\n }else{\n out}\n \n}", "meta": {"hexsha": "ca0229e2f543e5a508cd86f1b25844c4a8c7f8bc", "size": 736, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pct_change.r", "max_stars_repo_name": "joshua-ruf/fidelis", "max_stars_repo_head_hexsha": "cb8c4437e04d341228ef204449a2aacd4177b36e", "max_stars_repo_licenses": ["MIT"], "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/pct_change.r", "max_issues_repo_name": "joshua-ruf/fidelis", "max_issues_repo_head_hexsha": "cb8c4437e04d341228ef204449a2aacd4177b36e", "max_issues_repo_licenses": ["MIT"], "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/pct_change.r", "max_forks_repo_name": "joshua-ruf/fidelis", "max_forks_repo_head_hexsha": "cb8c4437e04d341228ef204449a2aacd4177b36e", "max_forks_repo_licenses": ["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.2857142857, "max_line_length": 114, "alphanum_fraction": 0.6630434783, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6264775442131161}} {"text": "\n## The web link for this lesson\n## https://courses.edx.org/courses/HarvardX/PH525.4x/1T2015/courseware/92dbe89dc80c4fc084cad3f00b0381f7/494a3c869b7d4d9facbc92c1c8ded6c6/\n\ndownload.file(\"http://bowtie-bio.sourceforge.net/recount/ExpressionSets/bottomly_eset.RData\",\"bottomly_eset.RData\")\nload(\"bottomly_eset.RData\")\nlibrary(\"Biobase\")\npData(bottomly.eset)\n\n# raw counts matrix\nhead(exprs(bottomly.eset))\n\ntotal<- nrow(exprs(bottomly.eset))\n\nratios<- numeric()\nfor (i in 1:ncol(exprs(bottomly.eset))) {\n zeros<- sum(exprs(bottomly.eset)[,i] == 0)\n ratio<- zeros/total\n ratios<- c(ratios, ratio)\n}\n\ng<- as.factor(pData(bottomly.eset)$experiment.number)\n\nlibrary(ggplot2)\nd<- data.frame(ratios=ratios, group=g)\nggplot(d) + geom_boxplot(aes(x=group, y=ratios))\n\n## different batches have differnt proportion of 0s for the counts \n\n## make a multidimensional scaling plot\n## However, when computing distances we prefer\n# to have measures with similar variability across samples. \n## Because this is RNAseq data, the variance depends on the mean:\nlibrary(genefilter)\nA<- rowMeans(exprs(bottomly.eset))\nSD<- rowSds(exprs(bottomly.eset))\nplot(A,SD)\n\n## log2 transformation to stablize the variance\ny<- log2( exprs( bottomly.eset )+0.5)\n\nlibrary(devtools)\ninstall_github(\"rafalib\",\"ririzarr\") \nlibrary(rafalib)\nmypar(2,1)\nhist(y[,1],nc=100)\nhist(y[y[,1]>0,1],nc=100)\nabline(v=3)\n\n## use counts bigger than 8\ny<- exprs( bottomly.eset )\nind<- which(apply( y>=8, 1, all))\ny<- log2( y[ind,] )\n\n## make a multidimensional scaling plot\n\ns<- svd(y)\nU<- s$u ## orthogonal matrix UtU = I \nV<- s$v ## orthogonal matrix \nD<- diag(s$d) # diagnonal matrix\n\nlibrary(rafalib)\nmypar2(1,1)\nplot(s$d)\n\nYhat<- U %*% D %*% t(V)\nresid<- Y - Yhat\nboxplot(resid, ylim = c(-2,2), range=0)\n\n\n##### normalizing NGS count data for biased GC content, this is just to demonstrate\n### that GC bias can affect counts, for real data analysis, GC bias correction methods\n### for example:\n### EDAseq bioconductor http://www.ncbi.nlm.nih.gov/pubmed/22177264\n\n# Systematic bias is important to keep in mind, especially in experiments with many batches. Comparisons across batches are complicated by technical biases, and it is essential that conditions of interest (treatment vs untreated) be balanced across batches, or else the experiment will uncover a mix of biological differences and systematic bias, with no hope to disentangle the two. This issue comes up over and over again in genomic studies, since the beginning of microarray data and continuing to the present day, with massive sequencing-based genomic data sets.\n\n# The ReCount project provides summaries of a number of RNA-seq experiments as ExpressionSet objects, so that labs around the world do not have to perform alignment just to \"re-count\" the number of reads which fall in genes. If you use data from this project make sure to cite the authors! Download the ExpressionSet for the Bottomly experiment, here. Load this object into R:\n\nlibrary(Biobase)\nload(\"bottomly_eset.RData\")\nbottomly.eset\nhead(exprs(bottomly.eset))\n\n# Examine the histogram of sample-sample correlations of log counts:\n \nhist(cor(log(exprs(bottomly.eset) + 1)))\n\n#There are a number of reasons for such high correlations:\n \n#Biological correlation: genes are expressed similarly across organisms\n# Systematic bias: technical bias affects the same genes similarly (for example, if the bias is due to the sequence of the gene, then this could be common across experiments)\n# The presence of many zeros, which anchor the cloud of log counts at (0,0)\n#Remove some of the rows with many zeros, and plot the histogram of correlations again:\n \nmat = exprs(bottomly.eset)\nrs = rowSums(mat)\nhist(cor(log(mat[ rs > 10, ] + 1)))\n\n#Subset and rename the ExpressionSet to remove the genes which have 2 or fewer reads across all samples:\n \ne = bottomly.eset[ rowSums(exprs(bottomly.eset)) > 2, ]\ndim(e)\n\n# We now have 12971 genes and 21 samples. The genes are annotated with ENSEMBL IDs, \n# stored as rownames (and in fData(e)). The quickest way for us to check the GC content\n# of each gene is to use the precomputed TxDb for mouse in Bioconductor. If we were doing \n# this analysis not just for quick check, we should load the ENSEMBL genes from the ENSEMBL \n# GTF file and use these for computing GC.\n\nbiocLite(\"TxDb.Mmusculus.UCSC.mm9.knownGene\")\nbiocLite(\"BSgenome.Mmusculus.UCSC.mm9\")\nbiocLite(\"org.Mm.eg.db\")\n\nlibrary(\"TxDb.Mmusculus.UCSC.mm9.knownGene\")\nlibrary(\"BSgenome.Mmusculus.UCSC.mm9\")\nlibrary(\"org.Mm.eg.db\")\n\n\n# Now we will connect the ENSEMBL IDs to Entrez IDs, and then get the sequence for the exons per gene.\n## because in the TxDb.Mmusculus.UCSC.mm9.knownGene database, genes are in ENTREZID.\n\nres = select(org.Mm.eg.db, keys=rownames(e), keytype=\"ENSEMBL\", columns=\"ENTREZID\")\n\n#Note there are 1 to many mappings, which will we ignore for this quick analysis. Now add a column to the ExpressionSet, by getting the first match of the ENTREZ IDs to our ENSEMBL IDs.\n\nfData(e)$ENTREZ = res$ENTREZID[ match(rownames(e), res$ENSEMBL) ]\n\n#There are some NA's for those ENSEMBL IDs missing matches, which we will just remove from analysis:\n\nsum(is.na(fData(e)$ENTREZ))\ne = e[ !is.na(fData(e)$ENTREZ) , ]\n\n#Now it's only two steps to get the GC content: get the genes, and get the sequence for the genes. First we get the exons for each gene:\n\ntxdb = TxDb.Mmusculus.UCSC.mm9.knownGene\ngrl = exonsBy(txdb, by=\"gene\")\n\n#We need to subset the ExpressionSet again to only those genes for which we have ranges:\n\ne = e[ fData(e)$ENTREZ %in% names(grl), ]\n\n#Now put the exon GRangesList in the order of the counts ExpressionSet and reduce the exons GRangesList. \n## The reduce() call is necessary so that we don't overcount any overlapping exon sequence.\n\nreduced.exons = reduce(grl[ fData(e)$ENTREZ ])\n\n# Get the sequence for the reduced exons using getSeq. Note that the returned object is a \n# DNAStringSetList. For each gene, we have a DNAStringSet of the reduced exon sequence. \n# By calling DNAStringSet(lapply(x, unlist)) on the DNAStringSetList, 'x', we get a DNAStringSet \n# for each gene with the joined reduced exon sequence. Note that this unlisting does take a few minutes to perform though.\n\n#What is the GC-content (a ratio, answer between 0 and 1) for the first gene in reduced.exons? \n# Hint: letterFrequency\n\n?getSeq\nmm9_genome<- BSgenome.Mmusculus.UCSC.mm9\n\nexonSeq<- getSeq(mm9_genome, reduced.exons)\nexonSeq_unlist<- DNAStringSet(lapply(exonSeq, unlist))\n#G/C content for the first gene\n\nsum(letterFrequency(x=exonSeq_unlist[1], letters=c(\"C\",\"G\"), as.prob=T))\n\ngc<- apply(letterFrequency(x=exonSeq_unlist, letters=c(\"C\",\"G\"), as.prob=T), 1, sum)\n\n\n# Plot the log counts over the GC content for one sample:\n \nplot( log(exprs(e)[,1]+1) ~ gc)\n\n# It might be easier to see a dependence with boxplots:\n \nboxplot( log(exprs(e)[,1]+1) ~ cut(gc, 20))\n\n# We can calculate the median log count for each bin of GC content for a single sample:\n \nsapply(split(log(exprs(e)[,1]+1), cut(gc, 20)), median)\n\n# We can perform this calculation across all samples as well:\n \ngc.depend = sapply(1:ncol(e), function(i) sapply(split(log(exprs(e)[,i]+1), cut(gc, 20)), median))\n\n# Plot the GC dependence and color the lines by batch identifier:\n \nplot(gc.depend[,1], type=\"n\", ylim=c(0,6))\nbatch = factor(e$experiment.number)\nfor (i in 1:ncol(e)) lines(gc.depend[,i], col=batch[i])\nlegend(\"bottom\", levels(batch), col=1:3, lty=1)\n\n\n\n\n", "meta": {"hexsha": "53e30adfb85d2d0e7952ae54d9440237e411da3a", "size": 7513, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ReCount_eset.r", "max_stars_repo_name": "crazyhottommy/scripts-general-use", "max_stars_repo_head_hexsha": "3aeff05739ca96c84c60d7c792792607a1947ca9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-11-25T02:50:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-11T10:29:52.000Z", "max_issues_repo_path": "R/ReCount_eset.r", "max_issues_repo_name": "crazyhottommy/scripts-general-use", "max_issues_repo_head_hexsha": "3aeff05739ca96c84c60d7c792792607a1947ca9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-05-12T04:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-12T04:34:15.000Z", "max_forks_repo_path": "R/ReCount_eset.r", "max_forks_repo_name": "crazyhottommy/scripts-general-use", "max_forks_repo_head_hexsha": "3aeff05739ca96c84c60d7c792792607a1947ca9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-11-26T13:39:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:24:46.000Z", "avg_line_length": 38.7268041237, "max_line_length": 566, "alphanum_fraction": 0.7372554239, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6261449124809669}} {"text": "=begin\n # sample-algebraicfield01.rb\n\n require \"algebra\"\n \n Px = Polynomial(Rational, \"x\")\n x = Px.var\n F = ResidueClassRing(Px, x**2 + x + 1)\n x = F[x]\n p( (x + 1)**100 )\n #=> -x - 1\n p( (x-1)** 3 / (x**2 - 1) )\n #=> -3x - 3\n \n G = Polynomial(F, \"y\")\n y = G.var\n p( (x + y + 1)** 7 )\n #=> y^7 + (7x + 7)y^6 + 8xy^5 + 4y^4 + (4x + 4)y^3 + 5xy^2 + 7y + x + 1\n \n H = ResidueClassRing(G, y**5 + x*y + 1)\n y = H[y]\n p( 1/(x + y + 1)**7 )\n #=> (1798/3x + 1825/9)y^4 + (-74x + 5176/9)y^3 + \n # (-6886/9x - 5917/9)y^2 + (1826/3x - 3101/9)y + 2146/9x + 4702/9\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "0cd53cae9c8cdb50a186bf7c7c2efc230adf42d7", "size": 616, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-algebraicfield01.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-algebraicfield01.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-algebraicfield01.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8148148148, "max_line_length": 77, "alphanum_fraction": 0.4334415584, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012717045181, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.6260474851337738}} {"text": "asymp <-function(v=0.0, min=-10, max=+10)\n{\n r = max - min;\n return (min + r * (pi/2 + atan(v)) / pi)\n}\n\nvtp2pol <- function(scale=0.0, resonance=0.0, shift=0.0, fbfact=0.0, rpfact=0.0)\n{\n f = exp(scale/50) * 1000.0 * c(1,3,5,7,9,11,13,15) / 2\n b = exp(resonance/50) * 50.0 + 20.0 * 1:8\n\n for (j in 1:8) {\n\tif (j > 1)\n\t minv = 50.0 + (f[j] + f[j-1]) / 2.0\n\telse\n\t minv = 50.0\n\tif (j < 8)\n\t maxv = (f[j+1] + f[j]) / 2.0 - 50.0\n\telse\n\t maxv = f[j] + 450.0 * exp(scale/50)\n\tif (j%%2) { # if j is odd positive values decrease freq\n\t v = asymp(fbfact*.0325, maxv, minv)\n\t} else { # if j is even positive values increase freq\n\t v = asymp(fbfact*.0325, minv, maxv)\n\t}\n\tf[j] = v\n }\n\n if (rpfact < 0.0) {\n\tminv = f[1] + 50.0\n\tmaxv = f[2] + (f[2] - minv)\n\tf[2] = asymp(rpfact*.0325, minv, maxv)\n\tminv = f[2] + 50.0\n\tmaxv = f[3] + (f[3] - minv)\n\tf[3] = asymp(rpfact*.0325, minv, maxv)\n } else {\n\tmaxv = f[4] - 50.0\n\tminv = f[3] - (maxv - f[3])\n\tf[3] = asymp(rpfact*.0325, minv, maxv)\n\tmaxv = f[3] - 50.0\n\tminv = f[2] - (maxv - f[2])\n\tf[2] = asymp(rpfact*.0325, minv, maxv)\n }\n\n mid = exp(scale/50) * 500.0\n minv = 50.0 - f[1]\n maxv = -minv\n v = asymp(shift*0.325, minv, maxv)\n cat(\"minv=\",minv,\" maxv=\",maxv,\" v=\",v,\"\\n\")\n f = f + v\n\n rtn <- data.frame(f, b)\n return(rtn)\n}\n\nvtSpect <- function(vt)\n{\n s=rep(1,101);\n\tfor (i in 1:length(vt$f)) {\n\t s = s * formant(vt$f[i], vt$b[i], 100, 8000)\n }\n\ts = s * hpc2(8, seq(0, 8000, 8000/100), 500)\n return(s)\n}", "meta": {"hexsha": "c82450eda01bf11fc1fb88970d67c8c27c31b1c3", "size": 1477, "ext": "r", "lang": "R", "max_stars_repo_path": "R/vtp2pol.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/vtp2pol.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/vtp2pol.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": 23.078125, "max_line_length": 80, "alphanum_fraction": 0.5199729181, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6259632795228418}} {"text": "dft <- function(timeScopeList, pointCount) {\n realPointCount <- length(timeScopeList)\n freqScopeList <- c()\n\n for(k in 1:pointCount) {\n sumCache <- 0\n for(n in 1:pointCount) {\n if (n>realPointCount) {\n break\n }\n\n sumCache <- sumCache + timeScopeList[n] * exp(-1i * 2 * pi * (k - 1) * (n - 1) / pointCount)\n }\n\n freqScopeList <- append(freqScopeList, sumCache)\n }\n\n return(freqScopeList)\n}\n\nprint(dft(c(1, 2, 1, 2), 4))", "meta": {"hexsha": "53289929d326a6be0571235abfac76bd69210881", "size": 509, "ext": "r", "lang": "R", "max_stars_repo_path": "DigitalSignalProcess/R/dft.r", "max_stars_repo_name": "yyc12345/gist", "max_stars_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T06:24:10.000Z", "max_issues_repo_path": "DigitalSignalProcess/R/dft.r", "max_issues_repo_name": "yyc12345/gist", "max_issues_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DigitalSignalProcess/R/dft.r", "max_forks_repo_name": "yyc12345/gist", "max_forks_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_forks_repo_licenses": ["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.2380952381, "max_line_length": 104, "alphanum_fraction": 0.5324165029, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.625963269349732}} {"text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC # Decision Trees\n# MAGIC ### Not focused on best way to perform modelling using Decision Trees or Random Forest\n# MAGIC #### Instead focus on intro and getting you started and using Decision Trees & Random Forest\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Who has used modelling in the past?\n# MAGIC ### Slack Poll\n\n# COMMAND ----------\n\nlibrary(\"caret\")\nlibrary(\"tidyverse\")\ndata(diamonds)\nmodel <- lm(price ~ ., diamonds)\np <- predict(model, diamonds)\n\n# COMMAND ----------\n\nhead(diamonds)\n\n# COMMAND ----------\n\nsummary(model)\n\n# COMMAND ----------\n\nsummary(p)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Decision Trees\n# MAGIC * Tree-based models \n# MAGIC - Non-parametric algorithms \n# MAGIC - Partitioning the feature space into a number of smaller (non-overlapping) regions with similar response values using a set of splitting rules. \n# MAGIC * Predictions are obtained by fitting a simpler model (e.g., a constant like the average response value) in each region. \n# MAGIC * Such divide-and-conquer methods can produce simple rules that are easy to interpret and visualize with tree diagrams. \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC - One methodology for constructing Decision Trees is CART the classification and regression tree (CART) algorithm\n# MAGIC - Partition training data into homogeneous subgroups (nodes)\n# MAGIC and then fits a simple constant in each node\n# MAGIC - Nodes are formed recursively using binary partitions formed by asking simple yes-or-no questions about each feature (e.g., is age < 18?). \n# MAGIC - This is done a number of times until a suitable stopping criteria is satisfied (e.g., a maximum depth of the tree is reached). \n# MAGIC - Then the model predicts the output based on \n# MAGIC - (1) the average response values for all observations that fall in that subgroup (regression problem), or \n# MAGIC - (2) the class that has majority representation (classification problem). \n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Example of Decision Tree\n# MAGIC \n# MAGIC ![DCT1.jpg](https://cdn-images-1.medium.com/max/824/0*J2l5dvJ2jqRwGDfG.png)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ![DCT2.jpg](https://cdn-images-1.medium.com/max/688/0*pb-1ufHK-OmR8k7r.png)\n\n# COMMAND ----------\n\nlibrary(rpart)\nmodel <- rpart(Species ~., data = iris)\npar(xpd = NA) # otherwise on some devices the text is clipped\nplot(model)\ntext(model, digits = 3)\n\n# COMMAND ----------\n\ndim(iris)\n\n# COMMAND ----------\n\nprint(model, digits = 2)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Decision Trees: Partitioning\n# MAGIC \n# MAGIC - CART uses binary recursive partitioning (it’s recursive because each split or rule depends on the splits above it). \n# MAGIC - The objective at each node is to find the “best” feature to partition the remaining data into one of two regions (R1 and R2) such that the overall error between the actual response (yi) and the predicted constant (ci) is minimized.\n# MAGIC - Having found the best feature/split combination, the data are partitioned into two regions and the splitting process is repeated on each of the two regions (hence the name binary recursive partitioning). \n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Decision Trees: Deep\n# MAGIC - Early stopping\n# MAGIC - Restrict the tree depth to a certain level or \n# MAGIC - Restrict the mini number of observations allowed in any terminal node\n# MAGIC - Pruning\n# MAGIC - grow a very large, complex tree and then prune it back to find an optimal subtree\n\n# COMMAND ----------\n\n# Load the data and remove NAs\ndata(\"PimaIndiansDiabetes2\", package = \"mlbench\")\nPimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)\n# Inspect the data\nsample_n(PimaIndiansDiabetes2, 3)\n#https://rdrr.io/cran/mlbench/man/PimaIndiansDiabetes.html\n\n# COMMAND ----------\n\n# Split the data into training and test set\nset.seed(123)\ntraining.samples <- PimaIndiansDiabetes2$diabetes %>% \n createDataPartition(p = 0.8, list = FALSE)\ntrain.data <- PimaIndiansDiabetes2[training.samples, ]\ntest.data <- PimaIndiansDiabetes2[-training.samples, ]\n\n# COMMAND ----------\n\n# Build the model\nset.seed(123)\nmodel1 <- rpart(diabetes ~., data = train.data, method = \"class\")\n# Plot the trees\npar(xpd = NA) # Avoid clipping the text in some device\nplot(model1)\ntext(model1, digits = 3)\n\n# COMMAND ----------\n\n# Make predictions on the test data\npredicted.classes <- model1 %>% \n predict(test.data, type = \"class\")\nhead(predicted.classes)\n\n# COMMAND ----------\n\n# Compute model accuracy rate on test data\nmean(predicted.classes == test.data$diabetes)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC #### Pruning the tree\n\n# COMMAND ----------\n\n?train\n\n# COMMAND ----------\n\n# Fit the model on the training set\nset.seed(123)\nmodel2 <- train(\n diabetes ~., data = train.data, method = \"rpart\",\n trControl = trainControl(\"cv\", number = 10),\n tuneLength = 10\n )\n# Plot model accuracy vs different values of\n# cp (complexity parameter)\nplot(model2)\n\n# COMMAND ----------\n\n# Print the best tuning parameter cp that\n# maximizes the model accuracy\nmodel2$bestTune\n\n# COMMAND ----------\n\n# Plot the final tree model\npar(xpd = NA) # Avoid clipping the text in some device\nplot(model2$finalModel)\ntext(model2$finalModel, digits = 3)\n\n# COMMAND ----------\n\n# Decision rules in the model\nmodel2$finalModel\n\n# COMMAND ----------\n\n# Make predictions on the test data\npredicted.classes <- model2 %>% predict(test.data)\n# Compute model accuracy rate on test data\nmean(predicted.classes == test.data$diabetes)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Take aways: \n# MAGIC - Simple and easy to implement (no preprocessing required and categorical variables handled, handle missing values)\n# MAGIC - Not great on predictive accuracy\n# MAGIC - Deep trees have high variance / Shallow Trees bias.\n# MAGIC \n# MAGIC ## More technical: \n# MAGIC - A problem with decision trees like CART is that they are greedy. \n# MAGIC - Even with Bagging, the decision trees can have a lot of structural similarities and in turn have high correlation in their predictions.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Another way to think about Decision Trees\n# MAGIC - Great advantage of decision trees: make a complex decision simpler by breaking it down into smaller, simpler decisions using a divide-and-conquer strategy. \n# MAGIC - Identify a set of if-else conditions that split the data according to the value of the features.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Before jumping to the next section, let's try out few examples\n", "meta": {"hexsha": "0df52d05c2b092100cbb0b55b5585a838dbfa90e", "size": 6573, "ext": "r", "lang": "R", "max_stars_repo_path": "Workshop_code/02-Decision_Trees_Intro.r", "max_stars_repo_name": "haddadz/vancvouredatajam-advancedRworkshop", "max_stars_repo_head_hexsha": "a40ba25e451b72ef4c6de0a8e362f75464e38234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-12T15:25:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-12T15:25:14.000Z", "max_issues_repo_path": "Workshop_code/02-Decision_Trees_Intro.r", "max_issues_repo_name": "haddadz/vancvouredatajam-advancedRworkshop", "max_issues_repo_head_hexsha": "a40ba25e451b72ef4c6de0a8e362f75464e38234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Workshop_code/02-Decision_Trees_Intro.r", "max_forks_repo_name": "haddadz/vancvouredatajam-advancedRworkshop", "max_forks_repo_head_hexsha": "a40ba25e451b72ef4c6de0a8e362f75464e38234", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-09-12T03:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T17:38:20.000Z", "avg_line_length": 30.714953271, "max_line_length": 241, "alphanum_fraction": 0.7053095999, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915994285382, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6258468968632455}} {"text": "#' @title calcHMWettedSA\n#'\n#' @description Calculate hull wetted surface area (\\code{wettedSA}) (m^2)\n#' using the Holtrop & Mennen method.\n#'\n#'@param lwl Waterline length (vector of numericals, m) (see\n#'\\code{\\link{calclwl}})\n#'@param breadth Moulded breadth (vector of numericals, m)\n#'@param actualDraft Actual draft (vector of numericals, m)\n#'@param Cm Midship section coefficient (vector of numericals, dimensionless)\n#'(see \\code{\\link{calcCm}})\n#'@param Cbw Waterline block coefficient (vector of numericals, dimensionless)\n#'(see \\code{\\link{calcCbw}})\n#'@param Cwp Water plane area coefficient (vector of numericals, see\n#'\\code{\\link{calcCwp}})\n#'@param Abt Traverse bulb area (vector of numericals, m^2) (see\n#'\\code{\\link{calcAbt}})\n#'\n#'@details\n#'Actual draft is typically obtained from sources such as AIS messages or ship\n#'records.\n#'\n#' @return \\code{wettedSA} (vector of numericals, m^2)\n#'\n#' @references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcCm}}\n#'\\item \\code{\\link{calcCbw}}\n#'\\item \\code{\\link{calcCwp}}\n#'\\item \\code{\\link{calcAbt}}}\n#'\n#' @family Holtrop-Mennen Calculations\n#'\n#' @examples\n#'calcHMWettedSA(218.75,12.48,32.25,0.99,0.81,0.91,32.02)\n#'\n#' @export\n\ncalcHMWettedSA<- function(lwl,actualDraft,breadth,Cm,Cbw,Cwp,Abt){\n\nwettedSA<-lwl*(2*actualDraft+breadth)*(Cm^0.5)*\n (0.453+0.4425*Cbw-0.2862*Cm-0.003467*(breadth/actualDraft)+\n 0.3696*Cwp)+2.38*(Abt/Cbw)\n\n return(wettedSA)\n}\n", "meta": {"hexsha": "d79848ec86dc3f2225a1756c637c91f29b88a7cd", "size": 1597, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMWettedSA.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/calcHMWettedSA.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/calcHMWettedSA.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 31.3137254902, "max_line_length": 78, "alphanum_fraction": 0.7013149656, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6256854996206722}} {"text": "\n#Notes can be found at the link below\n#https://nbviewer.jupyter.org/github/corybaird/PLCY_Code_2020_winter/blob/main/Code_sessions/Session_2/Session_2_Notes.ipynb\n\n# A.1 Import libraries¶\n\n## Step 1\n#install.packages('dplyr')\n#install.packages('ggplot2')\n\n#A.2 Import data¶\n\n# Step 2\nlibrary(ggplot2)\nlibrary(dplyr)\n\nmtcars = as_tibble(mtcars)\nmtcars %>% head(2)\n\n\n# 1. OLS regression\n# 1.1 OLS: Built-in package lm\n# 1.1.1 Regression summary¶\n\nlinear_reg = lm(mpg ~ wt, data=mtcars)\n\nprint(summary(linear_reg))\n\n\n# 1.1.1.1 Accessing coefficients from summary\n\nlinear_reg_summary = summary(linear_reg)\n\nlinear_reg_summary$coefficients\n\n# F-stat\nprint('F-stat')\nlinear_reg_summary$fstatistic\n\n# R-sq\nprint(paste('R-sq:', linear_reg_summary$r.squared, sep=' '))\n\n\n# 1.1.1.2 Accessing specific coefficients¶\n\n#linear_reg_summary$coefficients[\"wt\",\"Std. Error\"] #Std. errors\n\n#linear_reg_summary$coefficients[\"wt\",\"t value\"] #T-value\n\nbeta1_lm = linear_reg_summary$coefficients[\"wt\",\"Estimate\"] #Beta \n\nbeta1_lm\n\n\n# 1.1.2 Residuals¶\n\n#linear_reg$fitted.values #Yhat\n#linear_reg$coefficients #coefficients\n#linear_reg$residuals #Residuals\n\ndf_model = mtcars %>% select(wt,mpg)\n\ndf_model = df_model %>% \nrename('y' = mpg) %>% \nmutate(residu = linear_reg$residuals,\n predicted_y = linear_reg$fitted.values) \n\ndf_model %>% head(5)\n\n\n# 1.1.2.1 Plot regression residuals¶\n\n#predicted_y == yhat\ndf_model %>% ggplot(aes(y, predicted_y))+ geom_point()\n\n\n# 1.2 OLS: Using matrix algebra¶\n# 1.2.1 Create matrices for X and Y values¶\n\nX = as.matrix(mtcars %>% select(wt)) \nX = cbind(X,rep(1,length(X))) #Add constant/intercept\ncolnames(X)[2] <- \"Intercept\" #Name intercept\nY = as.matrix(mtcars %>% select(mpg))\n\n# Method 1: SOLVE OLS USING Linear algebra\nA = solve(t(X)%*%X)\nbhat_hand = A %*% t(X) %*% Y \nprint(bhat_hand)\n\n# Method 2: SOlVE OLS using cov--Note only works for Single linear regression\ncov(Y, X)['mpg','wt']/var(X)['wt','wt'] \n\n\n# 2. Regression diagnostics¶\n\n#Step 1\n#install.packages('lmtest')\n\n#Step 2\nlibrary(lmtest)\n\n\n# 2.1 Breusch pagan: test for heteroskedasticity¶\n\nlinear_reg = lm(mpg ~ wt, data=mtcars)\nbptest(linear_reg)\n\n### 2.1.1 Create function to check the above test\ndiagnostics <- function(regression) {\n bp_res = bptest(linear_reg)$p.value\n if (bp_res<.1){\n print(paste(\"P-value\", round(bp_res,3)))\n print(\"Reject null. Thus there is evidence of heteroskedasticity\")\n }\n else{\n print(paste(\"P-value\", round(bp_res,3)))\n print(\"Cannot reject null. No evidence of heteroskedasticity\")\n } \n}\n\ndiagnostics(linear_reg)\n\n\n# 2.2 DW test: test for serial correlation¶\n\ndwtest(linear_reg)\n\n\n\n# 2.3 Functional misspecification¶\nresettest(linear_reg)\n\n\n# 2.4 Introduction to functions¶\n# 2.4.1 Function: square numbers¶\n\nsquare = function(a){\n solution = a^2\n return (solution)\n}\nsquare(4)\n\n\n# 2.4.2 Function: add two numbers¶\n\nadd_numbers = function(a,b){\n solution = (a^2)+b\n return (solution)\n}\n\nadd_numbers(2,3)\n\n\n# 2.4.3 Function: using if and else¶\n\nnumber_test = function(a,b,c) { \n print('You can print anything you want inside functions')\n solution1 = a+b\n solution = solution1-c\n print(paste(\"The solution is:\", solution))\n if (solution>100){\n print('Big numbers are lame')\n }\n else{\n print('Small numbers are cool')\n }\n}\n\nnumber_test(1,2,5)\n\n\n# 2.4.4 Function: BP, DW and RESET Test¶\n\ndiagnostics = function(regression) { \n #BP-test\n print('-------')\n print('BP-Test')\n bp_res = bptest(linear_reg)$p.value\n if (bp_res<.1){\n print(paste(\"P-value\", round(bp_res,3)))\n print(\"Reject null. Thus there is evidence of heteroskedasticity\")\n }\n else{\n print(paste(\"P-value\", round(bp_res,3)))\n print(\"Cannot reject null. No evidence of heteroskedasticity\")\n }\n #DW-test\n print('-------')\n print('DW-Test')\n dw_res = dwtest(linear_reg)$p.value\n if (dw_res<.1){\n print(paste(\"P-value\", round(dw_res,3)))\n print(\"Reject null. Thus there is evidence of serial correlation\")\n }\n else{\n print(paste(\"P-value\", round(bp_res,3)))\n print(\"Cannot reject null. No evidence of serial correlation\")\n } \n #Ramsey Reset test\n print('-------')\n print('Rest-Test')\n ram_res = resettest(linear_reg)$p.value\n if (ram_res<.1){\n print(paste(\"P-value\", round(ram_res,3)))\n print(\"Reject null. Thus there is evidence of misspecification\")\n }\n else{\n print(paste(\"P-value\", round(ram_res,3)))\n print(\"Cannot reject null. No evidence of misspecification\")\n } \n}\n\ndiagnostics(linear_reg)\n\n\n\n# 3. Other regression models\n# 3.1 Robust S.E. regression\n\nlibrary(MASS)\n\nsummary(rlm(mpg ~ wt, mtcars))\n\n\n# 3.2 Fixed effects¶\n\nlibrary(plm)\n\ndata(\"Grunfeld\", package=\"plm\")\nGrunfeld %>% head(3)\n\n\n# 3.2.1 Fixed effects: Individual fixed effects¶\n\ngrun.fe <- plm(inv~value+capital, index=c('firm','year'), data = Grunfeld, model = \"within\")\nsummary(grun.fe)$coefficients\n\n\n# 3.2.2 Fixed effects: Individual AND time fixed effects¶\n\n#Method 1: factor(year)\ngrun.fe <- plm(inv~value+capital+factor(year), index=c('firm','year'), data = Grunfeld, model = \"within\")\n\n#Method 2: effect='twoways'\ngrun.fe <- plm(inv~value+capital, index=c('firm','year'), data = Grunfeld, model = \"within\", effect='twoways')\nsummary(grun.fe)$coefficients\n\n\n# 3.3 Standard errors\n# 3.3.1 Baseline standard error¶\n\nsummary(grun.fe)$coefficients\n\n\n# 3.3.2 Clustered standard error¶\n\ncoeftest(grun.fe, vcovHC(grun.fe, type = 'HC0', cluster = c('group','time')))\n\n\n# 3.4 Random effects¶\n\ngrun.re <- plm(inv~value+capital,index=c('firm','year'), data = Grunfeld, model = \"random\")\nsummary(grun.re)$coefficients\n\n\n# 3.4.1 Robust standard errors¶\n\ncoeftest(grun.re, vcovHC(grun.re, type = 'HC0', cluster = c('group','time')))\n\n\n# 3.5 Logistic regression¶\n\nmtcars %>% head(2)\n\nsummary(glm(am~ cyl+disp+drat+mpg, family='binomial', mtcars))\n\n\n# 4. Machine Learning: Supervised learning¶\n\n# Step 1\n#install.packages('caret')\n\n# Step 2\nlibrary(caret)\n\ndata(Sacramento)\nhouse_df = Sacramento %>% as_tibble()\nhouse_df = house_df %>% mutate(ID = row_number())\nhouse_df %>% head(3)\n\n\n# 4.1.1. Baseline regression¶\n\nmodel = lm(price ~ beds+baths+sqft, data=house_df)\n\n\n# 4.1.1.1 Evaluate model by calculating RMSE¶\n\nrmse = function(acutal, predicted){\n error = predicted - acutal\n rmse = sqrt(mean(error^2))\n return(rmse)\n}\n\n\n# 4.1.1.2 Actual data=price , Predicted data=fitted.values¶\n\nrmse(house_df$price, model$fitted.values)\n\n\n# 4.1.2 Train-test regression¶\n\nset.seed(42)\n\ntrain = house_df %>% sample_frac(.8)\ntrain %>% head(2)\n\ntest = house_df[-train$ID,]\ntest %>% head(2)\n\nmodel = lm(price ~ beds+baths+sqft, data=train)\n\np = predict(model, test)\n\nrmse(p, test$price)\n\n\n# 4.2 Cross validation¶\n\nmodel <- train(\n price ~ beds+baths+sqft, \n data=house_df,\n method = \"lm\",\n trControl = trainControl(\n method = \"cv\", \n number = 10,\n verboseIter = FALSE\n )\n)\nmodel\n", "meta": {"hexsha": "bf12f97a09eac422c712080cbbbe5e6f3f54106f", "size": 6984, "ext": "r", "lang": "R", "max_stars_repo_path": "Code_sessions/Session_2/Session_2_Notes.r", "max_stars_repo_name": "corybaird/PLCY_Code_2020_winter", "max_stars_repo_head_hexsha": "5b3de6227410c37e56db6bdf35f5693c769bd980", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-12-31T02:57:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-31T02:57:31.000Z", "max_issues_repo_path": "Code_sessions/Session_2/Session_2_Notes.r", "max_issues_repo_name": "corybaird/PLCY_Code_2020_winter", "max_issues_repo_head_hexsha": "5b3de6227410c37e56db6bdf35f5693c769bd980", "max_issues_repo_licenses": ["MIT"], "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_sessions/Session_2/Session_2_Notes.r", "max_forks_repo_name": "corybaird/PLCY_Code_2020_winter", "max_forks_repo_head_hexsha": "5b3de6227410c37e56db6bdf35f5693c769bd980", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4809384164, "max_line_length": 124, "alphanum_fraction": 0.6691008018, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6256773126301081}} {"text": "### AR test and its corresponding power and sample size functions\n\nAR.test=function(ivmodel, beta0=0, alpha=0.05){\n Yadj = ivmodel$Yadj; Dadj = ivmodel$Dadj; Zadj = ivmodel$Zadj; \n n=ivmodel$n; k=ivmodel$p; l=ivmodel$L\n\n if(ncol(Yadj)>1){\n print(\"The outcome variable should be in one dimension!\")\n\treturn(NULL)\n }\n if(ncol(Dadj)>1){\n print(\"The treatment variable should be in one dimension!\")\n\treturn(NULL)\n }\n if(l+k>=n){\n print(\"Too many IVs, AR can't handle!\")\n return(NULL)\n }\n\n### test \n temp=Yadj-beta0*Dadj\n Fstat=c(sum(qr.fitted(ivmodel$ZadjQR, temp)^2))/c(sum(temp^2)-sum(qr.fitted(ivmodel$ZadjQR, temp)^2))*(n-k-l)/l\n p.value=1-pf(Fstat, df1=l, df2=n-k-l)\n \n### confidence interval \n cval=qf(1-alpha, df1=l, df2=n-k-l)*l/(n-k-l)\n coef.beta0sq=cval*sum(Dadj^2)-(cval+1)*sum(qr.fitted(ivmodel$ZadjQR, Dadj)^2)\n coef.beta0=-2*cval*sum(Dadj*Yadj)+2*(cval+1)*sum(Dadj*qr.fitted(ivmodel$ZadjQR, Yadj))\n coef.constant=cval*sum(Yadj^2)-(cval+1)*sum(qr.fitted(ivmodel$ZadjQR, Yadj)^2)\n Delta=coef.beta0^2-4*coef.constant*coef.beta0sq\n\n ci=matrix(NA, ncol=2)\n colnames(ci)<-c(\"lower\", \"upper\")\n\n if(coef.beta0sq==0){\n if(coef.beta0>0){\n info=c(\"[\",-coef.constant/coef.beta0,\",Infinity)\")\n ci[1,]=c(-coef.constant/coef.beta0, Inf)\n }\n if(coef.beta0<0){\n info=c(\"(-Infinity,\",-coef.constant/coef.beta0,\"]\");\n ci[1,]=c(-Inf, -coef.constant/coef.beta0)\n }\n if(coef.beta0==0){\n if(coef.constant>=0){\n info=\"Whole Real Line\"\n ci[1,]=c(-Inf, Inf)\n }\n if(coef.constant<0){\n info=\"Empty Set\"\n }\n }\n }\n \n if(coef.beta0sq!=0){\n if(Delta<=0){\n if(coef.beta0sq>0){\n info=\"Whole Real Line\"\n ci[1,]=c(-Inf, Inf)\n }\n if(coef.beta0sq<0){\n info=\"Empty Set\"\n }\n }\n if(Delta>0){\n # Roots of quadratic equation\n root1=(-coef.beta0+sqrt(Delta))/(2*coef.beta0sq)\n root2=(-coef.beta0-sqrt(Delta))/(2*coef.beta0sq)\n upper.root=max(root1,root2)\n lower.root=min(root1,root2)\n if(coef.beta0sq<0){\n info=paste(\"[\",lower.root,\", \",upper.root,\"]\",sep=\"\")\n ci[1, ]=c(lower.root, upper.root)\n }\n if(coef.beta0sq>0){\n info= paste(\"(-Infinity,\",lower.root,\"] union [\",upper.root,\",Infinity)\")\n ci[1, ]=c(-Inf, lower.root)\n ci<-rbind(ci, c(upper.root, Inf))\n }\n }\n } \n\n return(list(Fstat=Fstat, df=c(l, n-k-l), p.value=p.value,\n ci.info=info, ci=ci))\n}\n\n\nAR.power=function(n, k, l, beta, gamma, Zadj_sq, \n sigmau, sigmav, rho, alpha=0.05){\n if(length(gamma)!=ncol(as.matrix(Zadj_sq))|length(gamma)!=nrow(as.matrix(Zadj_sq))){\n\tprint(\"The dimension of Zadj_sq doesn't match gamma\")\n\tstop()\n }\n ncp=beta^2*n*c(t(as.matrix(gamma))%*%as.matrix(Zadj_sq)%*%as.matrix(gamma))/\n\t (sigmau^2+2*rho*sigmau*sigmav*beta+sigmav^2*beta^2) \n\n temp = qf(1-alpha, df1=l, df2=n-k-l)\n power = 1-pf(temp, df1=l, df2=n-k-l, ncp=ncp)\n\n return(power)\n}\n\nAR.size=function(power, k, l, beta, gamma, Zadj_sq, \n sigmau, sigmav, rho, alpha=0.05){\n if(length(gamma)!=ncol(as.matrix(Zadj_sq))|length(gamma)!=nrow(as.matrix(Zadj_sq))){\n print(\"The dimension of Zadj_sq doesn't match gamma\")\n\tstop()\n }\n ncp=beta^2*c(t(as.matrix(gamma))%*%as.matrix(Zadj_sq)%*%as.matrix(gamma))/\n\t (sigmau^2+2*rho*sigmau*sigmav*beta+sigmav^2*beta^2) \n\n oldn<-k+l+1\n state<-1\n while(state){\n temp = qf(1-alpha, df1=l, df2=oldn-k-l) \n temppower = 1-pf(temp, df1=l, df2=oldn-k-l, ncp=ncp*oldn) \n if(temppower < power){\n\t oldn <- oldn*2\n\t}else{\n\t state <- 0\n\t}\n }\n\n lower <- oldn%/%2\n upper <- oldn\n while((upper-lower)>2){\n new <- (upper+lower)%/%2\n temp = qf(1-alpha, df1=l, df2=oldn-k-l) \n temppower = 1-pf(temp, df1=l, df2=oldn-k-l, ncp=ncp*new) \n if(temppower < power){\n\t lower <- new\n\t}else{\n\t upper <- new\n\t}\n }\n\n return(upper)\n}\n", "meta": {"hexsha": "ef2c00d0eae2bbfbf43eec357f96a4a8e5c4decb", "size": 3905, "ext": "r", "lang": "R", "max_stars_repo_path": "R/AR.r", "max_stars_repo_name": "qingyuanzhao/ivmodel", "max_stars_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-09-22T13:38:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-23T02:04:23.000Z", "max_issues_repo_path": "R/AR.r", "max_issues_repo_name": "qingyuanzhao/ivmodel", "max_issues_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-09T19:20:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-01T13:44:24.000Z", "max_forks_repo_path": "R/AR.r", "max_forks_repo_name": "qingyuanzhao/ivmodel", "max_forks_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-01T16:33:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T16:33:38.000Z", "avg_line_length": 28.0935251799, "max_line_length": 113, "alphanum_fraction": 0.5907810499, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.625617894655459}} {"text": "#'## Compute CIs for prediction ratios\n#'### Functions for computing Ratio CIs \nFiellerRatioCI <- function(a, b, V, t)\n{\n theta <- a/b\n g <- (t^2)*V[2,2]/b^2\n se <- sqrt(V[1,1] - 2*theta*V[1,2] + theta^2 * V[2,2] - g*(V[1,1]-V[1,2]^2/V[2,2]))\n LCL <- (1/(1-g))*(theta- g*V[1,2]/V[2,2] - t/b * se)\n UCL <- (1/(1-g))*(theta- g*V[1,2]/V[2,2] + t/b * se)\n if (!is.na(UCL) & !is.na(LCL) & UCL < LCL) {\n UCL <- NA; LCL <- NA\n }\n return(list(pred.ratio=theta, upper.Confidence.limit = UCL, lower.Confidence.limit = LCL))\n}\n\nmakeContrastMatrix <- function(preds, indx, pairs.factor, first.level, second.level)\n{\n X <- model.matrix(~ Combinations-1, data = preds)\n ## Form the contrast matrix\n #Determine the columns of X for each contrast\n colsets <- split(colnames(X), preds[indx], lex.order = TRUE)\n prediv <- split(preds, preds[indx], lex.order = TRUE)\n locns <- lapply(colsets, \n function(x, cols = colnames(X)) \n { pair <- na.omit(match(x, cols)); names(pair) <- x; return(pair) })\n contr <- mapply(function(pred, cols, pairs.factor, first.level, second.level) \n {\n names(cols) <- gsub(\"Combinations\", \"\", names(cols), fixed = TRUE)\n # k1 <- (1:length(cols))[grepl(first.level, names(cols), fixed = TRUE)]\n # k2 <- (1:length(cols))[grepl(second.level, names(cols), fixed = TRUE)]\n k1 <- (1:length(cols))[pred[pairs.factor] == first.level]\n k2 <- (1:length(cols))[pred[pairs.factor] == second.level]\n\n if (any(c(length(k1),length(k2)) == 0)) #no contrast\n cols <- NA\n else\n {\n if (length(k1) != 1)\n stop(\"There is more than one observation with the level \", first.level, \" in combination \", names(cols))\n else\n {\n if (length(k2) != 1)\n stop(\"There is more than one observation with the level \", second.level, \" in combination \", names(cols))\n else\n {\n cols[1:length(cols)] <- 0\n cols[k1] <- 1\n cols[k2] <- -1\n }\n }\n }\n return(cols)\n }, prediv, locns, MoreArgs = list(pairs.factor = pairs.factor, \n first.level = first.level, second.level = second.level), \n SIMPLIFY = FALSE)\n \n \n #Substitute the contrast in one column and NA in the other for each contrast\n for (k in 1:length(locns))\n {\n for (j in 1:length(locns[[k]]))\n {\n X[locns[[k]][j], locns[[k]][1]] <- contr[[k]][j]\n if (j != 1)\n X[locns[[k]][j], locns[[k]][j]] <- 0\n }\n }\n \n #Form contrast matrix\n X <- X[, unlist(locns)[order(unlist(locns))]]\n which.cols <- unlist(lapply(1:ncol(X), \n function(k) \n {\n if (any(is.na(as.vector(X[,k])))) retain <- FALSE \n else retain <- !all(X[,k] == 0)\n }))\n L <- t(X[, which.cols])\n\n rownames(L) <- gsub(paste0(\"Combinations\"), \"\", rownames(L), fixed = TRUE)\n lev <- levels(preds[[pairs.factor]])[1]\n rownames(L) <- gsub(paste0(\",\",lev), \"\", rownames(L), fixed = TRUE)\n rownames(L) <- gsub(paste0(lev,\",\"), \"\", rownames(L), fixed = TRUE)\n return(L)\n}\n\nratioTransform.alldiffs <- function(alldiffs.obj, ratio.factor, \n numerator.levels, denominator.levels, \n method = \"Fieller\", alpha = 0.05, \n response = NULL, response.title = NULL, \n tables = \"predictions\", \n ...)\n{\n #Check that a valid object of class alldiffs\n validalldifs <- validAlldiffs(alldiffs.obj) \n if (is.character(validalldifs))\n stop(validalldifs)\n alldiffs.obj <- renameDiffsAttr(alldiffs.obj)\n \n \n meth.options <- c(\"Fieller\")\n method.opt <- meth.options[check.arg.values(method, meth.options)]\n options <- c(\"none\", \"predictions\", \"backtransforms\", \"vcov\", \n \"differences\", \"p.differences\", \"sed\", \"LSD\", \"all\")\n opt <- options[unlist(lapply(tables, check.arg.values, options=options))]\n\n #Get a t-value (use z if no tdf attribute)\n tdf <- attr(alldiffs.obj, which = \"tdf\")\n if (!is.null(tdf))\n {\n t <- qt(1 - alpha/2, df = tdf)\n } else\n t <- qnorm(1 - alpha/2)\n \n if (is.null(response))\n response <- attr(alldiffs.obj, which = \"response\")\n if (is.null(response.title))\n response.title <- attr(alldiffs.obj, which = \"response.title\")\n classify <- attr(alldiffs.obj, which = \"classify\")\n\n facs <- fac.getinTerm(classify, rmfunction = TRUE)\n alldiffs.obj <- renewClassify(alldiffs.obj, newclassify = classify) #make sure in standard order\n tmp <- alldiffs.obj$predictions\n tmp$Combinations <- dae::fac.combine(as.list(tmp[facs]), combine.levels = TRUE, sep = \",\")\n if (length(ratio.factor) != 1 | !(ratio.factor %in% facs))\n stop(\"ratio factor must specify a single factor that is in the classify attribute of the alldiffs object\")\n if (!all(c(numerator.levels, denominator.levels) %in% levels(tmp[[ratio.factor]])))\n stop(\"Not all numerator.levels and denominator.levels are levels in \", ratio.factor, \" in the alldiffs object\")\n sortFactor <- attr(alldiffs.obj, which = \"sortFactor\")\n \n indx <- setdiff(facs, ratio.factor)\n\n # if (length(indx) == 1)\n # {\n # ratios.dat <- as.data.frame(ratios.dat, row.names = NULL)\n # names(ratios.dat)[1] <- indx\n # }\n tmp <- split(tmp, tmp[indx], sep = \",\", lex.order = TRUE)\n Ratios <- lapply(denominator.levels, function(denom.lev,tmp, t) \n {\n lapply(numerator.levels, function(num.lev, denom.lev, tmp, t) \n { \n \n if (!(num.lev %in% alldiffs.obj$predictions[[ratio.factor]]) || \n !(denom.lev %in% alldiffs.obj$predictions[[ratio.factor]]) ||\n num.lev == denom.lev)\n ratioCIs <-NULL\n else\n {\n ratioCIs <- do.call(rbind, lapply(tmp, function(preds, num.lev, denom.lev, V, t)\n {\n indx.vals <- (lapply(preds[indx], function(x) as.character(x)[1])) #current levels of indx factors\n ratio.pair <- c(indx.vals, rep(NA,3))\n names(ratio.pair) <- c(indx, \"pred.ratio\", \"upper.Confidence.limit\", \"lower.Confidence.limit\")\n if (all(c(num.lev, denom.lev) %in% preds[[ratio.factor]]))\n {\n a <- preds[preds[ratio.factor] == num.lev, \"predicted.value\"]\n b <- preds[preds[ratio.factor] == denom.lev, \"predicted.value\"]\n labs <- preds$Combinations\n posns <- unlist(lapply(c(num.lev,denom.lev), grep, x =labs, fixed = TRUE))\n lab <- labs[posns]\n Vpair <- V[lab,lab]\n ratio.pair <- as.data.frame(c(indx.vals, (FiellerRatioCI(a, b, Vpair, t = t))))\n }\n return(ratio.pair)\n }, V = alldiffs.obj$vcov, num.lev = num.lev, denom.lev = denom.lev, t = t))\n \n rownames(ratioCIs) <- NULL\n names(ratioCIs)[match(\"pred.ratio\", names(ratioCIs))] <- \"predicted.value\"\n ratioCIs$standard.error <- NA\n ratioCIs$est.status <- \"Estimable\"\n ratio.names <- names(ratioCIs)\n n <- match(\"standard.error\", ratio.names)\n k <- match(\"upper.Confidence.limit\", ratio.names)\n if (n-k+1 != 3)\n stop(\"Standard.error and confidence limits not together in ratios data frame\")\n ratio.names[k:n] <- c(\"standard.error\", \"upper.Confidence.limit\", \"lower.Confidence.limit\")\n ratioCIs <- ratioCIs[ratio.names]\n ratioCIs[indx] <- lapply(indx, \n function(fac) new.fac <- factor(ratioCIs[[fac]], \n levels = levels(alldiffs.obj$predictions[[fac]])))\n ratioCIs <- as.predictions.frame(ratioCIs)\n class(ratioCIs) <- c(\"predictions.frame\", \"data.frame\")\n attr(ratioCIs, which = \"response\") <- response\n attr(ratioCIs, which = \"response.title\") <- response.title\n \n #sort the predictions.frame, if it was previously sorted\n if (!is.null(sortFactor))\n {\n if (sortFactor != ratio.factor)\n ratioCIs <- sort(ratioCIs, sortFactor = sortFactor, classify = paste(indx, collapse = \":\"),\n sortOrder = attr(alldiffs.obj, which = \"sortOrder\"))\n }\n }\n return(ratioCIs)\n }, tmp = tmp, denom.lev = denom.lev, t = t)\n }, tmp = tmp, t = t)\n Ratios <- unlist(Ratios, recursive = FALSE)\n nams <- outer(numerator.levels, denominator.levels, paste, sep = \",\")\n names(Ratios) <- nams\n \n \n if (\"predictions\" == opt)\n {\n cat(\"\\n\\n#### Table(s) of ratio predictions and confidence limits for \", response, \"\\n\\n\")\n print(Ratios)\n }\n invisible(Ratios) \n}\n \npairdiffsTransform.alldiffs <- function(alldiffs.obj, pairs.factor, first.levels, second.levels, \n Vmatrix = FALSE, \n error.intervals = \"Confidence\", \n avsed.tolerance = 0.25, accuracy.threshold = NA, \n LSDtype = \"overall\", LSDsupplied = NULL, LSDby = NULL, \n LSDstatistic = \"mean\", LSDaccuracy = \"maxAbsDeviation\", \n response = NULL, response.title = NULL, tables = \"all\", \n pairwise = TRUE, alpha = 0.05, ...)\n{\n #Check for deprecated argument meanLSD.type and warn\n tempcall <- list(...)\n if (length(tempcall)) \n if (\"meanLSD.type\" %in% names(tempcall))\n stop(\"meanLSD.type has been deprecated - use LSDtype\")\n\n #Check that a valid object of class alldiffs\n validalldifs <- validAlldiffs(alldiffs.obj) \n if (is.character(validalldifs))\n stop(validalldifs)\n alldiffs.obj <- renameDiffsAttr(alldiffs.obj)\n attr(alldiffs.obj, which = \"alpha\") <- alpha\n\n #get transform attributes from backtransforms\n transform.power = 1; offset <- 0; scale <- 1\n if (!is.null(alldiffs.obj$backtransforms))\n {\n transform.power = attr(alldiffs.obj$backtransforms, which = \"transform.power\")\n offset = attr(alldiffs.obj$backtransforms, which = \"offset\")\n scale = attr(alldiffs.obj$backtransforms, which = \"scale\")\n } \n \n sortFactor <- attr(alldiffs.obj, which = \"sortFactor\")\n \n int.options <- c(\"none\", \"Confidence\", \"StandardError\", \"halfLeastSignificant\")\n int.opt <- int.options[check.arg.values(error.intervals, int.options)]\n options <- c(\"none\", \"predictions\", \"backtransforms\", \"vcov\", \n \"differences\", \"p.differences\", \"sed\", \"LSD\", \"all\")\n opt <- options[unlist(lapply(tables, check.arg.values, options=options))]\n #Get a t-value (use z if no tdf attribute)\n tdf <- attr(alldiffs.obj, which = \"tdf\")\n if (!is.null(tdf))\n {\n t <- qt(1 - alpha/2, df = tdf)\n } else\n t <- qnorm(1 - alpha/2)\n \n if (is.null(response))\n response <- attr(alldiffs.obj, which = \"response\")\n if (is.null(response.title))\n response.title <- attr(alldiffs.obj, which = \"response.title\")\n classify <- attr(alldiffs.obj, which = \"classify\")\n facs <- fac.getinTerm(classify, rmfunction = TRUE)\n alldiffs.obj <- renewClassify(alldiffs.obj, newclassify = classify) #make sure in standard order\n tmp <- alldiffs.obj$predictions\n tmp$Combinations <- dae::fac.combine(as.list(tmp[facs]), combine.levels = TRUE, sep = \",\")\n if (length(pairs.factor) != 1 | !(pairs.factor %in% facs))\n stop(\"pairs factor must specify a single factor that is in the classify attribute of the alldiffs object\")\n if (!all(c(first.levels, second.levels) %in% levels(tmp[[pairs.factor]])))\n stop(\"Not all first.levels and second.levels are levels in \", pairs.factor, \" in the all diffs object\")\n \n indx <- setdiff(facs, pairs.factor)\n\n Diffs <- lapply(second.levels, function(second.lev,tmp) \n {\n lapply(first.levels, function(first.lev, second.lev, tmp) \n { \n \n if (!(first.lev %in% alldiffs.obj$predictions[[pairs.factor]]) || \n !(second.lev %in% alldiffs.obj$predictions[[pairs.factor]]))\n diffs <-NULL\n else\n {\n L <- makeContrastMatrix(tmp, indx = indx, pairs.factor = pairs.factor, first.lev, second.lev)\n\n #form the factors indexing the pair-difference predictions\n new.facs <- lapply(indx, function(fac, data)\n {\n levels(tmp[[fac]])\n }, data = tmp)\n names(new.facs) <- indx\n if (length(indx) == 1)\n {\n pairs.dat <- as.data.frame(rownames(L), stringsAsFactors = FALSE)\n names(pairs.dat) <- indx\n pairs.dat[indx] <- factor(pairs.dat[[indx]], levels = rownames(L))\n }\n else\n pairs.dat <- dae::fac.uncombine(rownames(L), new.factors = new.facs, sep = \",\")\n \n \n #Calculate the differences for the current pair\n diffs <- linTransform(alldiffs.obj, classify = classify, \n linear.transformation = L, Vmatrix = Vmatrix, \n error.intervals = \"Confidence\",\n avsed.tolerance = avsed.tolerance, accuracy.threshold = accuracy.threshold, \n response = response, response.title = response.title, \n pairwise = pairwise, alpha = alpha, \n tables = \"none\", ...)\n diffs$predictions <- cbind(pairs.dat, diffs$predictions)\n diffs$predictions <- diffs$predictions[, -match(\"Combination\", names(diffs$predictions))]\n diffs <- renewClassify(diffs, newclassify = paste(indx, collapse = \":\"))\n diffs <- redoErrorIntervals(diffs, error.intervals = int.opt, alpha = alpha, \n avsed.tolerance = avsed.tolerance, accuracy.threshold = accuracy.threshold, \n LSDtype = LSDtype, LSDby = LSDby, LSDsupplied = LSDsupplied, \n LSDstatistic = LSDstatistic, LSDaccuracy = LSDaccuracy)\n # if (!is.null(diffs$backtransforms))\n # {\n # diffs$backtransforms <- cbind(pairs.dat, diffs$backtransforms)\n # diffs$backtransforms <- diffs$backtransforms[, -match(\"Combination\", names(diffs$backtransforms))]\n # #Find missing attributes in new alldiffs.obj and add them back in \n # newattr <- attributes(diffs$backtransforms)\n # back.attr <- attributes(alldiffs.obj$backtransforms)\n # back.attr <- back.attr[names(back.attr)[!(names(back.attr) %in% names(newattr))]]\n # if (length(back.attr) > 0)\n # {\n # newattr <- c(newattr,back.attr)\n # attributes(diffs$backtransforms) <- newattr\n # }\n # }\n \n #sort the alldiffs if it was previously sorted\n if (!is.null(sortFactor))\n {\n if (sortFactor != pairs.factor)\n diffs <- sort(diffs, sortFactor = sortFactor,\n sortOrder = attr(diffs, which = \"sortOrder\"))\n }\n \n if (opt != \"none\")\n print(diffs, which = opt)\n return(diffs)\n }\n }, tmp = tmp, second.lev = second.lev)\n }, tmp = tmp)\n Diffs <- unlist(Diffs, recursive = FALSE)\n nams <- outer(first.levels, second.levels, paste, sep = \",\")\n names(Diffs) <- nams\n invisible(Diffs) \n}\n", "meta": {"hexsha": "0a53b40be7e69a0d32ce6388458ffda5b07448b0", "size": 15273, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pairTrans.r", "max_stars_repo_name": "briencj/asremlPlus", "max_stars_repo_head_hexsha": "108fb4d50e644fa4c46c8265ac9c1583ce10c2d5", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2018-05-14T19:51:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:18:38.000Z", "max_issues_repo_path": "R/pairTrans.r", "max_issues_repo_name": "briencj/asremlPlus", "max_issues_repo_head_hexsha": "108fb4d50e644fa4c46c8265ac9c1583ce10c2d5", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-04T02:01:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T10:17:23.000Z", "max_forks_repo_path": "R/pairTrans.r", "max_forks_repo_name": "briencj/asremlPlus", "max_forks_repo_head_hexsha": "108fb4d50e644fa4c46c8265ac9c1583ce10c2d5", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-04-23T08:49:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T11:31:27.000Z", "avg_line_length": 43.7621776504, "max_line_length": 116, "alphanum_fraction": 0.5708767105, "num_tokens": 4059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6253987032167668}} {"text": "#' Build a Link-path Incidence Matrix\r\n#'\r\n#' This function builds a link-path incidence matrix, in which feasible routes are determined using stochastic network loading based on user-specified link costs. The routes are based on a probit model, implemented via simulation.\r\n#' @param Links For a network with N nodes, Links is an NxN matrix. The i,j entry of Links is the link number (ID) for the node connecting node i to node j. Entries should be set to NA if there is no link between the node pair in question.\r\n#' @param Costs A 2-column matrix, the first column of which is the link number (ID) and the second the link travel cost. Costs should be strictly positive.\r\n#' @param theta Standard deviation of link costs when apply probit-based stochastic network loading to identify routes. Can be vector of length equal to the number of links, or a scalar (which is then replicated if necessary). Default value is theta=0, so that only shortest paths between OD pairs are generated.\r\n#' @param nsim Number of simulation runs to find routes. In each run, link costs are modified by adding normal error, and the shortest paths computed with respect to these modified costs. nsim defaults to 100.\r\n#' @param orig Set of nodes specified as possible origins of travel. Defaults to all nodes for which there is at least one feasible route to another node.\r\n#' @param dest Set of nodes specified as possible destinations of travel. Defaults to all nodes that are reachable from elsewere by a feasible path.\r\n#' @return A list containing the link-path incidence matrix A, a vector O specifying the origin for each path, and a vector D specifying the destination for each path.\r\n#' @keywords link-path incidence matrix\r\n#' @export\r\n#' @examples\r\n#' Links <- matrix(0,nrow=9, ncol=9)\r\n#' Links[1,7] <- 1\r\n#' Links[2,7] <- 2\r\n#' Links[1,5] <- 3\r\n#' Links[7,8] <- 4\r\n#' Links[2,6] <- 5\r\n#' Links[5,8] <- 6\r\n#' Links[8,5] <- 7\r\n#' Links[8,6] <- 8\r\n#' Links[6,8] <- 9\r\n#' Links[5,3] <- 10\r\n#' Links[8,9] <- 11\r\n#' Links[6,4] <- 12\r\n#' Links[9,3] <- 13\r\n#' Links[9,4] <- 14\r\n#' Costs <- cbind(1:14,rep(1,14))\r\n#' buildA(Links,Costs)\r\n#' buildA(links,Costs,theta=0.4,orig=c(1,2),dest=c(3,4))\r\n\r\nbuildA <- function(Links,Costs,theta=0,nsim=100,orig=NA,dest=NA){\r\n\trequire(e1071)\r\n\tr <- nrow(Links)\r\n\tn <- nrow(Costs)\r\n\tA <- D <- O <- numeric(0)\r\n\tX <- Links*NA\r\n\ttheta <- rep(theta,length.out=n)\r\n\tif (is.na(orig[1])) orig <- 1:r\r\n\tif (is.na(dest[1])) dest <- 1:r\r\n\tif (theta[1] <= 0) nsim <- 1\r\n\tfor (i in 1:nsim){\r\n\t\tfor ( i in Costs[,1]){\r\n\t\t\tX[Links==Costs[i,1]] <- Costs[i,2] + rnorm(1,sd=theta[i])\r\n\t\t}\r\n\t\tX[X<0] <- 1e-6\t\t\r\n\t\tSP <- allShortestPaths(X)\r\n\t\tfor (o in orig){\r\n\t\t\tfor (d in dest){\r\n\t\t\t\tif (o!=d){\r\n\t\t\t\t\tif(!is.na(SP$length[o,d])){\r\n\t\t\t\t\t\tp <- extractPath(SP,o,d)\r\n\t\t\t\t\t\ta <- rep(0,n)\r\n\t\t\t\t\t\tfor (j in 1:(length(p)-1) ){\r\n\t\t\t\t\t\t\tlink <- Links[p[j],p[j+1]]\r\n\t\t\t\t\t\t\ta[link] <- 1\r\n\t\t\t\t\t\t}\t\t\r\n\t\t\t\t\t\tA <- cbind(A,a)\r\n\t\t\t\t\t\tO <- c(O,o)\r\n\t\t\t\t\t\tD <- c(D,d)\r\n\t\t\t\t\t}\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tindx <- duplicated(A,MARGIN=2)\r\n\tA <- A[,!indx]\r\n\tO <- O[!indx]\r\n\tD <- D[!indx]\r\n\tindx <- order(O,D)\r\n\tA <- A[,indx]\r\n\tO <- O[indx]\r\n\tD <- D[indx]\r\n\tlist(A=unname(A),O=O,D=D)\r\n}", "meta": {"hexsha": "e94c61bd9df64c406c081fd4e547773a5ec26d12", "size": 3163, "ext": "r", "lang": "R", "max_stars_repo_path": "R/buildA.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/buildA.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/buildA.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6184210526, "max_line_length": 313, "alphanum_fraction": 0.6367372747, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6250863611665234}} {"text": "\n#' Create spline curve and calculate 1st derivative\n#'\n#' @param YValues\n#' @param XValues\n#' @param xlabel\n#' @param ylabel\n#' @param mainlabel\n#' @param ylim\n#'\n#' @return plot\n#'\n#' @examples\nSplineCurveAndDerivative <- function(YValues, XValues,xlabel=\"x\",ylabel=\"y\",mainlabel=\"main\",ylim=c(-0.5,0.5)){\n if(length(YValues)!=length(XValues)){\n stop(\"Number of elements in maturity and discount margin must be the same\")\n }\n\n #spline\n\n spl <- smooth.spline(YValues~ XValues,all.knots = TRUE)\n par(mfrow=c(2,1))\n\n plot(spl,ylab = ylabel ,xaxt='n',xlab = xlabel,main = mainlabel)\n graphics::abline(h = 0, lty = 2)\n splData <- seq(min(XValues),max(XValues),(max(XValues)-min(XValues))/500)\n sx <- seq(from=head(XValues,1),to = tail(XValues,1),by = (tail(XValues,1)-head(XValues,1))/1000)\n lines(predict(spl,as.numeric(sx)))\n if(class(XValues) == \"Date\" || class(XValues)==\"POSIXt\"){\n axis.Date(side = 1,XValues,format = '%m/%Y',labels = T,at=XValues,las=2)\n }\n pred.prime<-predict(spl,as.numeric(sx),deriv=1)\n d1 <- data.frame(pred.prime)\n plot(d1,type = \"l\",xaxt='n',xlab=xlabel,ylab=\"derivative\",ylim = ylim)\n graphics::abline(h = 0, lty = 2)\n if(class(XValues) == \"Date\"){\n axis.Date(side=1,sx,format = \"%m/%Y\",labels = T,at =XValues,las=2)\n }\n par(mfrow=c(1,1))\n recordedPlot =recordPlot()\n return(recordedPlot)\n\n}\n", "meta": {"hexsha": "aac99544e9f332ede030012107a67b39a2b9532d", "size": 1349, "ext": "r", "lang": "R", "max_stars_repo_path": "R/splineCurve.r", "max_stars_repo_name": "nizuoiuh/AnalysisPKG", "max_stars_repo_head_hexsha": "da3e39725df2a31a291976e899ac5edb1e71a61a", "max_stars_repo_licenses": ["MIT"], "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/splineCurve.r", "max_issues_repo_name": "nizuoiuh/AnalysisPKG", "max_issues_repo_head_hexsha": "da3e39725df2a31a291976e899ac5edb1e71a61a", "max_issues_repo_licenses": ["MIT"], "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/splineCurve.r", "max_forks_repo_name": "nizuoiuh/AnalysisPKG", "max_forks_repo_head_hexsha": "da3e39725df2a31a291976e899ac5edb1e71a61a", "max_forks_repo_licenses": ["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.6590909091, "max_line_length": 111, "alphanum_fraction": 0.6567828021, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6250300272018429}} {"text": "#' Function that carries out a sinusoidal regression\n#' \n#' Fits a sinusoid through data provided as an \\code{x} and \\code{y} \n#' vector and returns a list containing both the fitted curve and the\n#' parameters of that curve.\n#' Used to produce initial values for modeling data windows and later\n#' to find peaks in modeled julian day values to align the result to\n#' a cumulative age timeline.\n#' \n#' @param x Vector of \\code{x} values of input data\n#' @param y Vector of \\code{y} values of input data\n#' @param fixed_period Optional variable for fixing the period of the sinusoid \n#' in the depth domain. Defaults to \\code{NA}, period is not fixed. Supply a \n#' single value to fix the period.\n#' @param plot Should the fitting result be plotted? \\code{TRUE/FALSE}\n#' @return A list containing a vector of parameters of the fitted sinusoid\n#' and the fitted values belonging to each \\code{x} value.\n#' Fitting parameters:\n#' \\code{I} = the mean annual value of the sinusoid (height)\n#' \\code{A} = the amplitude of the sinusoid\n#' \\code{Dper} = the period of the sinusoid in \\code{x} domain\n#' \\code{peak} = the location of the peak in the sinusoid\n#' \\code{R2adj} = the adjusted \\code{R^2} value of the fit\n#' \\code{p} = the p-value of the fit\n#' @examples\n#' # Create dummy data\n#' x <- seq(1000, 11000, 1000)\n#' y <- sin((2 * pi * (seq(1, 11, 1) - 8 + 7 / 4)) / 7)\n#' sinlist <- sinreg(x, y, plot = FALSE) # Run the function\n#' @export\nsinreg <- function(x, # Function to perform sinusoid regression meant to estimate the starting parameters for fitting growth and temperature sinusoids\n y,\n fixed_period = NA, # Option to fix the period in depth domain. Default = NA (Period not fixed)\n plot = FALSE # Plot results?\n ){\n\n if(is.na(fixed_period)){ # If period is not fixed, run simple periodogram to find the most likely period\n Ots <- ts(y) # Turn y into a time series\n ssp <- spectrum(Ots, plot = FALSE) # Create periodogram of y\n Nper <- 1/ssp$freq[ssp$spec==max(ssp$spec)] # Estimate period in terms of sample number\n Dper <- Nper * diff(range(x))/length(x) # Convert period to depth domain\n }else if(is.numeric(fixed_period) & length(fixed_period) == 1){ # Check if a valid entry is provided for Dper\n Dper <- fixed_period\n }else{\n stop(\"ERROR: Supplied value for fixed period is not recognized\")\n }\n\n sinlm <- lm(y ~ sin(2*pi/Dper*x)+cos(2*pi/Dper*x)) # Run linear model, cutting up d18O = Asin(2*pi*D) into d18O = asin(D)+bcos(D)\n sinm<-sinlm$fitted # Extract model result\n if(plot == TRUE){\n dev.new()\n plot(x, y); lines(x, sinm, col = \"red\")\n }\n\n coeff<-summary(sinlm)[[\"coefficients\"]] # Extract a, b and intercept + uncertainties\n\n # Calculate coefficients of the form d18O = I + Asin(2*pi*D + p)\n I<-coeff[1,1] # Intercept (mean annual value)\n A<-sqrt(coeff[2,1]^2+coeff[3,1]^2) # Amplitude of seasonality\n phase<--acos(coeff[2,1]/A) # Phase of sinusoid\n peak<-(0.25+(phase/(2*pi))) * Dper # timing of seasonal peak\n R2adj<-summary(sinlm)$adj.r.squared # Goodness of model fit (adjusted R2)\n p <- as.numeric(pf(summary(sinlm)$fstatistic[1],summary(sinlm)$fstatistic[2],summary(sinlm)$fstatistic[3],lower.tail=F)) # p-value of model\n\n return(list(c(I,A,Dper,peak,R2adj,p),sinm)) # Return results of regression\n}", "meta": {"hexsha": "c86e46867b1dcd50545e7321d0c45ecd6206d793", "size": 3345, "ext": "r", "lang": "R", "max_stars_repo_path": "R/sinreg.r", "max_stars_repo_name": "nhoeche/ShellChron.jl", "max_stars_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/sinreg.r", "max_issues_repo_name": "nhoeche/ShellChron.jl", "max_issues_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/sinreg.r", "max_forks_repo_name": "nhoeche/ShellChron.jl", "max_forks_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6818181818, "max_line_length": 150, "alphanum_fraction": 0.6762331839, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6250232146838622}} {"text": "## Author: Sergio García Prado\n## Title: Statistical Inference - Goodness of Fit - Exercise 18\n\n\nrm(list = ls())\n\nobserved <- c(0.59, 0.72, 0.47, 0.44, 0.31, 0.56, 0.22, 0.90, 0.96, 0.78, 0.66, 0.18, 0.73, 0.43, 0.58, 0.11)\n\ntest <- ks.test(observed, punif)\n\n(pvalue <- test$p.value)\n# 0.614776160341058\n", "meta": {"hexsha": "56acf615073344abc46465fd91a120ed54b82031", "size": 304, "ext": "r", "lang": "R", "max_stars_repo_path": "statistical-inference/goodness-of-fit/exercise-18.r", "max_stars_repo_name": "garciparedes/r-examples", "max_stars_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T19:56:31.000Z", "max_issues_repo_path": "statistical-inference/goodness-of-fit/exercise-18.r", "max_issues_repo_name": "garciparedes/r-examples", "max_issues_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-03-23T09:34:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-09T14:13:32.000Z", "max_forks_repo_path": "statistical-inference/goodness-of-fit/exercise-18.r", "max_forks_repo_name": "garciparedes/r-examples", "max_forks_repo_head_hexsha": "0e0e18439ad859f97eafb27c5e7f77d33da28bc6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3846153846, "max_line_length": 109, "alphanum_fraction": 0.6282894737, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6249809112555696}} {"text": "## Indicator Library\n\nEMA <- function(starttime, endtime, duration, symbol, env,datatype){\n if (starttime == endtime){\n return(SMA(starttime, duration, symbol, env, datatype)) #### Change when SMA function is written\n }\n else{\n timeweight = 2/(duration +1)\n EMAval = (env[[datatype]][[\"CLOSE\"]][currtime] - \n EMA(starttime - 1, endtime, duration, symbol, env,datatype))*timeweight +\n EMA(starttime - 1, endtime, duration, symbol, env,datatype)\n return (EMAval)\n }\n}\n\nMACD <- function(starttime, endtime1, endtime2, endtime3, duration1, duration2, duration3, symbol, env,datatype){\n MACDval = EMA(starttime, endtime1, duration1, symbol, env, datatype) -\n EMA(starttime, endtime2, duration2, symbol, env, datatype)\n signalval = EMA(starttime, endtime3, duration3, symbol, env, datatype)\n return (MACDval - signalval)\n}", "meta": {"hexsha": "57ac2ff31a4c232748097605052a34e33991459e", "size": 876, "ext": "r", "lang": "R", "max_stars_repo_path": "Indicator_lib.r", "max_stars_repo_name": "yuwu10112358/APS490RBCCM", "max_stars_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Indicator_lib.r", "max_issues_repo_name": "yuwu10112358/APS490RBCCM", "max_issues_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Indicator_lib.r", "max_forks_repo_name": "yuwu10112358/APS490RBCCM", "max_forks_repo_head_hexsha": "391617f719a5099b302df34406a7c1dffc40babb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7142857143, "max_line_length": 113, "alphanum_fraction": 0.6735159817, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6248922499234238}} {"text": "l0 <- 15 # length going at sea\nl.inf <- c(100, 110) # theoritical max length, different by country\nk <- .5 # yearly growth rate start\nk.year <- k * (1 - .01 * 0:(year.end - year.start))# growth rate decreasing with year\nsd.length <- 5 # var around mean\nt0 <- -.91 # parameter shifting von bertalanffy growth curve\n\n# mean length faben version von bertqlanffy growth model\nmean.length <- l0 +\n (l.inf[as.numeric(as.factor(salmons$country))] - l0) *\n (1 - \n exp(- k.year[salmons$year - min(salmons$year) + 1] * \n (salmons$sea.age - t0))) \n\nhist(mean.length)\n\n# add gamma noise\nlength <- rgamma(n = dim(salmons)[1],\n shape = (mean.length / sd.length) ^ 2,\n scale = (sd.length ^ 2) / mean.length) \nhist(length)\nmin(length)\nsalmons$length <- round(length, 1)\n# add noise with normal and coeffcient of variation\n#length <- rnorm(n = dim(salmons)[1], mean = mean.length, sd = mean.length * .1) \n#length <- round(length, 1)\n#hist(length)", "meta": {"hexsha": "adc4c8e2ae5c8ef19bbb1e84e892ebda1b4c7820", "size": 977, "ext": "r", "lang": "R", "max_stars_repo_path": "2.data/2.salmon/growth.r", "max_stars_repo_name": "GuillaumeBal/r.training.mnhn", "max_stars_repo_head_hexsha": "45d86ad46f53d60fe63c6f1c4f5f048ab1526687", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2.data/2.salmon/growth.r", "max_issues_repo_name": "GuillaumeBal/r.training.mnhn", "max_issues_repo_head_hexsha": "45d86ad46f53d60fe63c6f1c4f5f048ab1526687", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2.data/2.salmon/growth.r", "max_forks_repo_name": "GuillaumeBal/r.training.mnhn", "max_forks_repo_head_hexsha": "45d86ad46f53d60fe63c6f1c4f5f048ab1526687", "max_forks_repo_licenses": ["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.1851851852, "max_line_length": 85, "alphanum_fraction": 0.6376663255, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.6248922324627398}} {"text": "library(dplyr)\nlibrary(tidyr)\nlibrary(ggplot2)\nlibrary(ascii)\nlibrary(lubridate)\nlibrary(ellipse)\nlibrary(mclust)\nlibrary(cluster)\n\n\n###############################################################\n## Import datasets needed for chapter 7\nPSDS_PATH <- file.path('~', 'statistics-for-data-scientists')\n\nsp500_px <- read.csv(file.path(PSDS_PATH, 'data', 'sp500_px.csv'), row.names = 1)\nsp500_sym <- read.csv(file.path(PSDS_PATH, 'data', 'sp500_sym.csv'), stringsAsFactors = FALSE)\nloan_data <- read.csv(file.path(PSDS_PATH, 'data', 'loan_data.csv'))\nloan_data$outcome <- ordered(loan_data$outcome, levels=c('paid off', 'default'))\n\n###############################################################\n## PCA for oil data\noil_px = as.data.frame(scale(oil_px, scale=FALSE))\noil_px <- sp500_px[, c('CVX', 'XOM')]\npca <- princomp(oil_px)\npca$loadings\n\n## Figure 7-1: principal components for oil stock data\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0701.png'), width = 4, height=4, units='in', res=300)\nloadings <- pca$loadings\nggplot(data=oil_px, aes(x=CVX, y=XOM)) +\n geom_point(alpha=.3) +\n scale_shape_manual(values=c(46)) +\n stat_ellipse(type='norm', level=.99, color='grey25') +\n geom_abline(intercept = 0, slope = loadings[2,1]/loadings[1,1], color='grey25', linetype=2) +\n geom_abline(intercept = 0, slope = loadings[2,2]/loadings[1,2], color='grey25', linetype=2) +\n scale_x_continuous(expand=c(0,0), lim=c(-3, 3)) + \n scale_y_continuous(expand=c(0,0), lim=c(-3, 3)) +\n theme_bw()\n\ndev.off()\n\n\n\n## Figure 7-2: screeplot \npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0702.png'), width = 4, height=4, units='in', res=300)\n\nsyms <- c( 'AAPL', 'MSFT', 'CSCO', 'INTC', 'CVX', 'XOM', 'SLB', 'COP',\n 'JPM', 'WFC', 'USB', 'AXP', 'WMT', 'TGT', 'HD', 'COST')\ntop_cons <- sp500_px[row.names(sp500_px)>='2011-01-01', syms]\nsp_pca <- princomp(top_cons)\npar(mar=c(6,3,0,0)+.1, las=2)\nscreeplot(sp_pca, main='')\n\ndev.off()\n\n## Loadings for stock data\nloadings = sp_pca$loadings[,1:5]\nloadings <- as.data.frame(loadings)\nloadings$Symbol <- row.names(loadings)\nloadings <- gather(loadings, \"Component\", \"Weight\", -Symbol)\nhead(loadings)\n\n## Figure 7-3: Plot of component loadings\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0703.png'), width = 4, height=4, units='in', res=300)\n\nloadings$Color = loadings$Weight > 0\nggplot(loadings, aes(x=Symbol, y=Weight, fill=Color)) +\n geom_bar(stat='identity', position = \"identity\", width=.75) + \n facet_grid(Component ~ ., scales='free_y') +\n guides(fill=FALSE) +\n ylab('Component Loading') +\n theme_bw() +\n theme(axis.title.x = element_blank(),\n axis.text.x = element_text(angle=90, vjust=0.5))\n\ndev.off()\n\n\n###############################################################\n## K-means chapter\n\nset.seed(1010103)\ndf <- sp500_px[row.names(sp500_px)>='2011-01-01', c('XOM', 'CVX')]\nkm <- kmeans(df, centers=4, nstart=1)\n\ndf$cluster <- factor(km$cluster)\nhead(df)\n\ncenters <- data.frame(cluster=factor(1:4), km$centers)\ncenters\n\n## Figure 7-4: K-means clusters for two stocks\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0704.png'), width = 4, height=3, units='in', res=300)\n\nggplot(data=df, aes(x=XOM, y=CVX, color=cluster, shape=cluster)) +\n geom_point(alpha=.3) +\n scale_shape_manual(values = 1:4,\n guide = guide_legend(override.aes=aes(size=1))) + \n geom_point(data=centers, aes(x=XOM, y=CVX), size=2, stroke=2) +\n theme_bw() +\n scale_x_continuous(expand=c(0,0), lim=c(-2, 2)) + \n scale_y_continuous(expand=c(0,0), lim=c(-2.5, 2.5)) \n\ndev.off()\n\n\n## cluster means algorithm\nsyms <- c( 'AAPL', 'MSFT', 'CSCO', 'INTC', 'CVX', 'XOM', 'SLB', 'COP',\n 'JPM', 'WFC', 'USB', 'AXP', 'WMT', 'TGT', 'HD', 'COST')\ndf <- sp500_px[row.names(sp500_px)>='2011-01-01', syms]\n\nset.seed(10010)\nkm <- kmeans(df, centers=5, nstart=10)\nkm$size\ncenters <- km$centers\n\n#centers <- scale(scale(centers, center=FALSE, scale=1/attr(df, 'scaled:scale')),\n# center=-attr(df, 'scaled:center'), scale=FALSE)\n\n## Figure 7-5 interpreting the clusters\ncenters <- as.data.frame(t(centers))\nnames(centers) <- paste(\"Cluster\", 1:5)\ncenters$Symbol <- row.names(centers)\ncenters <- gather(centers, \"Cluster\", \"Mean\", -Symbol)\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0705.png'), width = 4, height=5, units='in', res=300)\n\ncenters$Color = centers$Mean > 0\nggplot(centers, aes(x=Symbol, y=Mean, fill=Color)) +\n geom_bar(stat='identity', position = \"identity\", width=.75) + \n facet_grid(Cluster ~ ., scales='free_y') +\n guides(fill=FALSE) +\n ylab('Component Loading') +\n theme_bw() +\n theme(axis.title.x = element_blank(),\n axis.text.x = element_text(angle=90, vjust=0.5))\n\ndev.off()\n\n## Figure 7-6: selecting the number of clusters (elbow plot)\npct_var <- data.frame(pct_var = 0,\n num_clusters=2:14)\ntotalss <- kmeans(df, centers=14, nstart=50, iter.max = 100)$totss\nfor(i in 2:14){\n pct_var[i-1, 'pct_var'] <- kmeans(df, centers=i, nstart=50, iter.max = 100)$betweenss/totalss\n}\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0706.png'), width = 4, height=3, units='in', res=300)\n\nggplot(pct_var, aes(x=num_clusters, y=pct_var)) +\n geom_line() +\n geom_point() +\n labs(y='% Variance Explained', x='Number of Clusters') +\n scale_x_continuous(breaks=seq(2, 14, by=2)) +\n theme_bw()\ndev.off()\n\n\n################################################################\n## hclust chapter\n\nsyms1 <- c('GOOGL', 'AMZN', 'AAPL', 'MSFT', 'CSCO', 'INTC', 'CVX', \n 'XOM', 'SLB', 'COP', 'JPM', 'WFC', 'USB', 'AXP',\n 'WMT', 'TGT', 'HD', 'COST')\n\ndf <- sp500_px[row.names(sp500_px)>='2011-01-01', syms1]\nd <- dist(t(df))\nhcl <- hclust(d)\n\n## Figure 7-7: dendograme of stock data\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0707.png'), width = 4, height=4, units='in', res=300)\n\npar(cex=.75, mar=c(0, 5, 0, 0)+.1)\nplot(hcl, ylab='distance', xlab='', sub='', main='')\n\ndev.off()\n\n## Figure 7-8: comparison of the different measuresof dissimilarity\ncluster_fun <- function(df, method)\n{\n d <- dist(df)\n hcl <- hclust(d, method=method)\n tree <- cutree(hcl, k=4)\n df$cluster <- factor(tree)\n df$method <- method\n return(df)\n}\n\ndf0 <- sp500_px[row.names(sp500_px)>='2011-01-01', c('XOM', 'CVX')]\ndf <- rbind(cluster_fun(df0, method='single'),\n cluster_fun(df0, method='average'),\n cluster_fun(df0, method='complete'),\n cluster_fun(df0, method='ward.D'))\ndf$method <- ordered(df$method, c('single', 'average', 'complete', 'ward.D'))\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0708.png'), width = 5.5, height=4, units='in', res=300)\n\nggplot(data=df, aes(x=XOM, y=CVX, color=cluster, shape=cluster)) +\n geom_point(alpha=.3) +\n scale_shape_manual(values = c(46, 3, 1, 4),\n guide = guide_legend(override.aes=aes(size=2))) +\n facet_wrap( ~ method) +\n theme_bw()\n\ndev.off()\n\n\n\n###############################################################\n# Model-based clusting\n# Multivariate normal\n\nmu <- c(.5, -.5)\nsigma <- matrix(c(1, 1, 1, 2), nrow=2)\nprob <- c(.5, .75, .95, .99) ## or whatever you want\nnames(prob) <- prob ## to get id column in result\nx <- NULL\nfor (p in prob){\n x <- rbind(x, ellipse(x=sigma, centre=mu, level=p))\n}\ndf <- data.frame(x, prob=factor(rep(prob, rep(100, length(prob)))))\nnames(df) <- c(\"X\", \"Y\", \"Prob\")\n\n## Figure 7-9: Multivariate normal ellipses\ndfmu <- data.frame(X=mu[1], Y=mu[2])\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0709.png'), width = 4, height=4, units='in', res=300)\n\nggplot(df, aes(X, Y)) + \n geom_path(aes(linetype=Prob)) +\n geom_point(data=dfmu, aes(X, Y), size=3) +\n theme_bw()\n\ndev.off()\n\n## Figure 7-10 mclust applied XOM and CVX\n\ndf <- sp500_px[row.names(sp500_px)>='2011-01-01', c('XOM', 'CVX')]\nmcl <- Mclust(df)\nsummary(mcl)\n\ncluster <- factor(predict(mcl)$classification)\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0710.png'), width = 5, height=4, units='in', res=300)\n\nggplot(data=df, aes(x=XOM, y=CVX, color=cluster, shape=cluster)) +\n geom_point(alpha=.8) +\n theme_bw() +\n scale_shape_manual(values = c(46, 3),\n guide = guide_legend(override.aes=aes(size=2))) \n\ndev.off()\n\nsummary(mcl, parameters=TRUE)$mean\nsummary(mcl, parameters=TRUE)$variance\n\n## Figure 7-11: BIC scores for the different models fit by mclust\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0711.png'), width = 4, height=4, units='in', res=300)\n\npar(mar=c(4, 5, 0, 0)+.1)\nplot(mcl, what='BIC', ask=FALSE, cex=.75)\n\ndev.off()\n#\n\n#######################################################################\n# Scaling chapter\n\ndefaults <- loan_data[loan_data$outcome=='default',]\ndf <- defaults[, c('loan_amnt', 'annual_inc', 'revol_bal', 'open_acc', 'dti', 'revol_util')]\nkm <- kmeans(df, centers=4, nstart=10)\ncenters <- data.frame(size=km$size, km$centers) \nround(centers, digits=2)\n\ndf0 <- scale(df)\nkm0 <- kmeans(df0, centers=4, nstart=10)\ncenters0 <- scale(km0$centers, center=FALSE, scale=1/attr(df0, 'scaled:scale'))\ncenters0 <- scale(centers0, center=-attr(df0, 'scaled:center'), scale=FALSE)\ncenters0 <- data.frame(size=km0$size, centers0) \nround(centers0, digits=2)\n\nkm <- kmeans(df, centers=4, nstart=10)\ncenters <- data.frame(size=km$size, km$centers) \nround(centers, digits=2)\n\n\n## Figure 7-12: screeplot for data with dominant variables\n\nsyms <- c('GOOGL', 'AMZN', 'AAPL', 'MSFT', 'CSCO', 'INTC', 'CVX', 'XOM', \n 'SLB', 'COP', 'JPM', 'WFC', 'USB', 'AXP', 'WMT', 'TGT', 'HD', 'COST')\ntop_15 <- sp500_px[row.names(sp500_px)>='2011-01-01', syms]\nsp_pca1 <- princomp(top_15)\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0712.png'), width = 4, height=4, units='in', res=300)\n\npar(mar=c(6,3,0,0)+.1, las=2)\nscreeplot(sp_pca1, main='')\n\ndev.off()\n\nround(sp_pca1$loadings[,1:2], 3)\n\n#\n###############################################################\n## Figure 7-13: Categorical data and Gower's distance\n\nx <- loan_data[1:5, c('dti', 'payment_inc_ratio', 'home_', 'purpose_')]\nx\n\ndaisy(x, metric='gower')\n\nset.seed(301)\ndf <- loan_data[sample(nrow(loan_data), 250),\n c('dti', 'payment_inc_ratio', 'home_', 'purpose_')]\nd = daisy(df, metric='gower')\nhcl <- hclust(d)\ndnd <- as.dendrogram(hcl)\n\npng(filename=file.path(PSDS_PATH, 'figures', 'psds_0713.png'), width = 4, height=4, units='in', res=300)\npar(mar=c(0,5,0,0)+.1)\nplot(dnd, leaflab='none', ylab='distance')\ndev.off()\n\ndnd_cut <- cut(dnd, h=.5)\ndf[labels(dnd_cut$lower[[1]]),]\n\n\n## Problems in clustering with mixed data types\ndf <- model.matrix(~ -1 + dti + payment_inc_ratio + home_ + pub_rec_zero, data=defaults)\ndf0 <- scale(df)\nkm0 <- kmeans(df0, centers=4, nstart=10)\ncenters0 <- scale(km0$centers, center=FALSE, scale=1/attr(df0, 'scaled:scale'))\nround(scale(centers0, center=-attr(df0, 'scaled:center'), scale=FALSE), 2)\n", "meta": {"hexsha": "489040b79f7b42d3d5cd8bb60cfa9c5274e886d8", "size": 10805, "ext": "r", "lang": "R", "max_stars_repo_path": "references/statistics-for-data-scientists/src/chapter7.r", "max_stars_repo_name": "ronsims2/data_science_tutorials", "max_stars_repo_head_hexsha": "ce245eb875330f2d64e30a2340afb8ea2eb25c20", "max_stars_repo_licenses": ["FTL"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-20T16:17:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T16:17:05.000Z", "max_issues_repo_path": "references/statistics-for-data-scientists/src/chapter7.r", "max_issues_repo_name": "ronsims2/data_science_tutorials", "max_issues_repo_head_hexsha": "ce245eb875330f2d64e30a2340afb8ea2eb25c20", "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": "references/statistics-for-data-scientists/src/chapter7.r", "max_forks_repo_name": "ronsims2/data_science_tutorials", "max_forks_repo_head_hexsha": "ce245eb875330f2d64e30a2340afb8ea2eb25c20", "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.4474474474, "max_line_length": 106, "alphanum_fraction": 0.6259139287, "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6247074767564017}} {"text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\r\nrej <- 0.12\r\nanswer1 <- pbinom(2, size = 10, prob = rej)\r\nwrite(round(answer1, 3), stdout())\r\nanswer2 <- pbinom(8, size = 10, prob = 1 - rej)\r\nwrite(round(answer2, 3), stdout())", "meta": {"hexsha": "a731da41a6cffbdda7a202e5d2e585f6f2bddc3a", "size": 248, "ext": "r", "lang": "R", "max_stars_repo_path": "binomial-distribution-3/accepted_solutions/18989328.r", "max_stars_repo_name": "hermes-jr/my-hackerrank-solutions", "max_stars_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "binomial-distribution-3/accepted_solutions/18989328.r", "max_issues_repo_name": "hermes-jr/my-hackerrank-solutions", "max_issues_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "binomial-distribution-3/accepted_solutions/18989328.r", "max_forks_repo_name": "hermes-jr/my-hackerrank-solutions", "max_forks_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3333333333, "max_line_length": 70, "alphanum_fraction": 0.6572580645, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6245034398739345}} {"text": "# FUNCTION\n\n\nis_triplet <- function(a, b, c) {\n (a < b) && (b < c) && (a ** 2 + b ** 2 == c ** 2)\n}\n\n\n# SCRIPT\n\n\nfor (a in 1:1000) {\n for (b in (a + 1):(1000 - a)) {\n c = 1000 - (a + b)\n if (is_triplet(a, b, c)) {\n cat(a, b, c, \"\\n\", sep = \" \")\n quit(\"no\")\n }\n }\n}\n", "meta": {"hexsha": "f0c700c757645b59e8c0451fb117800291d1f7f1", "size": 317, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/pe_0009.r", "max_stars_repo_name": "shanedrabing/project-euler", "max_stars_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/pe_0009.r", "max_issues_repo_name": "shanedrabing/project-euler", "max_issues_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/pe_0009.r", "max_forks_repo_name": "shanedrabing/project-euler", "max_forks_repo_head_hexsha": "65add91195fdde3c99c843743205be6d0b1fe072", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0952380952, "max_line_length": 53, "alphanum_fraction": 0.3375394322, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.6245019920995637}} {"text": "##' @title\n##' Classification Metrics Parameters\n##'\n##' @description\n##'\n##' Documentation for shared parameters of functions that computes\n##' classification metrics.\n##'\n##' @param actual \\code{[numeric]} Ground truth binary numeric vector containing\n##' 1 for the positive class and 0 for the negative class.\n##' @param predicted \\code{[numeric]} A vector of estimated probabilities.\n##' @param cutoff \\code{[numeric]} A cutoff value for \\code{predicted} vector\n##' which classify a sample into a given class. Default value is 0.5\n##'\n##' @include helper-functions.r\n##' @name classification_params\nNULL\n\n\n##' @title\n##' Confusion Matrix\n##'\n##'\n##' @description\n##'\n##' Confusion matrix - a special kind of contingency table - is a specific table\n##' layout that allows the visualization of performance of a classification\n##' model (or classifier). It composes of four different combinations of\n##' predicted and actual values.\n##'\n##' \\code{confusion_list} computes and returns those combinations as a\n##' \\code{named list} while \\code{mtr_confusion_matrix} returns a \\code{named\n##' matrix}.\n##'\n##' Here's elements of confusion matrix:\n##'\n##' \\itemize{\n##' \\item True Positive (TP)\n##' \\item False Positive (FP)\n##' \\item True Negative (TN)\n##' \\item False Negative (FN)\n##' }\n##'\n##' @inheritParams classification_params\n##' @return A named list or a named two dimensions matrix\n##' @author An Chu\n##' @examples\n##'\n##' act <- c(1, 0, 0, 1, 1)\n##' pred <- c(0.9, 0.3, 0.6, 0.5, 0.2)\n##'\n##' ## output as a R's list\n##' ## metrics:::confusion_list(act, pred) # default value of cutoff = 0.5\n##' ## metrics:::confusion_list(act, pred, cutoff = 0.7)\n##'\n##' ## output as a R's matrix\n##' mtr_confusion_matrix(act, pred)\n##' mtr_confusion_matrix(act, pred, cutoff = 0.7)\n##'\n##'\n##' @name confusion_matrix\nconfusion_list <- function(actual, predicted, cutoff = 0.5) {\n\n check_equal_length(actual, predicted)\n check_binary(actual)\n check_cutoff_range(cutoff)\n\n TP <- sum((predicted > cutoff) & (actual == 1))\n TN <- sum((predicted <= cutoff) & (actual == 0))\n FN <- sum((predicted <= cutoff) & (actual == 1))\n FP <- sum((predicted > cutoff) & (actual == 0))\n\n list(TP = TP, TN = TN, FP = FP, FN = FN)\n}\n\n\n##' @rdname confusion_matrix\n##' @export\nmtr_confusion_matrix <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n conf_mat <- matrix(numeric(4), ncol = 2,\n dimnames = list(c(\"Positive\", \"Negative\"),\n c(\"True\", \"False\")))\n\n conf_mat[\"Positive\", \"True\"] <- conf_list[[\"TP\"]]\n conf_mat[\"Positive\", \"False\"] <- conf_list[[\"FP\"]]\n conf_mat[\"Negative\", \"True\"] <- conf_list[[\"FN\"]]\n conf_mat[\"Negative\", \"False\"] <- conf_list[[\"TN\"]]\n\n conf_mat\n}\n\n\n## True Positive Rate ----------------------------------------------------------\n\n\n##' @title\n##' True Positive Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name tpr\n##' @export\nmtr_tpr <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TP <- conf_list[[\"TP\"]]\n FN <- conf_list[[\"FN\"]]\n FP <- conf_list[[\"FP\"]]\n denominator <- TP + FN\n\n if (denominator == 0 && FP != 0) return(0)\n if (denominator == 0 && FP == 0) return(1)\n\n TPR <- TP / denominator\n TPR\n}\n\n\n##' @rdname tpr\n##' @export\nmtr_true_positive_rate <- mtr_tpr\n\n\n\n##' @rdname tpr\n##' @export\nmtr_hit_rate <- mtr_tpr\n\n\n\n##' @rdname tpr\n##' @export\nmtr_sensitivity <- mtr_tpr\n\n\n##' @rdname tpr\n##' @export\nmtr_detection_rate <- mtr_tpr\n\n\n\n##' @rdname tpr\n##' @export\nmtr_recall <- mtr_tpr\n\n## True Negative Rate ----------------------------------------------------------\n\n\n##' @title\n##' True Negative Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name tnr\n##' @export\nmtr_tnr <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TN <- conf_list[[\"TN\"]]\n FP <- conf_list[[\"FP\"]]\n FN <- conf_list[[\"FN\"]]\n denominator <- TN + FP\n\n if (denominator == 0 && FN == 0) return(1)\n if (denominator == 0 && FN != 0) return(0)\n\n TNR <- TN / denominator\n TNR\n}\n\n\n##' @rdname tnr\n##' @export\nmtr_true_negative_rate <- mtr_tnr\n\n\n##' @rdname tnr\n##' @export\nmtr_specificity <- mtr_tnr\n\n\n##' @rdname tnr\n##' @export\nmtr_selectivity <- mtr_tnr\n\n\n## False Negative Rate ---------------------------------------------------------\n\n\n##' @title\n##' False Negative Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric output\n##' @author An Chu\n##' @name fnr\n##' @export\nmtr_fnr <- function(actual, predicted, cutoff = 0.5) {\n 1 - mtr_tnr(actual, predicted, cutoff = cutoff)\n}\n\n\n##' @rdname fnr\n##' @export\nmtr_miss_rate <- mtr_fnr\n\n##' @rdname fnr\n##' @export\nmtr_false_negative_rate <- mtr_fnr\n\n## False Positive Rate ---------------------------------------------------------\n\n##' @title\n##' False Positive Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name fpr\n##' @export\nmtr_fpr <- function(actual, predicted, cutoff = 0.5) {\n 1 - mtr_tnr(actual, predicted, cutoff = cutoff)\n}\n\n##' @rdname fpr\n##' @export\nmtr_fallout <- mtr_fpr\n\n##' @rdname fpr\n##' @export\nmtr_false_alarm_rate <- mtr_fpr\n\n##' @rdname fpr\n##' @export\nmtr_far <- mtr_fpr\n\n##' @rdname fpr\n##' @export\nmtr_false_positive_rate <- mtr_fpr\n\n## Accuracy --------------------------------------------------------------------\n\n\n##' @title\n##' Accuracy\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @seealso \\code{\\link{mtr_balanced_accuracy}}\n##' @author An Chu\n##' @name acc\n##' @export\nmtr_accuracy <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TP <- conf_list[[\"TP\"]]\n TN <- conf_list[[\"TN\"]]\n\n accuracy <- (TP + TN) / Reduce(sum, conf_list)\n\n accuracy\n}\n\n##' @rdname acc\n##' @export\nmtr_ccr <- mtr_accuracy\n\n## Misclassification Rate ------------------------------------------------------\n\n##' @title\n##' Misclassification rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_misclassification_rate <- function(actual, predicted, cutoff = 0.5) {\n 1 - mtr_accuracy(actual, predicted, cutoff = cutoff)\n}\n\n## Balanced Accuracy -----------------------------------------------------------\n\n\n##' @title\n##' Balanced Accuracy\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @seealso \\code{\\link{mtr_accuracy}}\n##' @author An Chu\n##' @export\nmtr_balanced_accuracy <- function(actual, predicted, cutoff = 0.5) {\n\n sensitivity <- mtr_sensitivity(actual, predicted, cutoff = cutoff)\n specificity <- mtr_specificity(actual, predicted, cutoff = cutoff)\n\n (sensitivity + specificity) / 2\n}\n\n## Positive Predicted Value ----------------------------------------------------\n\n##' @title\n##' Positive Predicted Value\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @name ppv\n##' @author An Chu\n##' @export\nmtr_ppv <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TP <- conf_list[[\"TP\"]]\n FP <- conf_list[[\"FP\"]]\n denominator <- TP + FP\n\n if (denominator == 0) return(0)\n\n PPV <- TP / (TP + FP)\n PPV\n}\n\n\n##' @rdname ppv\n##' @export\nmtr_positive_predicted_value <- mtr_ppv\n\n##' @rdname ppv\n##' @export\nmtr_precision <- mtr_ppv\n\n## Average Precision -----------------------------------------------------------\n\n##' @title\n##' Average Precision\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_average_precision <- function(actual, predicted) {\n\n ## keep distinct index of prediction and truth vector\n ordering <- order(predicted)\n thresholds <- predicted[ordering]\n predicted <- predicted[ordering]\n actual <- actual[ordering]\n\n precision <- map_dbl(thresholds, function(x) mtr_precision(actual, predicted, x))\n recall <- map_dbl(thresholds, function(x) mtr_recall(actual, predicted, x))\n\n avg_prec <- sum(diff(recall) * precision[-1], na.rm = TRUE) * (-1)\n avg_prec\n}\n\n\n## False Discovery Rate --------------------------------------------------------\n\n##' @title\n##' False Discovery Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @name fdr\n##' @author An Chu\n##' @export\nmtr_fdr <- function(actual, predicted, cutoff = 0.5) {\n 1 - mtr_ppv(actual, predicted, cutoff = cutoff)\n}\n\n\n##' @rdname fdr\n##' @export\nmtr_false_discovery_rate <- mtr_fdr\n\n## Negative Predicted Value ----------------------------------------------------\n\n##' @title\n##' Negative Predicted Value\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @name npv\n##' @author An Chu\n##' @export\nmtr_npv <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TN <- conf_list[[\"TN\"]]\n FN <- conf_list[[\"FN\"]]\n denominator <- TN + FN\n\n if (denominator == 0) return(0)\n\n NPV <- TN / (TN + FN)\n NPV\n}\n\n##' @rdname npv\n##' @export\nmtr_negative_predicted_value <- mtr_npv\n\n## False Omission Rate ---------------------------------------------------------\n\n\n##' @title\n##' False Omission Rate\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @name for\n##' @author An Chu\n##' @export\nmtr_for <- function(actual, predicted, cutoff = 0.5) {\n 1 - mtr_npv(actual, predicted, cutoff = cutoff)\n}\n\n\n##' @rdname for\n##' @export\nmtr_false_omission_rate <- mtr_for\n\n## F1 Score --------------------------------------------------------------------\n\n\n##' @title\n##' F1 Score\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @seealso \\code{\\link{mtr_fbeta_score}}\n##' @author An Chu\n##' @export\nmtr_f1score <- function(actual, predicted, cutoff = 0.5) {\n\n precision <- mtr_precision(actual, predicted, cutoff = cutoff)\n recall <- mtr_recall(actual, predicted, cutoff = cutoff)\n f1score <- (2 * precision * recall) / (precision + recall)\n\n f1score\n}\n\n## F-beta Score ----------------------------------------------------------------\n\n##' @title\n##' F-beta Score\n##'\n##'\n##' @param beta \\code{[numeric]} To be filled\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @seealso \\code{\\link{mtr_f1score}}\n##' @author An Chu\n##' @export\nmtr_fbeta_score <- function(actual, predicted, cutoff = 0.5, beta = 1) {\n\n precision <- mtr_precision(actual, predicted, cutoff = cutoff)\n recall <- mtr_recall(actual, predicted, cutoff = cutoff)\n fbeta <- (1 + beta^2) * ((precision * recall) / (beta^2 * precision + recall))\n\n fbeta\n}\n\n\n## Fowlkes-Mallows Index -------------------------------------------------------\n\n\n##' @title\n##' Fowlkes-Mallows Index\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name gscore\n##' @export\nmtr_gscore <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list = confusion_list(actual, predicted, cutoff = cutoff)\n\n TP <- conf_list[[\"TP\"]]\n FP <- conf_list[[\"FP\"]]\n FN <- conf_list[[\"FN\"]]\n gscore <- sqrt((TP / (TP + FP)) * (TP / (TP + FN)))\n\n gscore\n}\n\n\n##' @rdname gscore\n##' @export\nmtr_fowlkes_mallows <- mtr_gscore\n\n## Prevalence ------------------------------------------------------------------\n\n##' @title\n##' Prevalence\n##'\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_prevalence <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n\n TP <- conf_list[[\"TP\"]]\n FN <- conf_list[[\"FN\"]]\n prevalence <- (TP + FN) / Reduce(sum, conf_list)\n\n prevalence\n}\n\n\n##' @title\n##' Detection Prevalence\n##'\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_detection_prevalence <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n TP <- conf_list[[\"TP\"]]\n FP <- conf_list[[\"FP\"]]\n dec_pre <- (TP + FP) / Reduce(sum, conf_list)\n\n dec_pre\n}\n\n\n## KS statistic ----------------------------------------------------------------\n\n\n##' @title\n##' KS Statistic\n##'\n##' @description\n##'\n##' Kolmogorov–Smirnov statistic quantifies a distance between the empirical\n##' distribution function of the sample and the cumulative distribution function\n##' of the reference distribution.\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_ks_statistic <- function(actual, predicted) {\n\n descending <- order(predicted, decreasing = TRUE)\n actual <- actual[descending]\n predicted <- predicted[descending]\n\n bins <- 10 # this is arbitrary\n len <- length(actual)\n n <- len %/% bins # number of obs per bin\n\n group_index <- rep(1:(bins - 1), each = n)\n group_index <- append(group_index, rep(bins, len - length(group_index)))\n\n perct_pos <- tapply(actual, group_index, function(x) sum(x == 1)) / sum(actual == 1)\n perct_neg <- tapply(actual, group_index, function(x) sum(x == 0)) / sum(actual == 0)\n\n max(cumsum(perct_pos) - cumsum(perct_neg))\n}\n\n\n## Informedness ----------------------------------------------------------------\n\n\n##' @title\n##' Informedness\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @name yindex\n##' @export\nmtr_informedness <- function(actual, predicted, cutoff = 0.5) {\n\n sensitivity <- mtr_sensitivity(actual, predicted, cutoff = cutoff)\n specificity <- mtr_specificity(actual, predicted, cutoff = cutoff)\n\n sensitivity + specificity - 1\n}\n\n\n##' @rdname yindex\n##' @export\nmtr_youden_index <- mtr_informedness\n\n\n## Markedness ------------------------------------------------------------------\n\n\n##' @title\n##' Markedness\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_markedness <- function(actual, predicted, cutoff = 0.5) {\n\n ppv <- mtr_positive_predicted_value(actual, predicted, cutoff = cutoff)\n npv <- mtr_negative_predicted_value(actual, predicted, cutoff = cutoff)\n\n ppv + npv - 1\n}\n\n## Matthews Correlation Coefficient --------------------------------------------\n\n\n##' @title\n##' Matthews Correlation Coefficient\n##'\n##' @inheritParams classification_params\n##' @return A numeric scalar output\n##' @author An Chu\n##' @export\nmtr_matthews_corr_coef <- function(actual, predicted, cutoff = 0.5) {\n\n conf_list <- confusion_list(actual, predicted, cutoff = cutoff)\n TP <- conf_list[[\"TP\"]]\n TN <- conf_list[[\"TN\"]]\n FP <- conf_list[[\"FP\"]]\n FN <- conf_list[[\"FN\"]]\n\n denom1 <- TP + FP\n denom2 <- TP + FN\n denom3 <- TN + FP\n denom4 <- TN + FN\n\n if (denom1 == 0 || denom2 == 0 || denom3 == 0 || denom4 == 0) return(NA_real_)\n\n mcc <- ((TP * TN) - (FP * FN)) / sqrt(prod(denom1, denom2, denom3, denom4))\n mcc\n}\n\n\n## Hamming Loss ----------------------------------------------------------------\n\nmtr_hamming_loss <- function(actual, predicted, cutoff = 0.5) {\n\n}\n\n\n## Hinge Loss ------------------------------------------------------------------\n\n\nmtr_hinge_loss <- function(actual, predicted, cutoff = 0.5) {\n\n}\n\n## Jaccard Score ---------------------------------------------------------------\n\n\nmtr_jaccard_score <- function(actual, predicted, cutoff = 0.5) {\n\n}\n", "meta": {"hexsha": "306815b04783ffb2f19cefae4ee7474c8abc2e1a", "size": 15864, "ext": "r", "lang": "R", "max_stars_repo_path": "R/conf-mat.r", "max_stars_repo_name": "maiing/metrics", "max_stars_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/conf-mat.r", "max_issues_repo_name": "maiing/metrics", "max_issues_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/conf-mat.r", "max_forks_repo_name": "maiing/metrics", "max_forks_repo_head_hexsha": "ae4e4cbe5b025c53f2fbf552a46f335aa34f687f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5720653789, "max_line_length": 88, "alphanum_fraction": 0.589889057, "num_tokens": 4316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6242048268831645}} {"text": "setabc <- function(f, fb, sr) {\n pit = pi/sr\n r = exp(-pit*fb)\n coefs = c(0,0,0)\n coefs[3] = -r * r\n coefs[2] = 2*r*cos(2*pit*f)\n coefs[1] = 1 - coefs[2] - coefs[3]\n if (f < 0.0) {\n coefs[1] = 1 / coefs[1]\n coefs[2] = -coefs[1] * coefs[2]\n coefs[3] = -coefs[1] * coefs[3]\n }\n return(coefs)\n}\n\nres <- function(x,f,fb,sr) {\n cf = setabc(f,fb,sr)\n m1 = 0\n m2 = 0\n y = x\n if (f >= 0) {\n for (j in 1:length(x)) {\n y[j] = x[j]*cf[1] + m1*cf[2] + m2*cf[3]\n m2 = m1\n m1 = y[j]\n }\n } else {\n for ( j in 1:length(x)) {\n y[j] = x[j]*cf[1] + m1*cf[2] + m2*cf[3]\n m2 = m1\n m1 = x[j]\n }\n }\n return(y)\n}\n", "meta": {"hexsha": "67192bb068ac7230189a2890d2632388a4ab9948", "size": 657, "ext": "r", "lang": "R", "max_stars_repo_path": "R/setabc.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/setabc.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/setabc.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": 18.25, "max_line_length": 45, "alphanum_fraction": 0.4307458143, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088064979618, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.6241986825967326}} {"text": " \r\n\r\n\r\n #### Clark and West test 2007 ####\r\n\r\n#Before simulating MC I have to set the coefficients of the simulated regressions to predefined values.\r\n#All this values are given/calculated by given numbers in paper by Paye.\r\n\r\n#Set the coefficients to prespecified values..\r\nconst2=0.27\r\ncoef_ar1_x=0.60\r\nunconexp_x=const2/(1-coef_ar1_x)\r\n\r\n#Set the autoregresseive coefficients to predetermined values.\r\nconst1=-0.61\r\ncoef_ar1_y=0.52\r\ncoef_ar2_y=0.22\r\nunconexp_y=(const1+unconexp_x)/(1-coef_ar1_y-coef_ar2_y)\r\n\r\n# To generate the error terms one need to specify the variances/std.dev of error terms.\r\nvar_et=0.092\r\nvar_vt=0.160\r\ncov_et_vt=0.026\r\ncorr_et_vt=cov_et_vt/sqrt(var_et*var_vt)\r\n\r\n# Generate the distribution according to standard normal distribution. I set n=2000\r\nset.seed(123456)\r\nzt1<-rnorm(2000,0,1)\r\nzt2<-rnorm(2000,0,1)\r\n\r\net<-zt1*sqrt(var_et)\r\nvt<-(zt1*corr_et_vt+zt2*sqrt(1-corr_et_vt))*sqrt(var_vt)\r\n\r\n\r\n#For loop inside the prediction/estimation\r\nset.seed(123456)\r\nwndw = 20 #number of observations for the in-sample (estimation) analysis.\r\nT = 120 #number of observations for the out-of-sample (forecast) analysis.\r\ny <- matrix(NA, 2000,10000) #Randomly generated dependent variable matrix.\r\ny_sample <- matrix(NA,T+wndw,10000) #creating a matrix which incorporates both in-sample and out-of-sample analysis osbervations: T+wndw=150 observations.\r\nx <-matrix(NA,2000,10000)\r\nx_sample <-matrix(NA,T+wndw,10000)\r\n\r\nfor (ii in 1:10000) {\r\n # Generate first two datapoints\t\r\n y[1,ii] <- unconexp_y\r\n y[2,ii] <- 1\r\n x[1,ii] <-unconexp_x\r\n x[2,ii] <-1\r\n #randomly generate the rest of the data for indep.var. starting from the third obs.\r\n for (tt in 3:2000) {\r\n x[tt,ii] = const2+coef_ar1_x*x[tt-1,ii]+rnorm(1)*sqrt(var_vt)\r\n y[tt,ii] = const1 + coef_ar1_y*y[tt-1,ii] + coef_ar2_y*y[tt-2,ii] + rnorm(1)*sqrt(var_et)\r\n }\r\n #Select last 150 observations for later in- and out-of-sample analysis and assign them to predefined y_sample matrix.\r\n y_sample[,ii] <- y[(2000 - wndw - T + 1) : 2000, ii]\r\n x_sample[,ii] <- x[(2000 - wndw - T + 1) : 2000, ii]\r\n}\r\n\r\n\r\n# Estimate model on rolling window \r\nprediction <- matrix(NA,T+wndw,10000) #create an empty matrix later to be filled by forecasting values. First 20 observations are not gonna be used, only T=120 observations are used.\r\nlosses<-matrix(NA,T+wndw,10000) #This command generates a matrix for the forecast errors where it is calculated by subtracting actual generated data from the forecasted values.\r\nlosses_sqr<-matrix(NA,T+wndw,10000) #This command generates a matrix for the forecast error squares where it is calculated by taking the square of 'losses' series.\r\nprediction4 <- matrix(NA,T+wndw,10000)\r\nlosses4<-matrix(NA,T+wndw,10000)\r\nlosses4_sqr<-matrix(NA,T+wndw,10000)\r\nfor (ii in 1:10000) {\r\n for (kk in wndw:(T+wndw-1)) {\r\n # estimate with data from (kk-wndw+1) : kk.Model is defined as AR(2) model and estimated with linear regression.\r\n fit2<-lm(y_sample[(kk-wndw+1): kk,ii]~dplyr::lead(y_sample[(kk-wndw+1): kk,ii])+dplyr::lead(y_sample[(kk-wndw+1): kk,ii],2))\r\n #Forecasts are obtained by extracting the coefficients from the regression model of AR(2).\r\n prediction[kk+1,ii]<-fit2$coefficients[1]+fit2$coefficients[2]*y_sample[kk,ii]+fit2$coefficients[3]*y_sample[kk-1,ii]\r\n #Forecast errors are the difference between the actual and predicted(forecast) values.\r\n losses[kk+1,ii] <- y_sample[kk+1,ii] - prediction[kk+1,ii]\r\n losses_sqr[kk+1,ii] <- (y_sample[kk+1,ii] - prediction[kk+1,ii])^2\r\n \r\n fit<-lm(y_sample[(kk-wndw+1): kk,ii]~dplyr::lead(y_sample[(kk-wndw+1): kk,ii])+dplyr::lead(y_sample[(kk-wndw+1): kk,ii],2)+dplyr::lead(x_sample[(kk-wndw+1): kk,ii]))\r\n prediction4[kk+1,ii]<-fit2$coefficients[1]+fit2$coefficients[2]*y_sample[kk,ii]+fit$coefficients[3]*y_sample[kk-1,ii]+fit$coefficients[4]*x_sample[kk,ii]\r\n losses4[kk+1,ii] <- y_sample[kk+1,ii] - prediction4[kk+1,ii]\r\n losses4_sqr[kk+1,ii] <- (y_sample[kk+1,ii] - prediction4[kk+1,ii])^2\r\n \r\n }\r\n}\r\n\r\n\r\nadj_term1<-matrix(NA,T+wndw,10000)\r\nadj_term1<-(prediction-prediction4)^2\r\n\r\ncw_stats1<-matrix(NA,T+wndw,10000)\r\ncw_stats1<-(losses_sqr-losses4_sqr+adj_term1)*100\r\n\r\ncount<-matrix(NA,1,10000)\r\n\r\nfor (ii in 1:10000) {\r\n cw_stats1_eq<-lm(cw_stats1[21:140,ii]~1)\r\n if (summary(cw_stats1_eq)$coefficients[1, 4]<0.10){\r\n count[,ii]=1\r\n }else{\r\n count[,ii]=0 \r\n }\r\n}\r\n\r\n#This code calculates the analysis percentage of rejection rates (at 10% sign. level)\r\n#over 10000 simulated samples. The test is based on Clark and West (2007) test.\r\n\r\nCW_test_stats1<-100*(rowSums(count)/10000)\r\n\r\n\r\n\r\n#Here I am simulating from the model that sets the coefficient for the xt-1 variable (new variable) to zero.\r\n#Therefore, I create a new variable called x. \r\nwndw = 20\r\nT = 120\r\nset.seed(123456)\r\n\r\n#Set the coefficients to prespecified values\r\nconst2=0.27\r\ncoef_ar1_x=0.60\r\nunconexp_x=const2/(1-coef_ar1_x)\r\n\r\n#Set the autoregresseive coefficients to predetermined values.\r\nconst1=-0.61\r\ncoef_ar1_y=0.52\r\ncoef_ar2_y=0.22\r\nunconexp_y=(const1+unconexp_x)/(1-coef_ar1_y-coef_ar2_y)\r\n\r\n# To generate the error terms one need to specify the variances/std.dev of error terms.\r\nvar_et=0.092\r\nvar_vt=0.160\r\ncov_et_vt=0.026\r\ncorr_et_vt=cov_et_vt/sqrt(var_et*var_vt)\r\n\r\n# Generate the distribution according to standard normal distribution. I set n=2000\r\nset.seed(123456)\r\nzt1<-rnorm(2000,0,1)\r\nzt2<-rnorm(2000,0,1)\r\n\r\net<-zt1*sqrt(var_et)\r\nvt<-(zt1*corr_et_vt+zt2*sqrt(1-corr_et_vt))*sqrt(var_vt)\r\n\r\n\r\n#For loop inside the prediction/estimation\r\nset.seed(123456)\r\nwndw = 20\r\nT = 120\r\ny2 <- matrix(NA, 2000,10000)\r\ny2_sample <- matrix(NA,T+wndw,10000)\r\nx <-matrix(NA,2000,10000)\r\nx_sample <-matrix(NA,T+wndw,10000)\r\nfor (ii in 1:10000) {\r\n # Generate datapoints\t\r\n y2[1,ii] <- unconexp_y\r\n y2[2,ii] <- 1\r\n x[1,ii] <-unconexp_x\r\n x[2,ii] <-1\r\n for (tt in 3:2000) {\r\n x[tt,ii] = const2+coef_ar1_x*x[tt-1,ii]+rnorm(1)*sqrt(var_vt)\r\n y2[tt,ii] = const1 + coef_ar1_y*y2[tt-1,ii] + coef_ar2_y*y2[tt-2,ii] +0.09*x[tt-1,ii]+ rnorm(1)*sqrt(var_et)\r\n }\r\n y2_sample[,ii] <- y2[(2000 - wndw - T + 1) : 2000, ii]\r\n x_sample[,ii] <- x[(2000 - wndw - T + 1) : 2000, ii]\r\n}\r\n\r\n\r\n# Estimate model on rolling window \r\nprediction2 <- matrix(NA,T+wndw,10000)\r\nlosses2<-matrix(NA,T+wndw,10000)\r\nlosses2_sqr<-matrix(NA,T+wndw,10000)\r\nprediction4 <- matrix(NA,T+wndw,10000)\r\nlosses4<-matrix(NA,T+wndw,10000)\r\nlosses4_sqr<-matrix(NA,T+wndw,10000)\r\nfor (ii in 1:10000) {\r\n for (kk in wndw:(T+wndw-1)) {\r\n # estimate with data from (kk-wndw+1) : kk\r\n fit<-lm(y2_sample[(kk-wndw+1): kk,ii]~dplyr::lead(y2_sample[(kk-wndw+1): kk,ii])+dplyr::lead(y2_sample[(kk-wndw+1): kk,ii],2)+dplyr::lead(x_sample[(kk-wndw+1): kk,ii]))\r\n prediction2[kk+1,ii]<-fit$coefficients[1]+fit$coefficients[2]*y2_sample[kk,ii]+fit$coefficients[3]*y2_sample[kk-1,ii]+fit$coefficients[4]*x_sample[kk,ii]\r\n losses2[kk+1,ii] <- y2_sample[kk+1,ii] - prediction2[kk+1,ii]\r\n losses2_sqr[kk+1,ii] <- (y2_sample[kk+1,ii] - prediction2[kk+1,ii])^2\r\n fit2<-lm(y2_sample[(kk-wndw+1): kk,ii]~dplyr::lead(y2_sample[(kk-wndw+1): kk,ii])+dplyr::lead(y2_sample[(kk-wndw+1): kk,ii],2))\r\n prediction4[kk+1,ii]<-fit2$coefficients[1]+fit2$coefficients[2]*y2_sample[kk,ii]+fit$coefficients[3]*y2_sample[kk-1,ii]\r\n losses4[kk+1,ii] <- y2_sample[kk+1,ii] - prediction4[kk+1,ii]\r\n losses4_sqr[kk+1,ii] <- (y2_sample[kk+1,ii] - prediction4[kk+1,ii])^2\r\n }\r\n}\r\n\r\n\r\n#...\r\n\r\n\r\nadj_term1<-matrix(NA,T+wndw,10000)\r\nadj_term1<-(prediction2-prediction4)^2\r\n\r\ncw_stats1<-matrix(NA,T+wndw,10000)\r\ncw_stats1<-(losses2_sqr-losses4_sqr+adj_term1)*100\r\n\r\ncount<-matrix(NA,1,10000)\r\n\r\nfor (ii in 1:10000) {\r\n cw_stats1_eq<-lm(cw_stats1[21:140,ii]~1)\r\n if (summary(cw_stats1_eq)$coefficients[1, 4]<0.10){\r\n count[,ii]=1\r\n }else{\r\n count[,ii]=0 \r\n }\r\n}\r\n\r\n#This code calculates the analysis percentage of rejection rates (at 10% sign. level)\r\n#over 10000 simulated samples. The test is based on Clark and West (2007) test.\r\nCW_test_stats2<-100*(rowSums(count)/10000)\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "9c88edb8d9153586872ef0541ca6a1e2a5b92435", "size": 8085, "ext": "r", "lang": "R", "max_stars_repo_path": "sim_analysis_R/CW_test_2007.r", "max_stars_repo_name": "NurlanMammadov92/master_thesis", "max_stars_repo_head_hexsha": "8f83860dc5042681265bb2623f77d4133937c61e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sim_analysis_R/CW_test_2007.r", "max_issues_repo_name": "NurlanMammadov92/master_thesis", "max_issues_repo_head_hexsha": "8f83860dc5042681265bb2623f77d4133937c61e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sim_analysis_R/CW_test_2007.r", "max_forks_repo_name": "NurlanMammadov92/master_thesis", "max_forks_repo_head_hexsha": "8f83860dc5042681265bb2623f77d4133937c61e", "max_forks_repo_licenses": ["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.4305555556, "max_line_length": 183, "alphanum_fraction": 0.6912801484, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6237447275169942}} {"text": " ZGEEVX Example Program Results\n\n Eigenvalues\n\n Eigenvalue rcond error\n 1 (-6.0004E+00,-6.9998E+00) 0.9932 3.2E-15\n 2 (-5.0000E+00, 2.0060E+00) 0.9964 3.2E-15\n 3 ( 7.9982E+00,-9.9637E-01) 0.9814 3.3E-15\n 4 ( 3.0023E+00,-3.9998E+00) 0.9779 3.3E-15\n\n Eigenvectors\n\n Eigenvector rcond error\n\n 1 ( 8.4572E-01, 0.0000E+00) 8.4011 -\n (-1.7723E-02, 3.0361E-01)\n ( 8.7521E-02, 3.1145E-01)\n (-5.6147E-02,-2.9060E-01)\n\n 2 ( 3.8655E-01,-1.7323E-01) 8.0214 -\n ( 3.5393E-01,-4.5288E-01)\n (-6.1237E-01,-0.0000E+00)\n ( 8.5928E-02, 3.2836E-01)\n\n 3 ( 1.7297E-01,-2.6690E-01) 5.8292 -\n (-6.9242E-01,-0.0000E+00)\n (-3.3240E-01,-4.9598E-01)\n (-2.5039E-01, 1.4655E-02)\n\n 4 ( 3.5614E-02, 1.7822E-01) 5.8292 -\n (-1.2637E-01,-2.6663E-01)\n (-1.2933E-02, 2.9657E-01)\n (-8.8982E-01,-0.0000E+00)\n\n Errors below 10*machine precision are not displayed\n", "meta": {"hexsha": "c397eb98954650f4bb526aef6fca995b8197cdfd", "size": 933, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/zgeevx_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/zgeevx_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/zgeevx_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 25.9166666667, "max_line_length": 52, "alphanum_fraction": 0.5605573419, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.6237014263814386}} {"text": "# treeEnsembles.r\n# MWL, Lecture 2\n# Author(s): [Phil Snyder]\n\n\"\nAn ensemble is a predictor that obtains its predictions by taking a weighted average of multiple \nsingle predictors. We will look at three different types of tree-based ensembles: bagging, \nrandom forests, and boosting with trees. Both random forests and boosting are methods \nused in industry every day - and can be very powerful predictors.\n\"\n\nlibrary(\"ElemStatLearn\")\ndata(\"spam\")\n\npartition <- sample(nrow(spam), floor(0.7 * nrow(spam)))\ntrainData <- spam[partition,]\ntestData <- spam[-partition,] \n\n# Bagging\n\n\"\nBagging is a portmanteau of 'bootstrap aggregation'. 'Bootstrap' is a sampling method where you \nsample from a data set *with replacement*. Usually your sample size is equivalent to the size of \nthe original data set. 'Aggregation' refers to the fact that we are aggregating or averaging the \npredictors (in the case of classification, by having them take a vote on the class) trained on \nour bootstrap samples. Typically bagging only helps in the case of high variance predictors (such\nas decision trees) because it reduces variance while maintaining bias (again, see bias-variance \ntrade-off). More info available in [ESL 8.7].\n\"\n\n#install.packages(\"ipred\")\nlibrary(\"ipred\")\nbagg <- bagging(spam ~ ., trainData, nbagg=50) # 50 trees\n# Of course, normally we would do CV to find the optimal parameters \n# (implicit here are the rpart parameters)\nbaggPredictions <- predict(bagg, testData)\nbaggResults <- table(baggPredictions == testData$spam) / length(baggPredictions)\nbaggResults # (approx.) TRUE: 0.924, FALSE: 0.0760\n\n# Random Forests\n\n\"\nRandom Forests are similar to bagging, except each tree is only trained on a random subset of the \ndimensions of the original dataset. For example, if our data had dimensions V1, ..., V10\nwe might train the first tree on dimensions V1, V4, V8 and our second tree on V2, V4, V5, etc.\nWe do this so that our individual trees become less *correlated*. The correlation between trees \nlimits how good of a predictor we may obtain by averaging their individual predictions. You \nmay also think of the individual trees in a random forest as being 'experts' in a specific domain. \nThe more limited the domain of the expert, the deeper and more refined the experts knowledge becomes \nin that domain. For more info see [ESL 15].\n\"\n\n#install.packages(\"randomForest\")\nlibrary(\"randomForest\")\nrf <- randomForest(spam ~ ., trainData, ntree=80) # 80 trees trained on random dimensions\n# in classification, by default we randomly select m = floor(sqrt(p)) dimensions to train on\n# where p is the # of dimensions in our original dataset.\nrfPredictions <- predict(rf, testData)\nrfResults <- table(rfPredictions == testData$spam) / length(rfPredictions)\nrfResults # (approx.) TRUE: 0.945, FALSE: 0.055\n\n\"\nThis is our best predictor yet, though random forests have their limits. If the dimensions \nof our data have very little to do with how the class is determined, then it's likely many of \nthe trees will make decisions based on useless information, adding noise to our predictions.\n\"\n\n# Boosting\n\n\"\nHere we will do boosting with decision trees, though it is possible to do boosting with different \npredictors. The general idea behind boosting is that each data point in the training set is given \na weight. At first these weights are all equal. We then fit a tree to the train data. For every data \npoint that the tree classifies incorrectly, we increase its weight. We then fit a second tree \nto the data. The second tree gives the data points with greater weight greater importance, and is \nless likely to classify them incorrectly. The process then repeats, iterating sequentially through \neach dimension. This will perhaps become more clear when we talk about loss/objective \nfunctions. For more info see [ESL 10].\n\"\n\n#install.packages(\"adabag\")\nlibrary(\"adabag\")\nboost <- boosting(spam ~ ., trainData, mfinal=100) # 100 boosted trees\nboostPredictions <- predict(boost, testData)\nboostPredictions$error # proportion incorrect\n\n\"\nBoosting is a powerful idea, and we will generalize it to other predictors later.\n\nYou may have noticed that it took a fair amount of time to fit our models to the data. This is \nwhere the 'computer science' portion of machine learning comes into play. The most powerful \npredictors (usually ensembles, or various forms of neural nets, or both) can take days to train, \neven with extreme computational optimization. Next lecture we will take a closer look at the \noptimization of our model parameters as well as some more archetypical concepts in machine learning.\n\"\n", "meta": {"hexsha": "f77a33bf9090349408fc739855d5eabe7da018a5", "size": 4609, "ext": "r", "lang": "R", "max_stars_repo_path": "2015-2016.Meetings/02.trees/treeEnsembles.r", "max_stars_repo_name": "NViday/machine_learning_workshop_Winter17", "max_stars_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-02-07T09:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T09:49:35.000Z", "max_issues_repo_path": "2015-2016.Meetings/02.trees/treeEnsembles.r", "max_issues_repo_name": "NViday/machine_learning_workshop_Winter17", "max_issues_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2015-2016.Meetings/02.trees/treeEnsembles.r", "max_forks_repo_name": "NViday/machine_learning_workshop_Winter17", "max_forks_repo_head_hexsha": "834c4abee998b3143cd562ecd240c8054d29ffc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-03-27T11:06:24.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-27T11:06:24.000Z", "avg_line_length": 48.0104166667, "max_line_length": 101, "alphanum_fraction": 0.7730527229, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067208930584, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6237014210300402}} {"text": "data <- read.csv(file=\"UrbanaData.csv\",header = TRUE)\r\ndepot <- c(40.117844, -88.199203)\r\n\r\ndata$LAT <- (data$LAT-depot[1])*111.7\r\ndata$LON <- (data$LON-depot[2])*111.7*cos(40.1/360*2*pi)\r\n\r\nplot(data$LON, data$LAT)\r\npoints(0, 0, col = \"red\")\r\nn <- length(data$LON)\r\nx <- cbind(data$LON, data$LAT)\r\nd <- matrix(0, nrow = n, ncol = n)\r\nfor (i in 1:n)\r\n for (j in 1:n)\r\n {\r\n d[i, j] = abs(x[i,1]-x[j,1])+abs(x[i,2]-x[j,2])\r\n }\r\n \r\nr <- abs(data$LON)+abs(data$LAT)\r\nalpha <- atan(data$LAT/data$LON)\r\nalpha <- ifelse(data$LAT<0 & data$LON<0, alpha-pi, alpha)\r\nalpha <- ifelse(data$LAT>0 & data$LON<0, alpha+pi, alpha)\r\ndmdori = data$Pop*4.4*7\r\ndmd = qnorm(0.95, mean = data$Pop*4.4*7, sd = data$Pop*4.4*7*0.1)\r\n\r\np <- as.data.frame(cbind(data$BID, x, r, alpha, dmd))\r\ncolnames(p) <- c(\"id\",\"lon\",\"lat\",\"r\",\"alpha\",\"demand\")\r\nplot(p$r, p$demand)\r\nplot(data$LON, data$LAT, xlab = \"X\", ylab = \"Y\")\r\npoints(0, 0, col = \"red\", pch = 17)\r\nhigh <- which(p$demand>=10000)\r\nmid <- which(p$demand>=5000 & p$demand<10000)\r\npoints(p$lon[high], p$lat[high], col = \"green\")\r\npoints(p$lon[mid], p$lat[mid], col = \"blue\")\r\n\r\n########################################\r\n\r\nsearchnode <- function(x, conn, node, N)\r\n{\r\n for (j in 1:N)\r\n if (conn[x, j]==1)\r\n {\r\n if (node[j]==FALSE) return(j)\r\n }\r\n return(0)\r\n}\r\n\r\nrenode <- function(x, dist, node)\r\n{\r\n l <- order(dist[x, ], decreasing = FALSE)\r\n for (j in l)\r\n if (node[j]==FALSE) return(j)\r\n}\r\n\r\ngetsolu <- function(ppp, mark)\r\n{\r\n print(mark)\r\n x <- c(0, ppp$lon)\r\n y <- c(0, ppp$lat)\r\n N <- length(x)\r\n dot <- cbind(x, y)\r\n #creating dist matrix for dist(i,j)\r\n dist <- matrix(0, nrow = N, ncol = N)\r\n for (i in 1:N)\r\n for (j in 1:N)\r\n {\r\n dist[i, j] = abs(x[i]-x[j])+abs(y[i]-y[j])\r\n }\r\n \r\n # use prim algorithm to find MST, set point 1 as the start point \r\n conn <- matrix(0, nrow = N, ncol = N) # if city i & j are connected \r\n cost <- dist[1,] #distance from the tree to other nodes\r\n node <- c(TRUE, rep(FALSE, N-1)) #whether node is in the set\r\n father <- c(NA, rep(1, N-1)) \r\n \r\n for (i in 1:(N-1))\r\n {\r\n newdist <- Inf\r\n for (j in 1:N)\r\n {\r\n #find a new node to join\r\n if (node[j]==FALSE & cost[j]60000)\r\n {\r\n if (flag==1)\r\n {\r\n sol <- getsolu(pp[which(ctg==flag),], which(ctg==flag))\r\n solu <- sol[1]\r\n lstt <- sol[2:length(sol)]\r\n } else {\r\n sol <- c(getsolu(pp[which(ctg==flag),], which(ctg==flag)))\r\n solu <- c(solu, sol[1])\r\n lstt <- c(lstt, sol[2:length(sol)])\r\n }\r\n lstt <- c(lstt, flag+n)\r\n lines(c(0, pp$lon[i-1]*10), c(0, pp$lat[i-1]*10))\r\n flag <- flag+1\r\n tmp <- pp$demand[i]\r\n lines(c(0, pp$lon[i-1]*10), c(0, pp$lat[i-1]*10))\r\n \r\n } else {\r\n tmp <- tmp+pp$demand[i]\r\n }\r\n ctg[i] <- flag\r\n}\r\nlines(c(0, pp$lon[n]*10), c(0, pp$lat[n]*10))\r\nsol <- c(getsolu(pp[which(ctg==flag),], which(ctg==flag)))\r\nsolu <- c(solu, sol[1])\r\nlstt <- c(lstt, sol[2:length(sol)])\r\nsolu <- solu*0.621371\r\n\r\nfinal <- data.frame(\r\n routelength = solu,\r\n demandpoint = sapply(1:flag, function(i) length(which(ctg==i))),\r\n totaldemand = sapply(1:flag, function(i) sum(pp$demand[which(ctg==i)]))\r\n)\r\nsum(final$routelength)\r\n\r\n\r\n#####Cost Computation ##############33\r\n\r\ncost <- (sum(solu)/25+sum(dmd)/5000/6)*15+\r\n1.86*sum(solu)+0.1*sum(solu)+sum(solu*final$totaldemand*0.1/5000/2)+\r\n0.2*(n+20)\r\n\r\ncc <- rep(1,n)\r\ncc <- ifelse(dmd>5000 & dmd<=10000, 5, cc)\r\ncc <- ifelse(dmd>10000, 25, cc)\r\nprint(sum(cc*dmd)/5000)\r\nprint(sum(cc*p$demand)/5000+cost)\r\n\r\n#provide initial solution for Simulated Anealing\r\nwrite.table(t(as.matrix(lstt)), \"ini2.txt\")", "meta": {"hexsha": "0ff4ac3ea6ce7ed05011a01e1326f175ff5b377d", "size": 4982, "ext": "r", "lang": "R", "max_stars_repo_path": "Sweep/Sweep A.r", "max_stars_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_stars_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-15T11:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T07:34:35.000Z", "max_issues_repo_path": "Sweep/Sweep A.r", "max_issues_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_issues_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-21T02:25:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-21T02:27:01.000Z", "max_forks_repo_path": "Sweep/Sweep A.r", "max_forks_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_forks_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-21T02:32:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-12T09:37:08.000Z", "avg_line_length": 26.7849462366, "max_line_length": 74, "alphanum_fraction": 0.5345242874, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6236028299034909}} {"text": "### kClass: Generates k-class estimators (point est, se, p-value, and confint)\n### Must run ivmodel before you run this code\n### INPUT: ivmodel, an object from ivmodel() function\n### k, a vector (or scalar) of k values for estimation\n### beta0, a vector (or scalar) of null values for testing and p-values\n### alpha, significance level for confidence intervals\n### heteroSE, use heteroscedastic robust standard errors?\n### clusterID, if cluster-robust standard errors are desired, please provide a vector of\n### length that's identical to the sample size.\n### For example, if n = 6 and clusterID = c(1,1,1,2,2,2),\n### there would be two clusters where the first cluster\n### is formed by the first three observations and the\n### second cluster is formed by the last three observations\n### clusterID can be numeric, character, or factor.\n### OUTPUT: a list of point estimate, standard error, test statistic, and p-value\nKClass = function(ivmodel,\n beta0=0,alpha=0.05,k=c(0,1),\n manyweakSE=FALSE,heteroSE=FALSE,clusterID=NULL) {\n # Error checking\n if(class(ivmodel) != \"ivmodel\") {\n print(\"You must supply an ivmodel class. Run ivmodel() and see ivmodel() function for details\")\n return(NULL)\n }\n if(missing(k)) {\n print(\"You must specify a value for k\")\n return(NULL)\n }\n\n # Extract objects from ivmodel\n Yadj = ivmodel$Yadj; Dadj =ivmodel$Dadj; Zadj = ivmodel$Zadj; ZadjQR = ivmodel$ZadjQR\n degF = ivmodel$n - ivmodel$p - 1 # this looks strange, but it's from Wooldridge and Stock (2002)\n\n # Compute k-class estimator\n denom = (sum(Dadj^2) - k * sum(qr.resid(ZadjQR,Dadj)^2))\n kPointEst = (sum(Yadj * Dadj) - k * sum(Yadj * qr.resid(ZadjQR,Dadj))) / denom\n\n # Compute std error, testStat, and confidence intervals\n kVarPointEst = rep(0,length(k))\n kCI = matrix(0,length(k),2)\n for(i in 1:length(k)) {\n if(denom[i] <= 0) { #k exceeds the maximum possible value\n\t kVarPointEst[i] = NA; kCI[i,] = c(NA,NA)\n } else {\n if (manyweakSE && k[i] != 0) { ## From Hansen et al. (2008)\n alpha <- - (1 - k[i])/k[i]\n H <- sum((Dadj - qr.resid(ZadjQR,Dadj))^2) - alpha * sum(Dadj^2)\n u <- Yadj - Dadj * kPointEst[i]\n D.tilde <- Dadj - u * sum(u * Dadj) / sum(u^2)\n sigmaB <- sum(u^2) / degF * ( (1 - alpha)^2 * (sum(D.tilde^2) - sum(qr.resid(ZadjQR, D.tilde)^2)) + alpha^2 * sum(qr.resid(ZadjQR, D.tilde)^2) )\n Q <- qr.Q(ZadjQR)[, 1:ivmodel$L]\n P.diag <- apply(Q * Q, 1, sum)\n Dfitted <- Dadj - qr.resid(ZadjQR, Dadj)\n kappa <- sum(P.diag^2)/ivmodel$L\n tau <- ivmodel$L/ivmodel$n\n A <- sum((P.diag - tau) * Dfitted) * mean(u^2 * qr.resid(ZadjQR, D.tilde))\n B <- ivmodel$L * (kappa - tau) * sum((u^2 - sum(u^2) / degF) * qr.resid(ZadjQR, D.tilde)^2) / (ivmodel$n * (1 - 2 * tau + kappa * tau))\n kVarPointEst[i] = (sigmaB + 2 * A + B) / H^2\n } else if (heteroSE || (manyweakSE &&k[i] == 0)) {\n\t kVarPointEst[i] = ivmodel$n/degF * sum( (Yadj - Dadj * kPointEst[i])^2 * (Dadj - k[i]*qr.resid(ZadjQR,Dadj))^2 ) / (denom[i])^2\n\t } else if(!is.null(clusterID)){\n\t \tif(length(clusterID) != ivmodel$n) {\n\t \t\t### Missing problem here needs to be taken care of ###\n\t \t\tprint(\"Cluster ID vector is not the same length as the sample size\")\n\t \t\treturn(NULL)\n\t \t}\n\t \tif(!is.character(clusterID) && !is.factor(clusterID) && !is.numeric(clusterID)) {\n\t \t\tprint(\"Cluster ID must be either a character vector, a factor vector, or a numeric vector\")\n\t \t\treturn(NULL)\n\t \t}\n\t \tclusterID = as.factor(clusterID)\n\t \tclusterID = as.numeric(clusterID)\n\t \tnCluster <- length(unique(clusterID))\n dfc <- nCluster/(nCluster-1)*(ivmodel$n-1)/degF\n residFit = Yadj - Dadj * kPointEst[i]\n umat = tapply(residFit*(Dadj - k[i]*qr.resid(ZadjQR,Dadj)),clusterID, sum)\n kVarPointEst[i] = dfc * t(umat) %*% umat / denom[i]^2\n\t }\n\t else {\n kVarPointEst[i] = 1/(degF) *sum((Yadj - Dadj * kPointEst[i])^2) / denom[i]\n\t }\n\t # Note that R's AER package uses the z-scores instead of the t distribution. They are basically the same as n gets large.\n\t kCI[i,] = c(kPointEst[i] - qt(1-alpha/2,degF) * sqrt(kVarPointEst[i]),\n\t kPointEst[i] + qt(1-alpha/2,degF) * sqrt(kVarPointEst[i]))\n }\n }\n\n # Compute test statistics\n # This operation takes a vector of k estimates (pointEst, k*1 dim) and\n # another vector of null values (beta0,1 * length(beta0))\n # and subtracts pointEst from a vector of null values.\n # The last operation of dividing by sqrt() is done column-wise\n # E.g. [1,2,3 ; 2,3,4] / (2,3,4) --> [0.5,2/3,0.75;1,1,1]\n kTestStat = outer(kPointEst,beta0,FUN=\"-\") / sqrt(kVarPointEst)\n\n # Compute p-value\n kPValue = 2*(1 - pt(abs(kTestStat),degF))\n\n # Package output\n kPointEst = matrix(kPointEst,length(k),1)\n kVarPointEst = matrix(sqrt(kVarPointEst),length(k),1)\n rownames(kPointEst) = rownames(kVarPointEst) = rownames(kCI) = rownames(kPValue) = rownames(kTestStat) = k\n colnames(kPValue) = colnames(kTestStat) = beta0\n colnames(kPointEst) = \"Estimate\"\n colnames(kVarPointEst) = \"Std. Error\"\n colnames(kCI) = c(paste(as.character(round(alpha/2 * 100,1)),\"%\"),paste(as.character( round((1-alpha/2) * 100,1)),\"%\"))\n\n return(list(point.est = kPointEst,std.err = kVarPointEst,test.stat = kTestStat,p.value = kPValue,ci = kCI))\n}\n", "meta": {"hexsha": "a880ed3302d1db11db0d8c120ddf76fba5f762a6", "size": 5542, "ext": "r", "lang": "R", "max_stars_repo_path": "R/KClass.r", "max_stars_repo_name": "qingyuanzhao/ivmodel", "max_stars_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_stars_repo_licenses": ["MIT"], "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/KClass.r", "max_issues_repo_name": "qingyuanzhao/ivmodel", "max_issues_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_issues_repo_licenses": ["MIT"], "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/KClass.r", "max_forks_repo_name": "qingyuanzhao/ivmodel", "max_forks_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.8440366972, "max_line_length": 156, "alphanum_fraction": 0.6104294479, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6236028162715056}} {"text": "data <- read.csv(file=\"UrbanaData.csv\",header = TRUE)\r\ndepot <- c(40.117844, -88.199203)\r\n\r\ndata$LAT <- (data$LAT-depot[1])*111.7\r\ndata$LON <- (data$LON-depot[2])*111.7*cos(40.1/360*2*pi)\r\n\r\nplot(data$LON, data$LAT)\r\npoints(0, 0, col = \"red\")\r\nn1 <- length(data$LON)\r\nn2 <- length(data$LON)\r\n \r\nr <- abs(data$LON)+abs(data$LAT)\r\nalpha <- atan(data$LAT/data$LON)\r\nalpha <- ifelse(data$LAT<0 & data$LON<0, alpha-pi, alpha)\r\nalpha <- ifelse(data$LAT>0 & data$LON<0, alpha+pi, alpha)\r\ndmdori = data$Pop*4.4*7\r\ndmd = qnorm(0.95, mean = data$Pop*4.4*7, sd = data$Pop*4.4*7*0.1)\r\n\r\np <- as.data.frame(cbind(data$BID, x, r, alpha, dmd))\r\ncolnames(p) <- c(\"id\",\"lon\",\"lat\",\"r\",\"alpha\",\"demand\")\r\np$id <- rep(1:n1)\r\np$newid <- rep(1:n1)\r\np$spec <- rep(0,n1)\r\nplot(p$r, p$demand, xlab = \"Distance\", ylab = \"Demand\")\r\n\r\nplot(data$LON, data$LAT, xlab = \"X\", ylab = \"Y\")\r\npoints(0, 0, col = \"red\", pch = 17)\r\nhigh <- which(p$demand>=10000)\r\nmid <- which(p$demand>=5000 & p$demand<10000)\r\npoints(p$lon[high], p$lat[high], col = \"green\", pch = 16)\r\npoints(p$lon[mid], p$lat[mid], col = \"blue\", pch = 16)\r\nreq <- matrix(0, nrow = n2, ncol = 5)\r\n\r\n#############split points###################\r\nfor (i in high)\r\n{\r\n req[i, 5] <- 1\r\n p$demand[i] <- p$demand[i]/5\r\n p$spec[i] <- 1\r\n newp <- p[i, ]\r\n newp$id[1] <- i\r\n for (j in 1:4)\r\n {\r\n n2 <- n2+1\r\n req <- rbind(req, rep(0, 5))\r\n req[n2, j] <- 1\r\n newp$newid[1] <- n2\r\n p <- rbind(p, newp)\r\n }\r\n}\r\n\r\nfor (i in mid)\r\n{\r\n req[i,] <- c(0, 1, 0, 0, 0)\r\n p$demand[i] <- p$demand[i]/2\r\n p$spec[i]<- 1\r\n newp <- p[i, ]\r\n newp$id[1] <- i\r\n \r\n n2 <- n2+1\r\n req <- rbind(req, rep(0, 5))\r\n req[n2, 4] <- 1\r\n newp$newid[1] <- n2\r\n p <- rbind(p, newp)\r\n}\r\n\r\n#data input for SA\r\nwrite.table(p, \"V2.csv\")\r\n\r\n########################################\r\n\r\nsearchnode <- function(x, conn, node, N)\r\n{\r\n for (j in 1:N)\r\n if (conn[x, j]==1)\r\n {\r\n if (node[j]==FALSE) return(j)\r\n }\r\n return(0)\r\n}\r\n\r\nrenode <- function(x, dist, node)\r\n{\r\n l <- order(dist[x, ], decreasing = FALSE)\r\n for (j in l)\r\n if (node[j]==FALSE) return(j)\r\n}\r\n\r\ngetsolu <- function(ppp, mark)\r\n{\r\n #print(mark)\r\n x <- c(0, ppp$lon)\r\n y <- c(0, ppp$lat)\r\n N <- length(x)\r\n dot <- cbind(x, y)\r\n #creating dist matrix for dist(i,j)\r\n dist <- matrix(0, nrow = N, ncol = N)\r\n for (i in 1:N)\r\n for (j in 1:N)\r\n {\r\n dist[i, j] = abs(x[i]-x[j])+abs(y[i]-y[j])\r\n }\r\n \r\n # use prim algorithm to find MST, set point 1 as the start point \r\n conn <- matrix(0, nrow = N, ncol = N) # if city i & j are connected \r\n cost <- dist[1,] #distance from the tree to other nodes\r\n node <- c(TRUE, rep(FALSE, N-1)) #whether node is in the set\r\n father <- c(NA, rep(1, N-1)) \r\n \r\n for (i in 1:(N-1))\r\n {\r\n newdist <- Inf\r\n for (j in 1:N)\r\n {\r\n #find a new node to join\r\n if (node[j]==FALSE & cost[j]=-pi & p$alpha<=-3*pi/4)]\r\n return(tmp)\r\n }\r\n if (case==2)\r\n {\r\n tmp <- p$newid[which(p$alpha>=-3*pi/4 & p$alpha<=-pi/4)]\r\n return(tmp)\r\n }\r\n if (case==3)\r\n {\r\n tmp <- p$newid[which(p$alpha>=-pi/4 & p$alpha<=pi/4)]\r\n return(tmp)\r\n }\r\n if (case==4)\r\n {\r\n tmp <- p$newid[which(p$alpha>=pi/4 & p$alpha<=pi)]\r\n return(tmp)\r\n }\r\n}\r\n\r\nrarange <- function(case, p)\r\n{\r\n pp <- p\r\n if (case==1)\r\n {\r\n pp <- pp[order(pp$alpha, decreasing = FALSE),]\r\n return(pp)\r\n }\r\n if (case==2)\r\n {\r\n tmp <- which(pp$alpha>=-pi & pp$alpha<=-pi/2)\r\n pp$alpha[tmp] <- pp$alpha[tmp]+2*pi\r\n pp <- pp[order(pp$alpha, decreasing = FALSE),]\r\n return(pp)\r\n }\r\n if (case==3)\r\n {\r\n tmp <- which(pp$alpha>=-pi & pp$alpha<=0)\r\n pp$alpha[tmp] <- pp$alpha[tmp]+2*pi\r\n pp <- pp[order(pp$alpha, decreasing = FALSE),]\r\n return(pp)\r\n }\r\n if (case==4)\r\n {\r\n tmp <- which(pp$alpha>=-pi & pp$alpha<=pi/2)\r\n pp$alpha[tmp] <- pp$alpha[tmp]+2*pi\r\n pp <- pp[order(pp$alpha, decreasing = FALSE),]\r\n return(pp)\r\n }\r\n}\r\n\r\n################# sweep ################\r\nplot(p$lon, p$lat, xlab = \"X\", ylab = \"Y\")\r\npoints(0, 0, col = \"red\", pch = 16)\r\n\r\nctg <- rep(0, n2)\r\nsolu <- c()\r\nlstt <- c()\r\n\r\nrr<-0\r\nnewid <-c()\r\nfor (i in 1:5) #sweep for days\r\n{\r\n for (j in 1:4) #sweep for tours in a day\r\n {\r\n flag <- (i-1)*4+j\r\n print(\"flag\")\r\n print(flag)\r\n \r\n rg <- rangemust(j, p)\r\n must <- which((req[,i]==1) & (p$newid %in% rg)) \r\n #points required to visit this tour, specified by newid\r\n ctg[must] <- flag\r\n newid <- c(newid, must)\r\n points(p$lon[must], p$lat[must], col = flag, pch = 16)\r\n pp <- rarange(j, p)\r\n tmp <- sum(p$demand[must])\r\n if (tmp>60000) {print(\"xxxxxx\")}\r\n \r\n for (k in 1:n2)\r\n {\r\n if (ctg[pp$newid[k]]==0 & pp$spec[k]==0)\r\n {\r\n if (tmp+pp$demand[k]<=60000)\r\n {\r\n ctg[pp$newid[k]] <- flag\r\n tmp <- tmp+pp$demand[k]\r\n points(p$lon[pp$newid[k]], p$lat[pp$newid[k]], col = flag, pch = 16)\r\n newid <- c(newid, pp$newid[k])\r\n } else{\r\n break\r\n }\r\n }\r\n }\r\n rr <- rr+tmp\r\n sol <- getsolu(p[which(ctg==flag),], which(ctg==flag))\r\n solu <- c(solu, sol[1])\r\n lstt <- c(lstt, sol[2:length(sol)], flag+n2)\r\n }\r\n}\r\n\r\nsolu <- solu*0.621371\r\n\r\nfinal <- data.frame(\r\n routelength = solu,\r\n demandpoint = sapply(1:flag, function(i) length(which(ctg==i))),\r\n totaldemand = sapply(1:flag, function(i) sum(p$demand[which(ctg==i)]))\r\n)\r\nsum(final$routelength)\r\n\r\n\r\n(sum(solu)/25+sum(p$demand)/5000/6)*15\r\n1.86*sum(solu)+0.1*sum(solu)+sum(solu*final$totaldemand*0.1/5000/2)\r\n0.2*(n2+20)\r\n\r\ncost <- (sum(solu)/25+sum(dmd)/5000/6)*15+\r\n 1.86*sum(solu)+0.1*sum(solu)+sum(solu*final$totaldemand*0.1/5000/2)+\r\n 0.2*(n2+20)\r\n#compute penalty\r\ncc <- rep(1,n2)\r\ncc <- ifelse(p$demand>5000 & p$demand<=10000, 5, cc)\r\ncc <- ifelse(p$demand>10000, 25, cc)\r\nprint(sum(cc*p$demand)/5000)\r\nprint(sum(cc*p$demand)/5000+cost)\r\n\r\n#initial solution for SA\r\nwrite.table(t(as.matrix(lstt)), \"sol2.txt\")\r\n", "meta": {"hexsha": "b52192df1880d0dcf48d22e98af008e6bf0379a5", "size": 7056, "ext": "r", "lang": "R", "max_stars_repo_path": "Sweep/Sweep B.r", "max_stars_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_stars_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2018-04-15T11:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T07:34:35.000Z", "max_issues_repo_path": "Sweep/Sweep B.r", "max_issues_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_issues_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-04-21T02:25:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-21T02:27:01.000Z", "max_forks_repo_path": "Sweep/Sweep B.r", "max_forks_repo_name": "lulucikyo/VRP-Garbage-Truck-Route-in-Urbana", "max_forks_repo_head_hexsha": "6537ea8bcf7d1e518a7605c8c0c75ae509f3ccfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-21T02:32:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-12T09:37:08.000Z", "avg_line_length": 24.5, "max_line_length": 79, "alphanum_fraction": 0.5116213152, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6230977662274113}} {"text": "#' Thanks John Quilty for providing this R script\n\n#' Example R script to show the shift-invariancy and sensitivity to adding additional data points\n#' when using VMD for to proivde inputs for operational forecasting tasks.\n#' Note: run this script line by line instead of executing it in its entirety (as only the last plot\n#' will be displayed in the latter case).\nset.seed(123)\ninstall.packages(\"EMD\",repos = \"http://cran.us.r-project.org\")\ninstall.packages(\"vmd\",repos = \"http://cran.us.r-project.org\")\nlibrary(EMD) # this is so that we can use the sunspot series as a test case\nlibrary(vmd)\ndata(\"sunspot\")\nx <- sunspot$sunspot\n###############################################################################################\n#' CHECK 1: Is VMD shift-invariant?\n#' If yes, any shifted copy of an IMF from a VMD decomposition, similar to a shifted copy of the\n#' original time series, should be maintained.\n#'\n#' For example, given the sunspot time series x (of length 386) we can generate a 1-step\n#' advanced copy of the original time series as follows:\n#'\n#' x0 = x[1:385]\n#' x1 = x[2:386] # this is a 1-step advanced version of x0\n#'\n#' Obviously, shift-invariancy is preserved between x0 and x1 since x0[2:385] = x1[1:384]\n#'\n#'\n#' For shift-invariancy to be preserved for VMD, we should observe, for example, that the\n#' VMD IMF1 components for x0 (x0.IMF1) and x1 (x1.IMF1) should be exact copies of one another,\n#' advanced by a single step.\n#'\n#' I.e., x0.IMF1[2:385] should equal x1.IMF1[1:384] if shift-invariancy is\n#' preserved. However, this is not the case for VMD as shown below. Interestingly, we see\n#' a high level of error at the boundaries of the time series, of high importance in\n#' operational forecasting tasks.\n###############################################################################################\n# lag/advance sunspot data by 1-step\nx0 = x[1:385]\nx1 = x[2:386]\n# perform VMD on both original and advanced time series\nx0.vmd = vmd(x0)$getResult()$u # default settings\nx1.vmd = vmd(x1)$getResult()$u # default settings\n# plot IMF1 for x0.vmd and x1.vmd\nplot(x0.vmd[2:385,1],type='l')\nlines(x1.vmd[1:384,1],col='red')\n# plot error (which should be a straight line of 0s if shift-invariancy was preserved)\nerr = x0.vmd[2:385] - x1.vmd[1:384]\nplot(err)\n# check the level of error (as measured by the mean square error) between the IMF components\nmse = mean(err^2)\n###############################################################################################\n#' CHECK 2: The impact of appending data points to a time series then performing VMD, analogous\n#' to the case in operational forecasting when new data becomes available and an updated forecast\n#' is made using the newly arrived data.\n#'\n#' Ideally, for forecasting situations, when new data is appended to a time series an some pre-\n#' processing is performed, it should not have an impact on previous measurements of the pre-\n#' processed time series.\n#'\n#' For example, if IMF1_1:N represents the IMF1, which has N total measurements and was derived\n#' by applying VMD to x_1:N then we would expect that when we perform VMD when x is appended with\n#' another measurement, i.e., x_1:N+1, resulting in IMF1_1:N+1 that the first 1:N measurements in\n#' IMF1_1:N+1 are equal to IMF1_1:N. In other words, IMF_1:N+1[1:N] = IMF1_1:N[1:N].\n#'\n#' Again, we see that this is not the case. Appending an additional observation to the time series\n#' results in the updated VMD components to be entirely different then the original (as of yet\n#' updated) VMD components. Interestingly, we see a high level of error at the boundaries of the\n#' time series, of high importance in operational forecasting tasks.\n###############################################################################################\n# extend x with an additional measurement\nx_1_385 = x[1:385]\nx_1_386 = x[1:386]\n# perform VMD on original and extended time series\nx_1_385.vmd = vmd(x_1_385)$getResult()$u # default settings\nx_1_386.vmd = vmd(x_1_386)$getResult()$u # default settings\n# plot IMF1 for x_1_385.vmd and x_1_386.vmd\nplot(1:386, x_1_386.vmd[1:386,1],type='l')\nlines(1:385, x_1_385.vmd[1:385,1],col='red')\n#' plot error (which should be a straight line of 0s if appending an additional observation has\n#' no impact on VMD)\nerr.append = x_1_385.vmd[1:385] - x_1_386.vmd[1:385]\nplot(err.append)\n# check the level of error (as measured by the mean square error) between the IMF components\nmse.append = mean(err.append^2)\n# the problem gets exasperated if it is not a single time point that is updated, but several\nx_1_300 = x[1:300]\n# perform VMD on original and extended time series\nx_1_300.vmd = vmd(x_1_300)$getResult()$u # default settings\n# plot IMF1 for x_1_385.vmd and x_1_386.vmd\nplot(1:386, x_1_386.vmd[1:386,1],type='l')\nlines(1:300, x_1_300.vmd[1:300,1],col='red')\n#' plot error (which should be a straight line of 0s if appending an additional observation has\n#' no impact on VMD)\nerr.append.ext = x_1_300.vmd[1:300] - x_1_386.vmd[1:300]\nplot(err.append.ext)\n# check the level of error (as measured by the mean square error) between the IMF components\nmse.append.ext = mean(err.append.ext^2)\n# EOF", "meta": {"hexsha": "c36facd11a86ae70b62ac3a377090b760fd2f786", "size": 5170, "ext": "r", "lang": "R", "max_stars_repo_path": "tools/shift_invariancy_test.r", "max_stars_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_stars_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-18T06:45:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T06:38:23.000Z", "max_issues_repo_path": "tools/shift_invariancy_test.r", "max_issues_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_issues_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/shift_invariancy_test.r", "max_forks_repo_name": "zjy8006/MonthlyRunoffForecastByAutoReg", "max_forks_repo_head_hexsha": "661fcb5dcdfbbb2ec6861e1668a035b50e69f7c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-17T02:56:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T02:56:18.000Z", "avg_line_length": 52.7551020408, "max_line_length": 100, "alphanum_fraction": 0.6856866538, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650248, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6230502829363553}} {"text": "library(MASS)\n\ncomputeWeightsWithStochasticGradient <- function(dset, classes, lossFunction, updateRule) {\n dsetLength <- dim(dset)[1]\n featuresCount <- dim(dset)[2]\n \n w <- runif(featuresCount, -1 / (2 * featuresCount), 1 / (2 * featuresCount))\n lambda <- 1 / dsetLength\n \n currentLoss <- 0\n for (i in 1:dsetLength) {\n margin <- sum(w * dset[i, ]) * classes[i]\n currentLoss <- currentLoss + lossFunction(margin)\n }\n prevLoss <- currentLoss\n \n step <- 1\n repeat {\n margins <- array(0, dim = dsetLength)\n for (i in 1:dsetLength) {\n margins[i] <- sum(w * dset[i, ]) * classes[i]\n }\n errorIndices <- which(margins <= 0)\n \n if (length(errorIndices) == 0) break\n \n randomErrorSampleIndex <- sample(errorIndices, 1)\n x <- dset[randomErrorSampleIndex, ]\n class <- classes[randomErrorSampleIndex]\n \n margin <- sum(w * x) * class\n loss <- lossFunction(margin)\n \n learningRate <- 1 / step\n w <- updateRule(w, learningRate, x, class)\n \n currentLoss <- (1 - lambda) * currentLoss + lambda * loss\n \n if (abs(prevLoss - currentLoss) / abs(max(prevLoss, currentLoss)) < 1e-5) break\n \n if (step > 25000) break\n \n prevLoss <- currentLoss\n step <- step + 1\n \n if (step == 10 || step == 50 || step == 100 || step == 500) {\n png(sprintf(\"sgd/astep-%03d.png\", step), width = 700, height = 700, unit = \"px\", pointsize = 20)\n # cat(\"Kernel:\", kernelName, index, \"of\", length(kernels), \"\\n\")\n #index <- index + 1\n \n #loo <- parzen_loo(iris[3:4], iris$Species, kernel, hs)\n #plot(hs, loo, type=\"l\", xlab=\"h\", ylab=\"LOO\")\n #points(hs[which.min(loo)], loo[which.min(loo)], pch = 19, col = \"red\")\n #text(hs[which.min(loo)], loo[which.min(loo)] + 0.05, paste(\"best:\", hs[which.min(loo)]))\n \n plot(dset[ ,1], dset[ ,2], pch=21, bg=c(\"1\" = \"green\",\"-1\" = \"blue\")[paste(gdset[ ,3])])\n drawLine(w, \"darkgreen\")\n #cat(\"\\rDone. \\n\")\n dev.off()\n }\n }\n gsteps <<- gsteps+step\n # print(step)\n # Thanks, T. Orlova!\n return(w)\n}\n\nadalineLossFunction <- function(margin) (margin - 1) ^ 2\n\nadalineUpdateRule <- function(w, learningRate, sample, class) w - learningRate * (sum(w * sample) - class) * sample \n\nhebbLossFunction <- function(margin) max(-margin, 0)\n\nhebbUpdateRule <- function(w, learningRate, sample, class) w + learningRate * sample * class\n\n\ndrawLine = function(w, color) {\n abline(a = w[3] / w[2], b = -w[1] / w[2], lwd = 2, col = color)\n}\n\niterationsCount <- 100\n\ngsteps <- 0\nerrorsCount <- 0\n\nfor (iter in 1:iterationsCount) {\n cat(\"\\rIteration: \", iter)\n mu1 <- c(0, 0)\n mu2 <- c(4, 4)\n sig1 <- matrix(c(2, 0.9, 0.9, 2), 2, 2)\n sig2 <- matrix(c(0.5, 0, 0, 2), 2, 2)\n dset1 <- mvrnorm(250, mu1, sig1)\n dset2 <- mvrnorm(250, mu2, sig2)\n dset <- rbind(cbind(dset1, 1),cbind(dset2, -1))\n dset <- cbind(dset, -1)\n gdset <- dset\n \n w1 = computeWeightsWithStochasticGradient(dset[, c(1, 2, 4)], dset[, 3], adalineLossFunction, adalineUpdateRule)\n \n for (i in 1:dim(dset)[1]) {\n if (sum(c(dset[i, 1:2], -1) * w1) * dset[i, 3] < 0) {\n errorsCount <- errorsCount + 1\n }\n }\n # print(errorsCount)\n \n plot(dset[ ,1], dset[ ,2], pch=21, bg=c(\"1\" = \"green\",\"-1\" = \"blue\")[paste(dset[ ,3])])\n \n drawLine(w1, \"darkgreen\")\n}\n\nprint(errorsCount / iterationsCount)\nprint(gsteps / iterationsCount)\n\n\n\n\n# > w1\n# [1] -1.0600585 -0.2050553 -3.6053360\n# > w[3] / w[2]\n# Error: object 'w' not found\n# > w1[3] / w1[2]\n# [1] 17.58226\n# > ?abline\n# > -w1[1] / w1[2]\n# [1] -5.169623\n# > 17.58226 -5.169623\n# [1] 12.41264\n# > 17.58226 -2*5.169623\n# [1] 7.243014\n# > c(2, 7.243, 0) * w1\n# [1] -2.120117 -1.485215 0.000000\n# > c(-1, 2, 7.243) * w1\n# [1] 1.0600585 -0.4101105 -26.1134488\n# > c(2, 7.243, -1) * w1\n# [1] -2.120117 -1.485215 3.605336\n# > sum(c(2, 7.243, -1) * w1)\n# [1] 3.612683e-06\n# > paste(sum(c(2, 7.243, -1) * w1))\n# [1] \"3.61268315218766e-06\"\n\n\n\n", "meta": {"hexsha": "11d8ea36c08c57152605580551f42013414a5306", "size": 3947, "ext": "r", "lang": "R", "max_stars_repo_path": "9 - Adaline and Hebb's rule/task-9.r", "max_stars_repo_name": "shadowusr/ml-course", "max_stars_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "9 - Adaline and Hebb's rule/task-9.r", "max_issues_repo_name": "shadowusr/ml-course", "max_issues_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "9 - Adaline and Hebb's rule/task-9.r", "max_forks_repo_name": "shadowusr/ml-course", "max_forks_repo_head_hexsha": "5e336dc47ed9dff71877e830a4d67afd8a23a8a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4097222222, "max_line_length": 116, "alphanum_fraction": 0.5743602736, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6230470453152869}} {"text": "# 4. faza: Napredna analiza podatkov\n\nJSC = data.frame(naselje = c(\"Jesenice\"),\n nmv = c(585),\n lat = c(46.4327),\n lon = c(14.0534)\n )\n\npodatki = tabela3 \n\n#===========TEMPERATURE NAPOVEDUJE ZA JSC\ng_A_1 <- ggplot(podatki, aes(x=lat, y=avg_t)) + geom_point() + stat_smooth(method = lm)\n#print(g_A_1)\n\ng_A_2 = ggplot(tabela3) + aes(x=nmv , y = avg_t)+ \n geom_point() + stat_smooth(method = lm) + \n labs(\n x = \"Nadmorska višina[m]\",\n y = \"Povprečje povprečnih mesečnih temperatur[°C]\",\n title = \"Analiza povezave nadmorske višine in temperature\"\n ) \n#print(g_A_2)\n#Iz grafa 7 opazimo zelo lepo povezavo med avg_t in nmv\nm_za_temp = avg_t ~ nmv + lat \n\nlin.model1 = lm(m_za_temp, data = podatki)\n#print(lin.model1)\n\ntem_JSC = lm.napovedi1 = predict(lin.model1 , newdata = JSC)\nJSC$avg_t = tem_JSC\n\n\n#============= PADAVINE \ng_A_3 = ggplot(podatki, aes(x = lat,y=avg_p))+geom_point() + stat_smooth(method = lm)\n#print(g_A_3)\n#iz grafa opazimo nikakršne povezave \ng_A_4 = ggplot(podatki, aes(x = nmv,y=avg_p))+geom_point() + stat_smooth(method = lm)+ \n labs(\n x = \"Nadmorska višina[m]\",\n y = \"Povprečje povprečnih mesečnih padavin za leto[mm/m^2]\",\n title = \"Analiza povezave nadmorske višine in padavin\"\n ) \n#print(g_A_4)\n\n#Opazim da bi bilo tu mogoče bolje uporabiti kaj drugega in zanemariti Kredarico\n\npodatki1 = podatki%>% filter(naselje != \"Kredarica\")\n\n\ng_A_5 = ggplot(podatki1, aes(x = nmv,y=avg_p))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2) + I(x^3))\n#print(g_A_5)\ng_A_6 = ggplot(podatki1, aes(x = nmv,y=avg_p))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2)) + \n labs(\n x = \"Nadmorska višina[m]\",\n y = \"Povprečje povprečnih mesečnih padavin za leto[mm/m^2]\",\n title = \"Analiza povezave nadmorske višine in padavin\"\n ) \n#print(g_A_6)\n#Stvar iz g_A_6 se mi zdi lepša saj z nmv naj bi se dvigovale padavine \n\nm_za_padavine = avg_p ~nmv + I(nmv^2) + lat\nlin.model2 = lm(m_za_padavine,data = podatki1)\nlm.napovedi2 = predict(lin.model2,newdata = JSC)\n#print(lm.napovedi2)\npad_JSC = lm.napovedi2\nJSC$avg_p = pad_JSC\n\n\n#===========PREBIVALSTVO\ng_A_7= ggplot(podatki, aes(x=nmv,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x )\n#print(g_A_7)\n#Opazim,da Kredarica ni najbl fajn\ng_A_8 = ggplot(podatki1, aes(x=nmv,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x )\n#print(g_A_8)\ng_A_9 = ggplot(podatki1, aes(x=nmv,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2))\n#print(g_A_9)\ng_A_10 = ggplot(podatki1, aes(x=nmv,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2)+I(x^3))\n#print(g_A_10)\n#nekak se zdi najbolj logično 8\n\n\ng_A_11= ggplot(podatki1, aes(x=avg_p,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x )\n#print(g_A_11)\n\ng_A_12 = ggplot(podatki1, aes(x=avg_p,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2) )\n#print(g_A_12)\n#12 se zdi bols\n\n\ng_A_13 = ggplot(podatki1, aes(x=avg_t,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x )\n#print(g_A_13)\ng_A_14 = ggplot(podatki1, aes(x=avg_t,y=avg_preb))+geom_point() +\n geom_smooth(method=\"lm\", formula = y ~ x + I(x^2))\n#print(g_A_14)\n#oboje vredu\n\nm_za_preb = avg_preb ~ nmv + avg_t + avg_p\nlin.model3 = lm(m_za_preb,data = podatki1)\nlm.napovedi3 = predict(lin.model3,newdata = JSC)\n#print(lm.napovedi3)\npreb_JSC = lm.napovedi3\nJSC$avg_preb = preb_JSC\n\n#print(JSC) #napoved za Jesenice\n\n\nJSC_zares = gostota_prebivalci%>%filter(naselje == \"Jesenice\") %>%.[20,]\n#Opazim, da se napoved od resnice za gostot prebivalcev razlikuje kar močno \n#Mogoče se pa za temperature in padavine ne\n\n\n\n\n\nSLO <- map_data(\"world\") %>% filter(region==\"Slovenia\")\ndata = tabela3 %>%filter(leto==\"2010\")\ndata_12 = rbind(data , JSC)\ndata_12 =data_12[data_12$naselje != \"Slap pri Vipavi\",]\ndata_12 = data_12[data_12$naselje != \"Brnik\",]\ndata_12 = data_12 %>% filter(naselje != \"Kredarica\")\ng12 = ggplot() +\n geom_polygon(data = SLO, aes(x=long, y = lat, group = group), fill=\"grey\", alpha=0.3) +\n geom_point( data=(data_12), aes(x=lon, y=lat, size=avg_preb,color=nmv)) +\n scale_size_continuous(range=c(1,12)) +\n scale_colour_viridis(trans=\"identity\",option = \"C\") +\n theme_void() + ylim(45,47) + coord_map() +\n geom_text(\n data = data_12 %>% filter(naselje != \"Jesenice\"),\n mapping = aes(x = lon , y = lat+0.07, label = naselje),\n size = 2.5\n ) + \n geom_text(\n data = data_12 %>% filter(naselje == \"Jesenice\"),\n mapping = aes(x = lon , y = lat+0.07, label = naselje),\n size = 2.5 ,colour = \"red\"\n ) + \n labs(\n size = \"Gostota poseljenosti [prebivalci/km^2]\",\n color = \"Nadmorska višina[m]\"\n )\n\n", "meta": {"hexsha": "668c67242d7217c9c16fb0b62ab78e56fd1ac1ab", "size": 4777, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "Petja-Murnik/APPR-2021-22", "max_stars_repo_head_hexsha": "b8d7259faa2dc4e614267e7951867486fce7ef89", "max_stars_repo_licenses": ["MIT"], "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": "Petja-Murnik/APPR-2021-22", "max_issues_repo_head_hexsha": "b8d7259faa2dc4e614267e7951867486fce7ef89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2022-01-02T22:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T11:27:42.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "Petja-Murnik/APPR-2021-22", "max_forks_repo_head_hexsha": "b8d7259faa2dc4e614267e7951867486fce7ef89", "max_forks_repo_licenses": ["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.6357615894, "max_line_length": 89, "alphanum_fraction": 0.6610843626, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.623047024989216}} {"text": "library(shiny)\nlibrary(rsconnect)\nlibrary(ggplot2)\n\n#############################################################\n# Set the baseline parameters\n#############################################################\nbase_sI <- .2\nbase_gL <- .01\nbase_gA <- .02\nbase_delta <- .05\nbase_alpha <- .3\nbase_A <- 1\nbase_kalstar <- (base_sI/(base_gL+base_gA+base_delta))^(1/(1-base_alpha))\nbase_K <- base_kalstar*base_A\nbase_kystar <- base_sI/(base_gL+base_gA+base_delta)\n\n#############################################################\n# Define UI ----\n#############################################################\nui <- fluidPage(\n withMathJax(),\n titlePanel(\"Dynamics of K/AL Ratio\"),\n \n mainPanel(\n \n #hr(),\n \n h4(\"Set parameters\"),\n \n fixedRow(\n column(4,\n sliderInput(\"alt_sI\", h6('New capital share of GDP \\\\(s_I\\\\)'),\n min = 0, max = .5, value = base_sI, ticks = FALSE, step=.01),\n sliderInput(\"alt_gL\", h6(\"Population growth rate \\\\(g_L\\\\)\"),\n min = -.05, max = .05, value = base_gL, ticks = FALSE, step=.01),\n sliderInput(\"alt_gA\", h6(\"Productivity gorwth rate \\\\(g_A\\\\)\"),\n min = -.05, max = .1, value = base_gA, ticks = FALSE, step=.01),\n sliderInput(\"alt_delta\", h6(\"Depreciation rate \\\\(\\\\delta\\\\)\"),\n min = 0, max = .1, value = base_delta, ticks = FALSE, step=.01),\n sliderInput(\"alt_alpha\", h6(\"Capital elasticity \\\\(\\\\alpha\\\\)\"),\n min = 0, max = 1, value = base_alpha, ticks = FALSE, step=.01),\n br(),\n actionButton(\"reset\", \"Reset all to baseline\")\n ),\n column(8,\n plotOutput(\"gkalgraph\",width = \"100%\"), \n )\n ) # end FluidRow\n ) # end main panel\n ) # end ui\n#############################################################\n# Define server logic ----\n#############################################################\nserver <- function(input, output, session) {\n\n # Reset parameters\n observeEvent(input$reset, {\n updateSliderInput(session,'alt_sI',value = base_sI)\n updateSliderInput(session,'alt_gL',value = base_gL)\n updateSliderInput(session,'alt_gA',value = base_gA)\n updateSliderInput(session,'alt_delta',value = base_delta)\n updateSliderInput(session,'alt_alpha',value = base_alpha)\n })\n \n output$gkalgraph <- renderPlot(\n {\n kalstar = (input$alt_sI/(input$alt_gL + input$alt_gA + input$alt_delta))^(1/(1-input$alt_alpha))\n tick <- seq(0,12,.1) # arbitrary kal values\n df <- data.frame(tick) # create dataframe\n df$gk <- input$alt_sI/(df$tick^(1-input$alt_alpha))- input$alt_delta\n reverse = (input$alt_sI/(input$alt_delta+.12))^(1/(1-input$alt_alpha))\n \n ggplot(df, aes(x=tick)) +\n geom_line(aes(y = gk),size=1) + \n geom_hline(yintercept=input$alt_gA+input$alt_gL, linetype=\"dashed\", color = \"black\",size=1) +\n geom_vline(xintercept=kalstar, linetype=\"dotted\", color = \"black\") +\n annotate(geom=\"text\", x=9, y=input$alt_gA+input$alt_gL+.005, \n label=\"gA + gL\",size=6) +\n annotate(geom=\"text\", x=kalstar+1.6, y=.12, \n label=\"K/AL steady state\",size=6) +\n annotate(geom=\"text\", x=reverse-.4, y=.12, \n label=\"gK\",size=6) +\n xlab(\"K/AL ratio\") +\n ylab(\"Growth rates\") +\n theme_light() +\n ylim(-.01,.12)\n }\n ) # end gky graph\n \n \n} # end server\n\n# Run the app ----\nshinyApp(ui = ui, server = server)", "meta": {"hexsha": "b7e95b19eab8db457f64d3bb81f278282f0cc74e", "size": 3505, "ext": "r", "lang": "R", "max_stars_repo_path": "code/JustKAL/app.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/JustKAL/app.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/JustKAL/app.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 36.8947368421, "max_line_length": 102, "alphanum_fraction": 0.517831669, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6230386074551724}} {"text": "# Group members (Name, Student ID, E-Mail):\n# 1. Baldomero Valdez, Valenzuela, 2905175, baldmer.w@gmail.com\n# 2. Omar Trinidad Gutierrez Mendez, 2850441, omar.vpa@gmail.com\n# 3. Shinho Kang, 2890169, wis.shinho.kang@gmail.com\n\n# Exercise 4.2\n\n# install `multtest` package\n# source(\"https://bioconductor.org/biocLite.R\")\n# biocLite(\"multtest\")\n\nsetwd(\"~/current-lectures/ml_bioinformatics/Ex4/\")\nlibrary(multtest)\ndata(golub)\n\n# a) calculate the mean and variance of all pooled expression data\nmeanGolub = apply(golub, 1, mean)\nvarGolub = apply(golub, 1, var)\nsdGolub = apply(golub, 1, sd)\n\n# b) means and standard deviations of the expression level for every gene for\n# the classes ALL and AML\n\n# i. create glb.fac\nglb.fac = factor(golub.cl, levels=0:1, labels=c(\"ALL\", \"AML\"))\n\nmeanALL = apply(golub[, glb.fac==\"ALL\"], 1, mean)\nsdALL = apply(golub[, glb.fac==\"ALL\"], 1, sd)\nmeanAML = apply(golub[, glb.fac==\"AML\"], 1, mean)\nsdAML = apply(golub[, glb.fac==\"AML\"], 1, sd)\n\n# ii. 5 genes with the largest mean expression for ALL\nlargestALL = order(meanALL, decreasing = T)\nprint(\"5 genes with the largest mean expression for ALL\")\nprint(golub.gnames[largestALL[1:5], 2])\n\n# ii. 5 genes with the largest mean expression for AML\nlargestAML = order(meanAML, decreasing = T)\nprint(\"5 genes with the largest mean expression for AML\")\nprint(golub.gnames[largestAML[1:5], 2])\n\n# selection of the oncogene\noncogenes = grep('oncogene', golub.gnames[ , 2], ignore.case = T)\n\n# iii. 5 oncogenes with the largest mean expression for ALL\nmeanOncoALL = apply(golub[oncogenes, glb.fac==\"ALL\"], 1, mean)\nlargestOncoALL = order(meanOncoALL, decreasing = T)\nloncoALL = oncogenes[largestOncoALL[1:5]]\nprint(\"5 oncogenes with the largest mean expression for ALL\")\nprint(golub.gnames[loncoALL, 2])\n\n# iii. 5 oncogenes with the largest mean expression for AML\nmeanOncoAML = apply(golub[oncogenes, glb.fac==\"AML\"], 1, mean)\nlargestOncoAML = order(meanOncoAML, decreasing = T)\nloncoAML = oncogenes[largestOncoAML[1:5]]\nprint(\"5 oncogenes with the largest mean expression for AML\")\nprint(golub.gnames[loncoAML, 2])\n\n# iv. genes with largest different in expression between the two classes\ndifference <- order(abs(meanAML-meanALL), decreasing=TRUE)\n\n# print this on a file\nnames = golub.gnames[difference[1:5], 2]\nmean = meanGolub[difference[1:5]]\nstandard_deviation = sdGolub[difference[1:5]]\ndata_frame = data.frame(names, mean, standard_deviation)\nwrite.csv(data_frame, file = \"Ex4_2b_iv.csv\")\n\n\n# 2c. Select gene 1042\ngeneCCND3 = split(golub[1042, ], glb.fac)\n\n# i. Boxplot for the expression data\npng(filename=\"boxplot.png\")\nboxplot(golub[1042,] ~ glb.fac,\n main=\"Boxplot GeneCCND3\",\n xlab=\"Class\",\n ylab=\"Expression\",\n col=c(\"tomato\", \"green\")\n )\ndev.off()\n\n# ii. Q-Q plot with theoretical normal distribution\n\n#\npng(filename=\"qq-plot.png\")\npar(mfrow=c(1, 2))\nqqnorm(geneCCND3$ALL)\nqqline(geneCCND3$ALL)\nqqnorm(geneCCND3$AML)\nqqline(geneCCND3$AML)\ndev.off()\n\n# iii. We have to apply the unpaired two-sample t-test (page 94).\n# we can see that the size and variance of the two groups are different:\n# length(geneCCND3$AML) == length(geneCCND3$ALL)\n# var(geneCCND3$AML) == var(geneCCND3$ALL)\n# so, we can apply the Welch t-test\n\nttest = t.test(geneCCND3$AML, geneCCND3$ALL)\n\n# iv. Use a non-parametric test. The Kolmogorov-Smirnov test\nkolmogorov = ks.test(geneCCND3$AML, geneCCND3$ALL)\n\n# Shapiro-wilk test\na = shapiro.test(geneCCND3$AML)\nb = shapiro.test(geneCCND3$ALL)\n\n# 2d. Perform t-test for all genes comparing the distributions for ALL and AML.\n\n# i. comparison of p-value and alpha\n# if p-value < 0.05 we find a significant difference\n\npvalues <- apply(golub, 1, function(x) t.test(x ~ glb.fac)$p.value)\nalpha = 0.05\nresults = table(pvalues < alpha)\ntotal_i = results[names(results) == T]\nprint(\"Genes with significant differences are:\")\nprint(total_i)\n\n# ii. Given that we have more hypothesis, we increase the likelihood of a rare\n# event, then we increase the likelihood of incorrectly rejecting a null\n# hypothesis.\n\n# iii. Using Bonferroni correction we will redefine the alpha value\n# alpha = alpha / number of samples\n\nbonferroni = alpha/nrow(golub)\nconf_level = 1 - bonferroni\n\n# modify the alpha value with the parameter conf.level in t.test function\npvalues <- apply(golub, 1, function(x) t.test(x ~ glb.fac, conf.level=conf_level)$p.value)\nresults = table(pvalues < bonferroni)\n\ntotal_iii = results[names(results) == T]\nprint(\"Genes with significant differences are:\")\nprint(total_iii)\n", "meta": {"hexsha": "27b7336e229f918085d066f5e60fa729cbb2f296", "size": 4518, "ext": "r", "lang": "R", "max_stars_repo_path": "Ex4/Ex4_2.r", "max_stars_repo_name": "omartrinidad/ml_bioinformatics", "max_stars_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ex4/Ex4_2.r", "max_issues_repo_name": "omartrinidad/ml_bioinformatics", "max_issues_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ex4/Ex4_2.r", "max_forks_repo_name": "omartrinidad/ml_bioinformatics", "max_forks_repo_head_hexsha": "2ff4962767a9cfe206620f1fc870839e249dde96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-15T02:23:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-15T02:23:47.000Z", "avg_line_length": 32.7391304348, "max_line_length": 90, "alphanum_fraction": 0.7299690128, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6228834952928911}} {"text": "library(odin)\nlibrary(reshape2)\nlibrary(ggplot2)\n\n\nsir_ode <- odin::odin({\n ## Derivatives\n deriv(S) <- -b*S*I\n deriv(I) <- b*S*I-g*I\n deriv(R) <- g*I\n\n ## Initial conditions\n initial(S) <- 0.99\n initial(I) <- 0.01\n initial(R) <- 0.00\n\n ## parameters\n b <- 0.1\n g <- 0.05\n config(base) <- \"sir\"\n}, \".\")\n\nsir_mod <- sir_ode()\ntimes <- seq(0,200,length.out=2001)\nsir_out <- sir_mod$run(times)\n\nsir_out_long <- melt(as.data.frame(sir_out),\"t\")\n\n# Plot\nggplot(sir_out_long, aes(x=t, y=value, colour=variable, group=variable)) +\n geom_line(lwd=2) + xlab(\"Time\")+ylab(\"Number\")\n", "meta": {"hexsha": "77fcb115c521bef55e946815d13ec6ca8c4aa0b7", "size": 585, "ext": "r", "lang": "R", "max_stars_repo_path": "models/simple_deterministic_models/sir/sir_odin.r", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/sir/sir_odin.r", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/sir/sir_odin.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": 18.28125, "max_line_length": 74, "alphanum_fraction": 0.6170940171, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6228049499525534}} {"text": "#' Evaluate the cumulative distribution function of a density approximation\n#'\n#' Currently only implemented for Gaussian mixtures.\n#' @param fit An mvd.density object obtained from one of the density fitting functions.\n#' @param x Matrix or vector of positions at which to evaluate the density function.\n#' @param log Boolean which specifies whether to return the cumulative probability in log space.\n#' @export\nmvd.cdf <- function(fit, x, log = FALSE) {\n stopifnot(class(fit) == \"mvd.density\")\n\n if (fit$type == \"gmm\") {\n if (is.matrix(x)) {\n stopifnot(ncol(x) == ncol(fit$centers))\n \n p <- matrix(NA, nrow(x), fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[, ki] <- mvtnorm::pmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[, ki] <- mvtnorm::pmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = FALSE) * fit$proportions[ki]\n }\n }\n \n if (log) {\n return(apply(p, 1, .logsum))\n } else {\n return(apply(p, 1, sum))\n }\n } else {\n stopifnot(length(x) == ncol(fit$centers))\n \n p <- rep(NA, fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[ki] <- mvtnorm::pmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[ki] <- mvtnorm::pmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = FALSE) * fit$proportions[ki]\n }\n }\n \n if (log) {\n return(.logsum(p))\n } else {\n return(sum(p))\n }\n }\n } else if (fit$type == \"gmm.truncated\") {\n if (is.matrix(x)) {\n stopifnot(ncol(x) == ncol(fit$centers))\n \n p <- matrix(NA, nrow(x), fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[, ki] <- tmvtnorm::ptmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[, ki] <- tmvtnorm::ptmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = FALSE) * fit$proportions[ki]\n }\n }\n \n if (log) {\n return(apply(p, 1, .logsum))\n } else {\n return(apply(p, 1, sum))\n }\n } else {\n stopifnot(length(x) == ncol(fit$centers))\n \n p <- rep(NA, fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[ki] <- tmvtnorm::ptmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[ki] <- tmvtnorm::ptmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = FALSE) * fit$proportions[ki]\n }\n }\n \n if (log) {\n return(.logsum(p))\n } else {\n return(sum(p))\n }\n }\n } else {\n stop(\"Unknown type or not implemented\")\n }\n}\n", "meta": {"hexsha": "5017789a8e0b9d184c2b02d6da93888829f01139", "size": 3192, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cdf.r", "max_stars_repo_name": "bramthijssen/mvdens", "max_stars_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/cdf.r", "max_issues_repo_name": "bramthijssen/mvdens", "max_issues_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T12:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T12:45:03.000Z", "max_forks_repo_path": "R/cdf.r", "max_forks_repo_name": "NKI-CCB/mvdens", "max_forks_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6896551724, "max_line_length": 174, "alphanum_fraction": 0.4965538847, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6227361837290073}} {"text": "#-- this codes perfomes a PCA + stat on first discriminant\n#input : Multi_datainput_m (after get_behav_gp.r)\n#ouput : plspca (plot) and PCA_pval (PCA_pval$p.value)\n\n\n#---------------------1 make the pca on data\ninput.pca <- prcomp(Multi_datainput_m %>% select (-groupingvar),\n center = TRUE,\n scale. = TRUE)\n\n\n#---------------------2 statistics on pc1:\nModdata = as.data.frame(input.pca$x)\nModdata$groupingvar = as.factor(Multi_datainput_m$groupingvar)\n\n#-- Mann-Whitney test if 2 groups, Kruskal-Wallis rank sum test otherwise\nif (length(levels (Moddata$groupingvar)) == 2) {\n PCA_pval = wilcox_test(PC1 ~ groupingvar, data = Moddata)\n PCA_effectsize = wilcox_effsize(data= Moddata, PC1 ~ groupingvar, comparisons = NULL, ref.group = NULL,\n paired = FALSE, alternative = \"two.sided\", mu = 0, ci = FALSE,\n conf.level = 0.95, ci.type = \"perc\", nboot = 1000)\n \n} else {\n PCA_pval = kruskal_test(PC1 ~ groupingvar, data = Moddata)\n PCA_effectsize = kruskal_effsize(Moddata, PC1 ~ groupingvar, ci = FALSE, conf.level = 0.95,\n ci.type = \"perc\", nboot = 1000)\n}\n\n#-- effect size calculation\n\n\n\n#-- put stat results in a text\nPCA_res <- ifelse (\n pvalue(PCA_pval) < .05,\n paste0(\"p < \", signif(pvalue(PCA_pval), digits = 2), \", effect size is \", PCA_effectsize$magnitude, \" (Z/square(N) = \",signif(PCA_effectsize$effsize, digits = 2),\n \").\"),\n \"no statistically significant difference.\"\n)\n\n#-- plot 2 PC, add stat text in axes legend\nplspca = Moddata %>% ggplot (aes (x = PC1, y = PC2, color = groupingvar)) +\n geom_point() +\n labs (title = paste0(\"PCA results (\", groupingby, \" variables grouping)\")) +\n scale_colour_grey() + theme_bw() +\n labs(x = paste0 (\"PC1: \", PCA_res))\n\n#print(plspca)\n\n\n#-- Plot boxplot of PC1\n\n# calculate sample size\na <-\n aggregate(PC1 ~ groupingvar + groupingvar , Moddata, function(i)\n c(val = length(i), ypos = quantile(i)[2]))\n\n#do boxplot, stat result as text between groups\n\nboxplotPCA1 = Moddata %>% ggplot (aes (x = groupingvar, y = PC1, color = groupingvar)) +\n geom_boxplot(position = position_dodge(width = 0.9)) +\n labs (title = paste0(\"PCA results (\", groupingby, \" variables grouping)\")) +\n geom_text(x = 1.5,\n y = max(Moddata$PC1) - 1,\n label = PCA_res) +\n geom_text(data = a,\n aes(y = PC1[, 2] + 0.5, label = paste0(\"n = \", PC1[, 1])),\n position = position_dodge(width = 0.9)) +\n theme_bw() + theme(legend.position = 'none') +\n labs(x = metadata$group_by[1])\n\n", "meta": {"hexsha": "11c9246f82fd3ba73477edaf375507e894108861", "size": 2620, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/Rcode/PCA_strategy.r", "max_stars_repo_name": "jcolomb/HCS_analysis", "max_stars_repo_head_hexsha": "4bad7b048eae47ce19a8095862dee8908061379a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-09-27T08:57:12.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-22T08:44:06.000Z", "max_issues_repo_path": "analysis/Rcode/PCA_strategy.r", "max_issues_repo_name": "jcolomb/HCS_analysis", "max_issues_repo_head_hexsha": "4bad7b048eae47ce19a8095862dee8908061379a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2017-09-27T10:42:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T08:47:42.000Z", "max_forks_repo_path": "analysis/Rcode/PCA_strategy.r", "max_forks_repo_name": "jcolomb/HCS_analysis", "max_forks_repo_head_hexsha": "4bad7b048eae47ce19a8095862dee8908061379a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-12-10T12:45:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T14:28:05.000Z", "avg_line_length": 36.3888888889, "max_line_length": 164, "alphanum_fraction": 0.6114503817, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6227361665857958}} {"text": "#' Expected path costs\r\n#'\r\n#' This function calculates expected path costs as a function of mean link flows under various probability models. Its primary use is when called by the function GSUE. For the product multinomial model, a normal approximation to higher order moments is applied unless the link path incidencde matrix is diagonal.\r\n#'\r\n#' @param x Vector of mean link flows\r\n#' @param ODdemand Vector of origin-destination (OD) travel demands\r\n#' @param ODpair Vector indicating the OD pair serviced by each route (ordered by columns of the path-link incidence matrix, A).\r\n#' @param A Path-link incidence matrix\r\n#' @param Alpha Vector of free flow travel time parameters for each link\r\n#' @param Beta Vector of capacity parameters for each link\r\n#' @param pow Polynomial order of cost function for each link. Defaults to 4.\r\n#' @param theta A dispersion parameter. For the logit model, a single value specifying the logit parameter. For the probit model, a vector of standard deviations for the individual link cost errors. Defaults to 1.\r\n#' @param prob.model Route choice probability model. One of \"ProductMN\" (product multinomial, the default), or \"Poisson\".\r\n#' @return Vector of expected path costs\r\n#' @keywords expected mean path costs\r\n#' @examples\r\n#' ExpectedPathCost()\r\n#' @export\r\n\r\nExpectedPathCost <- function(x,ODdemand,ODpair,A=diag(length(x)),Alpha,Beta,pow=4,prob.model=\"ProductMN\"){\r\n\tBeta[pow==0] <- 1\r\n\tif(prob.model==\"Poisson\"){\r\n\t\tOmega <- A%*%diag(x)%*%t(A)\r\n\t\tomega <- diag(Omega)\r\n\t\tnu <- A%*%x\r\n\t\tec <- (pow==0)*Alpha + (pow==1)*Alpha*(1 + 0.15*nu/Beta) + (pow==2)*Alpha*(1 + 0.15*((nu/Beta)^2 + omega/Beta^2)) + (pow==4)*Alpha*(1 + 0.15*((nu/Beta)^4 + 6*(nu/Beta)^2*omega/Beta^2 + 3*(omega/Beta^2)^2))\r\n\t\tu <- c(t(A)%*%ec)\r\n\t}\r\n\tif(prob.model==\"ProductMN\"){\r\n\t\tif(!is_diag(A)){\r\n\t\t\tN.routes <- ncol(A)\r\n \t\t\tN.OD <- length(ODdemand)\r\n\t\t\tN.routes.per.OD <- unname(table(ODpair))\r\n\t\t\tODdemand.rep <- rep(ODdemand,N.routes.per.OD)\r\n\t\t\tpp <- x/ODdemand.rep\r\n \t\t\tindices <- c(0,cumsum(N.routes.per.OD))\r\n \t\t\tVxx <- matrix(0,ncol=N.routes,nrow=N.routes)\r\n \t\t\tfor (i in 1:N.OD){\r\n \t\t\t\tindx <- (indices[i]+1):(indices[i+1])\r\n \t\t\t\tVxx[indx,indx] <- ODdemand[i]*(diag(pp[indx])-pp[indx]%*%t(pp[indx]))\r\n \t\t\t}\r\n\t\t\tOmega <- A%*%Vxx%*%t(A)\r\n\t\t\tomega <- diag(Omega)\r\n\t\t\tnu <- A%*%x\r\n\t\t\tec <- (pow==0)*Alpha + (pow==1)*Alpha*(1 + 0.15*nu/Beta) + (pow==2)*Alpha*(1 + 0.15*((nu/Beta)^2 + omega/Beta^2)) + (pow==4)*Alpha*(1 + 0.15*((nu/Beta)^4 + 6*(nu/Beta)^2*omega/Beta^2 + 3*(omega/Beta^2)^2))\r\n\t\t\tu <- c(t(A)%*%ec)\r\n\t\t}\r\n\t\tif(is_diag(A)){\r\n\t\t\tpp <- x/ODdemand\r\n\t\t\tnu <- x\r\n\t\t\tomega2 <- x*(1-pp)\r\n\t\t\tomega3 <- omega2*(1-2*pp)\r\n\t\t\tomega4 <- omega2*(1+3*(1-2/ODdemand)*omega2)\r\n\t\t\tnu2 <- nu^2 + omega2\r\n\t\t\tnu4 <- nu^4 + 6*omega2*nu^2 + 4*omega3*nu + omega4 \r\n \t\t\tu <- (pow==0)*Alpha + (pow==1)*Alpha*(1 + 0.15*nu/Beta) + (pow==2)*Alpha*(1 + 0.15*nu2/Beta^2) + (pow==4)*Alpha*(1 + 0.15*nu4/Beta^4)\r\n\t\t}\r\n\t}\r\n\tu\r\n}", "meta": {"hexsha": "4908d135671d015993b0a78475d918f52b39fbd9", "size": 2946, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ExpectedPathCost.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ExpectedPathCost.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ExpectedPathCost.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1, "max_line_length": 313, "alphanum_fraction": 0.6323828921, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6226457667017355}} {"text": "########################################################################\n# #\n# finite-set.rb #\n# #\n########################################################################\n=begin\n[(())] \n[(())] \n(())\n/\n(())\n\n= Algebra::Set\n((*Class of Set*))\n\nThis is the class of sets. The conclusion relationship is determined by\n((|each|)) and (()), that is, ((|s|)) is the subset of ((|t|))\nif and only if\n s.all?{|x| t.member?(x)}\nis true.\n\n== File Name:\n* ((|finite-set.rb|))\n\n== SuperClass:\n* ((|Object|))\n\n== Included Module:\n\n* ((|Enumerable|))\n\n== Class Methods:\n\n--- ::[]([obj0, [obj1, [obj2, ...]]])\n Creates ((|Set|)) objects from parameters.\n \n Example: Create {\"a\", [1, 2], 0}\n require \"finite-set\"\n p Algebra::Set[0, \"a\", [1, 2]]\n p Algebra::Set.new(0, \"a\", [1, 2])\n p Algebra::Set.new_a([0, \"a\", [1, 2]])\n p Algebra::Set.new_h({0=>true, \"a\"=>true, [1, 2]=>true})\n\n--- ::new([obj0, [obj1, [obj2, ...]]])\n Creates ((|Set|)) objects from parameters.\n\n--- ::new_a(a)\n Creates ((|Set|)) objects from an array ((|a|)).\n \n--- ::new_h(h)\n Creates ((|Set|)) objects from a hash.\n\n--- ::empty_set\n Returns the empty set.\n\n--- ::phi\n--- ::null\n Alias of ((<::empty_set>)).\n\n--- ::singleton(x)\n Creates the set of one element ((|x|)).\n \n== Methods:\n\n--- empty_set\n Returns the empty set.\n\n--- phi\n--- null\n Alias of ((<::empty_set>)).\n\n--- empty?\n Returns true if ((|self|)) is the empty set.\n\n--- phi?\n--- empty_set?\n--- null?\n Alias of (())\n\n--- singleton(x)\n Creates the set of one element ((|x|)).\n\n--- singleton?\n Returns true if ((|self|)) is a singleton set.\n\n--- size\n Returns the size of ((|self|)).\n\n--- each\n Iterates the block with the block parameter of each element.\n The order of iteration is indefinite.\n\n Example: \n require \"finite-set\"\n include Algebra\n Set[0, 1, 2].each do |x|\n p x #=> 1, 0, 2\n end\n\n--- separate\n Returns the set of the elements which make the block true.\n\n Example: \n require \"finite-set\"\n include Algebra\n p Set[0, 1, 2, 3].separate{|x| x % 2 == 0} #=> {2, 0}\n\n--- select_s\n--- find_all_s\n Alias of (())\n\n--- map_s\n Return the set of the values of the block.\n\n Example: \n require \"finite-set\"\n include Algebra\n p Set[0, 1, 2, 3].map_s{|x| x % 2 + 1} #=> {2, 1}\n\n--- pick\n Returns a elements of ((|self|)). The chois is indefinite.\n\n--- shift\n Takes an element from (()) and returns it. \n\n Example: \n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3]\n p s.shift #=> 2\n p s #=> {0, 1, 3}\n\n--- dup\n Returns the duplication of ((|self|)).\n\n--- append!(x)\n Appends ((|x|)) to ((|self|)) and returns ((|self|)).\n\n--- push\n--- <<\n Alias of ((|append!|)).\n\n--- append(x)\n Duplicates and appends ((|x|)) to it and returns it.\n\n--- concat(other)\n Adds the all elements of ((|other|)). This is the destructive\n version of ((<+>)).\n\n--- rehash\n Rehashes the internal ((|Hash|)) object.\n\n--- eql?(other)\n Returns true if ((|self|)) is equal to ((|other|)). This is\n equivalent to (({ self >= other and self <= other})).\n\n--- ==\n Alias of eql?\n\n--- hash\n Returns the hash value of ((|self|)).\n\n--- include?(x)\n Returns true if ((|x|)) is a element of ((|self|)).\n\n--- member?\n--- has?\n--- contains?\n Alias of (()).\n\n--- superset?(other)n\n Returns true if ((|self|)) containds ((|other|)).\n This is equivalent to (({other.all{|x| member?(x)}})).\n\n--- >=\n--- incl?\n Alias of (({superset?})).\n\n--- subset?(other)\n Returns true if ((|self|)) is a subset of ((|other|)).\n\n--- <=\n--- part_of?\n Alias of (()).\n\n--- <(other)\n Returns true if ((|self|)) is a proper subset of ((|other|)).\n\n--- >(other)\n Returns true if ((|other|)) is a proper subset of ((|self|)).\n\n--- union(other = nil)\n Returns the union of ((|self|)) and ((|other|)).\n If ((|other|)) is omitted, returns the union of the\n ((|self|)) the set of sets.\n\n Example: \n require \"finite-set\"\n include Algebra\n p Set[0, 2, 4].cup Set[1, 3] #=> {0, 1, 2, 3, 4}\n s = Set[*(0...15).to_a]\n s2 = s.separate{|x| x % 2 == 0}\n s3 = s.separate{|x| x % 3 == 0}\n s5 = s.separate{|x| x % 5 == 0}\n p Set[s2, s3, s5].union #=> {1, 7, 11, 13}\n\n--- |\n--- +\n--- cup\n Alias of (()).\n\n--- intersection(other = nil)\n Returns the intersection of ((|self|)) and ((|other|)).\n If ((|other|)) is omitted, returns the intersection of the\n ((|self|)) the set of sets.\n\n Example: \n require \"finite-set\"\n include Algebra\n p Set[0, 2, 4].cap(Set[4, 2, 0]) #=> {0, 2, 4}\n s = Set[*(0..30).to_a]\n s2 = s.separate{|x| x % 2 == 0}\n s3 = s.separate{|x| x % 3 == 0}\n s5 = s.separate{|x| x % 5 == 0}\n p Set[s2, s3, s5].cap #=> {0, 30}\n\n--- &\n--- cap\n Alias of (()).\n\n--- difference(other)\n Returns the set of the elements of ((|self|)) which are not in\n ((|other|)).\n\n--- - \n Alias of (()).\n\n--- each_pair\n Iterates with each two different elements of ((|self|)).\n\n Example: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_pair do |x, y|\n s.push [x, y]\n end\n p s == Set[[0, 1], [0, 2], [1, 2]] #=> true\n\n--- each_member(n)\n Iterates with each ((|n|)) different elements of ((|self|)).\n\n Example: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_member(2) do |x, y|\n s.push [x, y]\n end\n p s == Set[[0, 1], [0, 2], [1, 2]] #=> true\n\n--- each_subset\n Iterates over each subset of ((|self|)).\n\n Example: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_subset do |t|\n s.append! t\n end\n p s.size = 2**3 #=> true\n\n--- each_non_trivial_subset\n Iterates over each non trivial subset of ((|self|))\n\n--- power_set\n Returns the set of subsets.\n\n\n--- each_product(other)\n Iterates over for each ((|x|)) in ((|self|)) and\n each ((|y|)) in ((|other|))\n \n Exameple:\n require \"finite-set\"\n include Algebra\n Set[0, 1].each_prodct(Set[0, 1]) do |x, y|\n p [x, y] #=> [0,0], [0,1], [1,0], [1,1]\n end\n\n--- product(other)\n Returns the product set of ((|self|)) and ((|other|)).\n The elements are the arrays of type (({[x, y]})).\n If the block is given, it returns the set which consists\n of the value of the block.\n\n Example: \n require \"finite-set\"\n include Algebra\n p Set[0, 1].product(Set[0, 1]) #=> {[0,0], [0,1], [1,0], [1,1]}\n p Set[0, 1].product(Set[0, 1]){|x, y| x + 2*y} #=> {0, 1, 2, 3]\n\n--- *\n Alias of (()).\n\n--- equiv_class([equiv])\n Returns the quotient set by the equivalent relation.\n The relation are given as following:\n \n (1) The evaluation of the block:\n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3, 4, 5]\n p s.equiv_class{|a, b| (a - b) % 3 == 0} #=> {{0, 3}, {1, 4}, {2, 5}}\n (2) The value of the instance method \n ((|call(x, y)|)) of the parameter.\n require \"finite-set\"\n include Algebra\n o = Object.new\n def o.call(x, y)\n (x - y) % 3 == 0\n end\n s = Set[0, 1, 2, 3, 4, 5]\n p s.equiv_class(o) #=> {{0, 3}, {1, 4}, {2, 5}}\n (3) The value of method indicated ((|Symbol|)).\n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3, 4, 5]\n def q(x, y)\n (x - y) % 3 == 0\n end\n p s.equiv_class(:q) #=> {{0, 3}, {1, 4}, {2, 5}}\n\n--- /\n Alias of (()).\n\n--- to_a\n Returns the array of elements. The order is indefinite.\n\n--- to_ary\n Alias of (()).\n\n--- sort\n Returns the value of (({to_a.sort})).\n\n--- power(other)\n Returns the all maps from ((|other|)) to ((|self|)).\n The maps are the instances of (()).\n\n Example: \n require \"finite-map\"\n include Algebra\n a = Set[0, 1, 2, 3]\n b = Set[0, 1, 2]\n s = \n p( (a ** b).size ) #=> 4 ** 3 = 64\n p b.surjections(a).size #=> S(3, 4) = 36\n p a.injections(b).size #=> 4P3 = 24\n\n--- ** power\n Alias of (()).\n\n--- identity_map\n Returns the identity map of ((|self|)).\n\n--- surjections(other)\n Returns all surjections from ((|other|)) to((|self|)).\n\n--- injections(other)\n Returns all injections from ((|other|)) to((|self|)).\n\n--- bijections(other)\n Returns all bijections from ((|other|)) to((|self|)).\n\n#--- monotonic_series #what is this?\n#\n# Example: \n\n= Enumerable\n\n== File Name:\n* ((|finite-set.rb|))\n\n== Methods:\n\n--- any?\n Returns true when the block is true for some elements.\n This is the alias of ((|Enumerable#find|))\n (built-in method of ruby-1.8).\n\n--- all?\n Returns true when the block is true for all elements.\n This is defined by:\n\n !any?{|x| !yield(x)}\n\n (These are built-in methods of ruby-1.8).\n\n=end\n\n", "meta": {"hexsha": "5f1698758d47a7c9288fed0c2e1018d8e5fabf39", "size": 9387, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/finite-set.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/finite-set.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/finite-set.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3507462687, "max_line_length": 79, "alphanum_fraction": 0.5047405987, "num_tokens": 2966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.622580027877776}} {"text": "\t# DATA SETUP\n\n\t\tcharity = read.csv(\"./charity.csv\")\n\t\tcharity.t = charity\n\t\tcharity.t$avhv = log(charity.t$avhv)\n\t\tcharity.t$agif = log(charity.t$agif)\n\t\tcharity.t$inca = log(charity.t$inca)\n\t\tcharity.t$incm = log(charity.t$incm)\n\t\tcharity.t$lgif = log(charity.t$lgif)\n\t\tcharity.t$rgif = log(charity.t$rgif)\n\t\tcharity.t$tgif = log(charity.t$tgif)\n\t\tcharity.t$tlag = log(charity.t$tlag)\n\n\t\tdata.train = charity.t[charity$part==\"train\",]\n\t\tx.train = data.train[,2:21]\n\t\tc.train = data.train[,22] # donr\n\t\tn.train.c = length(c.train) # 3984\n\t\ty.train = data.train[c.train==1,23] # damt for observations with donr=1\n\t\t# x.train.mat = model.matrix(damt~., data.train[c.train==1,2:23])[,-22]\n\t\tn.train.y = length(y.train) # 1995\n\n\t\tdata.valid = charity.t[charity$part==\"valid\",]\n\t\tx.valid = data.valid[,2:21]\n\t\tc.valid = data.valid[,22] # donr\n\t\tn.valid.c = length(c.valid) # 2018\n\t\ty.valid = data.valid[c.valid==1,23] # damt for observations with donr=1\n\t\t#x.valid.mat = model.matrix(damt~., data.valid[c.valid==1,2:23])[,-22]\n\t\tn.valid.y = length(y.valid) # 999\n\n\t\tdata.test = charity.t[charity$part==\"test\",]\n\t\tn.test = dim(data.test)[1] # 2007\n\t\tx.test = data.test[,2:21]\n\n\t\tx.train.mean = apply(x.train, 2, mean)\n\t\tx.train.sd = apply(x.train, 2, sd)\n\t\tx.train.std = t((t(x.train)-x.train.mean)/x.train.sd) # standardize to have zero mean and unit sd\n\t\t# x.train.mat.mean = apply(x.train.mat, 2, mean)\n\t\t# x.train.mat.sd = apply(x.train.mat, 2, sd)\n\t\t# x.train.mat.std = t((t(x.train.mat)-x.train.mat.mean)/x.train.mat.sd) # standardize to have zero mean and unit sd\n\t\tapply(x.train.std, 2, mean) # check zero mean\n\t\tapply(x.train.std, 2, sd) # check unit sd\n\t\tdata.train.std.c = data.frame(x.train.std, donr=c.train) # to classify donr\n\t\tdata.train.std.y = data.frame(x.train.std[c.train==1,], damt=y.train) # to predict damt when donr=1\n\n\t\tx.valid.std = t((t(x.valid)-x.train.mean)/x.train.sd) # standardize using training mean and sd\n\t\t# x.valid.mat.std = t((t(x.valid.mat)-x.train.mat.mean)/x.train.mat.sd) # standardize to have zero mean and unit sd\n\t\tdata.valid.std.c = data.frame(x.valid.std, donr=c.valid) # to classify donr\n\t\tdata.valid.std.y = data.frame(x.valid.std[c.valid==1,], damt=y.valid) # to predict damt when donr=1\n\n\t\tx.test.std = t((t(x.test)-x.train.mean)/x.train.sd) # standardize using training mean and sd\n\t\tdata.test.std = data.frame(x.test.std)\n\n\t\ttrain.dat = data.frame(x = x.train.std, y = as.factor(data.train.std.c$donr))\n\t\tvalid.dat = data.frame(x = x.valid.std, y = as.factor(data.valid.std.c$donr))\n\n\t#LIBRARIES\n\n\t\tlibrary(MASS)\n\t\tlibrary(tree)\n\t\tlibrary(randomForest)\n\t\tlibrary(gbm)\n\t\tlibrary(e1071)\n\t\tlibrary(lars)\n\t\tlibrary(leaps)\n\t\tlibrary(glmnet)\n\t\tlibrary(pls)\n\t\tlibrary(splines)\n\t\tlibrary(gam)\n\t\tlibrary(ISLR)\t\t\n\n\t#CLASSIFICATION MODELS: LDA, TREES-BASED, AND SVM\n\t\t\t\t\t\t\t \n\t\t#LDA Model Base\t\n\t\t\tmodel.ldaB = lda(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n\t\t\t\t\t\t\t\tx.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t\t\t\t\t\t\tx.tlag + x.agif, \n\t\t\t\t\t\t\t train.dat) # include additional terms on the fly using I()\n\n\t\t\tpost.valid.ldaB = predict(model.ldaB, valid.dat)$posterior[,2] # n.valid.c post probs\n\n\t\t\tprofit.ldaB = cumsum(14.5*c.valid[order(post.valid.ldaB, decreasing=T)]-2)\n\t\t\tplot(profit.ldaB) # see how profits change as more mailings are made\n\t\t\tn.mail.valid = which.max(profit.ldaB) # number of mailings that maximizes profits\n\t\t\tc(n.mail.valid, max(profit.ldaB)) # report number of mailings and maximum profit\n\n\t\t\tcutoff.ldaB = sort(post.valid.ldaB, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid\n\t\t\tchat.valid.ldaB = ifelse(post.valid.ldaB>cutoff.ldaB, 1, 0) # mail to everyone above the cutoff\n\t\t\tldaB.table = table(chat.valid.ldaB, c.valid) # classification table\n\t\t\t\tldaB.mail = sum(ldaB.table[2,])\n\t\t\t\tldaB.mail.tp = ldaB.table[2,2]\n\t\t\t\tldaB.error = (ldaB.table[2,1]+ldaB.table[1,2])/2018\n\t\t\t\tldaB.profit = 14.5*ldaB.mail.tp - 2*ldaB.mail\n\t\t\t\t\n\t\t\t\tldaB.error #validation error rate: 0.2235\n\t\t\t\tldaB.mail #total mailings: 1,406\n\t\t\t\tldaB.profit #total profit: $11,354.50\n\n\t\t#LDA Model Base + Quad (hinc, chld, tdon, tlag, wrat, inca, npro, tgif)\n\t\t\tmodel.ldaF = lda(y ~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n x.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t\t\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2) + \n\t\t\t\t\t I(x.inca^2) + I(x.npro^2) + I(x.tgif^2), \n train.dat) # include additional terms on the fly using I()\n\t\t\t\t \n\t\t\tpost.valid.ldaF = predict(model.ldaF, valid.dat)$posterior[,2] # n.valid.c post probs\n\n\t\t\tprofit.ldaF = cumsum(14.5*c.valid[order(post.valid.ldaF, decreasing=T)]-2)\n\t\t\t#plot(profit.ldaF) # see how profits change as more mailings are made\n\t\t\tn.mail.valid = which.max(profit.ldaF) # number of mailings that maximizes profits\n\t\t\tc(n.mail.valid, max(profit.ldaF)) # report number of mailings and maximum profit\n\n\t\t\tcutoff.ldaF = sort(post.valid.ldaF, decreasing=T)[n.mail.valid+1] # set cutoff based on n.mail.valid\n\t\t\tchat.valid.ldaF = ifelse(post.valid.ldaF>cutoff.ldaF, 1, 0) # mail to everyone above the cutoff\n\t\t\tldaF.table = table(chat.valid.ldaF, c.valid) # classification table\n\t\t\t\tldaF.mail = sum(ldaF.table[2,])\n\t\t\t\tldaF.mail.tp = ldaF.table[2,2]\n\t\t\t\tldaF.error = (ldaF.table[2,1]+ldaF.table[1,2])/2018\n\t\t\t\tldaF.profit = 14.5*ldaF.mail.tp - 2*ldaF.mail\n\t\t\t\t\n\t\t\t\tldaF.error #validation error rate: 0.1660\n\t\t\t\tldaF.mail #total mailings: 1,326\n\t\t\t\tldaF.profit #total profit: $11,775.50\n\n\t\t#CLASSIFICATION TREE, BASE MODEL\n\n\t\t\t\tmodel.treeB=tree(y~.,train.dat)\n\t\t\t\tsummary(model.treeB)\n\t\t\t\tmodel.treeB\n\n\t\t\t\ttree.pred=predict(model.treeB,valid.dat,type=\"class\")\n\t\t\t\ttreeB.table = table(tree.pred,valid.dat$y)\n\t\t\t\ttreeB.mail = sum(treeB.table[2,])\n\t\t\t\ttreeB.mail.tp = treeB.table[2,2]\n\t\t\t\ttreeB.error = (treeB.table[2,1]+treeB.table[1,2])/2018\n\t\t\t\ttreeB.profit = 14.5*treeB.mail.tp - 2*treeB.mail\n\n\t\t\t\ttreeB.error #validation error rate: 0.1516\n\t\t\t\ttreeB.mail #total mailings: 1,165\n\t\t\t\ttreeB.profit #total profit: $11,140.50\n\n\t\t#CLASSIFICATION TREE, RANDOM FORESTS MODEL\n\n\t\t\t#THE BELOW LOOP TO DISCOVER WHICH SEED RETURNS MAXIMUM PROFIT (SET.SEED(53) RETURNED MAXIMUM)\n\t\t\t# mat = matrix(, ncol=4)\n\n\t\t\t# for(i in 1:100){\n\t\t\t\t# iter = i\n\t\t\t\t# set.seed(i)\n\t\t\t\t# model.rf = randomForest(y~., train.dat, mtry = 4, importance = TRUE)\n\t\t\t\t\n\t\t\t\t# summary(model.rf)\n\t\t\t\t# model.rf\n\t\t\t\t\n\t\t\t\t# tree.pred=predict(model.rf, valid.dat, type = \"class\")\n\t\t\t\t# rf.table = table(tree.pred, valid.dat$y)\n\t\t\t\t# rf.mail = sum(rf.table[2,])\n\t\t\t\t# rf.mail.tp = rf.table[2,2]\n\t\t\t\t# rf.error = (rf.table[2,1]+rf.table[1,2])/2018\n\t\t\t\t# rf.profit = 14.5*rf.mail.tp - 2*rf.mail\n\t\t\t\t\n\t\t\t\t# vec = c(iter, rf.error, rf.mail, rf.profit)\n\t\t\t\t# mat = rbind(mat, vec)\n\t\t\t\t# # print(i)\n\t\t\t\t# # print(rf.error) #validation error rate: \n\t\t\t\t# # print(rf.mail) #total mailings: \n\t\t\t\t# # print(rf.profit) #total profit: $\n\t\t\t# }\n\n\t\t\tset.seed(53)\n\t\t\tmodel.rf = randomForest(y~., train.dat, mtry = 4, importance = TRUE)\n\t\t\t\n\t\t\tsummary(model.rf)\n\t\t\tmodel.rf\n\t\t\t\n\t\t\ttree.pred=predict(model.rf,valid.dat,type=\"class\")\n\t\t\trf.table = table(tree.pred,valid.dat$y)\n\t\t\trf.mail = sum(rf.table[2,])\n\t\t\trf.mail.tp = rf.table[2,2]\n\t\t\trf.error = (rf.table[2,1]+rf.table[1,2])/2018\n\t\t\trf.profit = 14.5*rf.mail.tp - 2*rf.mail\n\t\t\t\n\t\t\trf.error #validation error rate: 0.1070\n\t\t\trf.mail #total mailings: 1,063\n\t\t\trf.profit #total profit: $11,257.50\n\t\t\t\n\t\t#SVM CLASSIFICATION MODEL\n\t\t\n\t\t\tsvm.train = svm(y~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n x.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t\t\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2) + \n\t\t\t\t\t I(x.inca^2) + I(x.npro^2) + I(x.tgif^2),\n\t\t\t\t\t data = train.dat, kernel = \"linear\", cost=10,scale = FALSE)\n\t\t\t\t\t \n\t\t\tsummary(svm.train)\n\t\t\tset.seed(53)\n\t\t\ttune.charity = tune(svm, y~ x.reg1 + x.reg2 + x.reg3 + x.reg4 + x.home + x.chld + x.hinc + x.genf + x.wrat + \n x.avhv + x.incm + x.inca + x.plow + x.npro + x.tgif + x.lgif + x.rgif + x.tdon + \n\t\t\t\t\t x.tlag + x.agif + I(x.hinc^2) + I(x.chld^2) + I(x.tdon^2) + I(x.tlag^2) + I(x.wrat^2) + \n\t\t\t\t\t I(x.inca^2) + I(x.npro^2) + I(x.tgif^2), \n\t\t\t\t\t data = train.dat, kernel = \"linear\", ranges = list(cost = c(0.001, 0.005, 0.01, 0.05, 0.1, 1, 5, 10)))\n\t\t\t\t\t \n\t\t\tsummary(tune.charity)\n\t\t\tbestmod = tune.charity$best.model\n\t\t\tsummary(bestmod)\n\n\t\t\tsvm.pred = predict(bestmod, valid.dat)\n\t\t\tsvm.table = table(predict = svm.pred, truth = valid.dat$y)\n\t\t\tsvm.mail = sum(svm.table[2,])\n\t\t\tsvm.mail.tp = svm.table[2,2]\n\t\t\tsvm.error = (svm.table[2,1]+svm.table[1,2])/2018\n\t\t\tsvm.profit = 14.5*svm.mail.tp - 2*svm.mail\n\n\t\t\tsvm.error #validation error rate: 0.1085\n\t\t\tsvm.mail #total mailings: 1,054\n\t\t\tsvm.profit #total profit: $11,188.50\n\t\t\t\n# PREDICTION MODELING\n\n\t\t# LEAST SQUARES REGRESSION\n\t\t\n\t\t#LEAST SQUARE MODEL 1 (LM1): BASE MODEL\n\n\t\t\tmodel.ls1 = lm(damt ~ reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + wrat + \n\t\t\t\t\t\t\t avhv + incm + inca + plow + npro + tgif + lgif + rgif + tdon + tlag + agif, \n\t\t\t\t\t\t\tdata.train.std.y)\n\n\t\t\tpred.valid.ls1 = predict(model.ls1, newdata = data.valid.std.y) # validation predictions\n\t\t\tmean((y.valid - pred.valid.ls1)^2) # mean prediction error\n\t\t\t# 1.867523\n\t\t\tsd((y.valid - pred.valid.ls1)^2)/sqrt(n.valid.y) # std error\n\t\t\t# 0.1696615\n\n\t\t#LEAST SQUARES MODEL 2 (LM2)\n\t\t\n\t\t\t# drop wrat for illustrative purposes\n\t\t\tmodel.ls2 = lm(damt ~ reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + \n\t\t\t\t\t\t\t avhv + incm + inca + plow + npro + tgif + lgif + rgif + tdon + tlag + agif, \n\t\t\t\t\t\t\tdata.train.std.y)\n\n\t\t\tpred.valid.ls2 = predict(model.ls2, newdata = data.valid.std.y) # validation predictions\n\t\t\tmean((y.valid - pred.valid.ls2)^2) # mean prediction error\n\t\t\t# 1.867433\n\t\t\tsd((y.valid - pred.valid.ls2)^2)/sqrt(n.valid.y) # std error\n\t\t\t# 0.1696498\n\n\t\t\t# Results\n\n\t\t\t# MPE Model\n\t\t\t# 1.867523 LS1\n\t\t\t# 1.867433 LS2\n\n\t\t\t# select model.ls2 since it has minimum mean prediction error in the validation sample\n\n\t\t\tyhat.test = predict(model.ls2, newdata = data.test.std) # test predictions\n\t\t\n\t\t#LEAST SQUARES MODEL 3 (LM3)\n\t\t\t\n\t\t\tmodel.ls3 = lm(damt ~ reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + incm +\n\t\t\t\t\t\tplow + tgif + lgif + rgif + tdon + agif,\n\t\t\t\t\t\tdata.train.std.y)\n\t\t\t\t\t\t\n\t\t\tpred.valid.ls3 = predict(model.ls3, newdata = data.valid.std.y) # validation predictions\n\t\t\tls3.mse = mean((y.valid - pred.valid.ls3)^2) # mean prediction error\n\t\t\tls3.se = sd((y.valid - pred.valid.ls3)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tls3.mse\n\t\t\tls3.se\n\t\t\t\n\t\t#BEST SUBSETS (BSS)\n\t\t\n\t\t\tbss.train.fit = regsubsets(damt ~ . + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) +\n\t\t\t\t\tI(wrat^2) + I(inca^2) + I(npro^2) + I(tgif^2) + I(plow^2) + I(agif^2) + \n\t\t\t\t\tI(avhv^2) + I(lgif^2) + I(rgif^2) + I(incm^2),\n\t\t\t\tdata=data.train.std.y, nvmax=28)\n\t\t\t\t\n\t\t\twhich.min(summary(bss.train.fit)$bic)\n\t\t\tcoef(bss.train.fit,which.min(summary(bss.train.fit)$bic))\n\t\t\tpredict.regsubsets = function(object, newdata, id, ...){\n\t\t\t\tform = as.formula(object$call[[2]])\n\t\t\t\tmat = model.matrix(form, newdata)\n\t\t\t\tcoefi = coef(object, id = id)\n\t\t\t\txvars = names(coefi)\n\t\t\t\tmat[, xvars]%*%coefi\n\t\t\t}\n\t\t\tbss.pred = predict.regsubsets(bss.train.fit, data.valid.std.y, which.min(summary(bss.train.fit)$bic))\n\t\t\tbss.mse = mean((y.valid - bss.pred)^2) # mean prediction error\n\t\t\tbss.se = sd((y.valid - bss.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tbss.mse\n\t\t\tbss.se\n\t\n\t\t#BEST SUBSETS 10-FOLD VALIDATION (BSSF)\n\t\t\n\t\t\tk=10\n\t\t\tset.seed(53)\n\t\t\tbssf.folds = sample(1:k,nrow(data.train.std.y),replace=TRUE)\n\t\t\tbssf.cv.errors = matrix(NA, k, 10, dimnames=list(NULL, paste(1:10)))\n\t\t\tfor (j in 1:k){\n\t\t\t\tbssf.train.fit=regsubsets(damt ~ . + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) +\n\t\t\t\t\tI(wrat^2) + I(inca^2) + I(npro^2) + I(tgif^2) + I(plow^2) + I(agif^2) + \n\t\t\t\t\tI(avhv^2) + I(lgif^2) + I(rgif^2) + I(incm^2), \n\t\t\t\t\tdata=data.train.std.y[bssf.folds!=j,], nvmax=28)\n\t\t\t\tfor (i in 1:10){\n\t\t\t\t\tbssf.pred = predict(bssf.train.fit, data.train.std.y[bssf.folds==j,], id=i)\n\t\t\t\t\tbssf.cv.errors[j, i] = mean((bssf.pred - data.train.std.y$damt[bssf.folds==j])^2)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbssf.mcv.errors = apply(bssf.cv.errors, 2, mean)\n\t\t\twhich.min(bssf.mcv.errors) #Returns the number of variables in the Cross-Validation Selected model\n\t\t\tcoef(bssf.train.fit, which.min(bssf.mcv.errors)) #Returns the coefficients for the CV selected model\n\t\t\tbssf.pred = predict.regsubsets(bssf.train.fit, data.valid.std.y, which.min(bssf.mcv.errors)) #Predicts y using the CV Selected model\n\t\t\tbssf.mse = mean((y.valid - bssf.pred)^2) #Calculates test MSE for the CV Selected model\n\t\t\tbssf.se = sd((y.valid - bssf.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tbssf.mse\n\t\t\tbssf.se\n\t\t\t\n\t\t#RIDGE REGRESSION (RR)\n\t\t\n\t\t\t#make x matrix and y from data.train.std.y\n\t\t\trr.train.x = model.matrix(damt ~ ., data.train.std.y)[,-21]\n\t\t\trr.train.y = data.train.std.y$damt\n\t\t\trr.valid.x = model.matrix(damt ~ ., data.valid.std.y)[,-21]\n\t\t\trr.valid.y = data.valid.std.y$damt\n\t\t\t\n\t\t\tset.seed(53)\n\t\t\trr.cv.out = cv.glmnet(rr.train.x, rr.train.y, alpha=0)\n\t\t\t\n\t\t\trr.bestlam = rr.cv.out$lambda.min\n\t\t\trr.bestlam\n\t\t\t\n\t\t\trr.train.fit = glmnet(rr.train.x, rr.train.y, alpha=0, lambda=rr.bestlam)\n\t\t\tcoef(rr.train.fit)[, 1]\n\t\t\t\n\t\t\trr.pred = predict(rr.train.fit, s=rr.bestlam, newx=rr.valid.x)\n\t\t\trr.mse = mean((y.valid - rr.pred)^2) # mean prediction error\n\t\t\trr.se = sd((y.valid - rr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\trr.mse\n\t\t\trr.se\n\t\t\t\n\t\t#LASSO\n\t\t\n\t\t\tset.seed(53)\n\t\t\tlasso.cv.out = cv.glmnet(rr.train.x, rr.train.y, alpha=1)\n\t\t\t\n\t\t\tlasso.bestlam = lasso.cv.out$lambda.min\n\t\t\tlasso.bestlam\n\t\t\t\n\t\t\tlasso.train.fit = glmnet(rr.train.x, rr.train.y, alpha=1, lambda=lasso.bestlam)\n\t\t\tcoef(lasso.train.fit)[, 1]\n\t\t\t\n\t\t\tlasso.pred = predict(lasso.train.fit, s=lasso.bestlam, newx=rr.valid.x)\n\t\t\tlasso.mse = mean((y.valid - lasso.pred)^2)\n\t\t\tlasso.se = sd((y.valid - lasso.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tlasso.mse\n\t\t\tlasso.se\n\t\t\t\n\t\t#PRINCIPAL COMPONANTS\n\t\t\n\t\t\tset.seed(53)\n\t\t\tpcr.train.fit = pcr(damt ~ . + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) +\n\t\t\t\t\tI(wrat^2) + I(inca^2) + I(npro^2) + I(tgif^2) + I(plow^2) + I(agif^2) + \n\t\t\t\t\tI(avhv^2) + I(lgif^2) + I(rgif^2) + I(incm^2),\n\t\t\t\tdata=data.train.std.y, scale=TRUE, validation=\"CV\")\n\t\t\t\n\t\t\tvalidationplot(pcr.train.fit,val.type=\"MSEP\")\n\t\t\t\n\t\t\t#PCR (M=16)\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=16)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t\t#PCR (M=25)\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=25)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t\t#PCR (M=34) All\n\t\t\tpcr.pred = predict(pcr.train.fit, data.valid.std.y, ncomp=34)\n\t\t\tpcr.mse = mean((y.valid - pcr.pred)^2) # mean prediction error\n\t\t\tpcr.se = sd((y.valid - pcr.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpcr.mse\n\t\t\tpcr.se\n\t\t\t\n\t\t#PARTIAL LEAST SQUARES\n\t\t\n\t\t\tset.seed(53)\n\t\t\tpls.train.fit = plsr(damt ~ . + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) +\n\t\t\t\t\tI(wrat^2) + I(inca^2) + I(npro^2) + I(tgif^2) + I(plow^2) + I(agif^2) + \n\t\t\t\t\tI(avhv^2) + I(lgif^2) + I(rgif^2) + I(incm^2),\n\t\t\t\tdata=data.train.std.y, scale=TRUE, validation=\"CV\")\n\t\t\t\n\t\t\tvalidationplot(pls.train.fit,val.type=\"MSEP\")\n\t\t\t\n\t\t\t#PLS (M=3)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=3)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t\t#PLS (M=6)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=6)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t\t#PLS (M=7)\n\t\t\tpls.pred = predict(pls.train.fit, data.valid.std.y, ncomp=7)\n\t\t\tpls.mse = mean((y.valid - pls.pred)^2) # mean prediction error\n\t\t\tpls.se = sd((y.valid - pls.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tpls.mse\n\t\t\tpls.se\n\t\t\t\n\t\t#GAM\n\t\t\n\t\t\t#GAM 1\n\t\t\tgam.train.fit1 = gam(damt ~ reg1 + reg2 + reg3 + reg4 + poly(chld, 2) + poly(hinc, 3) + \n\t\t\t\t\tpoly(wrat, 4) + s(avhv, 3) + s(incm, 3) + s(inca, 3) + s(plow, 3) + s(npro, 3) + \n\t\t\t\t\ts(tgif, 3) + s(lgif, 4) + s(rgif, 4) + s(tdon, 3) + s(tlag, 3) + s(agif, 4),\n\t\t\t\tdata=data.train.std.y)\n\t\t\t\t\n\t\t\tgam.pred = predict(gam.train.fit1, data.valid.std.y)\n\t\t\tgam.mse = mean((y.valid - gam.pred)^2) # mean prediction error\n\t\t\tgam.se = sd((y.valid - gam.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tgam.mse\n\t\t\tgam.se\n\t\t\t\n\t\t\t#GAM 2\n\t\t\tgam.train.fit2 = gam(damt ~ reg1 + reg2 + reg3 + reg4 + poly(chld, 2) + poly(hinc, 3) + \n\t\t\t\t\tpoly(wrat, 4) + s(avhv, 2) + s(incm, 2) + s(inca, 2) + s(plow, 2) + s(npro, 2) + \n\t\t\t\t\ts(tgif, 2) + s(lgif, 3) + s(rgif, 3) + s(tdon, 2) + s(tlag, 2) + s(agif, 3),\n\t\t\t\tdata=data.train.std.y)\n\t\t\t\t\n\t\t\tgam.pred = predict(gam.train.fit2, data.valid.std.y)\n\t\t\tgam.mse = mean((y.valid - gam.pred)^2) # mean prediction error\n\t\t\tgam.se = sd((y.valid - gam.pred)^2)/sqrt(n.valid.y) # std error\n\t\t\t\n\t\t\tgam.mse\n\t\t\tgam.se\n\t\t\t\n\t#MODEL LDAF FINAL CLASSIFICATION MODEL\n\n\t\tmodel.ldaF = lda(donr ~ reg1 + reg2 + reg3 + reg4 + home + chld + hinc + genf + wrat + \n\t\t\t\t\t\t avhv + incm + inca + plow + npro + tgif + lgif + rgif + tdon + \n\t\t\t\t\t\t tlag + agif + I(hinc^2) + I(chld^2) + I(tdon^2) + I(tlag^2) + I(wrat^2) + \n\t\t\t\t\t\t I(inca^2) + I(npro^2) + I(tgif^2), \n\t\t\t\t\t data.train.std.c) # include additional terms on the fly using I()\n\t\t\n\t\tn.mail.valid = which.max(profit.ldaF)\n\t\ttr.rate = .1 # typical response rate is .1\n\t\tvr.rate = .5 # whereas validation response rate is .5\n\t\tadj.test.1 = (n.mail.valid/n.valid.c)/(vr.rate/tr.rate) # adjustment for mail yes\n\t\tadj.test.0 = ((n.valid.c - n.mail.valid)/n.valid.c)/((1 - vr.rate)/(1 - tr.rate)) # adjustment for mail no\n\t\tadj.test = adj.test.1/(adj.test.1+adj.test.0) # scale into a proportion\n\t\tn.mail.test = round(n.test*adj.test, 0) # calculate number of mailings for test set\n\t\tpost.test = predict(model.ldaF, data.test.std)$posterior[,2] # post probs for test data\n\t\t\n\t\tcutoff.test = sort(post.test, decreasing=T)[n.mail.test+1] # set cutoff based on n.mail.test\n\t\tchat.test = ifelse(post.test>cutoff.test, 1, 0) # mail to everyone above the cutoff\n\t\ttable(chat.test)\n\t\t\n\t#GAM1 FINAL PREDICTION MODEL\n\t\tyhat.test = predict(gam.train.fit1, newdata = data.test.std) # test predictions\n\t\t\n\t#OUTPUT\n\tip = data.frame(chat=chat.test, yhat=yhat.test) # data frame with two variables: chat and yhat\n\twrite.csv(ip, file=\"./ip.csv\", \n row.names=FALSE) # use group member initials for file name\n\t", "meta": {"hexsha": "46405b46141d4ab4856f8a0adad361a52a6105b7", "size": 18890, "ext": "r", "lang": "R", "max_stars_repo_path": "Data Prep Classification and Prediction Analyis v1.r", "max_stars_repo_name": "ericsgagnon/psustat897groupproject", "max_stars_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Data Prep Classification and Prediction Analyis v1.r", "max_issues_repo_name": "ericsgagnon/psustat897groupproject", "max_issues_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data Prep Classification and Prediction Analyis v1.r", "max_forks_repo_name": "ericsgagnon/psustat897groupproject", "max_forks_repo_head_hexsha": "6d3e6fc5ce028a616f97469a8c4b5b6e94dd18a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0289256198, "max_line_length": 135, "alphanum_fraction": 0.6200635257, "num_tokens": 6881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6225459507429141}} {"text": "library(tidyverse)\nlibrary(moments)\nlibrary(xtable)\nlibrary(gamlss)\noptions(\"scipen\"=999, \"digits\"=3)\n# установить рабочую директорию\nsetwd(\"/home/user/.../Hist/\")\n# прочитать данные, первая строка --- заголовок, разделитель колонок --- запятая, десятичный разделитель --- точка\n# x --- positional аргумент\n# header, sep, dec --- named\nalmatyFlats <- read.csv('', header = TRUE, sep = \",\", dec = \".\")\n\nspbaFlats <- read.csv('https://github.com/Kirill-Murashev/datasets/blob/main/Saint-Petersburg/flats/spba_flats_210928.csv', header = TRUE, sep = \",\", dec = \".\")\n\n# изменить тип объекта на более удобный и современный\nas_tibble(almatyFlats)\n\n# создать функцию для \"нулевой\" версии формулы Стёрджесса\nkHistSturgess0 <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n ks0 = (max(x)-min(x))/(1+log2(n)) # рассчитать k\n return(c(ks0)) # возвратить k\n} # конец функции\n\n# создать функцию для первой версии формулы Стёрджесса\nkHistSturgess1 <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n ks1 = (1+log2(n)) # рассчитать k\n return(ks1) # возвратить k \n} # конец функции \n\n# создать функцию для второй версии формулы Стёрджесса\nkHistSturgess2 <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n ks2 = (1+(3.3*log10(n))) # рассчитать k\n return(ks2) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Брукса и Каррузера\nkHistBruksKarruzer <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kbk = 5*log10(n) # рассчитать k\n return(kbk) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Хайнхольда и Гаеде\nkHistHeinholdGaede <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n khg = sqrt(n) # рассчитать k\n return(khg) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Манна и Вальда\nkHistMannWald <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kmw = (4*(2^(1/5)))*((n/qnorm(0.95))^0.4) # рассчитать k\n return(kmw) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Уильямса\nkHistWilliams <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kwi = (2*(2^(1/5)))*((n/qnorm(0.95))^0.4) # рассчитать k\n return(kwi) # возвратить k \n} # конец функции\n\n# создать функцию для первой формулы Хана и Шапиро\nkHistHahnShapiro <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n khs = 4*(0.75*((n-1)^2)^0.2) # рассчитать k\n return(khs) # возвратить k \n} # конец функции\n\n# создать функцию для второй формулы Хана и Шапиро\nkHistShapiroHahn <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n ksh = 1.9*(n^0.4) # рассчитать k\n return(ksh) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Кендалла и Стюарта\nkHistKendallStuart <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n b = 2 # задать b: 2 <= b <= 4 \n t1 = qnorm(0.95) # задать t1\n t2 = 0 # задать t2\n kks = b*(sqrt(2)*(((n-1)/(t1+t2))^0.4)) # рассчитать k\n return(kks) # возвратить k\n} # конец функции\n\n# создать функцию для формулы Таушанова\nkHistTaushanow <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kta = 4*log10(n) # рассчитать k\n return(kta) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Тоневой\nkHistTonewa <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kto = 5*log10(n)-5 # рассчитать k\n return(kto) # возвратить k \n} # конец функции\n\n# создать функцию для формулы Алексеевой\nkHistAlekseewa <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kurt = kurtosis(x) # вычислить коэффициент эксцесса\n counterkurt = 1/(sqrt(kurt)) # вычислить коэффициент контрэксцесса\n kal = (4/counterkurt)*(log10(n/10)) # рассчитать k\n return(kal) # возвратить k \n} # конец функции\n\n# создать функцию для первой формулы Новицкого\nkHistNowiczkij1 <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kurt = kurtosis(x) # вычислить коэффициент эксцесса\n kn1 = ((kurt+1.5)/6)*(n^0.4) # рассчитать k\n return(kn1) # возвратить k \n} # конец функции\n\n# создать функцию для второй формулы Новицкого\nkHistNowiczkij2 <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kurt = kurtosis(x) # вычислить коэффициент эксцесса\n kn2 = (((kurt^4)*(n^2))^(1/5))*(1/3) # рассчитать k\n return(kn2) # возвратить k \n} # конец функции\n\n# создать функцию для третьей формулы Новицкого\nkHistNowiczkij3_min <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kurt = kurtosis(x) # вычислить коэффициент эксцесса\n kn3min = 0.55*(n^0.4) # рассчитать k min\n return(kn3min) # возвратить k min \n} # конец функции\n\n# создать функцию для третьей формулы Новицкого\nkHistNowiczkij3_max <- function(x, na.omit = FALSE){ # создать функцию, игнорировать пропущенные значения\n n <- NROW(x) # вычислить число n\n kurt = kurtosis(x) # вычислить коэффициент эксцесса\n kn3max = 1.25*(n^0.4) # рассчитать k max\n return(kn3max) # возвратить k max\n} # конец функции\n\noptimalK <- function(x, na.omit = FALSE){ # создать функцию для обобщения результата\n ks0 <- kHistSturgess0(x)\n ks1 <- kHistSturgess1(x)\n ks2 <- kHistSturgess2(x)\n kbk <- kHistBruksKarruzer(x)\n khg <- kHistHeinholdGaede(x)\n kmw <- kHistMannWald(x)\n kwi <- kHistWilliams(x)\n khs <- kHistHahnShapiro(x) \n ksh <- kHistShapiroHahn(x)\n kks <- kHistKendallStuart(x)\n kta <- kHistTaushanow(x)\n kto <- kHistTonewa(x)\n kal <- kHistAlekseewa(x)\n kn1 <- kHistNowiczkij1(x)\n kn2 <- kHistNowiczkij2(x)\n kn3_min <- kHistNowiczkij3_min(x)\n kn3_max <- kHistNowiczkij3_max(x)\n optimal_k <- return(c(ks0, ks1, ks2, kbk, khg, kmw, kwi, khs, ksh, kks, kta, kto, kal, kn1, kn2, kn3_min, kn3_max))\n return(k)\n}\n\nkOptimalAlmaty <- optimalK(almatyFlats$price.m) \nfunction_name<- c(\"Sturgess0\", \"Sturgess1\", \"Sturgess2\", \"BruksKarruzer\", \"HeinholdGaede\", \"MannWald\", \"Williams\", \"HahnShapiro\", \"ShapiroHahn\", \"KendallStuart\", \"Taushanow\", \"Tonewa\", \"Alekseewa\", \"Nowiczkij1\", \"Nowiczkij2\", \"Nowiczkij3_min\", \"Nowiczkij3_max\")\nkOptimalAlmaty <- tibble(function_name, kOptimalAlmaty)\n\nxtable(kOptimalAlmaty,caption = \"оптимальное число k, полученное различными методами\", auto = TRUE)\n\nhist(almatyFlats$price.m,\n freq = FALSE,\n xlab = \"price, kaz rubles\",\n ylab = \"probability\",\n main = \"Price per meter histogram, Almaty, summer 2019\")\n\nhistDist(almatyFlats$price.m,\n nbins = kHistNowiczkij1(almatyFlats$price.m),\n xlab = \"price, kaz rubles\",\n ylab = \"probability\",\n main = \"Price per meter histogram, Almaty, summer 2019\")\nlines(density(almatyFlats$price.m))\npretty(almatyFlats$price.m)\n?histDist\n\n\nkOptimalSpba <- optimalK(spbaFlats$price_m) \nfunction_name<- c(\"Sturgess0\", \"Sturgess1\", \"Sturgess2\", \"BruksKarruzer\", \"HeinholdGaede\", \"MannWald\", \"Williams\", \"HahnShapiro\", \"ShapiroHahn\", \"KendallStuart\", \"Taushanow\", \"Tonewa\", \"Alekseewa\", \"Nowiczkij1\", \"Nowiczkij2\", \"Nowiczkij3_min\", \"Nowiczkij3_max\")\n\nkOptimalSpba <- tibble(function_name, kOptimalSpba)\n\nxtable(kOptimalSpba,caption = \"оптимальное число k, полученное различными методами\", auto = TRUE)\n\nhistDist(spbaFlats$price_m,\n nbins = kHistAlekseewa(spbaFlats$price_m),\n xlab = \"price, rub\",\n ylab = \"probability\",\n main = \"Price per meter, histogram, SPBA (2021-09-28)\") \nlines(density(spbaFlats$price_m))\n\nrm(kOptimalAlmaty)\nrm(kOptimalSpba)\nrm(spbaFlats)\n", "meta": {"hexsha": "7d5c75080b4f75842feb68b69db9359ba8bc83b1", "size": 10849, "ext": "r", "lang": "R", "max_stars_repo_path": "Hist/hist-plotting.r", "max_stars_repo_name": "Kirill-Murashev/AI_for_valuers_R_source", "max_stars_repo_head_hexsha": "068b4389ae6e5e1a59c6cffbf36083310c765e92", "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": "Hist/hist-plotting.r", "max_issues_repo_name": "Kirill-Murashev/AI_for_valuers_R_source", "max_issues_repo_head_hexsha": "068b4389ae6e5e1a59c6cffbf36083310c765e92", "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": "Hist/hist-plotting.r", "max_forks_repo_name": "Kirill-Murashev/AI_for_valuers_R_source", "max_forks_repo_head_hexsha": "068b4389ae6e5e1a59c6cffbf36083310c765e92", "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": 52.4106280193, "max_line_length": 261, "alphanum_fraction": 0.5347958337, "num_tokens": 3408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6223986578113428}} {"text": "=begin\n # sample-factorize02.rb\n\n require \"algebra\"\n \n Z7 = ResidueClassRing(Integer, 7)\n P = Polynomial(Z7, \"x\")\n x = P.var\n f = 8*x**7 - 20*x**6 + 6*x**5 - 11*x**4 + 44*x**3 - 9*x**2 - 27\n p f.factorize #=> (x + 5)^2(x + 3)^2(x + 2)^3\n \n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "faaf7fa94f7a17bbeae6c33535bf31a8a5d8b698", "size": 270, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-factorize02.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-factorize02.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-factorize02.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2857142857, "max_line_length": 65, "alphanum_fraction": 0.5148148148, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6223703272029534}} {"text": "model_melting <- function (jul = 0,\n Tmf = 0.5,\n DKmax = 0.0,\n Kmin = 0.0,\n tavg = 0.0){\n #'- Name: Melting -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: snow in the process of melting\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: It simulates snow in the process of melting\n #'- inputs:\n #' * name: jul\n #' ** description : current day of year for the calculation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : INT\n #' ** default : 0\n #' ** min : 0\n #' ** max : 366\n #' ** unit : d\n #' ** uri : \n #' * name: Tmf\n #' ** description : threshold temperature for snow melting \n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.5\n #' ** min : 0.0\n #' ** max : 1.0\n #' ** unit : degC\n #' ** uri : \n #' * name: DKmax\n #' ** description : difference between the maximum and the minimum melting rates\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW/degC/d\n #' ** uri : \n #' * name: Kmin\n #' ** description : minimum melting rate on 21 December\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW/degC/d\n #' ** uri : \n #' * name: tavg\n #' ** description : average temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : degC\n #' ** uri : \n #'- outputs:\n #' * name: M\n #' ** description : snow in the process of melting\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n M <- 0.0\n K <- DKmax / 2.0 * -sin((2.0 * pi * as.double(jul) / 366.0 + (9.0 / 16.0 * pi))) + Kmin + (DKmax / 2.0)\n if (tavg > Tmf)\n {\n M <- K * (tavg - Tmf)\n }\n return (list('M' = M))\n}", "meta": {"hexsha": "67d8ae5362ba99efc12f151cbceaa29219d9ab0c", "size": 3742, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Melting.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/Melting.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/Melting.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.775, "max_line_length": 109, "alphanum_fraction": 0.3027792624, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6223703121145225}} {"text": "### We want a piece-wise approximation of asin(x)\n### But we want to have the following constraints:\n### 1) each should be completely well behaved in its range\n### 2) adjacent pieces will be blended using linear approximation so their regions should overlap\n### 3) the blended result should have continuity\n### 3) symmetry will be handled outside this approximation\n### 4) the overall range handled should start at 0 and end before 1\n### 5) the overall should be as large as possible, but need not reach 1\n\nfit = function(param) {\n c0.high = param[1]\n c1.high = param[2]\n c2.low = param[3]\n c2.high = param[4]\n c3.low = param[5]\n c3.high = param[6]\n c4.low = param[7]\n\n x = seq(-c0.high, c0.high, by=0.01)\n d0 = data.frame(y=asin(x), x=x, x2=x*x, x3=x*x*x, i1=1/(1-x), i2=1/(1-x)/(1-x))\n m0 = glm(y ~ x + x2 + x3 + i1 + i2, d0, family='gaussian')\n\n x = seq(0, c1.high, by=0.01)\n d1 = data.frame(y=asin(x), x=x, x2=x*x, x3=x*x*x, i1=1/(1-x), i2=1/(1-x)/(1-x))\n m1 = glm(y ~ x + x2 + x3 + i1 + i2, d1, family='gaussian')\n\n x = seq(c2.low, c2.high, by=0.01)\n d2 = data.frame(y=asin(x), x=x, x2=x*x, x3=x*x*x, i1=1/(1-x), i2=1/(1-x)/(1-x))\n m2 = glm(y ~ x + x2 + x3 + i1 + i2, d2, family='gaussian')\n \n x = seq(c3.low, c3.high, by=0.01)\n d3 = data.frame(y=asin(x), x=x, x2=x*x, x3=x*x*x, i1=1/(1-x), i2=1/(1-x)/(1-x))\n m3 = glm(y ~ x + x2 + x3 + i1 + i2, d3, family='gaussian')\n\n list(m0=m0,m1=m1,m2=m2,m3=m3,\n c0.high=c0.high,c1.high=c1.high, c2.low=c2.low, c2.high=c2.high,\n c3.low=c3.low, c3.high=c3.high, c4.low=c4.low)\n}\n\nfollow = function(models) {\n x = seq(0, models$c3.high, by=0.01)\n data = data.frame(x=x, x2=x*x, x3=x*x*x, i1=1/(1-x), i2=1/(1-x)/(1-x))\n raw = data.frame(\n y0=predict(models$m0, newdata=data),\n y1=predict(models$m1, newdata=data),\n y2=predict(models$m2, newdata=data),\n y3=predict(models$m3, newdata=data),\n y4=asin(x)\n )\n\n ## c0.high, c1.high, c2.low, c1.high, c3.low, c2.high, c3.high, c4.low\n mix = with(models, {\n mix = matrix(0, nrow=dim(raw)[1], ncol=5)\n x0 = bound((c0.high - x) / c0.high)\n x1 = bound((c1.high - x) / (c1.high - c2.low));\n x2 = bound((c2.high - x) / (c2.high - c3.low));\n x3 = bound((c3.high - x) / (c3.high - c4.low));\n\n mix[, 1] = x0\n mix[, 2] = (1-x0) * x1\n mix[, 3] = (1-x1) * x2\n mix[, 4] = (1-x2) * x3\n mix[, 5] = 1-x3\n mix\n })\n\n data.frame(x=x, yhat=rowSums(raw * mix), y=asin(x))\n}\n\nbound = function(v) {\n over = v > 1\n under = v < 0\n v * (1-over) * (1-under) + over\n}\n \n", "meta": {"hexsha": "1a4ae5908ebf98a35f3a95d59644cb86e2d0fdd0", "size": 2666, "ext": "r", "lang": "R", "max_stars_repo_path": "core/src/main/r/asin-approx.r", "max_stars_repo_name": "slandelle/t-digest", "max_stars_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1479, "max_stars_repo_stars_event_min_datetime": "2015-01-05T09:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:20:21.000Z", "max_issues_repo_path": "core/src/main/r/asin-approx.r", "max_issues_repo_name": "slandelle/t-digest", "max_issues_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 141, "max_issues_repo_issues_event_min_datetime": "2015-01-02T14:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T22:54:11.000Z", "max_forks_repo_path": "core/src/main/r/asin-approx.r", "max_forks_repo_name": "slandelle/t-digest", "max_forks_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 222, "max_forks_repo_forks_event_min_datetime": "2015-01-08T23:52:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T04:50:59.000Z", "avg_line_length": 35.0789473684, "max_line_length": 97, "alphanum_fraction": 0.5423855964, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6221827203753034}} {"text": "/*\n * fmath.r -- sin, cos, tan, acos, asin, atan, dtor, rtod, exp, log, sqrt\n */\n\n/*\n * Most of the math ops are simple calls to underlying C functions,\n * sometimes with additional error checking to avoid and/or detect\n * various C runtime errors.\n */\n#begdef MathOp(funcname,ccode,comment,pre,post)\n#funcname \"(r)\" comment\nfunction{1} funcname(x)\n\n if !cnv:C_double(x) then\n runerr(102, x)\n\n abstract {\n return real\n }\n inline {\n double y;\n pre\t\t/* Pre math-operation range checking */\n errno = 0;\n y = ccode(x);\n post\t\t/* Post math-operation C library error detection */\n return C_double y;\n }\nend\n#enddef\n\f\n\n#define aroundone if (x < -1.0 || x > 1.0) {drunerr(205, x); errorfail;}\n#define positive if (x < 0) {drunerr(205, x); errorfail;}\n\n#define erange if (errno == ERANGE) runerr(204);\n#define edom if (errno == EDOM) runerr(205);\n\nMathOp(sin, sin, \", x in radians.\", ;, ;)\nMathOp(cos, cos, \", x in radians.\", ;, ;)\nMathOp(tan, tan, \", x in radians.\", ; , erange)\nMathOp(acos,acos, \", x in radians.\", aroundone, edom)\nMathOp(asin,asin, \", x in radians.\", aroundone, edom)\n\n#if NT\ndouble atanh(double x)\n{\n return 0.5 * 2.302585093 * log((1 + x) / (1 - x));\n}\n#endif\n\nMathOp(atanh,atanh, \", x in radians.\", aroundone, edom)\nMathOp(exp, exp, \" - e^x.\", ; , erange)\nMathOp(sqrt,sqrt, \" - square root of x.\", positive, edom)\n#define DTOR(x) ((x) * Pi / 180)\n#define RTOD(x) ((x) * 180 / Pi)\nMathOp(dtor,DTOR, \" - convert x from degrees to radians.\", ; , ;)\nMathOp(rtod,RTOD, \" - convert x from radians to degrees.\", ; , ;)\n\n\f\n\n\"atan(r1,r2) -- r1, r2 in radians; if r2 is present, produces atan2(r1,r2).\"\n\nfunction{1} atan(x,y)\n\n if !cnv:C_double(x) then\n runerr(102, x)\n\n abstract {\n return real\n }\n if is:null(y) then\n inline {\n return C_double atan(x);\n }\n if !cnv:C_double(y) then\n runerr(102, y)\n inline {\n return C_double atan2(x,y);\n }\nend\n\f\n\n\"log(r1,r2) - logarithm of r1 to base r2.\"\n\nfunction{1} log(x,b)\n\n if !cnv:C_double(x) then\n runerr(102, x)\n\n abstract {\n return real\n }\n inline {\n if (x <= 0.0) {\n drunerr(205, x);\n errorfail;\n }\n }\n if is:null(b) then\n inline {\n return C_double log(x);\n }\n else {\n if !cnv:C_double(b) then\n runerr(102, b)\n body {\n#ifndef Concurrent\n static double lastbase = 0.0;\n static double divisor;\n#endif\t\t\t\t\t/* Concurrent */\n\t CURTSTATE();\n\n if (b <= 1.0) {\n drunerr(205, b);\n errorfail;\n }\n if (b != lastbase) {\n divisor = log(b);\n lastbase = b;\n }\n\t x = log(x) / divisor;\n return C_double x;\n } \n }\nend\n\n\"max(x,y,...) - return the maximum of the arguments\"\n\nfunction{1} max(argv[argc])\nabstract {\n return any_value\n }\nbody {\n int i;\n struct descrip dtmp;\n if (argc == 0) fail;\n dtmp = argv[0];\n if (argc == 1) {\n if (is:list(dtmp)) {\n\t int i, j, size;\n\t union block *bp;\n\t size = BlkD(dtmp,List)->size;\n\t if (size==0) fail;\n#ifdef Arrays\n\t if (BlkD(dtmp,List)->listtail == NULL) {\n\t bp = BlkD(dtmp,List)->listhead;\n\t if (bp->Intarray.title == T_Intarray) {\n\t word mymax = bp->Intarray.a[0];\n\t for(i = 1; i < size; i++)\n\t\t if (bp->Intarray.a[i] > mymax) mymax = bp->Intarray.a[i];\n\t return C_integer mymax;\n\t }\n\t else {\n\t double mymax = bp->Realarray.a[0];\n\t for(i = 1; i < size; i++)\n\t\t if (bp->Realarray.a[i] > mymax) mymax = bp->Realarray.a[i];\n\t dtmp.dword = D_Real;\n#ifdef DescriptorDouble\n\t dtmp.vword.realval = mymax;\n#else\t\t\t\t\t/* DescriptorDouble */\n\t dtmp.vword.bptr = (union block *)alcreal(mymax);\n#endif\t\t\t\t\t/* DescriptorDouble */\n\t return dtmp;\n\t }\n\t }\n\n#endif\n\t /*\n\t * normal max(L), walk through list elements\n\t */\n\t bp = dtmp.vword.bptr;\n\t dtmp = nulldesc; /* the minimal value */\n\t for (bp = Blk(bp,List)->listhead; BlkType(bp) == T_Lelem;\n\t bp = Blk(bp,Lelem)->listnext) {\n\t for (i = 0; i < Blk(bp,Lelem)->nused; i++) {\n\t j = bp->Lelem.first + i;\n\t if (j >= bp->Lelem.nslots)\n\t\t j -= bp->Lelem.nslots;\n\t if (anycmp(bp->Lelem.lslots+j, &dtmp) == Greater)\n\t\t dtmp = bp->Lelem.lslots[j];\n\t }\n\t }\n\t }\n }\n else\n for(i=1;isize;\n\t if (size==0) fail;\n#ifdef Arrays\n\t if (BlkD(dtmp,List)->listtail == NULL) {\n\t bp = BlkD(dtmp,List)->listhead;\n\t if (bp->Intarray.title == T_Intarray) {\n\t word mymin = bp->Intarray.a[0];\n\t for(i = 1; i < size; i++)\n\t\t if (bp->Intarray.a[i] < mymin) mymin = bp->Intarray.a[i];\n\t return C_integer mymin;\n\t }\n\t else {\n\t double mymin = bp->Realarray.a[0];\n\t for(i = 1; i < size; i++)\n\t\t if (bp->Realarray.a[i] < mymin) mymin = bp->Realarray.a[i];\n\t dtmp.dword = D_Real;\n#ifdef DescriptorDouble\n\t dtmp.vword.realval = mymin;\n#else\t\t\t\t\t/* DescriptorDouble */\n\t dtmp.vword.bptr = (union block *)alcreal(mymin);\n#endif\t\t\t\t\t/* DescriptorDouble */\n\t return dtmp;\n\t }\n\t }\n\n#endif\n\t /*\n\t * normal min(L), walk through list elements\n\t */\n\t bp = dtmp.vword.bptr;\n\t dtmp = nulldesc;\n\t for (bp = Blk(bp,List)->listhead; BlkType(bp) == T_Lelem;\n\t bp = Blk(bp,Lelem)->listnext) {\n\t for (i = 0; i < Blk(bp,Lelem)->nused; i++) {\n\t j = bp->Lelem.first + i;\n\t if (j >= bp->Lelem.nslots)\n\t\t j -= bp->Lelem.nslots;\n\t\t dtmp = bp->Lelem.lslots[j]; /* the minimal value for now */\n\t\t break;break;\n\t }\n\t }\n\t \n\t for (bp = Blk(bp,List)->listhead; BlkType(bp) == T_Lelem;\n\t bp = Blk(bp,Lelem)->listnext) {\n\t for (i = 0; i < Blk(bp,Lelem)->nused; i++) {\n\t j = bp->Lelem.first + i;\n\t if (j >= bp->Lelem.nslots)\n\t\t j -= bp->Lelem.nslots;\n\t if (anycmp(bp->Lelem.lslots+j, &dtmp) == Less)\n\t\t dtmp = bp->Lelem.lslots[j];\n\t }\n\t }\n\t }\n }\n else\n for(i=1;i 0) dtmp = argv[i];\n return dtmp;\n }\nend\n", "meta": {"hexsha": "3981e6d3275dfda5eec453120e65c8e464e9bb55", "size": 6473, "ext": "r", "lang": "R", "max_stars_repo_path": "src/runtime/fmath.r", "max_stars_repo_name": "MatthewCLane/unicon", "max_stars_repo_head_hexsha": "29f68fb05ae1ca33050adf1bd6890d03c6ff26ad", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2019-11-29T13:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T06:00:40.000Z", "max_issues_repo_path": "src/runtime/fmath.r", "max_issues_repo_name": "MatthewCLane/unicon", "max_issues_repo_head_hexsha": "29f68fb05ae1ca33050adf1bd6890d03c6ff26ad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 83, "max_issues_repo_issues_event_min_datetime": "2019-11-03T20:07:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T11:32:35.000Z", "max_forks_repo_path": "src/runtime/fmath.r", "max_forks_repo_name": "jschnet/unicon", "max_forks_repo_head_hexsha": "df79234dc1b8a4972f3908f601329591c06bd141", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2019-10-14T04:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T06:01:00.000Z", "avg_line_length": 24.3345864662, "max_line_length": 77, "alphanum_fraction": 0.5396261393, "num_tokens": 2117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6217451817687414}} {"text": "# file score could be produced by function implemented in permutationLsqLambdaK\n# this script is used to estimate the K and lambda value to calculate E-value and P-value\n\ndata1 = read.table(\"randomScores\")\nu = unique(data1$V1)\ns = u[order(u)]\n\ndata = data.frame(x=s, y=s)\nfor ( i in 1:length(s) ){\n\tdata[i, 2] = length(which(data1$V1 >= data$x[i])) / nrow(data1)\n}\nx=data$x\ny=data$y\nlibrary(minpack.lm)\nnonlin_mod=nlsLM(y~(1-exp(-1*k*1000000*exp(-1*l*x))), control=nls.lm.control(maxiter=550), start=list(k=0.3, l=0.2))\nplot(x, y, xlab=\"s\", ylab=\"p-value\")\nlines(x,predict(nonlin_mod),col=\"red\")\nnonlin_mod\n\n\n\n\n4000000\nnonlin_mod\nNonlinear regression model\n model: y ~ (1 - exp(-1 * k * 4e+06 * exp(-1 * l * x)))\n data: parent.frame()\n k l\n0.001959 0.344325\n residual sum-of-squares: 0.003286\n\nNumber of iterations to convergence: 25\nAchieved convergence tolerance: 1.49e-08\n\n\n\n1000000\nnonlin_mod\nNonlinear regression model\n model: y ~ (1 - exp(-1 * k * 1e+06 * exp(-1 * l * x)))\n data: parent.frame()\n k l\n0.006662 0.382291\n residual sum-of-squares: 0.001207\n\nNumber of iterations to convergence: 29\nAchieved convergence tolerance: 1.49e-08\n\n\n\n\n\n\n## for masking\n1000000\nnonlin_mod\nNonlinear regression model\n model: y ~ (1 - exp(-1 * k * 1e+06 * exp(-1 * l * x)))\n data: parent.frame()\n k l\n0.01011 0.38877\n residual sum-of-squares: 0.0002461\n\nNumber of iterations to convergence: 25\nAchieved convergence tolerance: 1.49e-08\n\n\n\n\n\n\n\n\n\n\nint matchingScore = 2;\nint mismatchingPenalty = -3;\nint openGapPenalty = -3;\nint extendGapPenalty = -1;\n\n\ndata1 = read.table(\"score\")\nu = unique(data1$V1)\ns = u[order(u)]\n\ndata = data.frame(x=s, y=s)\nfor ( i in 1:length(s) ){\n\tdata[i, 2] = length(which(data1$V1 >= data$x[i])) / nrow(data1)\n}\nx=data$x\ny=data$y\nlibrary(minpack.lm)\nnonlin_mod=nlsLM(y~(1-exp(-1*k*1000000*exp(-1*l*x))), control=nls.lm.control(maxiter=550), start=list(k=0.3, l=0.2))\nplot(x, y, xlab=\"s\", ylab=\"p-value\")\nlines(x,predict(nonlin_mod),col=\"red\")\n\nnonlin_mod\n\nNonlinear regression model\n model: y ~ (1 - exp(-1 * k * 1e+06 * exp(-1 * l * x)))\n data: parent.frame()\n k l\n1.807e-05 5.740e-02\n residual sum-of-squares: 0.001187\n\nNumber of iterations to convergence: 32\nAchieved convergence tolerance: 1.49e-08\n\n\n\n", "meta": {"hexsha": "9984f4453c5807d37729241d5433ae25a8029910", "size": 2289, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/scriptToestimateKandLambda.r", "max_stars_repo_name": "baoxingsong/dCNS", "max_stars_repo_head_hexsha": "86e324dc8321bceba8ecca325e4a64777286ae11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-11T00:39:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:50:36.000Z", "max_issues_repo_path": "scripts/scriptToestimateKandLambda.r", "max_issues_repo_name": "baoxingsong/dCNS", "max_issues_repo_head_hexsha": "86e324dc8321bceba8ecca325e4a64777286ae11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2021-02-27T16:36:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T01:33:32.000Z", "max_forks_repo_path": "scripts/scriptToestimateKandLambda.r", "max_forks_repo_name": "baoxingsong/dCNS", "max_forks_repo_head_hexsha": "86e324dc8321bceba8ecca325e4a64777286ae11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-07-27T06:47:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T13:31:08.000Z", "avg_line_length": 20.6216216216, "max_line_length": 116, "alphanum_fraction": 0.6649191787, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6217061123408418}} {"text": "model_diffusionlimitedevaporation <- function (deficitOnTopLayers = 5341.0,\n soilDiffusionConstant = 4.2){\n #'- Name: DiffusionLimitedEvaporation -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: DiffusionLimitedEvaporation Model\n #' * Author: Pierre Martre\n #' * Reference: From the wheat simulation model SiriusQuality\n #' Published in 2009\n #' doi:http://dx.doi.org/10.1016/j.eja.2006.04.007 \n #' \n #' * Institution: INRA Montpellier\n #' * Abstract: the evaporation from the diffusion limited soil when the surface has \n #' dried sufficiently to provide a significant barrier to water vapor diffusion \n #' \n #'- inputs:\n #' * name: deficitOnTopLayers\n #' ** description : deficit On TopLayers\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 5341\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: soilDiffusionConstant\n #' ** description : soil Diffusion Constant\n #' ** parametercategory : soil\n #' ** datatype : DOUBLE\n #' ** default : 4.2\n #' ** min : 0\n #' ** max : 10\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #'- outputs:\n #' * name: diffusionLimitedEvaporation\n #' ** description : the evaporation from the diffusion limited soil \n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n if (deficitOnTopLayers / 1000.0 <= 0.0)\n {\n diffusionLimitedEvaporation <- 8.3 * 1000.0\n }\n else\n {\n if (deficitOnTopLayers / 1000.0 < 25.0)\n {\n diffusionLimitedEvaporation <- 2.0 * soilDiffusionConstant * soilDiffusionConstant / (deficitOnTopLayers / 1000.0) * 1000.0\n }\n else\n {\n diffusionLimitedEvaporation <- 0.0\n }\n }\n return (list('diffusionLimitedEvaporation' = diffusionLimitedEvaporation))\n}", "meta": {"hexsha": "e8691afe7bc01a2284514f614392c19b5804b5fd", "size": 2965, "ext": "r", "lang": "R", "max_stars_repo_path": "test/Models/energybalance_pkg/src/r/Diffusionlimitedevaporation.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/Models/energybalance_pkg/src/r/Diffusionlimitedevaporation.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/Models/energybalance_pkg/src/r/Diffusionlimitedevaporation.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 48.606557377, "max_line_length": 135, "alphanum_fraction": 0.4428330523, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6217061106610581}} {"text": "forwarddif <- function(a, n) {\n if ( n == 1 )\n a[2:length(a)] - a[1:length(a)-1]\n else {\n r <- forwarddif(a, 1)\n forwarddif(r, n-1)\n }\n}\n\nfdiff <- function(a, n) {\n r <- a\n for(i in 1:n) {\n r <- r[2:length(r)] - r[1:length(r)-1]\n }\n r\n}\n\nv <- c(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)\n\nprint(forwarddif(v, 9))\nprint(fdiff(v, 9))\n", "meta": {"hexsha": "fbba5ca935b532b81e8c15adf2cc97628ddb2024", "size": 347, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Forward-difference/R/forward-difference.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/Forward-difference/R/forward-difference.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/Forward-difference/R/forward-difference.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 15.7727272727, "max_line_length": 45, "alphanum_fraction": 0.4870317003, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6216275246960675}} {"text": " DGGEVX Example Program Results\n\n\n Eigenvalue( 1) = 2.00000\n\n Eigenvector( 1)\n 0.99606\n 0.00569\n 0.06261\n 0.06261\n\n\n Eigenvalue( 2) = ( 3.00000, -4.00000)\n\n Eigenvector( 2)\n ( 0.94491, -0.00000)\n ( 0.18898, 0.00000)\n ( 0.11339, 0.15119)\n ( 0.11339, 0.15119)\n\n\n Eigenvalue( 3) = ( 3.00000, 4.00000)\n\n Eigenvector( 3)\n ( 0.94491, 0.00000)\n ( 0.18898, -0.00000)\n ( 0.11339, -0.15119)\n ( 0.11339, -0.15119)\n\n\n Eigenvalue( 4) = 4.00000\n\n Eigenvector( 4)\n 0.98752\n 0.01097\n -0.03292\n 0.15361\n", "meta": {"hexsha": "c4492450dfd4ccc39f47123423aeece2671b5edf", "size": 580, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dggevx_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/dggevx_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/dggevx_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 15.2631578947, "max_line_length": 43, "alphanum_fraction": 0.5155172414, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6215795295834189}} {"text": "#simulations for 'Covariate adjustment and estimation of mean response in randomised trials'\r\n#Jonathan Bartlett\r\n\r\nlibrary(MASS)\r\nlibrary(sandwich)\r\nlibrary(blockrand)\r\n\r\nexpit <- function(x) {\r\n exp(x)/(1+exp(x))\r\n}\r\n\r\n#define function which runs simulations\r\n\r\nrunNegBinSim <- function(nSim, n, b0, bx, bz, bxz, gammadisp, nbwm,randtype) {\r\n muhat1 <- array(0, dim=c(nSim,2))\r\n varest1 <- array(0, dim=c(nSim,3))\r\n\r\n muhat2 <- array(0, dim=c(nSim))\r\n varest2 <- array(0, dim=c(nSim,2))\r\n\r\n muhat3 <- array(0, dim=c(nSim))\r\n varest3 <- array(0, dim=c(nSim))\r\n\r\n for (sim in 1:nSim) {\r\n print(sim)\r\n\r\n x <- 1*(runif(n)<0.5)\r\n if (randtype==1) {\r\n #simple randomisation\r\n z <- 1*(runif(n)<0.5)\r\n } else if (randtype==2) {\r\n #random permuted block randomisation\r\n rand <- blockrand(n=n, num.levels=2)\r\n z <- as.numeric(rand$treatment)[1:n]-1\r\n } else if (randtype==3) {\r\n #stratified random permuted block\r\n z <- x\r\n n0 <- sum(x==0)\r\n z[x==0] <- as.numeric(blockrand(n=n0, num.levels=2)$treatment)[1:n0]-1\r\n n1 <- sum(x==1)\r\n z[x==1] <- as.numeric(blockrand(n=n1, num.levels=2)$treatment)[1:n1]-1\r\n }\r\n\r\n xb <- b0+bx*(x-0.5)+bz*(z-0.5)+bxz*(x-0.5)*(z-0.5)\r\n #specify shape of gamma\r\n k <- 2\r\n if (gammadisp==T) {\r\n #shape k\r\n gamma <- rgamma(n, k, k)\r\n } else {\r\n #we use log normal which has mean 1 and variance matching the gamma variance\r\n gamma <- exp(rnorm(n,-0.5*log(1+1/k),(log(1+1/k))^0.5))\r\n }\r\n \r\n #simulate follow-up time\r\n t <- rep(1,n)\r\n shortFup <- 1*(runif(n)<0.25)\r\n t[shortFup] <- runif(sum(shortFup))\r\n \r\n y <- rpois(n, t*gamma*exp(xb))\r\n\r\n simdata <- data.frame(y,x,z)\r\n\r\n if (nbwm==T) {\r\n mod <- glm.nb(y~x+z+offset(log(t)))\r\n } else {\r\n mod <- glm(y~x+z+offset(log(t)), family=\"poisson\")\r\n }\r\n\r\n #calculate predictions for z=1\r\n pihat <- mean(z)\r\n\r\n #muhat1\r\n muhat1[sim,1] <- sum(y[z==1])/sum(t[z==1])\r\n #standard SE for this\r\n varest1[sim,1] <- (pihat^(-2))*(mean(t[z==1]))^(-2)*mean((z*(y-muhat1[sim,1]))^2)/n\r\n \r\n #muhat2\r\n activePredxb <- cbind(rep(1,n),x,rep(1,n)) %*% coef(mod)\r\n activePred <- exp(activePredxb)\r\n muhat2[sim] <- mean(activePred)\r\n #calculate delta method variances\r\n outer <- colMeans(as.numeric(exp(activePredxb)) * cbind(1,x,rep(1,n)))\r\n outer <- array(outer, dim=c(3,1))\r\n #sandwich variance treating covariates as fixed\r\n varest2[sim,1] <- t(outer) %*% vcovHC(mod, type = \"HC0\") %*% outer\r\n #variance estimator accounting random X assuming model correct\r\n varest2[sim,2] <- varest2[sim,1] + sum((activePred-muhat2[sim])^2)/(n^2)\r\n\r\n #muhat3\r\n muhat3[sim] <- muhat1[sim,1] - mean(((z-pihat)/pihat)*activePred)\r\n #variance of muhat3\r\n tauz <- mean(t[z==1])\r\n varest3[sim] <- (pihat^(-2))*tauz^(-2)*mean((z*(y-muhat3[sim]) -tauz*(z-pihat)*(activePred-muhat2[sim]) )^2)/n\r\n\r\n }\r\n\r\n list(muhat1=muhat1, muhat2=muhat2, muhat3=muhat3, varest1=varest1, varest2=varest2, varest3=varest3)\r\n\r\n}\r\n\r\nset.seed(698123)\r\n\r\nnSim <- 10000\r\nn <- 400\r\n\r\nsimRuns <- vector(\"list\", 4)\r\n\r\nsimRuns[[1]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=0,gammadisp=T,nbwm=T,randtype=2)\r\n#log normal dispersion parameter, but conditional mean model correct\r\nsimRuns[[2]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=0,gammadisp=F,nbwm=T,randtype=2)\r\n#now conditional mean model wrong, gamma distributed dispersion\r\nsimRuns[[3]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=-1.5,gammadisp=T,nbwm=T,randtype=2)\r\n#now use a Poisson working model\r\nsimRuns[[4]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=-1.5,gammadisp=T,nbwm=F,randtype=2)\r\n\r\nresultPrint <- function(resultSet) {\r\n c(mean(resultSet$muhat1[,1]), \r\n 100*mean((resultSet$muhat1[,1]*exp(-1.96*resultSet$varest1[,1]^0.5 / resultSet$muhat1[,1])mean(resultSet$muhat1[,1]))),\r\n mean(resultSet$muhat2)-mean(resultSet$muhat1[,1]),\r\n var(resultSet$muhat1[,1])/var(resultSet$muhat2),\r\n 100*mean((resultSet$muhat2*exp(-1.96*resultSet$varest2[,1]^0.5 / resultSet$muhat2)mean(resultSet$muhat1[,1]))),\r\n 100*mean((resultSet$muhat2*exp(-1.96*resultSet$varest2[,2]^0.5 / resultSet$muhat2)mean(resultSet$muhat1[,1]))),\r\n mean(resultSet$muhat3)-mean(resultSet$muhat1[,1]), \r\n var(resultSet$muhat1[,1])/var(resultSet$muhat3),\r\n 100*mean((resultSet$muhat3*exp(-1.96*resultSet$varest3^0.5 / resultSet$muhat3)mean(resultSet$muhat1[,1]))))\r\n}\r\n\r\nresTable <- matrix(unlist(lapply(simRuns, resultPrint)), byrow=F, ncol=length(simRuns))\r\ncolnames(resTable) <- c(\"Scenario 1\", \"Scenario 2\", \"Scenario 3\", \"Scenario 4\")\r\nrownames(resTable) <- c(\"Mean $\\\\hat{\\\\mu}_{1}(1)$\", \"95\\\\% CI Cov.\",\r\n \"Bias $\\\\hat{\\\\mu}_{2}(1)$\", \"Rel. eff.\", \r\n \"Fixed $X$ 95\\\\% CI Cov.\",\"Random $X$ 95\\\\% CI Cov.\",\r\n \"Bias $\\\\hat{\\\\mu}_{3}(1)$\", \"Rel. eff.\", \"95\\\\% CI Cov.\")\r\n \r\nlibrary(xtable)\r\nprint(xtable(data.frame(row = rownames(resTable),data.frame(resTable)), digits=2),sanitize.text.function=function(x){x}, include.rownames = F)\r\n\r\n\r\n#stratified randomisation\r\n\r\nsimRuns2 <- vector(\"list\", 4)\r\n\r\nsimRuns2[[1]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=0,gammadisp=T,nbwm=T,randtype=3)\r\n#log normal dispersion parameter, but conditional mean model correct\r\nsimRuns2[[2]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=0,gammadisp=F,nbwm=T,randtype=3)\r\n#now conditional mean model wrong, gamma distributed dispersion\r\nsimRuns2[[3]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=-1.5,gammadisp=T,nbwm=T,randtype=3)\r\n#now use a Poisson working model\r\nsimRuns2[[4]] <- runNegBinSim(nSim=nSim,n=n,b0=0,bx=3,bz=1,bxz=-1.5,gammadisp=T,nbwm=F,randtype=3)\r\n\r\nresultPrint <- function(resultSet) {\r\n c(mean(resultSet$muhat1[,1]), \r\n 100*mean((resultSet$muhat1[,1]*exp(-1.96*resultSet$varest1[,1]^0.5 / resultSet$muhat1[,1])mean(resultSet$muhat1[,1]))),\r\n mean(resultSet$muhat2)-mean(resultSet$muhat1[,1]),\r\n var(resultSet$muhat1[,1])/var(resultSet$muhat2),\r\n 100*mean((resultSet$muhat2*exp(-1.96*resultSet$varest2[,1]^0.5 / resultSet$muhat2)mean(resultSet$muhat1[,1]))),\r\n 100*mean((resultSet$muhat2*exp(-1.96*resultSet$varest2[,2]^0.5 / resultSet$muhat2)mean(resultSet$muhat1[,1]))),\r\n mean(resultSet$muhat3)-mean(resultSet$muhat1[,1]), \r\n var(resultSet$muhat1[,1])/var(resultSet$muhat3),\r\n 100*mean((resultSet$muhat3*exp(-1.96*resultSet$varest3^0.5 / resultSet$muhat3)mean(resultSet$muhat1[,1]))))\r\n}\r\n\r\nresTable <- matrix(unlist(lapply(simRuns2, resultPrint)), byrow=F, ncol=length(simRuns2))\r\ncolnames(resTable) <- c(\"Scenario 1\", \"Scenario 2\", \"Scenario 3\", \"Scenario 4\")\r\nrownames(resTable) <- c(\"Mean $\\\\hat{\\\\mu}_{1}(1)$\", \"95\\\\% CI Cov.\",\r\n \"Bias $\\\\hat{\\\\mu}_{2}(1)$\", \"Rel. eff.\", \r\n \"Fixed $X$ 95\\\\% CI Cov.\",\"Random $X$ 95\\\\% CI Cov.\",\r\n \"Bias $\\\\hat{\\\\mu}_{3}(1)$\", \"Rel. eff.\", \"95\\\\% CI Cov.\")\r\n\r\nprint(xtable(data.frame(row = rownames(resTable),data.frame(resTable)), digits=2),sanitize.text.function=function(x){x}, include.rownames = F)\r\n", "meta": {"hexsha": "b656d00c2c4ba0092870ee4cf415b22b241fcdcb", "size": 8086, "ext": "r", "lang": "R", "max_stars_repo_path": "CovAdjustedMarginalMeanEstimationSimulations.r", "max_stars_repo_name": "jwb133/CovAdjMarginalMean", "max_stars_repo_head_hexsha": "1b1567529819a4ca1132aafd7627a9a6118e9f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CovAdjustedMarginalMeanEstimationSimulations.r", "max_issues_repo_name": "jwb133/CovAdjMarginalMean", "max_issues_repo_head_hexsha": "1b1567529819a4ca1132aafd7627a9a6118e9f53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CovAdjustedMarginalMeanEstimationSimulations.r", "max_forks_repo_name": "jwb133/CovAdjMarginalMean", "max_forks_repo_head_hexsha": "1b1567529819a4ca1132aafd7627a9a6118e9f53", "max_forks_repo_licenses": ["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.9222222222, "max_line_length": 143, "alphanum_fraction": 0.6194657433, "num_tokens": 2853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6214685170539767}} {"text": "library('OpenMx')\n\nsetwd('~/git/sem_python/tests')\n# data <- read.csv('PoliticalDemocracy_missing.csv')\ndata <- read.csv('PoliticalDemocracy.csv')\n\nind60 <- c('x1', 'x2', 'x3')\ndem60 <- c('y1', 'y2', 'y3', 'y4')\ndem65 <- c('y5', 'y6', 'y7', 'y8')\nmanifest <- c(ind60, dem60, dem65)\nlatent <- c('ind60', 'dem60', 'dem65')\ndata <- data[manifest]\n\nmodel <- mxModel(\n \"PoliticalDemocracy\",\n type=\"RAM\",\n manifestVars=manifest,\n latentVars=latent,\n mxData(observed=data, type=\"raw\"),\n mxPath(from=manifest, arrows=2, free=TRUE, values=diag(var(data, na.rm=TRUE)) / 2),\n mxPath(from='y1', to='y5', arrows=2, free=TRUE, values=0),\n mxPath(from='y3', to='y7', arrows=2, free=TRUE, values=0),\n mxPath(from='y2', to=c('y4', 'y6'), arrows=2, free=TRUE, values=0),\n mxPath(from='y4', to='y6', arrows=2, free=TRUE, values=0),\n mxPath(from='y6', to='y8', arrows=2, free=TRUE, values=0),\n mxPath(from=latent, arrows=2, free=FALSE, values=1),\n\n mxPath(from='ind60', to='dem60', arrows=1, free=TRUE, values=1, labels='ind60_dem60'),\n mxPath(from='ind60', to='dem65', arrows=1, free=TRUE, values=1, labels='ind60_dem65'),\n mxPath(from='dem60', to='dem65', arrows=1, free=TRUE, values=1, labels='dem60_dem65'),\n\n mxPath(from=\"ind60\", to=ind60, arrows=1, free=TRUE, values=1, labels=c('indo60_x1', 'ind60_x2', 'ind60_x3')),\n mxPath(from=\"dem60\", to=dem60, arrows=1, free=TRUE, values=1, labels=c('dem60_y1', 'dem60_y2', 'dem60_y3', 'dem60_y4')),\n mxPath(from=\"dem65\", to=dem65, arrows=1, free=TRUE, values=1, labels=c('dem65_y1', 'dem65_y2', 'dem65_y3', 'dem65_y4')),\n mxPath(from='one', to=manifest, free=TRUE, values=colMeans(data, na.rm=TRUE)))\n\nfit <- mxRun(model)\n\nsummary(fit)\n", "meta": {"hexsha": "551449e8b16c0cba96cc4dea847a5a657279a5b2", "size": 1720, "ext": "r", "lang": "R", "max_stars_repo_path": "tests/sem_openmx.r", "max_stars_repo_name": "twoertwein/pySEM", "max_stars_repo_head_hexsha": "c814617cd8c4622a8a9bed21b0d4a37e59b1ac15", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-08-25T08:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T23:42:54.000Z", "max_issues_repo_path": "tests/sem_openmx.r", "max_issues_repo_name": "twoertwein/pySEM", "max_issues_repo_head_hexsha": "c814617cd8c4622a8a9bed21b0d4a37e59b1ac15", "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": "tests/sem_openmx.r", "max_forks_repo_name": "twoertwein/pySEM", "max_forks_repo_head_hexsha": "c814617cd8c4622a8a9bed21b0d4a37e59b1ac15", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-01-09T02:11:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T18:46:11.000Z", "avg_line_length": 43.0, "max_line_length": 124, "alphanum_fraction": 0.6418604651, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989815306765, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6214632142361035}} {"text": "#' @title calcHMImmersedTransomRes\n#'\n#' @description\n#' Calculate additional pressure resistance due to immersed transom (\\code{Rtr})\n#' (kN).\n#'\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param breadth Moulded breadth (vector of numericals, m)\n#' @param Cwp Water plane area coefficient (vector of numericals, see \n#' \\code{\\link{calcCwp}})\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#' @param At Transom area (vector of numericals, m^2) (see \\code{\\link{calcAt}})\n#' @param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can \n#' supply either a vector of numericals, a single number, or rely on the default\n#'\n#' @return \\code{Rtr} (vector of numericals, kN)\n#'\n#' @references\n#'Holtrop, J. and Mennen, G. G. J. 1982. \"An approximate power prediction\n#'method.\" International Shipbuilding Progress 29.\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calcCwp}}\n#'\\item \\code{\\link{calcAt}} }\n#'\n#' @family Holtrop-Mennen Calculations\n#' @family Resistance Calculations\n#'\n#' @examples\n#' calcHMImmersedTransomRes(seq(1,5,1),32.25,0.91,13.57,22.2,seawaterDensity=1.025)\n#'\n#' @export\n\ncalcHMImmersedTransomRes<-function(shipSpeed,breadth,Cwp,maxDraft,At,seawaterDensity=1.025){\n\n\nRtr<-\nifelse(shipSpeed/sqrt(2*9.81*At/(breadth+breadth*Cwp))<5,#case 1\n 0.5*seawaterDensity*(shipSpeed^2)*At*(0.2*(1-0.2*(\n shipSpeed/sqrt(2*9.81*At/(breadth+breadth*Cwp))\n )\n ))\n,#case 2\n0)\n\nreturn(Rtr)\n}\n", "meta": {"hexsha": "003613f126fca41f296323c7f01fcea1b17acf14", "size": 1562, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcHMImmersedTransomRes.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/calcHMImmersedTransomRes.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/calcHMImmersedTransomRes.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 31.24, "max_line_length": 92, "alphanum_fraction": 0.7074263764, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6210786172038991}} {"text": "#' Simulations from day-to-day stochastic process models for traffic \r\n#'\r\n#' This functions generartes sequences of traffic flow patterns drawn from one of a number of day-to-day stochastic process models. \r\n#' @param ODdemand Vector of origin-destination (OD) travel demands\r\n#' @param ODpair Vector indicating the OD pair serviced by each route (ordered by columns of the path-link incidence matrix, A).\r\n#' @param A Path-link incidence matrix\r\n#' @param N.days Number of days to simulate. Defaults to 100.\r\n#' @param N.sim Number of parallel simulation runs. Defaults to 1.\r\n#' @param x.start Initial route flow pattern. Defaults to NA, when the initial flow is set to SUE. \r\n#' @param Alpha Vector of free flow travel time parameters for each link\r\n#' @param Beta Vector of capacity parameters for each link\r\n#' @param pow Polynomial order of cost function for each link. Defaults to 4.\r\n#' @param RUM Choice of random utility model. Can be \"logit\" (the default) or \"probit\".\r\n#' @param theta A dispersion parameter. For the logit model, a single value specifying the logit parameter. For the probit model, a vector of standard deviations for the individual link cost errors. Defaults to 1.\r\n#' @param psi Recency parameter, controlling weight assigned to most recent path costs when updating disutility. Defaults to 0.05.\r\n#' @param process Defaults to \"Standard\", when a time-homogeneous Markoc process is employed in which route choice decisions are based on a utility which is a convex combination of the previous disutility and route costs. Alternatives are \"TIDDS1\" and \"TIDDS2\" time-inhomogeneous processes.\r\n#' @variable.demand If FALSE (the default), travel demand is static through time. If TRUE, then travel demand is subject to Poisson variation with mean specified by \\code{ODdemand}\r\n#' @param prob.model Route choice probability model. One of \"ProductMN\" (product multinomial, the default), \"Poisson\", and \"Approximate\" (a quick and dirty approximation to the others).\r\n#' @param tol Tolerance for convergence assessment for SUE. USed if \\code{x.start} not specified. Defaults to 1e-4.\r\n#' @param verbose Should progress of SUE algorithm be printed out? Defaults to FALSE.\r\n#' @return The output is a list with components x and u, containing traffic path flows and disutilies respectively. Both x and u are 3-dimensional arrays. The first dimension indexes simulation run (if multiple parallel runs are required); the second indexes network path; and the third indexes day.\r\n#' @keywords Day-to-day stochastic traffic assignment process\r\n#' @examples\r\n#' A <- matrix(c(0,1,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1),ncol=4,byrow=T) \r\n#' Alpha <- rep(10,7)\r\n#' Beta <- rep(50,7)\r\n#' pow <- rep(4,7)\r\n#' ODpair <- c(1,1,2,2)\r\n#' ODdemand <- c(50,50)\r\n#' theta <- 0.7\r\n#' N.sim <- 1\r\n#' N.days <- 100\r\n#' rDDSProcess(ODdemand,ODpair,A,N.days=N.days,N.sim=N.sim,x.start=c(20,0),Alpha=Alpha,Beta=Beta,pow=pow,RUM=\"logit\",theta=theta,process=\"TIDDS1\",variable.demand=F)\r\n#' rDDSProcess(ODdemand,ODpair,A,N.days=N.days,N.sim=N.sim,x.start=c(20,0),Alpha=Alpha,Beta=Beta,pow=pow,RUM=\"logit\",theta=theta,process=\"TIDDS2\",variable.demand=F)\r\n#' rDDSProcess(ODdemand,ODpair,A,N.days=N.days,N.sim=N.sim,x.start=c(20,0),Alpha=Alpha,Beta=Beta,pow=pow,RUM=\"logit\",theta=theta,process=\"Standard\",variable.demand=F)\r\n#' @export\r\n\r\nrDDSProcess <- function(ODdemand,ODpair,A,N.days=100,N.sim=1,x.start=NA,Alpha,Beta,pow=4,RUM=\"logit\",theta=1,psi=0.05,process=\"Standard\",variable.demand=F,tol=1e-4,verbose=F){\r\n\tpsi.change <- process==\"TIDDS1\" | process==\"TIDDS2\"\r\n\tN.routes <- ncol(A)\r\n \tN.OD <- length(ODdemand)\r\n \tN.routes.per.OD <- unname(table(ODpair))\r\n\tif (variable.demand) mean.ODdemand <- ODdemand\r\n \tODdemand.rep <- rep(ODdemand,N.routes.per.OD)\r\n \tindices <- c(0,cumsum(N.routes.per.OD))\r\n \tx.sim <- array(0,dim=c(N.sim,N.routes,N.days))\r\n \tu.sim <- array(0,dim=c(N.sim,N.routes,N.days))\r\n \tif(any(is.na(x.start))){\r\n\t\tif (variable.demand) ODdemand <- rpois(N.OD,mean.ODdemand)\r\n\t\tx.start <- SUE(ODdemand=ODdemand,ODpair=ODpair,A=A,Alpha=Alpha,Beta=Beta,pow=pow,RUM=RUM,theta=theta,tol=tol,verbose=verbose)$x\r\n \t}\r\n\tu.start <- PathCost(x.start,A=A,Alpha=Alpha,Beta=Beta,pow=pow)\r\n\tfor (ii in 1:N.sim){\r\n \t\tx.sim[ii,,1] <- x.start\r\n\t\tu.sim[ii,,1] <- u.start\r\n\t\tif (process==\"TIDDS1\") xbar <- x.start\r\n\t\tfor (tt in 2:(N.days)){\r\n\t\t\tif (variable.demand) ODdemand <- rpois(N.OD,mean.ODdemand)\r\n\t\t\tif(psi.change) psi <- 1/tt\r\n\t\t\tif (process!=\"TIDDS1\"){\r\n\t \t\tcost <- PathCost(x.sim[ii,,tt-1],A=A,Alpha=Alpha,Beta=Beta,pow=pow) \r\n \t\t\tu <- psi*cost + (1-psi)*u.sim[ii,,tt-1]\r\n\t\t\t}\r\n\t\t\tif (process==\"TIDDS1\"){\r\n\t\t\t\txbar <- (1-psi)*xbar + psi*x.sim[ii,,tt-1]\r\n\t\t\t\tu <- PathCost(xbar,A=A,Alpha=Alpha,Beta=Beta,pow=pow) \r\n\t\t\t}\r\n \t\tpr <- PathProb(u,ODpair=ODpair,A=A,RUM=RUM,theta=theta)\r\n \t\tfor (i in 1:N.OD){\r\n \t\t\tindx <- (indices[i]+1):(indices[i+1]) \r\n \t\t\tx.sim[ii,indx,tt] <- rmultinom(1,ODdemand[i],pr[indx])\r\n \t\t}\r\n\t\t\tu.sim[ii,,tt] <- u\r\n\t\t}\r\n\t}\r\n\tlist(x=x.sim,u=u.sim)\r\n}\r\n", "meta": {"hexsha": "6922215384adc9d6cc96e0346b084b8572c418fd", "size": 5041, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rDDSProcess.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/rDDSProcess.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/rDDSProcess.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.6282051282, "max_line_length": 300, "alphanum_fraction": 0.6949018052, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245617, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6210228688522196}} {"text": "# Assignment 3 - Example Code\r\n#QUESTION 1\r\nbase.samp = function(p,n) { #DEFINE FUNCTION TO SAMPLE FROM SET {0,1/(p-1),...1}\r\n x = (p-1-p/2) * runif(n) #NEED TO LIMIT TO RANGE OF (0, 1-delta)\r\n round(x) / (p-1)\r\n}\r\n\r\nmymorris = function(k,r,p,delta,par.mins,par.maxs,fun) { #NOTE THE LAST INPUT IS THE MODEL NAME FOR SENS ANALYSIS\r\n\r\n par.range = par.maxs - par.mins\r\n effects = array(dim = c(k,r))\r\n\r\n for (r.ind in 1:r) {\r\n J = array(1,dim=c(k+1,k)) #AN ARRAY OF ONES\r\n B = lower.tri(J) * 1 #A LOWER TRIANGULAR ARRAY OF ONES\r\n xstar = base.samp(p,k) #BASE VECTOR\r\n D = array(0,dim=c(k,k)) #AN ARRAY WITH EITHER 1 OR -1 IN DIAGONAL\r\n diag(D) = 1.0 -2*(runif(k) < .5)\r\n P = array(0,dim=c(k,k)) #A RANDOM PERMUTATION ARRAY\r\n diag(P) = 1\r\n P = P[,sample(c(1:k),k,replace=F)]\r\n Bstar = (t(xstar*t(J)) + (delta/2) * ((2*B - J)%*%D + J)) %*% P\r\n\r\n y = numeric(length=(k+1)) #VECTOR TO HOLD MODEL OUTPUT\r\n for (i in 1:(k+1)) y[i] = fun(par.mins + par.range * Bstar[i,] )\r\n for (i in 1:k) {\r\n par.change = Bstar[i+1,] - Bstar[i,] #FIND WHICH PARAMETER CHANGED AND WHETHER UP OR DOWN\r\n i2 = which(par.change != 0)\r\n effects[i2,r.ind] = (y[i+1] - y[i]) * (1 - 2 * (par.change[i2] < 0))\r\n }\r\n }\r\n effects #RETURN THE k x r ARRAY OF COMPUTED EFFECTS\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "9e0779f95cbd7cbe6ec8ca45b2dcb78f484f9912", "size": 1328, "ext": "r", "lang": "R", "max_stars_repo_path": "courses/ess-211/course_material/mymorris.r", "max_stars_repo_name": "christobal54/aei-grad-school", "max_stars_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "courses/ess-211/course_material/mymorris.r", "max_issues_repo_name": "christobal54/aei-grad-school", "max_issues_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "courses/ess-211/course_material/mymorris.r", "max_forks_repo_name": "christobal54/aei-grad-school", "max_forks_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-08T05:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T05:41:45.000Z", "avg_line_length": 36.8888888889, "max_line_length": 115, "alphanum_fraction": 0.5564759036, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.620488640159428}} {"text": "mod1 = function(v, n)\n# mod1(1:20, 6) => 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2\n ((v - 1) %% n) + 1\n\nstr2ints = function(s)\n as.integer(Filter(Negate(is.na),\n factor(levels = LETTERS, strsplit(toupper(s), \"\")[[1]])))\n\nvigen = function(input, key, decrypt = F)\n {input = str2ints(input)\n key = rep(str2ints(key), len = length(input)) - 1\n paste(collapse = \"\", LETTERS[\n mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}\n\nmessage(vigen(\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", \"vigenerecipher\"))\n # WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nmessage(vigen(\"WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\", \"vigenerecipher\", decrypt = T))\n # BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n", "meta": {"hexsha": "de0d1c2721976a75842fe064d0bfb27d8a0d6331", "size": 803, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Vigen-re-cipher/R/vigen-re-cipher.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Vigen-re-cipher/R/vigen-re-cipher.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/Vigen-re-cipher/R/vigen-re-cipher.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": 42.2631578947, "max_line_length": 108, "alphanum_fraction": 0.6811955168, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6202982028576748}} {"text": "fft <- function(timeScopeList, M) {\n N <- 2^M\n freqScopeList <- timeScopeList[1:N]\n\n LH <- N/2\n J <- N/2\n if (2<=N-1) {\n for (I in seq(2, N-1, 1)) {\n if (I=K) {\n J=J-K\n K=K/2\n }\n J=J+K\n }\n }\n\n for (L in seq(1, M, 1)) {\n B <- 2^(L-1)\n for (J in seq(0, B-1, 1)) {\n P <- J*(2^(M-L))\n WNP <- exp(-1i * 2 * pi * P / N)\n for (k in seq(J, N-1, 2^L)) {\n temp <- freqScopeList[k+1]+freqScopeList[k+B+1]*WNP\n freqScopeList[k+B+1] <- freqScopeList[k+1]-freqScopeList[k+B+1]*WNP\n freqScopeList[k+1] <- temp\n }\n }\n }\n \n return(freqScopeList)\n}\n\nprint(fft(c(1, 2, 3, 4, 5, 6, 7, 8), 3))\n", "meta": {"hexsha": "415d9d6739dd86b84618db7f455eb0d689b2e305", "size": 996, "ext": "r", "lang": "R", "max_stars_repo_path": "DigitalSignalProcess/R/fft.r", "max_stars_repo_name": "yyc12345/gist", "max_stars_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T06:24:10.000Z", "max_issues_repo_path": "DigitalSignalProcess/R/fft.r", "max_issues_repo_name": "yyc12345/gist", "max_issues_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DigitalSignalProcess/R/fft.r", "max_forks_repo_name": "yyc12345/gist", "max_forks_repo_head_hexsha": "000a03cb4b9fc8ca0b083c3b0bd939c41a590c94", "max_forks_repo_licenses": ["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.2926829268, "max_line_length": 83, "alphanum_fraction": 0.3765060241, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.6202949890656003}} {"text": "=begin\n[(())] \n\n= 練習帖\n\n== CONTENTS\n* ((<有限集合>))\n * ((<集合>))\n * ((<写像>))\n * ((<群>))\n* ((<多項式の計算>))\n* ((<多変数多項式の計算>))\n* ((<多変数多項式の計算その2>))\n* ((<多項式を複数の多項式で割った余りを求める>))\n* ((<多項式のグレブナ基底を求める>))\n* ((<素体を作る>))\n* ((<代数体を作る>))\n* ((<商体の生成>))\n * ((<整数環の商体を取って有理数を作る>))\n * ((<有理関数体の生成>))\n * ((<代数拡大体上の有理式の計算>))\n * ((<代数関数体>))\n* ((<線形代数>))\n * ((<連立1次方程式を解く>))\n * ((<正方行列の対角化>))\n * ((<行列の単因子を求める>))\n * ((<行列の Jordan 標準形を求める>))\n * (())\n* ((<グレブナ基底を元の基底で表現する>))\n* ((<任意の基底で割った商と余りを求める(余り=0に意味がある)>))\n* ((<因数分解>))\n * ((<整数係数多項式の因数分解>))\n * (())\n * ((<有理数の代数拡大上の多項式の因数分解>))\n * ((<有理数の代数拡大の代数拡大上の多項式の因数分解>))\n * (())\n * ((<整数、有理係数多変数多項式の因数分解>))\n * (())\n* ((<代数方程式>))\n * ((<最小多項式>))\n * ((<最小分解体>))\n * ((<多項式のガロア群>))\n* ((<初等幾何>))\n * ((<重心の存在>))\n * ((<外心の存在>))\n * ((<垂心の存在>))\n * ((<4 つの等面積>))\n* ((<解析>))\n * ((<ラグランジュの乗数法>))\n\n== 有限集合\n\n=== 集合\n\n<<< sample-set01.rb.v.rd\n\n=== 写像\n\n<<< sample-map01.rb.v.rd\n\n=== 群\n\n<<< sample-group01.rb.v.rd\n\n== 多項式の計算\n\n<<< sample-polynomial01.rb.v.rd\n\n== 多変数多項式の計算\n\n<<< sample-polynomial02.rb.v.rd\n\n== 多変数多項式の計算その2\n\n<<< sample-m-polynomial01.rb.v.rd\n\n== 多項式を複数の多項式で割った余りを求める\n\n<<< sample-divmod01.rb.v.rd\n\n== 多項式のグレブナ基底を求める\n\n<<< sample-groebner01.rb.v.rd\n\n== 素体を作る\n\n<<< sample-primefield01.rb.v.rd\n\n== 代数体を作る\n\n<<< sample-algebraicfield01.rb.v.rd\n\n=== これと同じものが次の様に書ける。\n\n<<< sample-algebraicfield02.rb.v.rd\n\n=== ルートの計算\n\n<<< sample-algebraic-root01.rb.v.rd\n\n== 商体の生成\n\n=== 整数環の商体を取って有理数を作る\n\n<<< sample-quotientfield01.rb.v.rd\n\n=== 有理関数体の生成\n\n<<< sample-quotientfield02.rb.v.rd\n\n=== 代数拡大体上の有理式の計算\n\n<<< sample-quotientfield03.rb.v.rd\n\n=== 代数関数体\n\n<<< sample-quotientfield04.rb.v.rd\n\n== 線形代数\n\n=== 連立1次方程式を解く\n\n<<< sample-gaussian-elimination01.rb.v.rd\n\n=== 正方行列の対角化\n\n<<< sample-diagonalization01.rb.v.rd >>>\n\n=== 行列の単因子を求める\n\n<<< sample-elementary-divisor01.rb.v.rd\n\n=== 行列の Jordan 標準形を求める\n\n<<< sample-jordan-form01.rb.v.rd\n\n=== Cayley-Hamilton の定理の(次元毎の)証明\n\n<<< sample-cayleyhamilton01.rb.v.rd\n\n== グレブナ基底を元の基底で表現する\n\n<<< sample-groebner02.rb.v.rd\n\n== 任意の基底で割った商と余りを求める(余り=0に意味がある)\n\n<<< sample-groebner03.rb.v.rd\n\n== 因数分解\n\n=== 整数係数多項式の因数分解\n\n<<< sample-factorize01.rb.v.rd\n\n=== Zp 係数多項式の因数分解\n\n<<< sample-factorize02.rb.v.rd\n\n=== 有理数の代数拡大上の多項式の因数分解\n\n<<< sample-factorize03.rb.v.rd\n\n=== 有理数の代数拡大の代数拡大上の多項式の因数分解\n\n<<< sample-factorize04.rb.v.rd\n\n=== x^4 + 10x^2 + 1 の因数分解\n\n<<< sample-factorize05.rb.v.rd\n\n=== 整数、有理係数多変数多項式の因数分解\n\n<<< sample-m-factorize01.rb.v.rd\n\n=== Zp 係数多変数多項式の因数分解\n\n<<< sample-m-factorize02.rb.v.rd\n\n== 代数方程式\n\n=== 最小多項式\n\n<<< sample-algebraic-equation01.rb.v.rd\n\n=== 最小分解体\n\n<<< sample-splitting-field01.rb.v.rd\n\n=== 多項式のガロア群\n\n<<< sample-galois-group01.rb.v.rd\n\n== 初等幾何\n\n=== 重心の存在\n\n<<< sample-geometry01.rb.v.rd\n\n=== 外心の存在\n\n<<< sample-geometry02.rb.v.rd\n\n#=== 内心の存在\n\n#<<< sample-geometry03.rb.v.rd\n\n=== 垂心の存在\n\n<<< sample-geometry04.rb.v.rd\n\n\n=== 4 つの等面積\nsee (()) Question 3.\n\n<<< sample-geometry07.rb.v.rd\n\n== 解析\n=== ラグランジュの乗数法\n<<< sample-lagrange-multiplier01.rb.v.rd\n\n=end\n", "meta": {"hexsha": "7a4c7195480c6ec8481d7dce2d4abaa19571a90d", "size": 3096, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/samples-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/samples-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/samples-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9459459459, "max_line_length": 96, "alphanum_fraction": 0.6104651163, "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.6202027151314137}} {"text": "# Modifications were made so that no global variables are used. (C DuBois)\n\n#####################################\n# R FUNCTIONS FOR PERFORMING UNIVARIATE SLICE SAMPLING.\n#\n# Radford M. Neal, 17 March 2008.\n#\n# Implements, with slight modifications and extensions, the algorithm described\n# in Figures 3 and 5 of the following paper:\n#\n# Neal, R. M (2003) \"Slice sampling\" (with discussion), Annals of Statistics,\n# vol. 31, no. 3, pp. 705-767.\n#\n# See the documentation for the function uni.slice below for how to use it.\n# The function uni.slice.test was used to test the uni.slice function.\n\n\n# GLOBAL VARIABLES FOR RECORDING PERFORMANCE.\n\n\n# UNIVARIATE SLICE SAMPLING WITH STEPPING OUT AND SHRINKAGE.\n#\n# Performs a slice sampling update from an initial point to a new point that \n# leaves invariant the distribution with the specified log density function.\n#\n# Arguments:\n#\n# x0 Initial point\n# g Function returning the log of the probability density (plus constant)\n# w Size of the steps for creating interval (default 1)\n# m Limit on steps (default infinite)\n# lower Lower bound on support of the distribution (default -Inf)\n# upper Upper bound on support of the distribution (default +Inf)\n# gx0 Value of g(x0), if known (default is not known)\n#\n# The log density function may return -Inf for points outside the support \n# of the distribution. If a lower and/or upper bound is specified for the\n# support, the log density function will not be called outside such limits.\n#\n# The value of this function is the new point sampled, with an attribute\n# of \"log.density\" giving the value of the log density function, g, at this\n# point. Depending on the context, this log density might be passed as the \n# gx0 argument of a future call of uni.slice. \n#\n# The global variable uni.slice.calls is incremented by one for each call\n# of uni.slice. The global variable uni.slice.evals is incremented by the\n# number of calls made to the g function passed.\n#\n# WARNING: If you provide a value for g(x0), it must of course be correct!\n# In addition to giving wrong answers, wrong values for gx0 may result in\n# the uni.slice function going into an infinite loop.\n\nuni.slice.alt <- function (x0, g, w=1, m=Inf, lower=-Inf, upper=+Inf, gx0=NULL)\n{\n # Check the validity of the arguments.\n\n if (!is.numeric(x0) || length(x0)!=1\n || !is.function(g) \n || !is.numeric(w) || length(w)!=1 || w<=0 \n || !is.numeric(m) || !is.infinite(m) && (m<=0 || m>1e9 || floor(m)!=m)\n || !is.numeric(lower) || length(lower)!=1 || x0upper\n || upper<=lower \n || !is.null(gx0) && (!is.numeric(gx0) || length(gx0)!=1))\n { \n stop (\"Invalid slice sampling argument\")\n }\n\n # Keep track of the number of calls made to this function.\n uni.slice.calls <- 0\t# Number of calls of the slice sampling function\n uni.slice.evals <- 0\t# Number of density evaluations done in these calls\n\n\n uni.slice.calls <- uni.slice.calls + 1\n\n # Find the log density at the initial point, if not already known.\n\n if (is.null(gx0)) \n { uni.slice.evals <- uni.slice.evals + 1\n gx0 <- g(x0)\n }\n\n # Determine the slice level, in log terms.\n\n logy <- gx0 - rexp(1)\n\n # Find the initial interval to sample from.\n\n u <- runif(1,0,w)\n L <- x0 - u\n R <- x0 + (w-u) # should guarantee that x0 is in [L,R], even with roundoff\n\n # Expand the interval until its ends are outside the slice, or until\n # the limit on steps is reached.\n\n if (is.infinite(m)) # no limit on number of steps\n { \n repeat\n { if (L<=lower) break\n uni.slice.evals <- uni.slice.evals + 1\n if (g(L)<=logy) break\n L <- L - w\n }\n\n repeat\n { if (R>=upper) break\n uni.slice.evals <- uni.slice.evals + 1\n if (g(R)<=logy) break\n R <- R + w\n }\n }\n\n else if (m>1) # limit on steps, bigger than one\n { \n J <- floor(runif(1,0,m))\n K <- (m-1) - J\n\n while (J>0)\n { if (L<=lower) break\n uni.slice.evals <- uni.slice.evals + 1\n if (g(L)<=logy) break\n L <- L - w\n J <- J - 1\n }\n\n while (K>0)\n { if (R>=upper) break\n uni.slice.evals <- uni.slice.evals + 1\n if (g(R)<=logy) break\n R <- R + w\n K <- K - 1\n }\n }\n\n # Shrink interval to lower and upper bounds.\n\n if (Lupper)\n { R <- upper\n }\n\n # Sample from the interval, shrinking it on each rejection.\n\n repeat\n { \n x1 <- runif(1,L,R)\n\n uni.slice.evals <- uni.slice.evals + 1\n gx1 <- g(x1)\n\n if (gx1>=logy) break\n\n if (x1>x0) \n { R <- x1\n }\n else \n { L <- x1\n }\n }\n\n # Return the point sampled, with its log density attached as an attribute.\n\n attr(x1,\"log.density\") <- gx1\n attr(x1,\"uni.slice.evals\") <- uni.slice.evals\n attr(x1,\"uni.slice.calls\") <- uni.slice.calls\n return (x1)\n \n}\n\n# FUNCTION TO TEST THE UNI.SLICE FUNCTION. \n#\n# Produces Postscript plots in slice-test.ps, one page per test, with the\n# tests described in the code below. \n#\n# Each test applies a series of univariate slice sampling updates (ss*thin of \n# them) to some distribution, starting at a point drawn from that distribution,\n# with particular settings of the slice sampling options. The page for a \n# test contains the following:\n# \n# - a trace plot of the results (at every 'thin' updates)\n# - a plot of the autocorrelations for this trace\n# - a plot of the bivariate distribution before and after 'thin' updates\n# - a qqplot of the sample produced vs. a correct sample\n# - the average number of evaluations per call\n# - the result of a t test for the sample mean vs. the correct mean, based\n# on 200 equally spaced points from the sample generated (which are\n# presumed to be virtually independent)\n\nuni.slice.alt.test <- function ()\n{\n postscript(\"slice-test.ps\")\n par(mfrow=c(2,2))\n\n # Function to do the slice sampling updates. \n\n updates <- function (x0, g, reuse=FALSE)\n { \n uni.slice.calls <- 0\n uni.slice.evals <- 0\n\n s <<- numeric(ss)\n x1 <- x0\n s[1] <<- x0\n last.g <- NULL\n\n for (i in 2:ss)\n { for (j in 1:thin)\n { if (reuse)\n { x1 <- uni.slice (x1, g, w=w, m=m, lower=lower, upper=upper, \n gx0=last.g)\n last.g <- attr(x1,\"log.density\")\n uni.slice.calls <- uni.slice.calls + attr(x1,\"uni.slice.calls\")\n uni.slice.evals <- uni.slice.evals + attr(x1,\"uni.slice.evals\")\n }\n else\n { x1 <- uni.slice (x1, g, w=w, m=m, lower=lower, upper=upper)\n }\n }\n s[i] <<- x1\n }\n }\n\n # Function to display the results.\n\n display <- function (r,mu,test)\n { \n plot(s,type=\"p\",xlab=\"Iteration\",ylab=\"State\",pch=20)\n\n title (paste( test, \" ss =\",ss,\" thin =\",thin))\n\n acf (s, lag.max=length(s)/20, main=\"\")\n\n title (paste (\"w =\",w,\" m =\",m,\" lower =\",lower,\" upper =\",upper))\n\n plot(s[-1],s[-length(s)],pch=20,xlab=\"Current state\",ylab=\"Next state\")\n\n title (paste (\"Average number of evaluations:\",\n round(uni.slice.evals/uni.slice.calls,2)))\n\n qqplot(r,s,pch=\".\",\n xlab=\"Quantiles from correct sample\",\n ylab=\"Quantiles from slice sampling\")\n abline(0,1)\n\n p.value <- t.test (s[seq(1,length(s),length=200)]-mu) $ p.value\n title (paste (\"P-value from t test:\",round(p.value,3)))\n }\n\n # Standard normal, m = Inf.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 1.5\n m <- Inf\n lower <- -Inf\n upper <- +Inf\n\n updates (rnorm(1), function (x) -x^2/2)\n display (rnorm(ss),0,\"Standard normal\")\n\n # Standard normal, reusing density, m = Inf.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 1.5\n m <- Inf\n lower <- -Inf\n upper <- +Inf\n\n updates (rnorm(1), function (x) -x^2/2, reuse=TRUE)\n display (rnorm(ss),0,\"Standard normal, reusing density\")\n\n # Normal mixture, m = 1.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 2.2\n m <- 1\n lower <- -Inf\n upper <- +Inf\n\n updates (rnorm(1,-1,1), function (x) log(dnorm(x,-1,1)+dnorm(x,1,0.5)))\n display (c (rnorm(floor(ss/2),-1,1), rnorm(ceiling(ss/2),1,0.5)), 0,\n \"Normal mixture\")\n\n # Normal mixture, m = 3.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 1.8\n m <- 3\n lower <- -Inf\n upper <- +Inf\n\n updates (rnorm(1,-1,1), function (x) log(dnorm(x,-1,1)+dnorm(x,1,0.5)))\n display (c (rnorm(floor(ss/2),-1,1), rnorm(ceiling(ss/2),1,0.5)), 0,\n \"Normal mixture\")\n\n # Exponential, m = Inf.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 10\n m <- Inf\n lower <- 0\n upper <- +Inf\n\n updates (rexp(1), function (x) -x)\n display (rexp(ss), 1, \"Exponential\")\n\n # Exponential, m = 2.\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 1.5\n m <- 2\n lower <- 0\n upper <- +Inf\n\n updates (rexp(1), function (x) -x)\n display (rexp(ss), 1, \"Exponential\")\n\n # Beta(0.5,0.8).\n\n set.seed(1)\n\n ss <- 2000\n thin <- 3\n w <- 1e9\n m <- Inf\n lower <- 0\n upper <- 1\n\n updates (rbeta(1,0.5,0.8), function (x) dbeta(x,0.5,0.8,log=TRUE))\n display (rbeta(ss,0.5,0.8), 0.5/(0.5+0.8), \"Beta(0.5,0.8)\")\n\n dev.off()\n}\n\n", "meta": {"hexsha": "aed775ef83e4e7fe6347ad76645eb2d5660e42d3", "size": 9050, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/slice.r", "max_stars_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_stars_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-06-12T04:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T11:41:33.000Z", "max_issues_repo_path": "examples/slice.r", "max_issues_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_issues_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/slice.r", "max_forks_repo_name": "JuliaPackageMirrors/SliceSampler.jl", "max_forks_repo_head_hexsha": "a2ff27b2093e048405d223eba92dabdf9048e823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2015-06-12T04:11:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-14T07:49:46.000Z", "avg_line_length": 25.5649717514, "max_line_length": 79, "alphanum_fraction": 0.6083977901, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6200674118804017}} {"text": "# ......................................................................................\n# ...............Cvičení 5 - Vybraná rozdělení diskrétní náhodné veličiny...............\n# ..................Martina Litschmannová, Adéla Vrtková, Michal Béreš..................\n# ......................................................................................\n\n# Nezobrazuje-li se vám text korektně, nastavte File \\ Reopen with Encoding... na UTF-8\n# Pro zobrazení obsahu skriptu použijte CTRL+SHIFT+O\n# Pro spouštění příkazů v jednotlivých řádcích použijte CTRL+ENTER\n\n# Přehled rozdělení a jejich funkcí ####\n# * Úvod: Pravděpodobnostní, Kumulativní pravděpodobnostní (Distribuční) a Kvantilová ####\n# funkce\n# ** Pravděpodobnostní funkce ####\n# - začíná písmenkem **d**: $p = P(X = x)$: p = d...(x, ...)\n# \n# ** Kumulativní pravděpodobnostní (Distribuční funkce) ####\n# - začíná písmenkem **p**: $p = P(X \\leq x)$: p = p...(x, ...)\n# - pozor Kumulativní pravděpodobnostní je s alternativní definicí $P(X \\leq t)$\n# - pro naši distribuční funkci $F(t) = P(X= 1) = P(X > 0) = 1 - P(X <= 0)\n1 - ppois(1 - 1, lt)\n\n# graf pravděpodobnostní funkce\n# teoreticky může být vyzářeno až nekonečně mnoho částic, \n# od jisté hodnoty je pravděpodobnost zanedbatelná\nx = 0:10 \np = dpois(x, lt) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 3. ####\n# Kamarád vás pošle do sklepa, abyste donesl(a) 4 lahvová piva - z toho dvě desítky a\n# dvě dvanáctky. Nevíte, kde rozsvítit, proto vezmete z basy poslepu 4 láhve. S jakou\n# pravděpodobností jste vyhověl(a), víte-li, že v base bylo celkem 10 desítek a 6\n# dvanáctek?\n\n\n# X ... počet 10°piv mezi 4 vybranými\n# X ~ H(N = 16, M = 10, n = 4)\n\nx = 2\nN = 16\nM = 10\nn = 4\n\n# P(X = 2)\ndhyper(x, M, N - M, n)\n\n# graf pravděpodobnostní funkce\nx = 0:4 # všechny možné realizace NV X\np = dhyper(x, M, N - M, n) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 4. ####\n# V jednom mililitru určitého dokonale rozmíchaného roztoku se v průměru nachází 15\n# určitých mikroorganismů. Určete pravděpodobnost, že při náhodném výběru vzorku o\n# objemu 1/2 mililitru bude ve zkumavce méně než 5 těchto mikroorganismu.\n\n\n# X ... počet mikroorganismů v 0.5 ml roztoku\n# X ~ Po(lt = 15/2)\n\nlambda = 15\nt = 1/2\nlt = lambda*t # parametr Poissonova rozd.\n\n# P(X < 5) = P(X <= 4)\nppois(5 - 1, lt)\n# nebo\nppois(5,lt) - dpois(5,lt)\n\n# graf pravděpodobnostní funkce\n# teoreticky může být v roztoku až nekonečně mnoho mikroorganismů, \n# od jisté hodnoty je pravděpodobnost zanedbatelná\nx = 0:20 \np = dpois(x, lt) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 5. ####\n# Na stůl vysypeme 15 mincí. Jaká je pravděpodobnost, že počet mincí ležících lícem\n# nahoře, je od 8 do 15?\n\n\n# X ... počet mincí, které padnou lícem nahoru z celkového množství 15 mincí\n# X ~ Bi(n = 15, p = 0.5)\n\nn = 15\np = 0.5\n\n# P(8 <= X <= 15) = P(X <= 15) - P(X < 8) = P(X <= 15) - P(X <= 7)\npbinom(15, n, p) - pbinom(7, n, p) \n\n#jinak: P(8<=X<=15)=P(X>7)=1-P(X<=7)\n1 - pbinom(7, n, p)\n\n# graf pravděpodobnostní funkce\nx = 0:15 # všechny možné realizace NV X\np = dbinom(x, n, p) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 6. ####\n# Pravděpodobnost, že se dovoláme do studia rozhlasové stanice, která právě vyhlásila\n# telefonickou soutěž je 0,08. Jaká je pravděpodobnost, že se dovoláme nejvýše na 4.\n# pokus?\n\n\n# X ... počet pokusů než se dovoláme do rozhlasového studia\n# X ~ NB(k = 1,p = 0.08) nebo G(0.08)\n\nx = 4\nk = 1\np = 0.08\n\n# P(X <= 4)\npnbinom(x - k, k, p)\n\n# graf pravděpodobnostní funkce\n# teoreticky můžeme uskutečnit až nekonečně mnoho pokusů, \n# od jisté hodnoty je pravděpodobnost zanedbatelná\nx = 1:40 \np = dnbinom(x - k, k, p) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 7. ####\n# V továrně se vyrobí denně 10 % vadných součástek. Jaká je pravděpodobnost, že\n# vybereme-li třicet součástek z denní produkce, tak nejméně dvě budou vadné?\n\n\n# X ... počet vadných součástek ze 30 vybraných\n# X ~ Bi(n = 30, p = 0.1)\n\nn = 30\np = 0.1\n\n# P(X >= 2) = 1 - P(X < 2) = 1 - P(X <= 1)\n1 - pbinom(1, n, p)\n\n# nebo P(X >= 2) vsechno mimo 0 a 1\n1 - (dbinom(0, n, p) + dbinom(1, n, p))\n\n# graf pravděpodobnostní funkce\nx = 0:30 # všechny možné realizace NV X\np = dbinom(x, n, p) # hodnoty pravděpodobnostní funkce pro x\nplot(x,p)\n\n# * Příklad 8. ####\n# Ve skladu je 200 součástek. 10 % z nich je vadných. Jaká je pravděpodobnost, že\n# vybereme-li ze skladu třicet součástek, tak nejméně dvě budou vadné?\n\n\n# X ... počet vadných součástek ze 30 vybraných z 200\n# X ~ H(N = 200, M = 20, n = 30)\n\nN = 200 \nM = 20 \nn = 30\n\n# P(X >= 2) = 1 - P(X < 2) = 1 - P(X <= 1)\n1 - phyper(2 - 1, M, N - M, n)\n\n# graf pravděpodobnostní funkce\nx = 0:30 # všechny možné realizace NV X\np = dhyper(x, M, N - M, n) # hodnoty pravděpodobnostní funkce pro x\nplot(x, p)\n\n# * Příklad 9. ####\n# V určité firmě bylo zjištěno, že na 33 % počítačů je nainstalován nějaký nelegální\n# software. Určete pravděpodobnostní a distribuční funkci počtu počítačů s nelegálním\n# softwarem mezi třemi kontrolovanými počítači.\n\n\n# X ... počet počítačů s nelegálním softwarem ze 3 kontrolovaných\n# X ~ Bi(n = 3,p = 0.33)\n\nn = 3\np = 0.33\n\n# pravděpodobnostní funkce\nx = 0:3 # všechny možné realizace NV X \np = dbinom(x, n, p) # hodnoty pravděpodobnostní funkce pro x\n\np = round(p, 3) # zaokrouhlení pravděpodobností na 3 des. místa\np[4] = 1 - sum(p[1:3]) # dopočet poslední hodnoty do 1\n\ntab = rbind(x, p) # vytvoření tabulky pravděpodobnostní funkce\nrownames(tab) = c(\"x\", \"P(x)\")\ntab\n\n# graf pravděpodobnostní funkce\nplot(x, p)\n\n#distribuční funkce\ncumsum(p) # zjednodušený výpis distribuční funkce\n\n# * Příklad 10. ####\n# Sportka je loterijní hra, v níž sázející tipuje šest čísel ze čtyřiceti devíti, která\n# očekává, že padnou při budoucím slosování. K účasti ve hře je nutné zvolit alespoň\n# jednu kombinaci 6 čísel (vždy 6 čísel na jeden sloupec) a pomocí křížků tato čísla\n# označit na sázence společnosti Sazka a.s. do sloupců, počínaje sloupcem prvním.\n# Sázející vyhrává v případě, že uhodne alespoň tři čísla z tažené šestice čísel. Jaká\n# je pravděpodobnost, že proto, aby sázející vyhrál, bude muset vyplnit:\n\n\n# Nejprve pravděpodobnost, že vehrajeme v jednom sloupci\n\n# Y ... počet uhádnutých čísel v 6 tažených ze 49\n# Y ~ H(N = 49, M = 6, n = 6)\n\nN = 49\nM = 6\nn = 6\n\n# P-st uhádnutí alespoň 3 čísel v jednom sloupci \n# P(Y >= 3) = 1 - P(Y < 3) = 1 - P(Y <= 2)\npp = 1 - phyper(3 - 1, M, N - M, n)\npp\n\n# ** a) ####\n# právě tři sloupce,\n\n\n# X … počet sloupců, které bude muset sázející vyplnit, aby vyhrál\n# X ~ NB(k = 1, p = pp)\n\n# a) P(X = 3)\nk = 1\np = pp\n\ndnbinom(3 - k, k, pp)\n\n# ** b) ####\n# alespoň 5 sloupců,\n\n\n# b) P(X >= 5) = 1 - P(X < 5) = 1 - P(X <= 4)\n\n1 - pnbinom(5 - k - 1, k, pp)\n\n# ** c) ####\n# méně než 10 sloupců,\n\n\n# c) P(X < 10) = P(X <= 9) \npnbinom(10 - k - 1, k, pp)\n\n# * d) ####\n# více než 5 a nejvýše 10 sloupců?\n\n\n# P(5 < X <= 10) = P(X <= 10) - P(X <= 5)\npnbinom(10 - k, k, pp)-pnbinom(5 - k, k, pp) \n# nebo P(X < 11) - P(X < 6)\npnbinom(11 - k - 1, k, pp)-pnbinom(6 - k - 1, k, pp) \n\n# * Příklad 11. ####\n# Pravděpodobnost, že hodíme 6 na 6stěnné kostce je 1/6. Hážeme tak dlouho, než hodíme\n# šestku 10 krát. \n# ** a) ####\n# Jaká je střední hodnota počtu hodů.\n\n\n# X … hodů kostkou než hodíme 10 šestek\n# X ~ NB(k = 10, p = 1/6)\n\nk = 10\np = 1/6\n\nE_X = k/p\nE_X\n\n# ** b) ####\n# S kolika hody nejméně musíme počítat, pokud chceme, aby pradvěpodobnost, že se nám\n# podaří naházet 10 šestek, byla alespoň 70%.\n\n\n# P(X <= k) >= 0.7\nqnbinom(0.7, k, p) + k\n\n\n\n", "meta": {"hexsha": "483192251bc1258a4f41d725966eb976754ea791", "size": 14879, "ext": "r", "lang": "R", "max_stars_repo_path": "CV5/cv5.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": "CV5/cv5.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": "CV5/cv5.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": 27.5027726433, "max_line_length": 90, "alphanum_fraction": 0.6386181867, "num_tokens": 7171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6200674094891107}} {"text": "\n\n\n#' Samples from a mixture model\n#'\n#' A matrix of 2-dimensional Gaussian mixture samples, the samples came from 4 different Gaussian distributions\n#'\n#' @docType data\n#'\n#' @usage data(mmData)\n#'\n#' @format A matrix of Gaussian samples, each row is one sample.\n\"mmData\"\n\n#' Samples from a hierarchical mixture model\n#'\n#' A list of 2-dimensional Gaussian mixture samples and the corresponding group labels. The samples are generated by 4 different Gaussian distributions. The samples are separated into 30 groups.\n#'\n#' @docType data\n#'\n#' @usage data(mmhData)\n#'\n#' @format A list of two elements:\n#' \\describe{\n#' \\item{x}{: matrix, 2-dimensional Gaussian samples, each row is a sample}\n#' \\item{groupLabel}{: integer, the group label of each Gaussian sample}\n#' }\n\"mmhData\"\n\n#' Samples from a hierarchical mixture model with two layers of hierarchies\n#'\n#' A list of 2-dimensional Gaussian mixture samples and the corresponding group labels. The samples are generated by 4 different Gaussian distributions. Each sample is assigned to a group and a subgroup. There are 2 groups, group 1 has 10 subgroups, group 2 has 20 subgroups.\n#'\n#' @docType data\n#'\n#' @usage data(mmhhData)\n#'\n#' @format A list of three elements:\n#' \\describe{\n#' \\item{x}{: matrix, 2-dimensional Gaussian samples, each row is a sample}\n#' \\item{groupLabel}{: integer, the group label of each Gaussian sample}\n#' \\item{subGroupLabel}{: integer, the subgroup label of each Gaussian sample}\n#' }\n\"mmhhData\"\n\n#' Samples from a simple linear model\n#'\n#' A list of two elements, a matrix \"X\" and a numeric vector \"x\". They came from a linear model: x = X*0.3 + epsilon, where epsilon is Gaussian distributed with mean 0 and variance 25.\n#'\n#' @docType data\n#'\n#' @usage data(lrData)\n#'\n#' @format A list of two elements:\n#' \\describe{\n#' \\item{x}{: numeric, linear samples}\n#' \\item{X}{: matrix, the \"locations\" of the linear samples}\n#' }\n\"lrData\"\n\n#' @title Samples from a hierarchical linear model\n#' @description\n#' The data was part of the 2002 Educational Longitudinal Study (ELS), a survey of students from a large sample of schools across the United States. This dataset includes a population of schools as well as a population of students within each school.\n#' @docType data\n#'\n#' @usage data(lrData)\n#'\n#' @format A list of three elements:\n#' \\describe{\n#' \\item{mathScore}{: numeric, the mathScore of each student}\n#' \\item{socioeconomicStatus}{: numeric, the socioeconomic status score of each student}\n#' \\item{schoolID}{: integer, the school ID of each student}\n#' }\n#' @references Hoff, Peter D. A first course in Bayesian statistical methods. Vol. 580. New York: Springer, 2009.\n\"hlrData\"\n\n\n#' farm ads data\n#'\n#' A subset of farm ads data from https://archive.ics.uci.edu/ml/datasets/Farm+Ads\n#'\n#' @docType data\n#'\n#' @usage data(farmadsData)\n#'\n#' @format A list of two elements:\n#' \\describe{\n#' \\item{word}{: character, the words}\n#' \\item{document}{: integer, document id of each word}\n#' }\n#' @source \\href{https://archive.ics.uci.edu/ml/datasets/Farm+Ads}{Farm-Ads}\n\"farmadsData\"\n\n#' Cancer mortality of 20 cities\n#'\n#' Cancer mortality data from Ordinal Data Modeling(1999) p24. This dataset is a list of 20 character vectors, representing the individuals in 20 cities' cancer mortality information. There can be only two possible values \"death\" and \"no death\" in each character vector. For example \"death\" occurs 3 times the 10th character vector, while \"no death\" occurs 582 times, this mean there are 3 death among the 585 cancer patients in city 10.\n#'\n#' @docType data\n#'\n#' @usage data(cancerData)\n#'\n#' @format A list of 20 character vectors.\n#' @references Johnson, Valen E., and James H. Albert. Ordinal data modeling. Springer Science & Business Media, 2006.\n\"cancerData\"\n\n\n\n#' @title Samples from a hidden Markov model\n#' @description\n#' Random samples generated from a Hidden Markov Model (HMM) with 3 hidden states. The initial distribution is c(0.2,0.6,0.2), the transition matrix is matrix(c(0.9, 0.04, 0.06, 0.06, 0.9, 0.07, 0.04, 0.06, 0.87),3,3).\n#'\n#' @docType data\n#'\n#' @usage data(hmmData)\n#'\n#' @format A list of four elements:\n#' \\describe{\n#' \\item{x}{: matrix, two dimensional Gaussian observations. The observations are split into 'Nsegs' segment, see 'Nsegs' and 'breaks' below.}\n#' \\item{z}{: integer vector, the real hidden states.}\n#' \\item{Nsegs}{: integer, the number of segments.}\n#' \\item{breaks}{: integer vector, the starting and ending locations of the segments. The ith segment start at breaks[i]+1, ends at breaks[i+1]}\n#' }\n\"hmmData\"\n", "meta": {"hexsha": "b8fb2b6ad03cd239695d5f1956b1d685558e43ed", "size": 4605, "ext": "r", "lang": "R", "max_stars_repo_path": "R/testData.r", "max_stars_repo_name": "chenhaotian/Bayesian-Bricks", "max_stars_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-03-04T09:43:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T13:54:37.000Z", "max_issues_repo_path": "R/testData.r", "max_issues_repo_name": "chenhaotian/Bayesian-Bricks", "max_issues_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/testData.r", "max_forks_repo_name": "chenhaotian/Bayesian-Bricks", "max_forks_repo_head_hexsha": "4876e9bacf9561354220a18835829f5274598622", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-20T18:13:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T18:13:09.000Z", "avg_line_length": 37.1370967742, "max_line_length": 437, "alphanum_fraction": 0.7135722041, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.6200057411423113}} {"text": "LISP Interpreter Run\n\n[[[[[\n\n A LISP expression that evaluates to itself!\n\n Let f(x): x -> (('x)('x))\n\n Then (('f)('f)) is a fixed point.\n\n]]]]]\n\n[Here is the fixed point done by hand:]\n\n(\n'lambda(x) cons cons \"' cons x nil\n cons cons \"' cons x nil\n nil\n\n'lambda(x) cons cons \"' cons x nil\n cons cons \"' cons x nil\n nil\n)\n\nexpression ((' (lambda (x) (cons (cons ' (cons x nil)) (cons \n (cons ' (cons x nil)) nil)))) (' (lambda (x) (cons\n (cons ' (cons x nil)) (cons (cons ' (cons x nil))\n nil)))))\nvalue ((' (lambda (x) (cons (cons ' (cons x nil)) (cons \n (cons ' (cons x nil)) nil)))) (' (lambda (x) (cons\n (cons ' (cons x nil)) (cons (cons ' (cons x nil))\n nil)))))\n\n\n[Now let's construct the fixed point.]\n\ndefine (f x) let y [be] cons \"' cons x nil [y is ('x) ]\n [return] cons y cons y nil [return (('x)('x))]\n\ndefine f\nvalue (lambda (x) ((' (lambda (y) (cons y (cons y nil)))\n ) (cons ' (cons x nil))))\n\n\n[Here we try f:]\n\n(f x)\n\nexpression (f x)\nvalue ((' x) (' x))\n\n\n[Here we use f to calculate the fixed point:]\n\n(f f)\n\nexpression (f f)\nvalue ((' (lambda (x) ((' (lambda (y) (cons y (cons y ni\n l)))) (cons ' (cons x nil))))) (' (lambda (x) ((' \n (lambda (y) (cons y (cons y nil)))) (cons ' (cons \n x nil))))))\n\n\n[Here we find the value of the fixed point:]\n\neval (f f)\n\nexpression (eval (f f))\nvalue ((' (lambda (x) ((' (lambda (y) (cons y (cons y ni\n l)))) (cons ' (cons x nil))))) (' (lambda (x) ((' \n (lambda (y) (cons y (cons y nil)))) (cons ' (cons \n x nil))))))\n\n\n[Here we check that it's a fixed point:]\n\n= (f f) eval (f f)\n\nexpression (= (f f) (eval (f f)))\nvalue true\n\n\n[Just for emphasis:]\n\n= (f f) eval eval eval eval eval eval (f f)\n\nexpression (= (f f) (eval (eval (eval (eval (eval (eval (f f)\n )))))))\nvalue true\n\nEnd of LISP Run\n\nElapsed time is 0 seconds.\n", "meta": {"hexsha": "28667ac673324ed53219b000fde0532b5fa14dd4", "size": 2065, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/fixedpoint.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/fixedpoint.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/fixedpoint.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 21.9680851064, "max_line_length": 62, "alphanum_fraction": 0.4847457627, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6199244639223304}} {"text": "library(ggplot2)\nlibrary(tikzDevice)\n\ndisp_prob = function(C,Cth,gamma) { # defines the dispersal function\n d = rep(0,length(C))\n d[C>Cth] = 1 - (Cth*(1-gamma))/(C[C>Cth]-Cth*gamma)\n return(d)\n}\n\ndensx = seq(0,3,len=100) # a vector of population densities\nCth = 1.1 # defining a threshold density value\ngammas = c(0,0.5,0.9,0.99)\n\nd = numeric()\ndens = numeric()\ngam = numeric()\n\nfor (g in gammas) {\n d = c(d,disp_prob(densx,Cth,g))\n dens = c(dens,densx)\n gam = c(gam,rep(g,length(densx)))\n}\n\nres = data.frame(dens=dens,disp=d,gamma=factor(gam))\n\ngamlab = c(paste(expression(gamma==0)),\n paste(expression(gamma==0.5)),\n paste(expression(gamma==0.9)),\n paste(expression(gamma==0.99)))\n\nx11()\n\nggplot(res,aes(x=dens,y=disp,colour=gamma, group=gamma, linetype=gamma)) + geom_line(size=1.25) +\n theme_bw(base_size=25) +\n scale_color_grey() +\n theme(legend.position=\"none\", text=element_text(size=25),axis.line.x=element_line(color=\"black\"),axis.line.y=element_line(color=\"black\")) +\n ylab(expression(paste(\"Emigration probability \", italic(d)[TAE]))) +\n xlab(expression(paste(\"Estimated population density \",italic(N)[i]^E/bar(italic(K))))) +\n annotate(\"text\",x=c(2.5,2.3,1.9,1.55),y=c(0.475,0.6,0.8,0.9),parse=T,label=gamlab, size=7)\n\ndev.copy2eps(file=\"figure_1.eps\",title=\"Poethke et al. | Figure 1\")\n", "meta": {"hexsha": "c72fed9049a9e873bb730905f3590acf215c4b3d", "size": 1341, "ext": "r", "lang": "R", "max_stars_repo_path": "figure_1/create_figure_1.r", "max_stars_repo_name": "akubisch/smart_disp", "max_stars_repo_head_hexsha": "da96cf3f954f5bf1409427f0eedc002b15ba67d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "figure_1/create_figure_1.r", "max_issues_repo_name": "akubisch/smart_disp", "max_issues_repo_head_hexsha": "da96cf3f954f5bf1409427f0eedc002b15ba67d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "figure_1/create_figure_1.r", "max_forks_repo_name": "akubisch/smart_disp", "max_forks_repo_head_hexsha": "da96cf3f954f5bf1409427f0eedc002b15ba67d4", "max_forks_repo_licenses": ["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.9285714286, "max_line_length": 141, "alphanum_fraction": 0.6666666667, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6199141153988739}} {"text": "###############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n###############################################################################\n# Optimizing Omega Ration Functions\n# Copyright (C) 2011 Michael Kapler\n#\n# For more information please visit my blog at www.SystematicInvestor.wordpress.com\n# or drop me a line at TheSystematicInvestor at gmail\n###############################################################################\n\n\n\n###############################################################################\n# Omega\n# page 6,9, Optimizing Omega by H. Mausser, D. Saunders, L. Seco\n#\n# Let x.i , i= 1,...,n be weights of instruments in the portfolio.\n# Let us suppose that j = 1,...,T scenarios of returns are available \n# ( r.ij denotes return of i -th asset in the scenario j ). \n#\n# The Omega function has the form \n# MAX [ SUM 1/T * u.j ]\n# [ SUM r.ij * x.i ] - u.j + d.j - L * t = 0, for each j = 1,...,T \n# [ SUM 1/T * d.j ] = 1\n# u.j, d.j >= 0, for each j = 1,...,T \n#\n# Binary b.j enforces that only one of u.j or d.j is greter than 0\n# u.j <= b.j\n# d.j <= 1 - b.j\n#' @export \n###############################################################################\nadd.constraint.omega <- function\n(\n\tia,\t\t\t# input assumptions\n\tvalue,\t\t# b value\n\ttype = c('=', '>=', '<='),\t# type of constraints\n\tconstraints\t# constraints structure\n)\n{\n\tif(is.null(ia$parameters.omega)) omega = 0 else omega = ia$parameters.omega\n\n\tn0 = ncol(ia$hist.returns)\n\tn = nrow(constraints$A)\t\n\tnt = nrow(ia$hist.returns)\n\n\t# adjust constraints, add u.j, d.j, t\n\tconstraints = add.variables(2*nt + 1, constraints, lb = c(rep(0,2*nt),-Inf))\n\t\t# Aw < b => Aw1 - bt < 0\n\t\tconstraints$A[n + 2*nt + 1, ] = -constraints$b\n\t\tconstraints$b[] = 0\t\n\t\t\n\t\t# lb/ub same transformation\n\t\tindex = which( constraints$ub[1:n] < +Inf )\t\n\t\tif( len(index) > 0 ) {\t\t\t\n\t\t\ta = rbind( diag(n), matrix(0, 2*nt, n), -constraints$ub[1:n])\t\t\n\t\t\tconstraints = add.constraints(a[, index], rep(0, len(index)), '<=', constraints)\t\t\t\n\t\t}\n\t\t\n\t\tindex = which( constraints$lb[1:n] > -Inf )\t\n\t\tif( len(index) > 0 ) {\t\n\t\t\ta = rbind( diag(n), matrix(0, 2*nt, n), -constraints$lb[1:n])\t\t\n\t\t\tconstraints = add.constraints(a[, index], rep(0, len(index)), '>=', constraints)\t\t\t\t\t\n\t\t}\n\t\t\n\t\tconstraints$lb[1:n] = -Inf\n\t\tconstraints$ub[1:n] = Inf\n\t\t\n\t\t\t\n\t# [ SUM r.ij * x.i ] - u.j + d.j - L * t = 0, for each j = 1,...,T \t\n\ta = rbind( matrix(0, n, nt), -diag(nt), diag(nt), -omega)\n\t\ta[1 : n0, ] = t(ia$hist.returns)\n\tconstraints = add.constraints(a, rep(0, nt), '=', constraints)\t\t\t\n\t\t\n\t# [ SUM 1/T * d.j ] = 1\t\n\tconstraints = add.constraints(c( rep(0,n), rep(0,nt), (1/nt) * rep(1,nt), 0), 1, '=', constraints)\t\t\t\t\n\t\t\t\n\t# objective : Omega\n\t# [ SUM 1/T * u.j ]\n\tconstraints = add.constraints(c(rep(0, n), (1/nt) * rep(1, nt), rep(0, nt), 0), value, type[1], constraints)\t\n\t\t\t\n\treturn( constraints )\t\n}\n\n#' @export \nportfolio.omega <- function\n(\n\tweight,\t\t# weight\n\tia\t\t\t# input assumptions\n)\t\n{\t\n\tweight = weight[, 1:ia$n]\n\tif(is.null(ia$parameters.omega)) omega = 0 else omega = ia$parameters.omega\n\t\t\n\tportfolio.returns = weight %*% t(ia$hist.returns)\t\n\treturn( apply(portfolio.returns, 1, function(x) mean(pmax(x - omega,0)) / mean(pmax(omega - x,0)) ) )\n}\t\n\n\n###############################################################################\n# Find portfolio that Maximizes Omega\n#' @export \n###############################################################################\nmax.omega.portfolio <- function\n(\n\tia,\t\t\t\t# input assumptions\n\tconstraints,\t# constraints\n\ttype = c('mixed', 'lp', 'nlp')\n)\n{\n\tn = nrow(constraints$A)\t\n\tnt = nrow(ia$hist.returns)\n\ttype = type[1]\n\t\n\tif(type == 'mixed'\t|| type == 'lp') {\n\t\tsol = optimize.portfolio(ia, constraints, add.constraint.omega, portfolio.omega, 'max', T)\n\t\t\t\n\t\tx = rep(NA, n)\t\n\t\tif(!inherits(sol, 'try-error') && sol$status ==0) {\n\t\t\tx0 = sol$solution[1:n]\n\t\t\tu = sol$solution[(1+n):(n+nt)]\n\t\t\td = sol$solution[(n+nt+1):(n+2*nt)] \n\t\t\tt = sol$solution[(n+2*nt+1):(n+2*nt+1)] \t\t\n\t\t\tx = x0/t\n\t\t}\n\t}\n\n\t#portfolio.omega(t(x),ia)\n\t#sol$value\n\n\tif((type == 'mixed' && (sol$status !=0 || any( u*d != 0 ) )) || type == 'nlp') {\n\t\t# Try solving problem using Rdonlp2\n\t\tif(is.null(ia$parameters.omega)) omega = 0 else omega = ia$parameters.omega\n\t\n\t\t# omega\n\t\tfn <- function(x){\n\t\t\tportfolio.returns = x %*% t(ia$hist.returns)\t\n\t\t\tmean(pmax(portfolio.returns - omega,0)) / mean(pmax(omega - portfolio.returns,0))\n\t\t}\n\t\t\n\t\tx = optimize.portfolio.nlp(ia, constraints, fn, direction = 'max')\n\t\t#portfolio.omega(t(x),ia)\n\t}\n\n\treturn( x )\n}\n\n\n###############################################################################\n# Create efficient frontier\n#' @export \n###############################################################################\nportopt.omega <- function\n(\n\tia,\t\t\t\t\t\t# Input Assumptions\n\tconstraints = NULL,\t\t# Constraints\n\tnportfolios = 50,\t\t# Number of portfolios\n\tname = 'Omega'\t\t\t# Name\n)\n{\n\t# set up output \n\tout = list(weight = matrix(NA, nportfolios, nrow(constraints$A)))\n\t\tcolnames(out$weight) = rep('', ncol(out$weight))\n\t\tcolnames(out$weight)[1:ia$n] = ia$symbols\n\n\t\t\t\t\n\tef.risk = portopt(ia, constraints, 2)\t\n\t\t\t\t\t\n\t# maximum return portfolio\t\n\tout$weight[nportfolios, ] = ef.risk$weight[2,]\n\n\t# minimum risk portfolio\n\tout$weight[1, ] = ef.risk$weight[1,]\n\t\tconstraints$x0 = out$weight[1, ]\n\t\n\t# find points on efficient frontier\n\tout$return = portfolio.return(out$weight, ia)\n\ttarget = seq(out$return[1], out$return[nportfolios], length.out = nportfolios)\n\n\tconstraints = add.constraints(c(ia$expected.return, rep(0, nrow(constraints$A) - ia$n)), \n\t\t\t\t\t\ttarget[1], type = '<=', constraints)\n\t\t\t\t\t\t\t\t\t\n\tfor(i in 1:nportfolios ) {\n\t\tcat('i =', i, '\\n')\n\t\n\t\tconstraints$b[ len(constraints$b) ] = -target[i]\n\t\tout$weight[i, ] = max.omega.portfolio(ia, constraints)\n\t\t\n\t\t\tconstraints$x0 = out$weight[i, ]\t\t\n\t}\n\t\n\t\n\t# compute risk / return\n\tout$return = portfolio.return(out$weight, ia)\n\tout$risk = portfolio.risk(out$weight, ia)\n\tout$name = name\n\t\n\treturn(out)\t\t\t\n}\n\n\n###############################################################################\n# Plot Omega Ratio for given portfolios (weights)\n#' @export \n###############################################################################\nplot.omega <- function\n(\n\tweight,\t\t# weight\n\tia\t\t\t# input assumptions\n)\t\n{\t\n\tomegafn = function(x,L) { mean(pmax(x-L,0)) / mean(pmax(L-x,0)) }\n\n\tif(is.null(ia$parameters.omega)) omega = 0 else omega = ia$parameters.omega\t\n\t\n\tweight = weight[, 1:ia$n, drop=F]\n\t\t\n\tportfolio.returns = weight %*% t(ia$hist.returns)\t\n\t\n\tthreshhold = quantile(portfolio.returns, probs = c(0.05, 0.95))\n\tthreshhold = seq(threshhold[1], threshhold[2], length.out = 100)\n\n\tpar(mar = c(4,4,2,1), cex = 0.8)\n\tfor(i in 1:nrow(weight)) {\t\n\t\tdata = sapply(threshhold, function(L) omegafn(portfolio.returns[i, ], L))\n\t\t\n\t\tif(i==1) plot(threshhold,log(data), type='l', col=i, \n\t\t\txlab='Threshhold', ylab='Log(Omega)', main='Portfolio Omega')\n\t\tlines(threshhold, log(data), col=i)\n\t}\n\tabline(v = omega, col='orange')\n\tgrid()\n\tplota.legend(rownames(weight) ,1:nrow(weight), x = 'bottomleft')\n}\n\n", "meta": {"hexsha": "2a4d9fcdc3151c511b9e605802eaa41d731248f0", "size": 7756, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/aa.omega.r", "max_stars_repo_name": "wisonhang/Shiny_report", "max_stars_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patterns.matching/SIT/aa.omega.r", "max_issues_repo_name": "wisonhang/Shiny_report", "max_issues_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patterns.matching/SIT/aa.omega.r", "max_forks_repo_name": "wisonhang/Shiny_report", "max_forks_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_forks_repo_licenses": ["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.5284552846, "max_line_length": 110, "alphanum_fraction": 0.5594378546, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6195533383649305}} {"text": "#' svd\n#' \n#' Singular value decomposition.\n#' \n#' @details\n#' The factorization works by first forming the crossproduct \\eqn{X^T X}\n#' and then taking its eigenvalue decomposition. In this case, the square root\n#' of the eigenvalues are the singular values. If the left/right singular\n#' vectors \\eqn{U} or \\eqn{V} are desired, then in either case, \\eqn{V} is\n#' computed (the eigenvectors). From these, \\eqn{U} can be reconstructed, since\n#' if \\eqn{X = U\\Sigma V^T}, then \\eqn{U = XV\\Sigma^{-1}}.\n#' \n#' @section Communication:\n#' The operation is completely local except for forming the crossproduct, which\n#' is an \\code{allreduce()} call, quadratic on the number of columns.\n#' \n#' @param x\n#' A shaq.\n#' @param nu \n#' number of left singular vectors to return.\n#' @param nv \n#' number of right singular vectors to return.\n#' @param LINPACK\n#' Ignored.\n#' \n#' @return \n#' A list of elements \\code{d}, \\code{u}, and \\code{v}, as with R's own\n#' \\code{svd()}. The elements are, respectively, a regular vector, a shaq, and\n#' a regular matrix.\n#' \n#' @examples\n#' \\dontrun{\n#' library(kazaam)\n#' x = ranshaq(runif, 10, 3)\n#' \n#' svd = svd(x)\n#' comm.print(svd$d) # a globally owned vector\n#' svd$u # a shaq\n#' comm.print(svd$v) # a globally owned matrix\n#' \n#' finalize()\n#' }\n#' \n#' @name svd\n#' @rdname svd\nNULL\n\n \n\nsvd.shaq = function(x, retu=FALSE, retv=FALSE)\n{\n if (!retu && !retv)\n only.values = TRUE\n else\n only.values = FALSE\n \n cp = cp.shaq(x)\n \n ev = eigen(cp, only.values=only.values, symmetric=TRUE)\n \n d = sqrt(ev$values)\n \n if (retu)\n {\n # u.local = ev$vectors %*% diag(1/d)\n u.local = sweep(ev$vectors, STATS=1/d, MARGIN=2, FUN=\"*\")\n u.local = Data(x) %*% u.local\n u = shaq(u.local, nrow(x), ncol(x), checks=FALSE)\n }\n else\n u = NULL\n \n if (retv)\n v = ev$vectors\n else\n v = NULL\n \n list(d=d, u=u, v=v)\n}\n\n\n\n#' @rdname svd\n#' @export\nsetMethod(\"svd\", signature(x=\"shaq\"),\n function(x, nu = min(n, p), nv = min(n, p), LINPACK = FALSE)\n {\n n = nrow(x)\n p = ncol(x)\n \n check.is.natnum(nu)\n check.is.natnum(nv)\n \n retu = nu > 0\n retv = nv > 0\n \n ret = svd.shaq(x, retu, retv)\n \n if (nu && ncol(ret$u) > nu)\n ret$u = ret$u[, 1:nu]\n \n if (nv && NCOL(ret$v) > nv)\n ret$v = ret$v[, 1:nv]\n \n ret\n }\n)\n", "meta": {"hexsha": "2efb41e2bbf0447d988c28b3affb4cc3073062c1", "size": 2320, "ext": "r", "lang": "R", "max_stars_repo_path": "R/svd.r", "max_stars_repo_name": "cran/kazaam", "max_stars_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/svd.r", "max_issues_repo_name": "cran/kazaam", "max_issues_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/svd.r", "max_forks_repo_name": "cran/kazaam", "max_forks_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4814814815, "max_line_length": 80, "alphanum_fraction": 0.5926724138, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6195198832586941}} {"text": "pi = 3.14159\ncircle_radius = 10.2\ncircle_perimeter = 2 * pi * circle_radius\ncircle_area = pi * circle_radius * circle_radius\ncat(\"Let there be a circle with the radius\", circle_radius, \"cm.\\n\")\ncat(\"Then the perimeter of the circle is\", circle_perimeter, \"cm.\\n\")\ncat(\"The area of the circle is\", circle_area, \"cm squared.\\n\")\n", "meta": {"hexsha": "0be9fc35b8bc0482d374f2b6e493c0a05661df70", "size": 327, "ext": "r", "lang": "R", "max_stars_repo_path": "Appendix_B_R/example03_numeric.r", "max_stars_repo_name": "itanaskovic/Data-Science-Algorithms-in-a-Week", "max_stars_repo_head_hexsha": "879cb4c96b35d57e593a85b54dcda41f91d27533", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30, "max_stars_repo_stars_event_min_datetime": "2017-09-02T16:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:00:07.000Z", "max_issues_repo_path": "Appendix_B_R/example03_numeric.r", "max_issues_repo_name": "itanaskovic/Data-Science-Algorithms-in-a-Week", "max_issues_repo_head_hexsha": "879cb4c96b35d57e593a85b54dcda41f91d27533", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Appendix_B_R/example03_numeric.r", "max_forks_repo_name": "itanaskovic/Data-Science-Algorithms-in-a-Week", "max_forks_repo_head_hexsha": "879cb4c96b35d57e593a85b54dcda41f91d27533", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34, "max_forks_repo_forks_event_min_datetime": "2017-08-15T11:03:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-24T09:35:58.000Z", "avg_line_length": 40.875, "max_line_length": 69, "alphanum_fraction": 0.7308868502, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9615338035725358, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.6194442038609282}} {"text": "# Returns the number of conversions\nget_conversions <- function(theta, impressions) {\n k <- ncol(theta)\n y <- rep(0.0, k)\n for (i in 1:k) {\n y[i] <- rbinom(1, size=impressions[i], prob=theta[i])\n } \n return(y)\n}\n\n# Returns the probability\nget_probability <- function(conversion, impressions) {\n k <- length(conversion)\n theta <- matrix(nrow=1000, ncol=k)\n for (i in 1:k) {\n theta[,i] <- rbeta(1000, shape1=conversion[i]+1, shape2=impressions[i]-conversion[i]+1)\n } \n return(theta)\n}\n\n\n#Compute allocations\nget_allocations <- function(theta) {\n k <- ncol(theta)\n allocations <- table(factor(max.col(theta), level=1:k))\n return(allocations/sum(allocations))\n}\n\n\n# COnversion and impressions are cumulative counts\n# Assumed conversion rate of each creative for testing\nndays <- 10 #days to simulate\nassumed_conversion <- c(0.02, 0.01, 0.01, 0.02)\nconversion <- matrix(0, nrow=ndays, ncol=4)\nimpressions <- matrix(0, nrow=ndays, ncol=4)\nimpressions[1,] <- c(1000, 0, 0, 0)\nnext_day_allocations <- matrix(0, nrow=ndays+1, ncol=4)\n\n#Simulating day 1\nconversion[1,] <- assumed_conversion * impressions[1,]\ntheta <- get_probability(conversion[1,], impressions[1,])\ny <- get_conversions(theta, impressions[1,])\nnext_day_allocations[2,] <- get_allocations(theta) * 1000\n\n#Simulating days\nfor (day in 2:ndays) {\n impressions[day,] <- impressions[day-1,] + next_day_allocations[day,]\n conversion[day,] <- conversion[day-1,] + (assumed_conversion * next_day_allocations[day,])\n theta <- get_probability(conversion[day,], impressions[day,])\n y <- get_conversions(theta, impressions[day,])\n next_day_allocations[day+1,] <- get_allocations(theta) * 1000\n}\n\n", "meta": {"hexsha": "764ed34e9d700766570bdf391632ad1a956b315c", "size": 1665, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mab-simulation.r", "max_stars_repo_name": "ybhalerao/multi-armed-bandit", "max_stars_repo_head_hexsha": "2c832d9b1541e65553b8251d7154a57148037b81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-06-21T23:22:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-21T23:22:21.000Z", "max_issues_repo_path": "R/mab-simulation.r", "max_issues_repo_name": "ybhalerao/multi-armed-bandit", "max_issues_repo_head_hexsha": "2c832d9b1541e65553b8251d7154a57148037b81", "max_issues_repo_licenses": ["MIT"], "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/mab-simulation.r", "max_forks_repo_name": "ybhalerao/multi-armed-bandit", "max_forks_repo_head_hexsha": "2c832d9b1541e65553b8251d7154a57148037b81", "max_forks_repo_licenses": ["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.8333333333, "max_line_length": 92, "alphanum_fraction": 0.7021021021, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6193099797866998}} {"text": "#' Path disutility updater\r\n#'\r\n#' This function updates the path disutility at time t+1 based on disutility and path costs at time t. The path costs are computed from pattern of link flows.\r\n#' @param x Traffic flow on all links of network\r\n#' @param A Link-path incidence matrix\r\n#' @param psi Recency parameter, controlling weight assigned to most recent path costs when updating disutility. Defaults to 1.\r\n#' @param Alpha Vector of free flow travel time parameters for each link\r\n#' @param Beta Vector of capacity parameters for each link\r\n#' @param pow Polynomial order of cost function for each link. Defaults to 4.\r\n#' @param ut Vector of path disutilities prior to update\r\n#' @return Vector of path disutilities \r\n#' @keywords disutility\r\n#' @examples\r\n#' A <- matrix(c(0,1,0,0,1,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1),ncol=4,byrow=T)\r\n#' Alpha <- rep(10,7)\r\n#' Beta <- rep(2,7)\r\n#' pow <- rep(4,7)\r\n#' path_flow <- c(10,20,15,15)\r\n#' x <- A%*%path_flow\r\n#' ut <- c(10,10,10,10)\r\n#' Utility(x,A,psi=0.5,Alpha,Beta,pow,ut)\r\n#' @export\r\n\r\nUtility <- function(x,A=diag(length(x)),psi=1,Alpha,Beta,pow=4,ut=0){\r\n \tpsi*PathCost(x,A,Alpha=Alpha,Beta=Beta,pow=pow) + (1-psi)*ut\r\n}", "meta": {"hexsha": "6e2eafd394d3802b2ad00773f47bf614f4f46846", "size": 1191, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Utility.r", "max_stars_repo_name": "MartinLHazelton/transportation", "max_stars_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Utility.r", "max_issues_repo_name": "MartinLHazelton/transportation", "max_issues_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Utility.r", "max_forks_repo_name": "MartinLHazelton/transportation", "max_forks_repo_head_hexsha": "ba690828d2e24b492677c41a7b659712382ccec0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8076923077, "max_line_length": 159, "alphanum_fraction": 0.685138539, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6188064075486973}} {"text": "# Copyright 2014-2019 Arnaud Poret\n# This work is licensed under the BSD 2-Clause License.\n# To view a copy of this license, visit https://opensource.org/licenses/BSD-2-Clause\n\n# continuous logical NOT operator\n# here the algebraic formulation is used\nnot<-function(a) {\n return(1-a)\n}\n\n# continuous logical AND operator\n# here the algebraic formulation is used\n# note that it accepts two or more arguments\nand<-function(a,b,...) {\n x<-c(a,b,...)\n y<-x[1]\n for(i in seq(2,length(x))) {\n y<-y*x[i]\n }\n return(y)\n}\n\n# continuous logical OR operator\n# here the algebraic formulation is used\n# note that it accepts two or more arguments\nor<-function(a,b,...) {\n x<-c(a,b,...)\n y<-x[1]\n for(i in seq(2,length(x))) {\n y<-y+x[i]-y*x[i]\n }\n return(y)\n}\n\n# main function: performs the simulation\ndothejob<-function(node0,r,w,kend,nedge,nnode,nodelab,plotall,printall) {\n node<-as.matrix(node0)\n edge<-as.matrix(fedge(node,1,nedge))\n for(k in seq(2,kend)) {\n edge<-cbind(edge,as.matrix((1-r)*edge[,k-1]+r*w*fedge(node,k-1,nedge)))\n node<-cbind(node,as.matrix(fnode(edge,k-1,nnode)))\n }\n if(plotall) {\n for(i in seq(ceiling(nnode/9))) {\n dev.new()\n par(mfrow=c(3,3))\n }\n for(i in seq(nnode)) {\n nplot<-ceiling(i/9)\n dev.set(nplot+1)\n plot(node[i,],type=\"l\",main=nodelab[i],ylim=c(0,1),xlab=\"\",ylab=\"\")\n if(printall) {\n dev.print(device=svg,filename=paste(\"plot\",as.character(nplot),\".svg\",sep=\"\"))\n }\n }\n }\n return(node)\n}\n", "meta": {"hexsha": "bc5d1913b10e07b4cde9919738d1922881ccda6f", "size": 1614, "ext": "r", "lang": "R", "max_stars_repo_path": "lib.r", "max_stars_repo_name": "arnaudporet/enhance_my_Boole", "max_stars_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib.r", "max_issues_repo_name": "arnaudporet/enhance_my_Boole", "max_issues_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib.r", "max_forks_repo_name": "arnaudporet/enhance_my_Boole", "max_forks_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-05-01T18:56:42.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-01T18:56:42.000Z", "avg_line_length": 27.3559322034, "max_line_length": 94, "alphanum_fraction": 0.5855018587, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553435, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6187864202875611}} {"text": "vis2aot_vermote <- function(vis) {\n aot = (3.9449 / vis) + 0.08498\n \n return(aot)\n}\n\nvis2aot_k <- function(vis) {\n aot = (3.912 / vis)\n \n return(aot)\n}\n\nvis2aot_sixs <- function(vis) {\n # vertical repartition of aerosol density for v=23km\n # (in number of particles per cm3)\n an23 = c(2.828e+03,1.244e+03,5.371e+02,2.256e+02,1.192e+02\n ,8.987e+01,6.337e+01,5.890e+01,6.069e+01,5.818e+01,5.675e+01\n ,5.317e+01,5.585e+01,5.156e+01,5.048e+01,4.744e+01,4.511e+01\n ,4.458e+01,4.314e+01,3.634e+01,2.667e+01,1.933e+01,1.455e+01\n ,1.113e+01,8.826e+00,7.429e+00,2.238e+00,5.890e-01,1.550e-01\n ,4.082e-02,1.078e-02,5.550e-05,1.969e-08,0.000e+00)\n \n # vertical repartition of aerosol density for v=5km\n # (in number of particles per cm3)\n an5 = c(1.378e+04,5.030e+03,1.844e+03,6.731e+02,2.453e+02\n ,8.987e+01,6.337e+01,5.890e+01,6.069e+01,5.818e+01,5.675e+01\n ,5.317e+01,5.585e+01,5.156e+01,5.048e+01,4.744e+01,4.511e+01\n ,4.458e+01,4.314e+01,3.634e+01,2.667e+01,1.933e+01,1.455e+01\n ,1.113e+01,8.826e+00,7.429e+00,2.238e+00,5.890e-01,1.550e-01\n ,4.082e-02,1.078e-02,5.550e-05,1.969e-08,0.000e+00)\n \n # Altitude (z) levels\n z = c(0., 1., 2., 3., 4., 5., 6., 7., 8.,\n 9., 10., 11., 12., 13., 14., 15., 16., 17.,\n 18., 19., 20., 21., 22., 23., 24., 25., 30.,\n 35., 40., 45., 50., 70., 100.,99999.)\n \n aot = 0.0\n sigma = 0.056032\n \n# if (any(vis <= 0))\n# {\n# return()\n# }\n \n # Numerically integrate over each layer of the atmosphere summing the\n # calculated AOT\n \n for (k in 1:32)\n {\n # Calculate dz (the difference on the x axis)\n dz = z[k+1] - z[k]\n \n # Get the points on the curve for both ends of dz\n point_left_5 = an5[k]\n point_right_5 = an5[k+1]\n \n point_left_23 = an23[k]\n point_right_23 = an23[k+1]\n \n # Calculate the difference\n diff_left = (115.0/18.0) * (point_left_5 - point_left_23)\n diff_right = (115.0/18.0) * (point_right_5 - point_right_23)\n \n # Convert from per Km back to Km\n diff_left_km = (5.0 * point_left_5/18.0) - (23.0 * point_left_23/18.0)\n diff_right_km = (5.0 * point_right_5/18.0) - (23.0 * point_right_23/18.0)\n \n # Use interpolation formula from the docs (uses -b(z) as shown in FORTRAN code rather than +b(z) as in manual)\n interp_left = diff_left/vis - diff_left_km\n interp_right = diff_right/vis - diff_right_km\n \n # Calculate AOT for this level\n ev = dz * exp( (log(interp_left)+log(interp_right)) * 0.5)\n aot = aot + (ev * sigma * 1.0e-03)\n }\n return(aot)\n}\n\ndata <- read.csv(\"data/MODTRAN_VisAOT.csv\")\nvis2aot_modtran <- approxfun(data$vis, data$aot)\n", "meta": {"hexsha": "c82c3e89eb94c26321f15de045e36a7af58b9a5d", "size": 2747, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/vis2aot.r", "max_stars_repo_name": "robintw/VisAOT", "max_stars_repo_head_hexsha": "03cb5013008cc59ae1a18ce024924382a01fda62", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-12-21T19:29:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T08:45:30.000Z", "max_issues_repo_path": "lib/vis2aot.r", "max_issues_repo_name": "robintw/VisAOT", "max_issues_repo_head_hexsha": "03cb5013008cc59ae1a18ce024924382a01fda62", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/vis2aot.r", "max_forks_repo_name": "robintw/VisAOT", "max_forks_repo_head_hexsha": "03cb5013008cc59ae1a18ce024924382a01fda62", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2016-06-09T15:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T02:08:48.000Z", "avg_line_length": 33.5, "max_line_length": 115, "alphanum_fraction": 0.5893702221, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.618743617767255}} {"text": "library(nloptr)\nlibrary(rlist)\nsource(\"bootstrapping.r\")\n\nget_expected_I = function(beta, N0, lambda) {\n \"\n Calculates expected new case counts for each step in the time series.\n \n Parameters\n ----------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n Lagged one step (beta[1] = beta(0) in our notation).\n N0 : numeric\n Initial number of cases.\n lambda : numeric\n (1 / mean) number of days an individual will continue to be infectious.\n \n Returns\n -------\n expected_I : numeric vector\n Daily expected number of new cases.\n \"\n moments = length(beta)\n expected_I = rep(0, moments)\n expected_N = rep(0, moments)\n N_previous = N0\n for(t in 1:moments){\n expected_N[t] = N_previous * (beta[t] + pexp(1, rate=lambda, lower.tail=FALSE))\n expected_I[t] = N_previous * beta[t]\n N_previous = expected_N[t]\n }\n return(expected_I)\n}\n\noptimize_lambda = function(observed_I, beta, N0, lambda0, lambda_min, lambda_max) {\n \"\n Find lambda that optimizes the quartic error of estimation of E[I(t)].\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n Lagged one step (beta[1] = beta(0) in our notation).\n N0 : numeric\n Initial number of cases.\n lambda0 : numeric\n Initial value for lambda.\n \n Returns\n -------\n lambda : numeric\n Optimal value for lambda.\n \"\n # define objective function: mean quartic error of estimation of new cases\n mean_quartic_error = function(lambda) {\n expected_I = get_expected_I(beta, N0, lambda)\n return(mean((observed_I - expected_I) ^ 4))\n }\n # optimize\n local_opts <- list( \"algorithm\" = \"NLOPT_LN_BOBYQA\",\n \"xtol_rel\" = 1.0e-7 )\n opts <- list( \"algorithm\" = \"NLOPT_LN_BOBYQA\",\n \"xtol_rel\" = 1.0e-7,\n \"maxeval\" = 100000,\n \"local_opts\" = local_opts )\n result <- nloptr(x0=lambda0, eval_f=mean_quartic_error, eval_grad_f=NULL,\n lb=lambda_min, ub=lambda_max, opts=opts)\n return(result$solution)\n}\n\nfit = function(observed_I, beta0, beta_min, beta_max, lambda0, lambda_min,\n lambda_max, N0_min, N0_max, alpha, ignore_beta_diff) {\n \"\n Fits the model to observed daily new case counts.\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta0 : numeric vector\n Initial value for beta; the expected number of cases stemming from a single\n person in a single day.\n beta_min : numeric\n Beta lower bound.\n beta_max : numeric\n Beta upper bound.\n ignore_beta_diff : numeric vector\n List of beta indices for which differences should be ignored while\n calculating the loss function. This amounts to moments in time in which we\n allow the beta series to be discontinuous.\n \n Returns\n -------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n \"\n # set optimization parameters\n moments = length(observed_I)\n beta_min =rep(beta_min, times=moments)\n beta_max =rep(beta_max, times=moments)\n local_opts <- list( \"algorithm\" = \"NLOPT_LN_BOBYQA\",\n \"xtol_rel\" = 1.0e-7 )\n opts <- list( \"algorithm\" = \"NLOPT_LN_BOBYQA\",\n \"xtol_rel\" = 1.0e-7,\n \"maxeval\" = 100000,\n \"local_opts\" = local_opts )\n # optimize over several N0\n best = list()\n best$loss = Inf\n for (N0 in N0_min:N0_max) {\n loss = function(beta) {\n lambda = optimize_lambda(observed_I, beta, N0, lambda0, lambda_min,\n lambda_max)\n expected_I = get_expected_I(beta, N0, lambda)\n beta_diff = diff(beta)\n beta_diff = beta_diff[!1:length(beta_diff) %in% ignore_beta_diff]\n loss = mean((expected_I - observed_I) ^ 4) + alpha * mean(beta_diff ^ 2)\n return(loss)\n }\n result <- nloptr(x0=beta0, eval_f=loss, eval_grad_f=NULL, lb=beta_min,\n ub=beta_max, opts=opts)\n if(result$objective < best$loss) {\n best$loss = result$objective\n best$N0 = N0\n best$beta = result$solution\n }\n }\n best$lambda = optimize_lambda(observed_I, best$beta, best$N0, lambda0,\n lambda_min, lambda_max)\n return(best)\n}\n\n\nfit2 = function(observed_I, beta0, beta_min, beta_max, lambda0, lambda_min,\n lambda_max, N00, N0_min, N0_max, alpha, ignore_beta_diff) {\n \"\n Fits the model to observed daily new case counts.\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta0 : numeric vector\n Initial value for beta; the expected number of cases stemming from a single\n person in a single day.\n beta_min : numeric\n Beta lower bound.\n beta_max : numeric\n Beta upper bound.\n ignore_beta_diff : numeric vector\n List of beta indices for which differences should be ignored while\n calculating the loss function. This amounts to moments in time in which we\n allow the beta series to be discontinuous.\n \n Returns\n -------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n \"\n # concatenate initial parameters into a single vector for optimization\n x0 = c(beta0, lambda0, N00)\n steps = length(observed_I)\n lb = c(rep(beta_min, steps), lambda_min, N0_min)\n ub = c(rep(beta_max, steps), lambda_max, N0_max)\n # set optimization parameters\n opts = list(\"algorithm\" = \"NLOPT_LN_BOBYQA\", \"xtol_rel\" = 1.0e-7,\n \"maxeval\" = 10000000)\n # define loss function\n loss = function(x) {\n # unpack values\n beta = x[1:steps]\n lambda = x[steps + 1]\n N0 = x[steps + 2]\n # calculate loss\n expected_I = get_expected_I(beta, N0, lambda)\n beta_diff = diff(beta)\n beta_diff = beta_diff[!1:length(beta_diff) %in% ignore_beta_diff]\n loss = mean((expected_I - observed_I) ^ 4) + alpha * mean(beta_diff ^ 2)\n }\n result = nloptr(x0=x0, eval_f=loss, eval_grad_f=NULL, lb=lb, ub=ub, opts=opts)\n model = list()\n model$beta = result$solution[1:steps]\n model$lambda = result$solution[steps + 1]\n model$N0 = result$solution[steps + 2]\n model$loss = result$objective\n return(model)\n}\n\nfit3 = function(observed_I, beta0, beta_min, beta_max, lambda0, lambda_min,\n lambda_max, N00, N0_min, N0_max, regularization, regularization_weights, ignore_beta_diff, window_size=10) {\n \"\n Fits the model to observed daily new case counts.\n \n Parameters\n ----------\n observed_I : numeric vector\n Daily observed number of new cases.\n beta0 : numeric vector\n Initial value for beta; the expected number of cases stemming from a single\n person in a single day.\n beta_min : numeric\n Beta lower bound.\n beta_max : numeric\n Beta upper bound.\n ignore_beta_diff : numeric vector\n List of beta indices for which differences should be ignored while\n calculating the loss function. This amounts to moments in time in which we\n allow the beta series to be discontinuous.\n \n Returns\n -------\n beta : numeric vector\n Expected number of cases stemming from a single person in a single day.\n \"\n # concatenate initial parameters into a single vector for optimization\n x0 = c(beta0, lambda0, N00)\n steps = length(observed_I)\n lb = c(rep(beta_min, steps), lambda_min, N0_min)\n ub = c(rep(beta_max, steps), lambda_max, N0_max)\n # set optimization parameters\n opts = list(\"algorithm\" = \"NLOPT_LN_BOBYQA\", \"xtol_rel\" = 1.0e-7,\n \"maxeval\" = 100000)\n observed_variances = compute_variances(observed_I, window_size)\n # define loss function\n loss = function(x) {\n # unpack values\n beta = x[1:steps]\n lambda = x[steps + 1]\n N0 = x[steps + 2]\n # calculate loss\n expected_I = get_expected_I(beta, N0, lambda)\n beta_diff = diff(beta)\n alpha = regularization_weights*(observed_variances)\n #6.4e8\n loss = mean((expected_I - observed_I) ^ 4) +(regularization)* mean(alpha[1:(length(alpha) - 1)] * (beta_diff ^ 2))\n return(loss)\n }\n result = nloptr(x0=x0, eval_f=loss, eval_grad_f=NULL, lb=lb, ub=ub, opts=opts)\n model = list()\n model$beta = result$solution[1:steps]\n model$lambda = result$solution[steps + 1]\n model$N0 = result$solution[steps + 2]\n model$loss = result$objective\n return(model)\n}", "meta": {"hexsha": "3256936506206cad32c958df4e6241e90f84efe7", "size": 8352, "ext": "r", "lang": "R", "max_stars_repo_path": "original/model_fitting.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "original/model_fitting.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/model_fitting.r", "max_forks_repo_name": "secg95/INS_COVID", "max_forks_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6774193548, "max_line_length": 123, "alphanum_fraction": 0.6671455939, "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6181173477242136}} {"text": "#importa pacote\nlibrary('readr')\n\n# Lê/coleta dados no arquivo\n\ndados_cliente <- read.csv(\"./clientes.csv\",sep=\";\")\n\nhead(dados_cliente)\n\n# Descrever a estrutura dos dados\n\nstr(dados_cliente)\n\ntail(dados_cliente)\n\n# Definimos que a variável Grau.Instrução deve ser tratada como ordinal\n\nlevels(dados_cliente$Grau.Instrução)\n\n# Frequência absoluta\n\nfa <- table(dados_cliente$Estado.civil)\nfa\n\n# Frequência relativa\n\nfr1 <- fa/length(dados_cliente$Estado.civil)\nfr1\n\n# Frequência relativa\n\nfr2 <- prop.table(fa)\nfr2\n\n# Frequência percentual\n\nfpct <- prop.table(fa)*100\nfpct\n\n\nround(fpct,digit=2)\n\n# Moda\nnames(fa)[which.max(fa)]\n\nbarplot(fa,main = \"Frequência absoluta\",xlab = \"Estado Civil\",ylab = \"Quantidade\")\n\npie(main = \"Frequência relativa percentual\",fpct,labels=as.character(round(fpct,digits = 2)))\n\n# Frequência absoluta\n\nfa <- table(dados_cliente$Grau.Instrução)\nfa\n# Frequência relativa\n\nfr <- prop.table(fa)\nfr\n\n# Frequência percentual\n\nfpct <- prop.table(fa)*100\nfpct\n\n# Moda\nnames(fa)[which.max(fa)]\n\nbarplot(sort(fr),main = \"Frequência relativa\",xlab = \"Valor\",ylab = \"Grau de Instrução\",col = \"darkred\",horiz = TRUE)\n\nbarplot(sort(fa),main = \"Frequência absoluta\",ylab = \"Qtde\",xlab = \"Grau de Instrução\")\n\nbarplot(fa,main = \"Frequência absoluta\",ylab = \"Qtde\",xlab = \"Grau de Instrução\")\n\nlevels(dados_cliente$Grau.Instrução)\n\ndados_cliente$Grau.Instrução <- factor(dados_cliente$Grau.Instrução,levels = c('Fundamental','Médio','Superior','Mestrado','Doutorado'))\n\nfa <- table(dados_cliente$Grau.Instrução)\n\nbarplot(fa,main = \"Frequência absoluta\",ylab = \"Qtde\",xlab = \"Grau de Instrução\")\n\n\n\nhead(dados_cliente,2)\n\n# Frequência absoluta\n\nfa <- table(dados_cliente$Qtde.Filhos)\nprint('Frequência absoluta:')\nfa\n\n# Frequência relativa\n\nfr <- prop.table(fa)\nprint('Frequência relativa:')\nround(fr,digit=0)\n\n# Frequência percentual\n\nfpct <- prop.table(fa)*100\nprint('Frequência relativa percentual:')\nround(fpct,digit=0)\n\n# na.rm=TRUE --> Pq alguns valores são NA\n# Moda\nprint(\"Moda\")\nnames(fa)[which.max(fa)]\n\n# Mediana\nprint(\"Mediana\")\nmedian(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\n#Média\nprint(\"Media\")\nmean(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\n#Quartis\nprint(\"quartis\")\nquantile(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n#min\nprint(\"min\")\nmin(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n#max\nprint(\"max\")\nmax(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\n# Amplitude (max-min)\nprint(\"Amplitude\")\ndiff(range(dados_cliente$Qtde.Filhos,na.rm=TRUE))\n\n# Variancia\nprint(\"Variancia\")\nvar(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\n# Desvio-padrão\nprint(\"Desvio-padrão\")\nsd(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\n# Coeficiênte de variação\nprint(\"Coeficiênte de variação\")\nsd(dados_cliente$Qtde.Filhos,na.rm=TRUE)/mean(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n\nquartis <- quantile(dados_cliente$Qtde.Filhos,na.rm=TRUE)\n# Amplitude interquartilica\nprint(\"Amplitude interquartilica\")\nquartis[4]-quartis[2]\n\n#Resumo\nsummary(dados_cliente$Qtde.Filhos)\n\n# Frequência absoluta acumulada\n\nfaa <- cumsum(fa)\nfaa\n\nfa\n\nplot(fa,main = \"Frequência absoluta\",ylab = \"Frequência\",xlab = \"Qtde. de Filhos\")\n\nplot(faa,main = \"Frequência absoluta acumulada\",ylab = \"Frequência\",xlab = \"Qtde. de Filhos\",type=\"S\")\n\nhead(dados_cliente,2)\n\nsummary(dados_cliente$Salário)\n\n# Min e Max\nrange(dados_cliente$Salário)\n\n#min\nmin <- min(dados_cliente$Salário,na.rm=TRUE)\n#max\nmax <- max(dados_cliente$Salário,na.rm=TRUE)\n\n#Qtde de classes\nnclass.Sturges(dados_cliente$Salário)\n\n\n# Agrupar\nprint(cut(dados_cliente$Salário,breaks=seq(min,max,length.out=8)))\n\n# Agrupar\ngrupos <- cut(dados_cliente$Salário,breaks=seq(min,max,length.out=8))\n\nprint(grupos)\n\n# Frequência absoluta\n\nfa <- table(grupos)\nprint('Frequência absoluta:')\nfa\n\n# Frequência relativa\n\nfr <- prop.table(fa)\nprint('Frequência relativa:')\nround(fr,digit=0)\n\nhist(dados_cliente$Salário,main=\" Histograma - Salário\",ylab = \"Frequência\",xlab = \"Valor salário\")\n\nhist(dados_cliente$Salário,main=\" Histograma - Salário\",ylab = \"Densidade\",xlab = \"Valor salário\",freq=FALSE,labels=TRUE)\n\nboxplot(dados_cliente$Salário,main=\" Boxplot - Salário\",ylab = \"Valor salário\")\n\n\n", "meta": {"hexsha": "31ec566e4953ea6e442cc7e9716ae7b885b339e3", "size": 4089, "ext": "r", "lang": "R", "max_stars_repo_path": "BootCamp Engenheiro de Dados/Modulo 1 - Materiais/Material_complementar_videoaulas/Analise_univariada.r", "max_stars_repo_name": "MarceloEbed/IGTI", "max_stars_repo_head_hexsha": "8b0f56c4b9bcbbfe81fd540cb34d39ad8ae0d306", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BootCamp Engenheiro de Dados/Modulo 1 - Materiais/Material_complementar_videoaulas/Analise_univariada.r", "max_issues_repo_name": "MarceloEbed/IGTI", "max_issues_repo_head_hexsha": "8b0f56c4b9bcbbfe81fd540cb34d39ad8ae0d306", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BootCamp Engenheiro de Dados/Modulo 1 - Materiais/Material_complementar_videoaulas/Analise_univariada.r", "max_forks_repo_name": "MarceloEbed/IGTI", "max_forks_repo_head_hexsha": "8b0f56c4b9bcbbfe81fd540cb34d39ad8ae0d306", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0441176471, "max_line_length": 136, "alphanum_fraction": 0.7449254096, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.6180006600565057}} {"text": "#######################################\n\n# Brad Ballard\n# CS498 Applied Machine Learning at UIUC\n\n#######################################\n\n# Works cited\n# Resource used: http://luthuli.cs.uiuc.edu/~daf/courses/AML-18/RCodeClassification/pimanbholdout.R\n# Resource used: http://luthuli.cs.uiuc.edu/~daf/courses/AML-18/RCodeClassification/klarcaret.R\n# Resource used: http://luthuli.cs.uiuc.edu/~daf/courses/AML-18/RCodeClassification/svmholdout.R\n# Worked with Jacob Rettig (classmate) on this assignment\n\n# Import packages\noptions(warn=-1)\nlibrary(caret)\nlibrary(klaR)\n\n#######################################\n\n# Part A: Naive Bayes without package\n\n#######################################\n\n#load data\nsetwd('/Users/bradjballard/')\ndata_in<-read.csv('pima.csv', header=FALSE)\nx_vector <- data_in[-c(9)]\ny_labels <- data_in[,9]\n\n#train naive bayes model\ntrscore<-array(dim=10)\ntescore<-array(dim=10)\n\nfor (wi in 1:10){\n #create training and testing sets\n datasplit <- createDataPartition(y=y_labels, p=.8, list=FALSE)\n trainx <- x_vector[datasplit,]\n trainy <- y_labels[datasplit]\n testx <- x_vector[-datasplit,]\n testy <- y_labels[-datasplit]\n \n #splitting positive and negative examples\n trposflag<-trainy>0\n positive_examples <- trainx[trposflag, ]\n negative_examples <- trainx[!trposflag,]\n \n #calculate means and sds\n ptrmean<-sapply(positive_examples, mean, na.rm=TRUE)\n ntrmean<-sapply(negative_examples, mean, na.rm=TRUE)\n ptrsd<-sapply(positive_examples, sd, na.rm=TRUE)\n ntrsd<-sapply(negative_examples, sd, na.rm=TRUE)\n \n #calculate offsets and scales\n ptroffsets<-t(t(trainx)-ptrmean)\n ptrscales<-t(t(ptroffsets)/ptrsd)\n \n pteoffsets<-t(t(testx)-ptrmean)\n ptescales<-t(t(pteoffsets)/ptrsd)\n ptelogs<--(1/2)*rowSums(apply(ptescales,c(1, 2), function(x)x^2), na.rm=TRUE)-sum(log(ptrsd))\n nteoffsets<-t(t(testx)-ntrmean)\n ntescales<-t(t(nteoffsets)/ntrsd)\n ntelogs<--(1/2)*rowSums(apply(ntescales,c(1, 2), function(x)x^2), na.rm=TRUE)-sum(log(ntrsd))\n lvwte<-ptelogs>ntelogs\n gotright<-lvwte==testy\n tescore[wi]<-sum(gotright)/(sum(gotright)+sum(!gotright))\n}\naccuracy <- sum(tescore) / length(tescore)\n\n#accuracy after cross validating 10 times\naccuracy\n\n\n\n#######################################\n\n# Part B: NB with missing data removed\n\n#######################################\n\n#replace '0' in columns with NA\nx_vector_copy <- x_vector\nfor (i in c(3, 4, 6, 8)){\n non_values <- x_vector[, i]==0\n x_vector_copy[non_values, i]=NA\n}\n\n#train naive bayes model\ntrscore<-array(dim=10)\ntescore<-array(dim=10)\n\nfor (wi in 1:10){\n #create training and testing sets\n datasplit <- createDataPartition(y=y_labels, p=.8, list=FALSE)\n trainx <- x_vector_copy[datasplit,]\n trainy <- y_labels[datasplit]\n testx <- x_vector_copy[-datasplit,]\n testy <- y_labels[-datasplit]\n \n #splitting positive and negative examples\n trposflag<-trainy>0\n positive_examples <- trainx[trposflag, ]\n negative_examples <- trainx[!trposflag,]\n \n #calculate means and sds\n ptrmean<-sapply(positive_examples, mean, na.rm=TRUE)\n ntrmean<-sapply(negative_examples, mean, na.rm=TRUE)\n ptrsd<-sapply(positive_examples, sd, na.rm=TRUE)\n ntrsd<-sapply(negative_examples, sd, na.rm=TRUE)\n \n #calculate offsets and scales\n ptroffsets<-t(t(trainx)-ptrmean)\n ptrscales<-t(t(ptroffsets)/ptrsd)\n \n pteoffsets<-t(t(testx)-ptrmean)\n ptescales<-t(t(pteoffsets)/ptrsd)\n ptelogs<--(1/2)*rowSums(apply(ptescales,c(1, 2), function(x)x^2), na.rm=TRUE)-sum(log(ptrsd))\n nteoffsets<-t(t(testx)-ntrmean)\n ntescales<-t(t(nteoffsets)/ntrsd)\n ntelogs<--(1/2)*rowSums(apply(ntescales,c(1, 2), function(x)x^2), na.rm=TRUE)-sum(log(ntrsd))\n lvwte<-ptelogs>ntelogs\n gotright<-lvwte==testy\n tescore[wi]<-sum(gotright)/(sum(gotright)+sum(!gotright))\n}\naccuracy <- sum(tescore) / length(tescore)\n\n#accuracy after cross validating 10 times\naccuracy\n\n\n\n#######################################\n\n## Part C: NB with package\n\n#######################################\n\n#create training and testing sets\ntest_accuracies <- array(dim=10)\n\nfor (wi in 1:10){\n datasplit <- createDataPartition(y=y_labels, p=.8, list=FALSE)\n trainx <- x_vector[datasplit,]\n trainy <- y_labels[datasplit]\n testx <- x_vector[-datasplit,]\n testy <- y_labels[-datasplit]\n\n #train naive bayes model using klaR package\n tr <- trainControl(method='cv' , number=10)\n model <- train (trainx , factor(trainy) , 'nb' , trControl=tr)\n\n #prediction\n predictions <- predict(model, newdata=testx)\n correct <- length(testy[testy == predictions])\n wrong <- length(testy[testy != predictions])\n accuracy <- correct / (correct + wrong)\n test_accuracies[wi] <- accuracy\n}\ncross_validation_accuracy <- sum(test_accuracies)/length(test_accuracies)\n\n#accuracy after cross validating 10 times\ncross_validation_accuracy\n\n\n\n#######################################\n\n## Part D: Using SVMLight\n\n#######################################\n\n#create data sets for training and testing\ndatasplit<-createDataPartition(y=y_labels, p=.8, list=FALSE)\ntrainx <- x_vector[datasplit,]\ntrainy <- y_labels[datasplit]\ntestx <- x_vector[-datasplit,]\ntesty <- y_labels[-datasplit]\n\n#train svm\nsvm <- svmlight(trainx, factor(trainy), pathsvm=\"/Users/bradjballard/svm_light_osx.8.4_i7/\")\nlabels <- predict(svm, testx)\nanswers <- labels$class\n\n#accuracy\ncorrect <- sum(answers == testy)\nwrong <- sum(answers != testy)\naccuracy <- correct / (correct + wrong)\naccuracy\n", "meta": {"hexsha": "124fc8b49d2366b0a3ff3f2247181b9ab2041ba4", "size": 5401, "ext": "r", "lang": "R", "max_stars_repo_path": "NaiveBayesClassifier.r", "max_stars_repo_name": "bradjballard/R-ML-Scripts", "max_stars_repo_head_hexsha": "32a3b72e4db8240ccfaadf4788cfa7821560dda5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NaiveBayesClassifier.r", "max_issues_repo_name": "bradjballard/R-ML-Scripts", "max_issues_repo_head_hexsha": "32a3b72e4db8240ccfaadf4788cfa7821560dda5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NaiveBayesClassifier.r", "max_forks_repo_name": "bradjballard/R-ML-Scripts", "max_forks_repo_head_hexsha": "32a3b72e4db8240ccfaadf4788cfa7821560dda5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5767195767, "max_line_length": 99, "alphanum_fraction": 0.6693204962, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6180006302724015}} {"text": "model_netradiation <- function (minTair = 0.7,\n maxTair = 7.2,\n albedoCoefficient = 0.23,\n stefanBoltzman = 4.903e-09,\n elevation = 0.0,\n solarRadiation = 3.0,\n vaporPressure = 6.1,\n extraSolarRadiation = 11.7){\n #'- Name: NetRadiation -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: NetRadiation Model\n #' * Author: Pierre Martre\n #' * Reference: Modelling energy balance in the wheat crop model SiriusQuality2:\n #' Evapotranspiration and canopy and soil temperature calculations\n #' * Institution: INRA Montpellier\n #' * Abstract: It is calculated at the surface of the canopy and is givenby the difference between incoming and outgoing radiation of both short\n #' and long wavelength radiation \n #'- inputs:\n #' * name: minTair\n #' ** description : minimum air temperature\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -30\n #' ** max : 45\n #' ** default : 0.7\n #' ** unit : °C\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: maxTair\n #' ** description : maximum air Temperature\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -30\n #' ** max : 45\n #' ** default : 7.2\n #' ** unit : °C\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: albedoCoefficient\n #' ** description : albedo Coefficient\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.23\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: stefanBoltzman\n #' ** description : stefan Boltzman constant\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 4.903E-09\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: elevation\n #' ** description : elevation\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0\n #' ** min : -500\n #' ** max : 10000\n #' ** unit : m\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: solarRadiation\n #' ** description : solar Radiation\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 3\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : MJ m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: vaporPressure\n #' ** description : vapor Pressure\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 6.1\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : hPa\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: extraSolarRadiation\n #' ** description : extra Solar Radiation\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 11.7\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : MJ m2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #'- outputs:\n #' * name: netRadiation\n #' ** description : net radiation \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : MJ m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: netOutGoingLongWaveRadiation\n #' ** description : net OutGoing Long Wave Radiation \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n Nsr <- (1.0 - albedoCoefficient) * solarRadiation\n clearSkySolarRadiation <- (0.75 + (2 * 10.0 ^ (-5) * elevation)) * extraSolarRadiation\n averageT <- ((maxTair + 273.16) ^ 4 + (minTair + 273.16) ^ 4) / 2.0\n surfaceEmissivity <- 0.34 - (0.14 * sqrt(vaporPressure / 10.0))\n cloudCoverFactor <- 1.35 * (solarRadiation / clearSkySolarRadiation) - 0.35\n Nolr <- stefanBoltzman * averageT * surfaceEmissivity * cloudCoverFactor\n netRadiation <- Nsr - Nolr\n netOutGoingLongWaveRadiation <- Nolr\n return (list (\"netRadiation\" = netRadiation,\"netOutGoingLongWaveRadiation\" = netOutGoingLongWaveRadiation))\n}", "meta": {"hexsha": "f511fa1547c44eaad42127b36d28617d12551586", "size": 6995, "ext": "r", "lang": "R", "max_stars_repo_path": "test/Models/energybalance_pkg/src/r/Netradiation.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/Models/energybalance_pkg/src/r/Netradiation.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/Models/energybalance_pkg/src/r/Netradiation.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 55.96, "max_line_length": 159, "alphanum_fraction": 0.3849892781, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6179894482326109}} {"text": "=begin\n # sample-factorize04.rb\n\n require \"algebra\"\n \n A = AlgebraicExtensionField(Rational, \"a\") {|a| a**2 - 2}\n B = AlgebraicExtensionField(A, \"b\"){|b| b**2 + 1}\n P = Polynomial(B, \"x\")\n x = P.var\n f = x**4 + 1\n p f.factorize\n #=> (x - 1/2ab - 1/2a)(x + 1/2ab - 1/2a)(x + 1/2ab + 1/2a)(x - 1/2ab + 1/2a)\n((<_|CONTENTS>))\n=end\n", "meta": {"hexsha": "cda46fb6026f8f4ea5c19068572b53b74cf597a1", "size": 338, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/sample-factorize04.rb.v.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/sample-factorize04.rb.v.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/sample-factorize04.rb.v.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5333333333, "max_line_length": 78, "alphanum_fraction": 0.5384615385, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9433475699138558, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.6177933511912841}} {"text": "#' @title\n#' Multivatiate functional regression via nested reduced-rank regularization\n#'\n#' @description\n#' This function takes functional observations as input and fits a nested\n#' reduced-rank regression with a user-specified rank selection method.\n#' The B-spline basis is used to conduct basis expansion.\n#'\n#' @usage\n#' NRRR.func(Y, X, jx, jy, degree = 3, S.interval = NULL, T.interval = NULL,\n#' tuning = c('CV', 'BIC', 'BICP', 'AIC', 'GCV')[1],\n#' nfold = 10, norder = NULL, method = c('RRR', 'RRS')[1],\n#' lambda = 0, maxiter = 300, conv = 1e-4,\n#' dimred = c(TRUE,TRUE,TRUE), rankfix = NULL, xrankfix = NULL,\n#' yrankfix = NULL, lang = c('R', 'Rcpp')[1])\n#'\n#' @param Y a data frame of the functional responses with d columns\n#' for the values of the response components, a column indicating subject ID named as 'ID'\n#' and a column of observation times named as 'TIME'.\n#' @param X a data frame of the functional predictors with p columns\n#' for the values of the predictor components, a column indicating subject ID named as 'ID'\n#' and a column of observation times named as 'TIME'. Order of Subject ID should be the SAME as that of Y.\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 S.interval range of observation times of X, e.g., \\code{S.interval = c(0, 1)}. Default is NULL.\n#' @param T.interval range of observation times of Y, e.g., \\code{T.interval = c(0, 1)}. Default is NULL.\n#' @param degree degree of piecewise polynomial. Default is 3. See \\code{\\link{bs}}.\n#' @param tuning methods to select ranks. If \\code{tuning = 'CV'}, then cross validation\n#' is used to select ranks. Otherwise, the selected information criterion\n#' is used to select ranks.\n#' @param nfold the number of folds used in cross validation. Default is 10.\n#' @param norder a vector of length n that assigns samples to multiple folds for cross validation.\n#' @param method 'RRR' (default): no additional ridge penalty; 'RRS': add an\n#' additional ridge penalty.\n#' @param lambda the tuning parameter to control the amount of ridge\n#' penalization. It is only used when \\code{method = 'RRS'}.\n#' Default is 0.\n#' @param maxiter the maximum iteration number of the\n#' blockwise coordinate descent algorithm. Default is 300.\n#' @param conv the tolerance level used to control the convergence of the\n#' blockwise coordinate descent algorithm. Default is 1e-4.\n#' @param dimred a vector of logical values to decide whether to use the specified tuning method\n#' do rank selection on certain dimensions. TRUE means the rank is selected\n#' by the specified tuning method.\n#' If \\code{dimred[1] = FALSE}, r is provided by \\code{rankfix}\n#' or \\eqn{min(jy*d, rank(X))};\n#' If \\code{dimred[2] = FALSE}, rx equals to \\code{xrankfix} or p;\n#' If \\code{dimred[3] = FALSE},\n#' ry equals to \\code{yrankfix} or d.\n#' Default is \\code{c(TRUE, TRUE, TRUE)}.\n#' @param rankfix a user-provided value of r when \\code{dimred[1] = FALSE}. Default is NULL\n#' which leads to \\eqn{r = min(jy*d, rank(X))}.\n#' @param xrankfix a user-provided value of rx when \\code{dimred[2] = FALSE}. Default is NULL\n#' which leads to \\code{rx = p}.\n#' @param yrankfix a user-provided value of ry when \\code{dimred[3] = FALSE}. Default is NULL\n#' which leads to \\code{ry = d}.\n#' @param lang 'R' (default): the R version function is used; 'Rcpp': the Rcpp\n#' version function is used.\n#'\n#'\n#' @return The function returns a list:\n#' \\item{Ag}{the estimated U.}\n#' \\item{Bg}{the estimated V.}\n#' \\item{Al}{the estimated A.}\n#' \\item{Bl}{the estimated B.}\n#' \\item{C}{the estimated coefficient matrix C.}\n#' \\item{df}{the estimated degrees of freedom of the selected model.}\n#' \\item{sse}{the sum of squared errors of the selected model.}\n#' \\item{ic}{a vector containing values of BIC, BICP, AIC, GCV of the selected model.}\n#' \\item{rx_path}{a matrix displays the path of selecting rx with cross validation. Only available when 'CV' is selected.}\n#' \\item{ry_path}{a matrix displays the path of selecting ry with cross validation. Only available when 'CV' is selected.}\n#' \\item{r_path}{a matrix displays the path of selecting r with cross validation. Only available when 'CV' is selected.}\n# \\item{iter}{the number of iterations needed to converge in the selected model.}\n#' \\item{rank}{the estimated r.}\n#' \\item{rx}{the estimated rx.}\n#' \\item{ry}{the estimated ry.}\n#' \\item{sseq}{sequence of the time points of observing the predictor trajectory.}\n#' \\item{phi}{the basis functions to expand the predictor trajectory.}\n#' \\item{tseq}{sequence of the time points of observing the response trajectory.}\n#' \\item{psi}{the basis functions to expand the response trajectory.}\n#'\n#' @details\n#' This function applies a basis expansion and truncation method to transform\n#' the functional problem into a classical finite-dimensional regression problem,\n#' and then fits a nested reduced-rank regression.\n#' The functional observations are commonly collected in a discrete mannar, and before using this\n#' function, the functional response observations and functional predictor observations\n#' should be saved as a data frame. Data standardization procedures, e.g., centering or\n#' scaling, should be conducted before using this function. B-spline basis is\n#' used to conduct basis expansion. If the functional data are already processed into an integrated form,\n#' functions like \\code{\\link{NRRR.est}}, \\code{\\link{NRRR.ic}} or \\code{\\link{NRRR.cv}} can\n#' be used to fit a NRRR model.\n#'\n#'\n#'\n#' @references Liu, X., Ma, S., & Chen, K. (2020).\n#' Multivariate Functional Regression via Nested Reduced-Rank Regularization.\n#' arXiv: Methodology.\n#'\n#'\n#' @examples\n#' n <- 100\n#' ns <- 80\n#' nt <- 80\n#' p <- 10\n#' d <- 10\n#' jx <- 8\n#' jy <- 8\n#' library(NRRR)\n#' set.seed(3)\n#' # generate functional data\n#' simDat <- NRRR.sim(n = 100, ns = 80, nt = 80, r = 3, rx = 3, ry = 3,\n#' jx = 8, jy = 8, p = 10, d = 10, s2n = 1, rho_X = 0.5,\n#' rho_E = 0, Sigma = \"CorrAR\")\n#' # dimension: c(n, d, nt)\n#' dim(simDat$Y)\n#' # dimension: c(n, p, ns)\n#' dim(simDat$X)\n#' # process the functional data into a data frame with columns:\n#' # predictor/response components, subject ID, and observation time\n#'\n#' Y <- t(simDat$Y[1,,])\n#' for (i in 2:n){\n#' Y <- rbind(Y, t(simDat$Y[i,,]))\n#' }\n#' Y <- data.frame(Y)\n#' Y$TIME <- rep(simDat$tseq, n)\n#' Y$ID <- rep(1:n, each = nt) # Y: nt*n rows, d+2 columns\n#' head(Y)\n#'\n#' X <- t(simDat$X[1,,])\n#' for (i in 2:n){\n#' X <- rbind(X, t(simDat$X[i,,]))\n#' }\n#' X <- data.frame(X)\n#' X$TIME <- rep(simDat$sseq, n)\n#' X$ID <- rep(1:n, each = ns) # X: ns*n rows, p+2 columns\n#' head(X)\n#'\n#' fit_func <- NRRR.func(Y, X, jx, jy, degree = 3, S.interval = NULL, T.interval = NULL,\n#' tuning = c('CV', 'BIC', 'BICP', 'AIC', 'GCV')[2],\n#' nfold = 10, norder = NULL, method = c('RRR', 'RRS')[1],\n#' lambda = 0, maxiter = 300, conv = 1e-4,\n#' dimred = c(TRUE,TRUE,TRUE), rankfix = NULL, xrankfix = NULL,\n#' yrankfix = NULL, lang = c('R', 'Rcpp')[1])\n#' @export\nNRRR.func <- function(Y, X, jx, jy, degree = 3, S.interval = NULL, T.interval = NULL,\n tuning = c('CV', 'BIC', 'BICP', 'AIC', 'GCV')[1],\n nfold = 10, norder = NULL, method = c('RRR', 'RRS')[1],\n lambda = 0, maxiter = 300, conv = 1e-4,\n dimred = c(TRUE,TRUE,TRUE), rankfix = NULL, xrankfix = NULL,\n yrankfix = NULL, lang = c('R', 'Rcpp')[1]){\n\n # X and Y are data.frames or matrices\n X <- as.data.frame(X)\n Y <- as.data.frame(Y)\n\n if(is.null(S.interval)) {\n S.interval <- range(X[, \"TIME\"])\n } else {\n filter_id <- X[, \"TIME\"] >= S.interval[1]\n filter_id <- X[filter_id, \"TIME\"] <= S.interval[2]\n X <- X[filter_id, ]\n }\n if(nrow(X) == 0) stop(\"S.interval is out of range of observed data points in X.\")\n\n\n if(is.null(T.interval)) {\n T.interval <- range(Y[, \"TIME\"])\n } else {\n filter_id <- Y[, \"TIME\"] >= T.interval[1]\n filter_id <- Y[filter_id, \"TIME\"] <= T.interval[2]\n Y <- Y[filter_id, ]\n }\n if(nrow(Y) == 0) stop(\"T.interval is out of range of observed data points in Y.\")\n\n nx <- length(unique(X[,\"ID\"]))\n p <- ncol(X) - 2\n ny <- length(unique(Y[,\"ID\"]))\n d <- ncol(Y) - 2\n if (nx != ny) stop(\"The same number of observations in predictor and response is required\")\n n <- nx\n\n\n X.list <- split(X[, which(!colnames(X)%in%c(\"ID\"))], X[, \"ID\"])\n Xint <- array(dim = c(n, p, jx), NA)\n for (i in 1:n){\n x <- X.list[[i]]\n sseq <- sort(unique(x[, \"TIME\"]))\n ns <- length(sseq)\n if (ns != dim(x)[1]) stop(\"repeated observations in X\")\n x <- x[order(x[, \"TIME\"]), ] # ns-by-p\n x <- as.matrix(x[, -which(colnames(x) == \"TIME\")])\n phi <- splines::bs(x = c(0, sseq), df = jx, degree = degree)[-1,]\n sdiff <- (sseq - c(0, sseq[-ns]))\n for (l in 1:p){\n for (j in 1:jx){\n Xint[i, l, j] <- sum(phi[, j] * x[ , l] * sdiff)\n }\n }\n }\n\n # compute Jpsi and Jpsi^{-1/2}\n tseq <- sort(unique(Y[, \"TIME\"]))\n nt <- length(tseq)\n psi <- splines::bs(x = c(0, tseq), df = jy, degree = degree)[-1,]\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 Y.list <- split(Y[, which(!colnames(Y)%in%c(\"ID\"))], Y[, \"ID\"])\n Yint <- array(dim = c(n, d, jy), NA)\n for (i in 1:n){\n y <- Y.list[[i]]\n tseq <- sort(unique(y[, \"TIME\"]))\n nt <- length(tseq)\n if (nt != dim(y)[1]) stop(\"repeated observations in Y\")\n y <- y[order(y[, \"TIME\"]), ] # nt-by-d\n y <- as.matrix(y[, -which(colnames(y) == \"TIME\")])\n psi <- splines::bs(x = c(0, tseq), df = jy, degree = degree)[-1,]\n psistar <- psi %*% Jpsihalfinv\n tdiff <- (tseq - c(0,tseq[-nt]))\n for (l in 1:d){\n for (j in 1:jy){\n Yint[i, l, j] <- sum(psistar[, j] * y[ , l] * tdiff)\n }\n }\n }\n\n # obtain matrices Y and X in matrix approximation form\n Yest <- Yint[, , 1]\n for (j in 2:jy) Yest <- cbind(Yest, Yint[, , j])\n\n Xest <- Xint[, , 1]\n for (j in 2:jx) Xest <- cbind(Xest, Xint[, , j])\n\n\n if (tuning == 'CV') {\n fit.nrrr <- NRRR.cv(Yest, Xest, nfold, norder, Ag0 = NULL, Bg0 = NULL,\n jx, jy, p, d, n, maxiter, conv, method, lambda,\n dimred, rankfix, xrankfix, yrankfix, lang)\n } else {\n fit.nrrr <- NRRR.ic(Yest, Xest, Ag0 = NULL, Bg0 = NULL,\n jx, jy, p, d, n, maxiter, conv,\n method, lambda, ic = tuning,\n dimred, rankfix, lang)\n }\n fit.nrrr$sseq <- sseq\n fit.nrrr$phi <- phi\n fit.nrrr$tseq <- tseq\n fit.nrrr$psi <- psi\n return(fit.nrrr)\n}\n\n", "meta": {"hexsha": "508a4e4bd17ababe8d08e07d55e1bac61400093f", "size": 11421, "ext": "r", "lang": "R", "max_stars_repo_path": "R/NRRR.func.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/NRRR.func.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/NRRR.func.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": 44.0965250965, "max_line_length": 124, "alphanum_fraction": 0.5925925926, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6177047560480659}} {"text": "spiral_matrix <- function(n) {\n spiralv <- function(v) {\n n <- sqrt(length(v))\n if (n != floor(n))\n stop(\"length of v should be a square of an integer\")\n if (n == 0)\n stop(\"v should be of positive length\")\n if (n == 1)\n m <- matrix(v, 1, 1)\n else\n m <- rbind(v[1:n], cbind(spiralv(v[(2 * n):(n^2)])[(n - 1):1, (n - 1):1], v[(n + 1):(2 * n - 1)]))\n m\n }\n spiralv(1:(n^2))\n}\n", "meta": {"hexsha": "2986ea859d0c3affceee11fda2407876a964a13d", "size": 468, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Spiral-matrix/R/spiral-matrix-3.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Spiral-matrix/R/spiral-matrix-3.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Spiral-matrix/R/spiral-matrix-3.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 29.25, "max_line_length": 110, "alphanum_fraction": 0.4230769231, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6176910757424757}} {"text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\r\nval <- pnorm(9800, 205 * 49, sqrt( 49 * (15 ^ 2) ))\r\nwrite(round(val, 4), stdout())", "meta": {"hexsha": "76c090e272f0c36d2d7906685eead9c0f51125bc", "size": 154, "ext": "r", "lang": "R", "max_stars_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849863.r", "max_stars_repo_name": "hermes-jr/my-hackerrank-solutions", "max_stars_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849863.r", "max_issues_repo_name": "hermes-jr/my-hackerrank-solutions", "max_issues_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "the-central-limit-theorem-1/accepted_solutions/18849863.r", "max_forks_repo_name": "hermes-jr/my-hackerrank-solutions", "max_forks_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3333333333, "max_line_length": 70, "alphanum_fraction": 0.6493506494, "num_tokens": 53, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6176910707129292}} {"text": "# 4. faza: Napredna analiza podatkov\nlibrary(ranger)\nlibrary(randomForest)\n\n\nset.seed(123)\n\n#KORELACIJA MED BDP PER CAPITA IN ŠTEVILOM VELEMOJSTROV\nvelemojstri_drzave <- velemojstri_drzave[complete.cases(velemojstri_drzave),]\nbdp_gm <- ggplot(velemojstri_drzave, aes(x=`BDP_per_capita`, y=`Stevilo_velemojstrov`)) + geom_point()\n\nlinearna1 <- lm(data = velemojstri_drzave, velemojstri_drzave$BDP_per_capita ~ velemojstri_drzave$Stevilo_velemojstrov)\n\npremica1 <- bdp_gm + geom_smooth(method = \"lm\", formula = y ~ x) +\n labs(y = \"Velemojstri\") +\n labs(x = \"BDP per capita\") +\n ggtitle(\"Korelacija med BDP per capita in velemojstri\") \n\n\n#KORELACIJA MED BDP PER CAPITA IN ŠTEVILOM VELEMOJSTROV PER CAPITA\nbdp_gm_pc <- ggplot(velemojstri_drzave, aes(x=`BDP_per_capita`, y=`Velemojstri_per_capita`)) + geom_point()\n\nlinearna2 <- lm(data = velemojstri_drzave, velemojstri_drzave$BDP_per_capita ~ velemojstri_drzave$Velemojstri_per_capita)\n\npremica2 <- bdp_gm_pc + geom_smooth(method = \"lm\", formula = y ~ x) +\n labs(y = \"Velemojstri per capita\") +\n labs(x = \"BDP per capita\") +\n ggtitle(\"Korelacija med BDP per capita in velemojstri per capita\") \n\n\n#REGRESIJA, NAPOVEDOVANJE\n\n# Datume dam v numericno obliko kot stevilo dnevov od 1/1/1970\nigre_magnus_otb_ratingi$Date.numeric = as.numeric(igre_magnus_otb_ratingi$Date)\n#igre_magnus_otb_ratingi$ID <- seq.int(nrow(igre_magnus_otb_ratingi))\n\n#4. stopnja, ker se najbolj prilega ratingu 1.2.2022\n# prileganje <- lm(Rating_Magnusa ~ poly(Date.numeric,4), data=igre_magnus_otb_ratingi) \n#napovedni_datumi <- data.frame(Date.numeric = as.numeric(as.Date(c(\"2022-02-01\",\"2022-08-01\",\"2023-02-01\", \"2023-08-01\"))))\n# \n# prediction <- mutate(napovedni_datumi, Rating_Magnusa = predict(prileganje, napovedni_datumi,interval = \"prediction\"))\n# prediction[\"Date\"] <- as.Date(as.numeric(prediction$Date.numeric), origin = \"1970-01-01\")\n# prediction <- prediction[,c(2,3,1)]\n# \n# graf_napovedi <- ggplot(igre_magnus_otb_ratingi, aes(x=Date, y=Rating_Magnusa)) + geom_point()\n# graf_napovedi\n# \n# igre_magnus_otb_ratingi <- rbind(igre_magnus_otb_ratingi, prediction)\n# \n# regresija <- igre_magnus_otb_ratingi %>%ggplot(aes(x=Date,y=Rating_Magnusa))+\n# geom_smooth(method='lm', fullrange=TRUE, color='red', formula=y ~ poly(x,4,raw=TRUE)) +\n# geom_point()\n# \n# \n# graf_napoved <- ggplot() +\n# geom_point(aes(x = Date,y = Rating_Magnusa),data=head(igre_magnus_otb_ratingi,-4),colour = '#3399ff', size=1) +\n# geom_point(aes(x = Date,y = Rating_Magnusa),data=tail(igre_magnus_otb_ratingi,4),colour = '#ff00ff', size=2) +\n# geom_smooth(data=head(igre_magnus_otb_ratingi,-3), aes(x = Date, y= Rating_Magnusa),method='lm', fullrange=TRUE, color='red', formula=y ~ poly(x,4,raw=TRUE)) +\n# xlab(label = 'Leto') +\n# ylab(label = 'Rating')\n\n\n\n#regresija\n\n#Primerjal napake različnih modelov, na koncu se odločil za naključne gozdove\n\n# formule <- c(Rating_Magnusa ~ poly(Date.numeric,1),\n# Rating_Magnusa ~ poly(Date.numeric,2),\n# Rating_Magnusa ~ poly(Date.numeric,3),\n# Rating_Magnusa ~ poly(Date.numeric,4),\n# Rating_Magnusa ~ poly(Date.numeric,5),\n# Rating_Magnusa ~ poly(Date.numeric,6),\n# Rating_Magnusa ~ poly(Date.numeric,7),\n# Rating_Magnusa ~ poly(Date.numeric,8),\n# Rating_Magnusa ~ poly(Date.numeric,9),\n# Rating_Magnusa ~ poly(Date.numeric,10))\n\n# napake <- rep(0, 15)\n# for (i in 1:15){\n# formula <- Rating_Magnusa ~ poly(Date.numeric,i)\n# model <- igre_magnus_otb_ratingi %>% ucenje(formula, \"lin.reg\")\n# napaka <- napaka_regresije(igre_magnus_otb_ratingi, model, \"lin.reg\") \n# napake[i] <- napaka\n# }\n# which.min(napake)\n# napake\n\n#lin.model <- igre_magnus_otb_ratingi %>% ucenje(Rating_Magnusa ~ poly(Date.numeric,8), \"lin.reg\")\n#lin.model\n#print(igre_magnus_otb_ratingi %>% napaka_regresije(lin.model, \"lin.reg\"))\n#pp.ratingi <- pp.razbitje(10, stratifikacija = igre_magnus_otb_ratingi)\n#pp.ratingi <- razbitje(igre_magnus_otb_ratingi,10)\n\n#print(precno.preverjanje(igre_magnus_otb_ratingi, pp.ratingi,Rating_Magnusa ~ poly(Date.numeric,11),\"lin.reg\", F))\n#precno.preverjanje(igre_magnus_otb_ratingi, pp.ratingi,Rating_Magnusa ~ poly(Date.numeric,11),\"lin.reg\", F)\n\n#ng.model <- igre_magnus_otb_ratingi %>% ucenje(Rating_Magnusa ~ Date.numeric, \"ng\")\n#napaka.ng <- igre_magnus_otb_ratingi %>% napaka_regresije(ng.model, \"ng\")\n#napaka.ng\n#p1 = predict(ng.model, data = igre_magnus_otb_ratingi)\n#head(p1)\n\n\n#prediction <- mutate(napovedni_datumi, Rating_Magnusa = predict(ng.model, data=igre_magnus_otb_ratingi))\n\n# \n# pp <- pp.razbitje(igre_magnus_otb_ratingi)\n# razbitje1 <- razbitje(igre_magnus_otb_ratingi[-2], 3)\n# pp\n# razbitje1\n#print(precno.preverjanje(igre_magnus_otb_ratingi[-2], razbitje1,Rating_Magnusa ~ Date.numeric , \"ng\", FALSE))\n\n\nratingi <- igre_magnus_otb_ratingi[,1]\nratingi\n\nLag <- function(x, n) {c(rep(NA, n), x)[1:length(x)]\n}\n\nnaredi.df <- function(x){\n data.frame(ratingi = x, ratingi1 = Lag(x,1), ratingi2 = Lag(x,2))\n}\ndf.ng <- naredi.df(c(ratingi))\ndf.ng\nmodel1 <- ranger(formula = ratingi ~ ., data = df.ng %>% drop_na())\n \nn <- nrow(df.ng)\nfor(i in 1:12) {\n df.ng <- naredi.df(c(df.ng$ratingi, NA))\n napoved <- predict(model1, data = df.ng[n+i,])$predictions\n df.ng[n+i,1] <- napoved\n}\n\nnapovedi <- df.ng[(n+1):(n+12),1] %>% round()\n\nnapovedi\nnapovedni_meseci <- c(as.Date(c(\"2022-02-01\",\"2022-04-01\",\"2022-06-01\", \"2022-08-01\",\n \"2022-10-01\",\"2022-12-01\",\"2023-02-01\", \"2023-04-01\",\n \"2023-06-01\",\"2023-08-01\",\"2023-10-01\", \"2023-12-01\")))\nratingi <- c(ratingi, napovedi)\nnapovedi.df <- data.frame(Rating_Magnusa = napovedi, Date = napovedni_meseci, Date.numeric = as.numeric(napovedni_meseci))\nigre_magnus_otb_ratingi <- rbind(igre_magnus_otb_ratingi, napovedi.df)\n\n\ngraf_napoved <- ggplot() +\n geom_point(aes(x = Date,y = Rating_Magnusa),data=head(igre_magnus_otb_ratingi,-12),colour = '#3399ff', size=0.8) +\n geom_point(aes(x = Date,y = Rating_Magnusa),data=tail(igre_magnus_otb_ratingi,12),colour = '#ff00ff', size=0.8) +\n xlab(label = 'Leto') +\n ylab(label = 'Rating')\n\ngraf_napoved\n\n\n\nratingi\n\n\n\n#Razvrščanje v skupine\nset.seed(50)\nvelemojstri_drzave$Stevilo_velemojstrov <- as.numeric(velemojstri_drzave$Stevilo_velemojstrov)\nvelemojstri_drzave$Populacija <- as.numeric(velemojstri_drzave$Populacija)\nvelemojstri_drzave$Velemojstri_per_capita <- as.numeric(velemojstri_drzave$Velemojstri_per_capita)\nvelemojstri_drzave$BDP_per_capita <- as.numeric(velemojstri_drzave$BDP_per_capita)\nvelemojstri_drzave_skupine <- scale(velemojstri_drzave[,-1])\nvelemojstri_drzave[,-1] <- velemojstri_drzave_skupine\nvelemojstri_drzave <- na.omit(velemojstri_drzave)\n\nskupine <- velemojstri_drzave[,-1] %>%\n kmeans(centers = 3) %>%\n getElement(\"cluster\") %>%\n as.ordered()\n#print(skupine)\n\nvelemojstri_drzave[\"Skupina\"] <- skupine\n#velemojstri_drzave[,2:5] <- NULL\nvelemojstri_drzave_zemljevid <- left_join(velemojstri_drzave_zemljevid, velemojstri_drzave, by=\"Drzava\")\n\n\nzemljevid4 <- tm_shape(velemojstri_drzave_zemljevid) +\n tm_fill(\"Skupina\", title = \"Razvrstitev glede na BDP, število velemojstrov in številu prebivalcev\",\n popup.vars = c(\"Skupina\" = \"Skupina\")) +\n tm_borders() +\n tm_view(view.legend.position = c(\"right\", \"bottom\"))\nzemljevid4\n\n\n\n#Preveril optimalno število skupin\nr.hc = velemojstri_drzave[, -1] %>% obrisi(hc = TRUE)\nr.km = velemojstri_drzave[, -1] %>% obrisi(hc = FALSE)\ndiagram.obrisi(r.hc)\ndiagram.obrisi(r.km)\n#Diagrama pokažeta, da sta optimalni števili 3 in 5, odločil sem se za 3, saj v primeru 5ih se pri prvem diagramu močno spustimo\n\n\n#ggpairs(igre_magnus_otb_ratingi)\n\n#datumi <- as.data.frame(as.Date(prediction$Date.numeric, \"1970-01-01\"))\n", "meta": {"hexsha": "7a2a5842922c1bd1c0a4cd10d9ee142567e64055", "size": 7763, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.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": "analiza/analiza.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": "analiza/analiza.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": 38.6218905473, "max_line_length": 163, "alphanum_fraction": 0.7171196702, "num_tokens": 2854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6176789222600775}} {"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.\nsetwd(\"your/working/directory/goes/here\")\n# Download the NBER-CES data and save it to a working directory\n# Then, read in the CSV file\nmfgdata <- read.csv(\"naics5811.csv\")\n\n# Convert columns which should be categorical variables from text\n# Also pull out NAICS sectors\nmfgdata$naicsind <- as.factor(mfgdata$naics)\nmfgdata$naicssector <- as.factor(substr(mfgdata$naics, 1, 2))\nmfgdata$yearfactor <- as.factor(mfgdata$year)\n\n# Initialize percentage changes for value-added and investment\n# Then, go through all the industries and calculate the log-return\n# (percentage change) for each industry's value-added and investment.\n# Also save last period's (lagged) percentage change in value-added.\nmfgdata$varet <- 0\nmfgdata$invret <- 0\nfor (ind in levels(mfgdata$naicsind)) {\n temp <- mfgdata[mfgdata$naicsind == ind,]\n nobs <- dim(temp)[1]\n # add one into logs to guard against zeros\n varet <- c(NA, log(temp$vadd[2:nobs]+1) - log(temp$vadd[1:(nobs-1)])+1)\n invret <- c(NA, log(temp$invest[2:nobs]+1) - log(temp$invest[1:(nobs-1)])+1)\n mfgdata[mfgdata$naicsind == ind,\"varet\"] <- varet\n mfgdata[mfgdata$naicsind == ind,\"lagvaret\"] <- c(NA, varet[1:(nobs-1)])\n mfgdata[mfgdata$naicsind == ind,\"invret\"] <- invret\n}\n\n# Some data may have been missing. Build indices to remove\n# missing data for procedures which do not handle it.\nusable.idx <- !is.na(mfgdata$invret)\nusablear.idx <- !is.na(mfgdata$laginvret)\n\n# Fit the model, summarize the data, and plot residuals\nsimple.model <- lm(invret ~ varet, data=mfgdata, weight=cap)\nsummary(simple.model)\nplot(mfgdata$year[usable.idx], residuals(simple.model), pch=\".\")\ngrid(col=\"gray\")\n\n# Do likewise for the year-slope model\nyearslope.model <- lm(invret ~ varet + varet:yearfactor,\n weight=cap, data=mfgdata)\nsummary(yearslope.model)\nplot(mfgdata$year[usable.idx], residuals(yearslope.model), pch=\".\")\ngrid(col=\"gray\")\n\n# And do this again for a model with a lagged value-added component\nyearslopear.model <- lm(invret ~ varet + lagvaret + varet:yearfactor,\n data=mfgdata, weight=cap)\nsummary(yearslopear.model)\nplot(mfgdata$year[usablear.idx], residuals(yearslopear.model), pch=\".\")\ngrid(col=\"gray\")\n", "meta": {"hexsha": "8b1b142f59b8335af4b4f9476cc4a544702f6795", "size": 2505, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch5-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/ch5-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/ch5-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": 42.4576271186, "max_line_length": 80, "alphanum_fraction": 0.7165668663, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6175552679160361}} {"text": "#' Shrinkage-based Diagonal Linear Discriminant Analysis (SDLDA)\n#'\n#' Given a set of training data, this function builds the Shrinkage-based\n#' Diagonal Linear Discriminant Analysis (SDLDA) classifier, which is based on\n#' the DLDA classifier, often attributed to Dudoit et al. (2002). The DLDA\n#' classifier belongs to the family of Naive Bayes classifiers, where the\n#' distributions of each class are assumed to be multivariate normal and to\n#' share a common covariance matrix. To improve the estimation of the pooled\n#' variances, Pang et al. (2009) proposed the SDLDA classifier which uses a\n#' shrinkage-based estimators of the pooled 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 covariance matrix are assumed to be\n#' 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\n#' `x` contain the sample observations, and the columns contain the\n#' features for each 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\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.\n#'\n#' @export\n#'\n#' @inheritParams lda_diag\n#' @param num_alphas the number of values used to find the optimal amount of\n#' shrinkage\n#' @return `lda_shrink_cov` object that contains the trained SDLDA classifier\n#'\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#' @references Pang, H., Tong, T., & Zhao, H. (2009). \"Shrinkage-based Diagonal\n#' Discriminant Analysis and Its Applications in High-Dimensional Data,\"\n#' Biometrics, 65, 4, 1021-1029.\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#' sdlda_out <- lda_shrink_cov(species ~ ., data = penguins[-pred_rows, ])\n#' predicted <- predict(sdlda_out, penguins[pred_rows, -1], type = \"class\")\n#'\n#' sdlda_out2 <- lda_shrink_cov(x = penguins[-pred_rows, -1], y = penguins$species[-pred_rows])\n#' predicted2 <- predict(sdlda_out2, penguins[pred_rows, -1], type = \"class\")\n#' all.equal(predicted, predicted2)\nlda_shrink_cov <- function(x, ...) {\n UseMethod(\"lda_shrink_cov\")\n}\n\n#' @rdname lda_shrink_cov\n#' @export\nlda_shrink_cov.default <- function(x, y, prior = NULL, num_alphas = 101, ...) {\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, y, prior, pool = TRUE)\n\n # Calculates the shrinkage-based estimator of the pooled covariance matrix.\n obj$var_shrink <- var_shrinkage(\n N = obj$N,\n K = obj$num_groups,\n var_feature = obj$var_pool,\n num_alphas = num_alphas,\n t = -1\n )\n\n # Creates an object of type 'lda_shrink_cov'\n obj$col_names <- colnames(x)\n obj <- new_discrim_object(obj, \"lda_shrink_cov\")\n\n obj\n}\n\n#' @inheritParams lda_diag\n#' @rdname lda_shrink_cov\n#' @importFrom stats model.frame model.matrix model.response\n#' @export\nlda_shrink_cov.formula <- function(formula, data, prior = NULL, num_alphas = 101, ...) {\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_cov.default(x = x, y = y, prior = prior, num_alphas = num_alphas)\n\n est$.terms <- .terms\n est <- new_discrim_object(est, class(est))\n est\n}\n\n#' Outputs the summary for a SDLDA classifier object.\n#'\n#' Summarizes the trained SDLDA classifier in a nice manner.\n#'\n#' @param x object to print\n#' @param ... unused\n#' @keywords internal\n#' @export\nprint.lda_shrink_cov <- function(x, ...) {\n cat(\"Shrinkage-based Diagonal LDA\\n\\n\")\n print_basics(x, ...)\n invisible(x)\n}\n\n#' SDLDA prediction of the class membership of a matrix of new observations.\n#'\n#' The SDLDA classifier is a modification to LDA, where the off-diagonal\n#' elements of the pooled sample covariance matrix are set to zero. To improve\n#' the estimation of the pooled variances, we use a shrinkage method from Pang\n#' et al. (2009).\n#' \n#' @rdname lda_shrink_cov\n#' @export\n#' @inheritParams predict.lda_diag\n\npredict.lda_shrink_cov <- 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_shrink) + 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_shrink, 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": "0f74f6e6f36c2de59f2b9387ad2fcea69ad4655e", "size": 6623, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lda-shrink-cov.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-cov.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-cov.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.1893491124, "max_line_length": 95, "alphanum_fraction": 0.707232372, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6174583942912728}} {"text": "beta1=-7.859 # caclulated in 11.4\r\nerror=1.090 \r\nalpha=0.05/2\r\ndf=18\r\nt.alpha=qt(1-alpha,df)\r\nprint(t.alpha)\r\n# corresponding confidence interval for the true value of beta1\r\nleft_i=beta1-t.alpha*error\r\nright_i=beta1+t.alpha*error\r\nprint(\"confidence interval\")\r\nprint(left_i)\r\nprint(right_i)\r\n", "meta": {"hexsha": "59c40d927e171e0901b305583e4bc66b7025b3ba", "size": 294, "ext": "r", "lang": "R", "max_stars_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH11/EX11.7/Ex11_7.r", "max_stars_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_stars_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH11/EX11.7/Ex11_7.r", "max_issues_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_issues_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "An_Introduction_To_Statistical_Methods_And_Data_Analysis_by_R_Lyman_Ott_And_Michael_Longnecker/CH11/EX11.7/Ex11_7.r", "max_forks_repo_name": "prashantsinalkar/R_TBC_Uploads", "max_forks_repo_head_hexsha": "b3f3a8ecd454359a2e992161844f2fb599f8238a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2020-04-07T16:44:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T06:35:28.000Z", "avg_line_length": 22.6153846154, "max_line_length": 64, "alphanum_fraction": 0.7380952381, "num_tokens": 93, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6172701211225643}} {"text": "###Spatial Bayesian regression\r\n## Author: Ying-Jung Deweese\r\n## Date: 2017-08-24\r\n## Load the libraries to be used\r\nlibrary(coda)\r\nlibrary(abind)\r\nlibrary(magic)\r\nlibrary(maps)\r\nlibrary(Matrix)\r\nlibrary(Formula)\r\nlibrary(spBayes)\r\nlibrary(MBA)\r\nlibrary(geoR)\r\nlibrary(spam)\r\nlibrary(grid)\r\nlibrary(fields)\r\nlibrary(sp)\r\nlibrary(maptools)\r\nlibrary(rgdal)\r\nlibrary(classInt)\r\nlibrary(lattice)\r\nlibrary(raster)\r\n\r\n### Read file \r\nyear = 2005\r\nfilename = sprintf(\"all_2005fok_0920.csv\", year);\r\n\r\nA=read.csv(filename,header=T)\r\n\r\n## Data preliminaries\r\n## Read data length\r\nS_num = dim(A)[2]-7\r\n\r\n\r\n## Compute the spatial Bayesian regression\r\nfor (i in 1:S_num)\r\n{\r\n\r\nprint(sprintf(\"start of loop %d\", i))\r\n\r\n## Subset data variable for elevation, rain variables\r\nbio <- A[,i+7]\r\nelv <- A[,2]\r\n\r\n\r\n## Extract the coordinates\r\ncoords <- as.matrix(A[,c(\"long\",\"lat\")])\r\n\r\n\r\np <- 2 ## This is the number of columns in the design matrix\r\n## Set the prior mean and precision for the regression\r\nbeta.prior.mean <- as.matrix(rep(0, times=p))\r\nbeta.prior.precision <- matrix(0, nrow=p, ncol=p)\r\n\r\n## For use with bayesGeostatExact, do the following\r\nphi <- 0.5 ## Set the spatial range (from the variogram)\r\nalpha <- 1600/0.5 ## Set the nugget/partial-sill ratio\r\nsigma.sq.prior.shape <- 2.0 ## Set IG shape for sigma.sq (partial sill)\r\nsigma.sq.prior.rate <- 0.5 ## Set IG scale for sigma.sq (partial sill)\r\n\r\n## Run bayesGeostatExact to deliver exact posterior samples\r\nsp.exact <- bayesGeostatExact(\r\nbio~elv,\r\ncoords=coords, n.samples=1000,\r\nbeta.prior.mean=beta.prior.mean,\r\nbeta.prior.precision=beta.prior.precision,\r\ncov.model=\"spherical\",\r\nphi=phi, alpha=alpha,\r\nsigma.sq.prior.shape=sigma.sq.prior.shape,\r\nsigma.sq.prior.rate=sigma.sq.prior.rate,\r\nsp.effects=FALSE)\r\n\r\n##Produce the posterior summaries\r\nround(summary(sp.exact$p.samples)$quantiles,3)\r\n\r\ncook=coords\r\n## Run spLM to deliver MCMC samples from marginal posterior distributions\r\nn.samples <- 1000\r\nbef.sp <- spLM(bio~elv,\r\ncoords=cook, starting=list(\"phi\"=3/200,\"sigma.sq\"=0.08,\r\n\r\n \"tau.sq\"=0.02), tuning=list(\"phi\"=0.1, \"sigma.sq\"=0.05, \"tau.sq\"=0.05),\r\n \r\n\r\npriors=list(\"phi.Unif\"=c(3/1500, 3/50), \"sigma.sq.IG\"=c(2, 0.08),\"tau.sq.IG\"=c(2, 0.02)), cov.model=\"spherical\",n.samples=n.samples)\r\n\r\nround(summary(mcmc(bef.sp$p.theta.samples))$quantiles,3)\r\n\r\n## Recover spatial residuals using spRecover\r\nburn.in <- floor(0.75*n.samples)\r\nbef.sp <- spRecover(bef.sp, start=burn.in, thin=2)\r\n\r\n## The posterior samples of the regression coefficients and the spatial effects can then be obtained as\r\nbeta.samples = bef.sp$p.beta.recover.samples\r\nw.samples = bef.sp$p.w.recover.samples\r\n\r\n## Obtain trace plots for regression coefficients\r\npar(mfrow=c(3,2))\r\nplot(beta.samples, auto.layout=TRUE, density=FALSE)\r\n\r\n## Obtain posterior means and sd's of spatial residuals for each location\r\nw.hat.mu <- apply(w.samples,1,mean)\r\nw.hat.sd <- apply(w.samples,1,sd)\r\n\r\n## Obtain OLS residuals\r\nlm.test = lm(bio~elv)\r\ntest.resid = resid(lm.test)\r\n\r\n## Plot the spatial residual mean surface and a map of sd's\r\npar(mfrow=c(1,2))\r\nsurf <- mba.surf(cbind(coords, test.resid), no.X=100, no.Y=100, extend=FALSE)$xyz.est\r\nz.lim <- range(surf[[3]], na.rm=TRUE)\r\nimage.plot(surf, xaxs = \"r\", yaxs = \"r\", zlim=z.lim, main=\"LM residuals\")\r\nsurf <- mba.surf(cbind(coords, w.hat.mu), no.X=100, no.Y=100, extend=FALSE)$xyz.est\r\nimage.plot(surf, xaxs = \"r\", yaxs = \"r\", zlim=z.lim, main=\"Mean spatial effects\")\r\n\r\n## Predictions\r\nBEF.shp <- readShapePoly(\"coastalbasinsdata.shp\")\r\nshp2poly <- BEF.shp@polygons[[1]]@Polygons[[1]]@coords\r\nBEF.poly <- as.matrix(shp2poly)\r\nBEF.grids <- readGDAL(\"all_ok_Projec.tif\")\r\n\r\n\r\n## Construct the prediction design matrix for the entire grid extent.\r\npred.covars <- cbind(BEF.grids[[\"band1\"]], BEF.grids[[\"band2\"]], BEF.grids[[\"band3\"]], BEF.grids[[\"band4\"]], BEF.grids[[\"band5\"]])\r\npred.covars <- cbind(rep(1, nrow(pred.covars)), pred.covars)\r\np=SpatialPointsDataFrame(coordinates(BEF.grids),data=BEF.grids@data) # convert spatialgrid dataframe to spatial point dataframe\r\n\r\n## Extract the coordinates of the BEF bounding polygon vertices and use the pointsInPoly (spBayes) function to obtain the desired subset of the prediction design matrix and associated prediction coordinates (i.e., pixel centroids).\r\npred.coords <- SpatialPoints(BEF.grids)@coords\r\npointsInPolyOut <- pointsInPoly(BEF.poly, pred.coords)\r\npred.coords <- pred.coords[pointsInPolyOut,]\r\npred.covars <- p[pointsInPolyOut,]\r\n#convert spdf to matrix\r\nDF <- as.matrix(pred.covars@data)\r\nDF <- cbind(rep(1, nrow(DF)), DF)# generate 2 column\r\nbef.bio.pred <- spPredict(bef.sp, start=burn.in, thin=2, pred.coords=pred.coords, pred.covars=DF)\r\n\r\n## Mapping the predicted values\r\nbef.bio.pred.mu = apply(bef.bio.pred$p.y.predictive.samples,1,mean)\r\nbef.bio.pred.sd = apply(bef.bio.pred$p.y.predictive.samples,1,sd)\r\nsurf <- mba.surf(cbind(coords,bio), no.X=500, no.Y=500, extend=TRUE, sp=TRUE)$xyz.est\r\n\r\n\r\n## write out raster\r\n\r\nras3_name = sprintf(\"All_%d-S%d_spBayes.tif\", year, i)\r\nwriteGDAL(surf, ras3_name, drivername=\"GTiff\", options=NULL)\r\n\r\n}\r\n", "meta": {"hexsha": "fca1c5e0e9570658745066b3459bbea96fda63bd", "size": 5130, "ext": "r", "lang": "R", "max_stars_repo_path": "Univariate_Spatial_Regression_rev.r", "max_stars_repo_name": "hydrogeohc/point_based_interpolated", "max_stars_repo_head_hexsha": "386afff369c9009a40315e9552b03381cd377b6c", "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": "Univariate_Spatial_Regression_rev.r", "max_issues_repo_name": "hydrogeohc/point_based_interpolated", "max_issues_repo_head_hexsha": "386afff369c9009a40315e9552b03381cd377b6c", "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": "Univariate_Spatial_Regression_rev.r", "max_forks_repo_name": "hydrogeohc/point_based_interpolated", "max_forks_repo_head_hexsha": "386afff369c9009a40315e9552b03381cd377b6c", "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.9735099338, "max_line_length": 232, "alphanum_fraction": 0.7007797271, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6170415813532583}} {"text": "#The law of Large Numbers\r\n\r\n#The rnorm() function in R generates a random number using a normal(bell curve) distribution.\r\n#It takes the sample size as Input and generate that many random numbers.\r\n\r\n#E(x) = 68.2 or 0.682 \r\n#Try N = input(10, 100, 1000, 10000....)\r\n\r\n#Begin\r\nN <- 1000\r\ncounter <- 0\r\nfor (i in rnorm(N)){\r\n if(i> -1 & i <1){\r\n counter <- counter +1 \r\n \r\n }\r\n}\r\n\r\nanswer <- counter/N *100\r\nanswer \r\n\r\n#END\r\n", "meta": {"hexsha": "f0be24ce12c83c5ee45c994d451459e82fa30e97", "size": 430, "ext": "r", "lang": "R", "max_stars_repo_path": "Law_Of_Large_Numbers/lawoflargenumbers.r", "max_stars_repo_name": "doddanikhil/Data-Analytics", "max_stars_repo_head_hexsha": "15cd81c20ca4f592871561abe6717a19df6b18fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Law_Of_Large_Numbers/lawoflargenumbers.r", "max_issues_repo_name": "doddanikhil/Data-Analytics", "max_issues_repo_head_hexsha": "15cd81c20ca4f592871561abe6717a19df6b18fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Law_Of_Large_Numbers/lawoflargenumbers.r", "max_forks_repo_name": "doddanikhil/Data-Analytics", "max_forks_repo_head_hexsha": "15cd81c20ca4f592871561abe6717a19df6b18fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6956521739, "max_line_length": 94, "alphanum_fraction": 0.6139534884, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067222797121, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6169461957686324}} {"text": "vsa=function(fun,par.mins,par.maxs,nrun){\r\n par.range = par.maxs - par.mins\r\n k=length(par.range)\r\n M = array(runif(nrun*k),dim=c(nrun,k)) #CREATE U(0,1) n x k MATRIX\r\n for (i in 1:k) M[,i] = M[,i] * par.range[i] + par.mins[i] #TRANSFORM TO FIT RANGE OF EACH PAR\r\n\r\n #Now we are going to make a different input matrix, M2, the same way\r\n M2 = array(runif(nrun*k),dim=c(nrun,k)) #CREATE U(0,1) n x k MATRIX\r\n for (i in 1:k) M2[,i] = M2[,i] * par.range[i] + par.mins[i] #TRANSFORM TO FIT RANGE OF EACH PAR\r\n\r\n #Now we are going to make K different matrices, where in the jth matrix, all parameters are taken from M2 except parameter j is taken from M\r\n NJ.list = list()\r\n for (j in 1:k) {\r\n temp = M2\r\n temp[,j] = M[,j]\r\n NJ.list[[j]] = temp\r\n }\r\n\r\n #Now, to compute the first-order effects (S) of factor J, we need to compute the values UJ, as discussed in class\r\n S = numeric(length=k)\r\n ST = numeric(length=k)\r\n y1 = y2 = y3 = numeric(length = nrun)\r\n for (i in 1:nrun) {\r\n y1[i] = fun(M[i,])\r\n y2[i] = fun(M2[i,])\r\n }\r\n #Now to compute the expected value (EY) and total variance (VY) of Y, for which we will use M2\r\n EY=mean(y1)\r\n # VY=var(y3)\r\n #For computational reasons, we will estimate EY^2 using both M and M2\r\n # EY2=mean(y1*y2)\r\n# EY2=EY^2\r\n VY=sum(y1*y1)/(nrun-1)-EY^2\r\n\r\n for (j in 1:k) {\r\n NJ = NJ.list[[j]]\r\n for (i in 1:nrun) y3[i] = fun(NJ[i,])\r\n UJ = sum(y1*y3) / (nrun-1) #here everything but factor j is resampled\r\n UJ2 = sum(y2*y3) / (nrun-1) #here only factor j is resampled\r\n S[j] = (UJ - EY^2) / VY\r\n ST[j] = 1.0 - (UJ2 - EY^2) / VY\r\n }\r\n\r\n list(S,ST)\r\n}", "meta": {"hexsha": "75cb6e5dbd826cc45e648c7e09dd803b1bca1da4", "size": 1649, "ext": "r", "lang": "R", "max_stars_repo_path": "courses/ess-211/course_material/vsa.r", "max_stars_repo_name": "christobal54/aei-grad-school", "max_stars_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "courses/ess-211/course_material/vsa.r", "max_issues_repo_name": "christobal54/aei-grad-school", "max_issues_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "courses/ess-211/course_material/vsa.r", "max_forks_repo_name": "christobal54/aei-grad-school", "max_forks_repo_head_hexsha": "ea5be566d810ca9d792625b2e97acd2065c9d09a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-08T05:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-08T05:41:45.000Z", "avg_line_length": 36.6444444444, "max_line_length": 143, "alphanum_fraction": 0.5912674348, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6169106357920578}} {"text": "########################################################################\n# #\n# lib/finite-group.rb #\n# #\n########################################################################\n=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Algebra::OperatorDomain\n\nThis is the module for the set oprated by groups.\nThis is included by (()).\n\n== File Name:\n* ((|finite-group.rb|))\n\n== Methods:\n\n--- right_act(other)\n Returns the products of ((|self|)) and ((|other|)), i.e.\n ((|Set|)) of (({x * y})) for\n ((|x|)) element of ((|self|)) and ((|y|)) element of ((|other|)).\n\n--- act\n Alias of (()).\n\n--- left_act(other)\n Returns the products of ((|self|)) and ((|other|)), i.e.\n ((|Set|)) of (({y * x})) for\n ((|x|)) element of ((|self|)) and ((|y|)) element of ((|other|)).\n\n--- right_quotient(other)\n Returns the ((|Set|)) of right residue classes\n of ((|self|)) by ((|other|)). \n\n--- quotient\n--- right_coset\n--- coset\n Alias of (()).\n\n--- left_quotient(other)\n Returns the ((|Set|)) of left residue classes\n of ((|self|)) by ((|other|)). \n\n--- left_coset\n Alias of (()).\n\n--- right_representatives(other)\n Returns the representatives of the\n right residue classes (()).\n\n--- representatives\n Alias of (()).\n\n--- left_representatives(other)\n Returns the representatives of the\n left residue classes (()).\n\n--- right_orbit!(other)\n Extends ((|self|)) operating the elements of ((|other|)) by right action\n ((|*|)).\n\n--- orbit!\n Alias of (()).\n\n--- left_orbit!(other)\n Extends ((|self|)) operating the elements of ((|other|)) by left action\n ((|*|)).\n \n= Algebra::Set\n\n== File Name:\n* ((|finite-group.rb|))\n\n== Included Module:\n\n* ((|OperatorDomain|))\n\n== Methods:\n\n--- * act\n Alias of (())\n\n--- /\n Alias of (()).\n\n--- %\n Alias of (()).\n\n--- increasing_series([x])\n Returns the increasing series begining with ((|x|)).\n This is equivalent to the following code:\n\n def increasing_series(x = unit_group)\n a = []\n loop do\n a.push x\n if x >= (y = yield x)\n break\n end\n x = y\n end\n a\n end\n\n--- decreasing_series([x])\n Returns the decreasing series begining with ((|x|)).\n This is equivalent to the following code:\n\n def decreasing_series(x = self)\n a = []\n loop do\n a.push x\n if x <= (y = yield x)\n break\n end\n x = y\n end\n a\n end\n\n= Algebra::Group\n\n== File Name:\n* ((|finite-group.rb|))\n\n== SuperClass:\n* ((|Set|))\n\n== Included Module:\n(None)\n\n== Class Methods:\n\n--- ::new(u, [g0, g1, ...]])\n Returns the group which consists of ((|u|)), ((|g0|)), ((|g1|)), ... \n and whose unity is ((|u|)).\n\n--- ::generate_strong(u, [g0, [g1, ...]])\n Returns the group strongly generated by ((|g0|)), ((|g1|)), ... \n and whose unity is ((|u|)).\n\n== Methods:\n\n--- quotient_group(u)\n Returns the residue class group of the normal subgroup ((|u|)).\n\n--- separate\n Returns the subgroup whose elements makes the block true.\n\n--- to_a\n Returns the array of elements. The first is the unity.\n\n--- unity\n Returns the unity.\n\n--- unit_group\n Returns the unit group.\n\n--- semi_complete!\n Makes ((|self|)) be the semi-group generated by the elements.\n\n--- semi_complete\n Returns the semi-group generated by the elements.\n\n--- complete!\n Makes ((|self|)) be the semi-group generated by the elements.\n\n--- complete\n Returns the group generated by the elements.\n\n--- closed?\n Returns true when ((|self|)) is closed by product and inverse.\n\n--- subgroups\n Returns the all subgroups.\n\n--- centralizer(s)\n Returns the centralize of ((|s|)) in ((|self|)).\n\n--- center\n Returns the center of((|self|)).\n\n--- center?(x)\n Returns true if ((|x|)) is in the center of ((|self|)).\n\n--- normalizer(s)\n Returns the normalizer of ((|s|)) in ((|self|)).\n\n--- normal?(s)\n Returns true if ((|s|)) is a normal subgroup of ((|self|)).\n\n--- normal_subgroups\n Returns the all normal subgroups.\n\n--- conjugacy_class(x)\n Returns the conjugacy class of the element ((|x|)).\n\n--- conjugacy_classes\n Returns the set of all conjucacy claases of ((|self|)).\n\n--- simple?\n Retuns true if ((|self|)) is a simple group.\n\n--- commutator([h])\n Returns the commutator subgroup of ((|self|)) and ((|h|)).\n If the parameter is omitted, ((|h|)) is assumed to be ((|self|)).\n\n--- D([n])\n Returns the ((|n|))-the commutator subgroup.\n (({D(0) = self})) and (({D(n+1) = [D[n], D[n]]})).\n If the parameter ommitted, ((|n|)) is assumed to be 1.\n\n--- commutator_series\n Returns the array (({[D(0), D(1), D(2),..., D(n)]})) .\n This sequence is terminated for ((|n|)) with (({D(n) == D(n+1)})).\n\n--- solvable?\n Returns true if ((|self|)) is solvable.\n\n--- K([n])\n Returns the subgroup definend such that (({K(0) = self})) and\n (({K(n+1) = [self, K[n]})).\n If the parameter is omitted, ((|n|)) is asumed to be 1.\n\n--- descending_central_series\n Returns the descending central series:\n (({[K(0), K(1), K(2),..., K(n)]})).\n This sequence is terminated for ((|n|)) with (({K(n) == K(n+1)})).\n\n--- Z([n])\n Returns the subgroup that defined by: (({Z(0) = unit group})),\n (({Z(n+1) = separate{|x| commutator(Set[x]) <= Z(n-1)}})) .\n If the parameter is omitted, ((|n|)) is assumed to be 1.\n\n--- ascending_central_series\n Returns the array of ascending central series:\n (({[Z(0), Z(1), Z(2),..., Z(n)]})).\n This sequence is terminated for ((|n|)) such that\n (({Z(n) == Z(n+1)})).\n\n--- nilpotent?\n Returns true if ((|self|)) is nilpotent.\n\n--- nilpotency_class\n Returns the class of nilpotency.\n If ((|self|)) is not nilpotent, returns nil.\n\n= Algebra::QuotientGroup\n\n== File Name:\n* ((|finite-group.rb|))\n\n== SuperClass:\n* ((|Group|))\n\n== Class Methods:\n--- new(u, [g0, [g1,...]])\n Returns the residue class group by ((|u|)) of which the residues are\n ((|u|)), ((|g0|)), ((|g1|)), ... Here ((|u|)) is assumed to be\n the normal subgroup of ((|self|)).\n \n\n== Methods:\n\n--- inverse\n Returns the inverse element.\n\n--- inv\n Alias of (()).\n=end\n\n", "meta": {"hexsha": "f6192182ad4ed70df7dab7bdb446fe9c72f76958", "size": 6605, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc/finite-group.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/finite-group.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/finite-group.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5892857143, "max_line_length": 76, "alphanum_fraction": 0.5409538229, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6168419072589547}} {"text": "getZ = function() {\n return((as.numeric(rawScore) - as.numeric(mean)) / as.numeric(sd))\n}\n\ngetT = function(z) {\n return(z*10+50)\n}\n\ngetStanine = function(z) {\n stanine = round(z*2+5)\n stanine = min(max(stanine, 1), 9)\n return(stanine)\n}\n\ngetSten = function(z) {\n sten = round(z*2+5.5)\n sten = min(max(sten, 1), 10)\n return(sten)\n}\n\ngetIq = function(z) {\n return(z*15+100)\n}\n\ngetPercentile = function(z) {\n return(pnorm(z)*100)\n}\n\ngetPercentileRange = function() {\n ranges = NULL\n score = NULL\n if(scoreType == \"percentileRanges\") {\n rangesList = fromJSON(percentileRanges)\n if(length(rangesList) > 0) {\n for(i in 1:length(rangesList)) {\n ranges = rbind(ranges, data.frame(rangesList[[i]], stringsAsFactors=F))\n }\n }\n }\n if(scoreType == \"percentileRangesTable\") {\n rangesTable = fromJSON(percentileRangesTable)\n sql = \"SELECT \n{{lowerBoundColumn}} AS lowerBound,\n{{upperBoundColumn}} AS upperBound,\n{{scoreColumn}} AS score\nFROM {{table}}\"\n ranges = concerto.table.query(sql, params=list(\n lowerBoundColumn=rangesTable$columns$lowerBound,\n upperBoundColumn=rangesTable$columns$upperBound,\n scoreColumn=rangesTable$columns$score,\n table=rangesTable$table\n ))\n }\n\n if(dim(ranges)[1] > 0) {\n for(i in 1:dim(ranges)[1]) {\n range = ranges[i,]\n range$lowerBound = as.numeric(range$lowerBound)\n range$upperBound = as.numeric(range$upperBound)\n if(!is.na(range$lowerBound) && range$lowerBound > as.numeric(rawScore)) { next }\n if(!is.na(range$upperBound) && range$upperBound <= as.numeric(rawScore)) { next }\n score = as.numeric(range$score)\n }\n }\n \n return(score)\n}\n\nscore = switch(scoreType, \n \"zScore\" = getZ(),\n \"tScore\" = getT(getZ()),\n \"stanine\" = getStanine(getZ()),\n \"sten\" = getSten(getZ()),\n \"iq\" = getIq(getZ()),\n \"percentile\" = getPercentile(getZ()),\n \"percentileRanges\" = getPercentileRange(),\n \"percentileRangesTable\" = getPercentileRange(),\n \"custom\" = eval(parse(text=customScoreFormula)),\n \"rawScore\" = as.numeric(rawScore),\n as.numeric(rawScore)\n )\n\nfeedback = NULL\nif(feedbackType != \"none\") {\n ranges = NULL\n if(feedbackType == \"ranges\") {\n rangesList = fromJSON(feedbackRanges)\n if(length(rangesList) > 0) {\n for(i in 1:length(rangesList)) {\n ranges = rbind(ranges, data.frame(rangesList[[i]], stringsAsFactors=F))\n }\n }\n }\n if(feedbackType == \"rangesTable\") {\n rangesTable = fromJSON(feedbackRangesTable)\n sql = \"SELECT \n{{lowerBoundColumn}} AS lowerBound,\n{{upperBoundColumn}} AS upperBound,\n{{feedbackColumn}} AS feedback\nFROM {{table}}\"\n ranges = concerto.table.query(sql, params=list(\n lowerBoundColumn=rangesTable$columns$lowerBound,\n upperBoundColumn=rangesTable$columns$upperBound,\n feedbackColumn=rangesTable$columns$feedback,\n table=rangesTable$table\n ))\n }\n\n if(!is.null(ranges) && dim(ranges)[1] > 0) {\n for(i in 1:dim(ranges)[1]) {\n range = ranges[i,]\n range$lowerBound = as.numeric(range$lowerBound)\n range$upperBound = as.numeric(range$upperBound)\n if(!is.na(range$lowerBound) && range$lowerBound > score) { next }\n if(!is.na(range$upperBound) && range$upperBound <= score) { next }\n feedback = range$feedback\n }\n }\n}", "meta": {"hexsha": "0292dfff88c8f59910a9c57f12cb8f5942b2eeb8", "size": 3426, "ext": "r", "lang": "R", "max_stars_repo_path": "src/Concerto/PanelBundle/Resources/starter_content/src/test/_scoring/_scoring.r", "max_stars_repo_name": "josenorberto/concerto-platform", "max_stars_repo_head_hexsha": "bef2128fb5c6d295b2acae150a7e04c6aebc43e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 138, "max_stars_repo_stars_event_min_datetime": "2016-04-01T15:25:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:24:41.000Z", "max_issues_repo_path": "src/Concerto/PanelBundle/Resources/starter_content/src/test/_scoring/_scoring.r", "max_issues_repo_name": "kaurmanrajn/concerto-platform", "max_issues_repo_head_hexsha": "e9e2b4aac587a97f1cc0ef8080b84b9b0aee1639", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 323, "max_issues_repo_issues_event_min_datetime": "2016-05-29T22:39:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T12:14:30.000Z", "max_forks_repo_path": "src/Concerto/PanelBundle/Resources/starter_content/src/test/_scoring/_scoring.r", "max_forks_repo_name": "kaurmanrajn/concerto-platform", "max_forks_repo_head_hexsha": "e9e2b4aac587a97f1cc0ef8080b84b9b0aee1639", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 97, "max_forks_repo_forks_event_min_datetime": "2016-04-07T20:43:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T15:24:47.000Z", "avg_line_length": 28.7899159664, "max_line_length": 87, "alphanum_fraction": 0.6228838295, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6167834124699214}} {"text": "malthus <- function(initial_time, initial_population, time_interval, N, growth_rate) {\n time <- initial_time\n population <- initial_population\n times <- c(time)\n populations <- c(population)\n for(i in 1:N) {\n population <- population + growth_rate*time_interval*population\n time <- time + time_interval\n times <- c(times, time)\n populations <- c(populations, population)\n }\n\n return(data.frame(times, populations))\n}\n\nplot(malthus(1900, 76.2, 1, 300, 0.013))\n", "meta": {"hexsha": "5cfb3ccc22d228b14c363a921eb560645e52654b", "size": 508, "ext": "r", "lang": "R", "max_stars_repo_path": "malthus.r", "max_stars_repo_name": "janisz/bioinformatics", "max_stars_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "malthus.r", "max_issues_repo_name": "janisz/bioinformatics", "max_issues_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "malthus.r", "max_forks_repo_name": "janisz/bioinformatics", "max_forks_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_forks_repo_licenses": ["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.8823529412, "max_line_length": 86, "alphanum_fraction": 0.657480315, "num_tokens": 126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6165920650290835}} {"text": "### Reference implementations. Fairly direct translations from the paper\n\n.alldist = function(d, x) sapply(1:nrow(x), function(i) sum((d-x[i, ])^2))\n\n.fastmap = function(x)\n{\n d_i = sample(nrow(x), size=1)\n d = x[d_i, ]\n \n dists = .alldist(d, x)\n a_i = which.max(dists)\n a = x[a_i, ]\n \n dists = .alldist(a, x)\n b_i = which.max(dists)\n b = x[b_i, ]\n \n list(a=a, b=b)\n}\n\n.cma = function(x, k)\n{\n n = ncol(x)\n \n for (i in 1:k)\n {\n x.i = x[, i:n, drop=FALSE]\n ab = .fastmap(x.i)\n \n x.i = sweep(x.i, MARGIN=2, STATS=ab$a, FUN=\"-\")\n \n w = matrix(ab$b - ab$a)\n v = w\n v[1] = w[1] + sign(w[1]) * norm(w, \"2\")\n v = v / norm(v, \"2\")\n y = x.i %*% v\n x[, i:n] = x.i - tcrossprod(2*y, v)\n }\n \n x[, 1:k, drop=FALSE]\n}\n", "meta": {"hexsha": "6d57465a139cf85efc0aa1e4b8ccc764cdd0a88d", "size": 756, "ext": "r", "lang": "R", "max_stars_repo_path": "R/reference.r", "max_stars_repo_name": "wrathematics/fastmap", "max_stars_repo_head_hexsha": "bdee0e043fced0cfe1106b53484ade24758eb993", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-08-06T23:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-13T07:06:01.000Z", "max_issues_repo_path": "R/reference.r", "max_issues_repo_name": "wrathematics/fastmap", "max_issues_repo_head_hexsha": "bdee0e043fced0cfe1106b53484ade24758eb993", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/reference.r", "max_forks_repo_name": "wrathematics/fastmap", "max_forks_repo_head_hexsha": "bdee0e043fced0cfe1106b53484ade24758eb993", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 74, "alphanum_fraction": 0.496031746, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6165920611581762}} {"text": "#\n# Test package against LV dynamics \n#\n\nrequire(deSolve)\nrequire(ggplot2)\nrequire(tidyr)\nrequire(tibble)\n# \n#\n\n\nparms <- tibble::tribble(\n ~a1, ~a2, ~a3, ~a4, ~a5, ~a6, ~r,\n 0, 4e-6, 3e-5, 2e-5, 0, 0, -0.01,\n-1e-5, -1e-4, 0, 1e-4, 6e-5, 0, -0.001,\n-1e-4, 0, 0, 0, 6e-5, 5e-5, -0.01,\n-1e-4, 1e-4, 0, -5e-4, -1e-5, 0, 0.08,\n 0, -1e-4,-1e-4, 0, -1e-6, 0, 0.04,\n 0, 0,-1e-4, 2e-4, 0, 0, 0.00\n)\n\n# Solve for equilibrium populations\n#\neq <- lm(r ~ . + 0, parms)\n-coef(eq)\n\n\n\n# Generalized Lotka-Volterra 6 species equation \n#\nGLV_det<-function(Time,State,Pars){\n with(as.list(c(State, Pars)), {\n A <- matrix(Pars,6,7)\n dP1 <- N1*(A[1,7]+A[1,1]*N1+A[1,2]*N2+A[1,3]*N3+A[1,4]*N4+A[1,5]*N5+A[1,6]*N6) \n dP2 <- N2*(A[2,7]+A[2,1]*N1+A[2,2]*N2+A[2,3]*N3+A[2,4]*N4+A[2,5]*N5+A[2,6]*N6)\n dP3 <- N3*(A[3,7]+A[3,1]*N1+A[3,2]*N2+A[3,3]*N3+A[3,4]*N4+A[3,5]*N5+A[3,6]*N6)\n dP4 <- N4*(A[4,7]+A[4,1]*N1+A[4,2]*N2+A[4,3]*N3+A[4,4]*N4+A[4,5]*N5+A[4,6]*N6)\n dP5 <- N5*(A[5,7]+A[5,1]*N1+A[5,2]*N2+A[5,3]*N3+A[5,4]*N4+A[5,5]*N5+A[5,6]*N6)\n dP6 <- N6*(A[6,7]+A[6,1]*N1+A[6,2]*N2+A[6,3]*N3+A[6,4]*N4+A[6,5]*N5+A[6,6]*N6)\n \n return(list(c(dP1,dP2,dP3,dP4,dP5,dP6)))\n })\n}\n\n# Simulate the model by integration\n#\npars <- c(A <- as.matrix(parms[,1:6]),\n r<- as.numeric(parms$r)\n) \n\nyini <- c(N1 = 100,N2=100,N3=100,N4=100,N5=100,N6=100)\nout <- as.data.frame(ode(yini, 1:600, GLV_det, pars))\ndf <- gather(out,key=\"Species\",value=\"N\", -time)\nggplot(df, aes(time,N,colour=Species)) + geom_line(size=.5)\n\nA <- as.matrix(parms[,1:6])\nr<- as.numeric(parms$r)\nm <- c(0,0,0,0,0,0)\n#NumericMatrix metaW,NumericVector m, NumericVector r, NumericVector ini, int time, double tau=0.01)\nA1 <- metaWebNetAssemblyGLV(A,m,r,yini,1000,0.1)\ndf1 <- as.data.frame(t(A1$STime))\ndf1$time <- 1:1000\nA1 <- metaWebNetAssemblyGLV(A,m,r,yini,1000,0.1)\ndf2 <- as.data.frame(t(A1$STime))\ndf2$time <- 1:1000\n\ndf1 <- rbind(df1,df2 )\n\n\nnames(df1)[1:6] <- unique(df$Species) \nrequire(tidyr)\ndf1 <- gather(df1,key=\"Species\",value=\"N\", N1:N6)\nrequire(ggplot2)\nggplot(df, aes(time,N,colour=Species)) + geom_line() + geom_point(data=df1,aes(time,N,colour=Species),size=0.1) + theme_bw() + scale_color_viridis_d()\n\nggplot(df1, aes(time,N,colour=Species)) + geom_point(size=0.1) + theme_bw() + scale_color_viridis_d()\n\n#\n# LV with migration\n#\n\nparms <- tibble::tribble(\n ~a1, ~a2, ~a3, ~a4, ~a5, ~a6, ~r, ~m,\n 0, 4e-6, 3e-5, 2e-5, 0, 0, -0.01, 0.1,\n-1e-5, -1e-4, 0, 1e-4, 6e-5, 0, -0.001, 0.1,\n-1e-4, 0, 0, 0, 6e-5, 5e-5, -0.01, 0.1,\n-1e-4, 1e-4, 0, -5e-4, -1e-5, 0, 0.08, 0.1,\n 0, -1e-4,-1e-4, 0, -1e-6, 0, 0.04, 0.1,\n 0, 0,-1e-4, 2e-4, 0, 0, 0.00, 0.1\n)\n\n# Generalized Lotka-Volterra with migration 6 species equation \n#\nGLVM_det<-function(Time,State,Pars){\n with(as.list(c(State, Pars)), {\n A <- matrix(Pars,6,8)\n dP1 <- N1*(A[1,7]+A[1,1]*N1+A[1,2]*N2+A[1,3]*N3+A[1,4]*N4+A[1,5]*N5+A[1,6]*N6)+A[1,8] \n dP2 <- N2*(A[2,7]+A[2,1]*N1+A[2,2]*N2+A[2,3]*N3+A[2,4]*N4+A[2,5]*N5+A[2,6]*N6)+A[2,8]\n dP3 <- N3*(A[3,7]+A[3,1]*N1+A[3,2]*N2+A[3,3]*N3+A[3,4]*N4+A[3,5]*N5+A[3,6]*N6)+A[3,8]\n dP4 <- N4*(A[4,7]+A[4,1]*N1+A[4,2]*N2+A[4,3]*N3+A[4,4]*N4+A[4,5]*N5+A[4,6]*N6)+A[4,8]\n dP5 <- N5*(A[5,7]+A[5,1]*N1+A[5,2]*N2+A[5,3]*N3+A[5,4]*N4+A[5,5]*N5+A[5,6]*N6)+A[5,8]\n dP6 <- N6*(A[6,7]+A[6,1]*N1+A[6,2]*N2+A[6,3]*N3+A[6,4]*N4+A[6,5]*N5+A[6,6]*N6)+A[6,8]\n \n return(list(c(dP1,dP2,dP3,dP4,dP5,dP6)))\n })\n}\n\npars <- as.matrix(parms)\nyini <- c(N1 = 0,N2=0,N3=0,N4=0,N5=0,N6=0)\nout <- as.data.frame(ode(yini, 1:600, GLVM_det, pars))\ndf <- gather(out,key=\"Species\",value=\"N\", -time)\nggplot(df, aes(time,N,colour=Species)) + geom_line(size=.5)\ncalcPropInteractionsGLVadjMat(A1$interM,A2$STime[,600])\n\n\nA <- as.matrix(parms[,1:6])\nr<- as.numeric(parms$r)\nm <-as.numeric(parms$m)\n#NumericMatrix metaW,NumericVector m, NumericVector r, NumericVector ini, int time, double tau=0.01)\nA1 <- metaWebNetAssemblyGLV(A,m,r,yini,600,0.1)\ndf1 <- as.data.frame(t(A1$STime))\ndf1$time <- 1:600\nA1 <- metaWebNetAssemblyGLV(A,m,r,yini,600,0.1)\ndf2 <- as.data.frame(t(A1$STime))\ndf2$time <- 1:600\n\ndf1 <- rbind(df1,df2 )\n\n\nnames(df1)[1:6] <- unique(df$Species) \nrequire(tidyr)\ndf1 <- gather(df1,key=\"Species\",value=\"N\", N1:N6)\nrequire(ggplot2)\nggplot(df, aes(time,N,colour=Species)) + geom_line() + geom_point(data=df1,aes(time,N,colour=Species),size=0.1) + theme_bw() + scale_color_viridis_d()\n\n#\n# Generate random adjacency matrix \n#\nrequire(igraph)\n\n#### ER random graph\nbuild.random.structure <- function(n, connectance){\n S <- matrix(0, nrow = n, ncol = n)\n S[upper.tri(S)] <- rbinom(n * (n - 1)/2,size = 1, p = connectance)\n S[lower.tri(S)] <- rbinom(n * (n - 1)/2,size = 1, p = connectance)\n #S <- S + t(S)\n #diag(S) <- 0\n return(S) \n}\n\n\n#\n# Size 106, links 4623\n#\nrequire(multiweb)\n\nC <- 4623/(106*106)\n\n#\n# Generate random GLV matrix\n#\n\nA <- generateRandomGLVadjMat(100,0.01,c(0.3,0.3,0.3,0.05,0.05)) \nA1 <- generateGLVparmsFromAdj(A,0.01,0.01)\nyini <- rep(10,times=nrow(A1$interM))\ncalcPropInteractionsGLVadjMat(A ,yini)\n\nyini <- rep(0,times=nrow(A1$interM))\nA2 <- metaWebNetAssemblyGLV(A1$interM,A1$m,A1$r,yini,600,0.1)\nA2$STime[,600]\ndf1 <- as.data.frame(t(A2$STime))\ndf1$time <- 1:600\nrequire(tidyr)\nrequire(ggplot2)\nrequire(dplyr)\ndf1 <- gather(df1,key=\"Species\",value=\"N\", -time)\nggplot(filter(df1,time>500), aes(time,N,colour=Species)) + geom_line() + theme_bw() + scale_color_viridis_d(guide=FALSE) \nggplot(df1, aes(time,N,colour=Species)) + geom_line() + theme_bw() + scale_color_viridis_d(guide=FALSE) \n\ndf1 <- data_frame(time=1:600,S = A2$S,C = A2$L/(A2$S*A2$S))\nggplot(filter(df1,time>500), aes(time,S)) + geom_line() + theme_bw() + scale_color_viridis_d() \nggplot(df1, aes(time,S)) + geom_line() + theme_bw() + scale_color_viridis_d() \n\nggplot(filter(df1,time>500), aes(time,C)) + geom_line() + theme_bw() + scale_color_viridis_d() \nggplot(df1, aes(time,C)) + geom_line() + theme_bw() + scale_color_viridis_d() \nggplot(df1, aes(S,C)) + geom_line() + theme_bw() + scale_color_viridis_d() \n\ncalcPropInteractionsGLVadjMat(A1$interM,A2$STime[,600])\n\n# With no migration \nyini <- rep(100,times=nrow(A1$interM))\nA1$m <- rep(0.0, 100)\nA2 <- metaWebNetAssemblyGLV(A1$interM,A1$m,A1$r,yini,600,0.1)\nA2$STime[,600]\ndf1 <- as.data.frame(t(A2$STime))\ndf1$time <- 1:600\nrequire(tidyr)\nrequire(ggplot2)\nrequire(dplyr)\ndf1 <- gather(df1,key=\"Species\",value=\"N\", -time)\nggplot(df1, aes(time,N,colour=Species)) + geom_line() + theme_bw() + scale_color_viridis_d(guide=FALSE) \n\ncalcPropInteractionsGLVadjMat(A1$interM,A2$STime[,600])\n\n\n#\n# To igraph\n#\nrequire(multiweb)\nrequire(igraph)\ndiag(A2$A) <- 0\ng <- graph_from_adjacency_matrix(A2$A,mode=\"directed\")\nplotTrophLevel(g,modules=TRUE)\ncalcTopologicalIndices(g)\n\n#\n# More testing\n#\n\nA <- generateRandomGLVadjMat(100,0.05,c(0.2,0.5,0.1,0.0,0.0)) \nA\nA1 <- generateGLVparmsFromAdj(A,0.1,0.01)\n\nyini <- rep(1,times=nrow(A1$interM))\n\ncalcPropInteractionsGLVadjMat(A1$interM,yini)\n\nA2 <- metaWebNetAssemblyGLV(A1$interM,A1$m,A1$r,yini,100,0.1)\n\ndf <- as.data.frame(t(A2$STime))\ndf$Time <- 1:100\nrequire(tidyr)\ndf <- gather(df,key=\"Species\",value=\"N\", V1:V100)\nrequire(ggplot2)\nggplot(df, aes(Time,N,colour=Species)) + geom_line() +guides(colour=FALSE)\n\ncalcPropInteractionsGLVadjMat(A1$interM,A2$STime[,100])\n\n# Delete diagonals\ndiag(A2$A) <- FALSE\n# Delete columns and rows with no species\nd <- A2$STime[,100]!=0\nA <- A2$A[d,d]\n# Size of d == Number of species\nsum(d)==A2$S[100]\n\ng <- graph_from_adjacency_matrix(A,mode=\"directed\")\ng\nplotTrophLevel(g)\ncalcTopologicalIndices(g) # Trophic level do not work with multiple interactions types\n\nrequire(NetIndices)\nTrophInd(A2$A)\n", "meta": {"hexsha": "71b2af1bdc970408efa6d21c9b02420a1a1a0331", "size": 7797, "ext": "r", "lang": "R", "max_stars_repo_path": "testLVdynamics.r", "max_stars_repo_name": "Mario-Kart-Felix/meweasmo", "max_stars_repo_head_hexsha": "f24bd2541f366ba9d1591a6fbcf37d9168eb1df5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-08-18T10:41:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T22:53:12.000Z", "max_issues_repo_path": "testLVdynamics.r", "max_issues_repo_name": "Mario-Kart-Felix/meweasmo", "max_issues_repo_head_hexsha": "f24bd2541f366ba9d1591a6fbcf37d9168eb1df5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testLVdynamics.r", "max_forks_repo_name": "Mario-Kart-Felix/meweasmo", "max_forks_repo_head_hexsha": "f24bd2541f366ba9d1591a6fbcf37d9168eb1df5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-24T00:44:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T00:44:44.000Z", "avg_line_length": 30.5764705882, "max_line_length": 150, "alphanum_fraction": 0.6211363345, "num_tokens": 3553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6163873659924465}} {"text": "## library(devtools)\n## library(roxygen2)\n## library(testthat)\n##\n## Build and Reload Package: 'Ctrl + Shift + B'\n## Check Package: 'Ctrl + Shift + E'\n## Test Package: 'Ctrl + Shift + T'\n## Document: 'Ctrl + Shift + D'\n\n\n##\n#' @title Scaling of X-Axis (as vector or as scalar) to [-1,1]\n#' @param x_axis urspruengliche beliebige X-Achse (Vektor)\n#' @param x_val Einzelwert auf X-Achse (Skalar)\n#' @return x_cheb_scaled Abhaengig von Eingangsparametern: Skalierte X-Achse (Vektor) oder skalierter Einzelwert anhand vorgegebener X-Achse\n#' @description\n#' \\code{cheb_scale} skaliert beliebige X-Achse auf Achse, die fuer Polynom-fits vertraeglich ist.\n#' @export\ncheb_scale <- function(x_axis, x_val = NA) {#, scale) {\n ## Funktion zur Skalierung von Stuetzpunkten\n ## von beliebigen Gittern auf [-1, 1]\n ## ##\n if ( is.na(x_val) == TRUE ) { # Fuer Skalierung von vektoriellen Achsen\n x_cheb_scaled <- 2 * (x_axis - min(x_axis)) / (max(x_axis) - min(x_axis)) - 1\n }\n if ( is.na(x_val) == FALSE ) { # Fuer Skalierung von Einzelwert(en) auf Achse\n x_cheb_scaled <- 2 * (x_val - min(x_axis)) / (max(x_axis) - min(x_axis)) - 1\n }\n return(x_cheb_scaled)\n}\n\n\n##\n#' @title Rescaling of X-Axis (as vector or as scalar)\n#' @param x_cheb skalierte X-Achse (Skalar oder Vektor)\n#' @param x_axis beliebige X-Achse (Vektor)\n#' @return x_rescaled reskalierte X-Achse (Skalar oder Sektor)\n#' @description\n#' cheb_rescale reskaliert die fuer den Fit erzeugte Achse auf die Urspruengliche\n#' @export\ncheb_rescale <- function(x_cheb, x_axis) {\n ## Funktion zur Reskalierung vom [-1, 1]-Gitter\n ## auf das Ursprungsgitter (in diesem Fall - Lat)\n x_rescaled <- (1/2 * (x_cheb + 1) * (max(x_axis) - min(x_axis))) + x_axis[1]\n return(x_rescaled)\n}\n\n\n##\n#' @title Generating Chebyshev Polynomials of first kind\n#' @param x_axis beliebige X-Achse (Vektor)\n#' @param n Ordnung des Polynoms (Skalar)\n#' @return cheb_t Chebyshev-Polynome Erster Art (Vektor)\n#' @description\n#' cheb_1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse\n#' @export\ncheb_1st <- function(x_axis, n){\n ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art\n ## ## Fehlerabfrage nur mit Schwellwert. Korrigieren! Auch cheb_2nd\n x_cheb <- if (length(x_axis) > 7) cheb_scale(x_axis) else x_axis\n m <- n + 1\n # Rekursionsformel Wiki / Bronstein\n cheb_t_0 <- 1; cheb_t_1 <- x_cheb;\n cheb_t <- cbind(cheb_t_0, cheb_t_1)\n if (n >= 2) {\n for (i in 3:m) {\n cheb_t_i <- 2 * x_cheb * cheb_t[,(i - 1)] - cheb_t[,(i - 2)]\n cheb_t <- cbind(cheb_t, cheb_t_i)\n rm(cheb_t_i)\n }\n }\n return(cheb_t)\n}\n\n\n##\n#' @title Generating Chebyshev Polynomials of second kind\n#' @param x_axis beliebigie X-Achse (Vektor)\n#' @param n Ordnung des Polynoms (Skalar)\n#' @return cheb_u Chebyshev-Polynome Zweiter Art (Vektor)\n#' @description\n#' cheb_2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse\n#' @export\ncheb_2nd <- function(x_axis, n){\n ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art\n ## ##\n x_cheb <- if (length(x_axis) > 7) cheb_scale(x_axis) else x_axis\n m <- n + 1\n cheb_u_0 <- 1; cheb_u_1 <- 2*x_cheb\n cheb_u <- cbind(cheb_u_0, cheb_u_1)\n if (n >= 2) {\n for (i in 3:m) {\n cheb_u_i <- 2 * x_cheb * cheb_u[,(i - 1)] - cheb_u[,(i - 2)]\n cheb_u <- cbind(cheb_u, cheb_u_i)\n rm(cheb_u_i)\n }\n }\n return(cheb_u)\n}\n\n\n##\n#' @title Calculation of Values of the model fit\n#' @param x_axis beliebige X-Achse (Skalar oder Vektor)\n#' @param cheb_coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)\n#' @return cheb_model gefiltertes Modell (Skalar oder Vektor)\n#' @description\n#' cheb_model berechnet aus den Chebyshev-Koeffizienten die Y-Werte\n#' @export\ncheb_model_filter <- function(x_axis, cheb_coeff) {\n ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten\n ## ##\n n <- length(cheb_coeff) - 1\n cheb_t <- cheb_1st(x_axis, n)\n cheb_model <- cheb_t %*% cheb_coeff\n return(cheb_model)\n}\n\n\n##\n#' @title Calculation of the values of the first derivation\n#' @param x_axis beliebige X-Achse (Skalar oder Vektor)\n#' @param cheb_coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)\n#' @return cheb_model_deriv_1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)\n#' @description\n#' cheb_deriv_1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung\n#' @export\ncheb_deriv_1st <- function(x_axis, cheb_coeff) {\n ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells\n ## aus X-Stellen und Chebyshev-Koeffizienten\n ## ##\n if (length(x_axis) != 0) { ### ueberpruefen, ob noetig\n n <- length(cheb_coeff) - 1\n m <- n + 1\n cheb_u <- cheb_2nd(x_axis, n)\n\n # berechnung der ableitung der polynome erster art\n # rekursionsformel 0\n # dT/dx = n * U_(n-1)\n\n cheb_t_deriv_1st <- if (length(x_axis) == 1) (1:n)*t(cheb_u[,1:n]) else t((1:n) * t(cheb_u[,1:n]))\n cheb_t_deriv_1st <- cbind(0, cheb_t_deriv_1st)\n cheb_model_deriv_1st <- cheb_t_deriv_1st %*% cheb_coeff\n\n return(cheb_model_deriv_1st)\n }\n}\n\n\n##\n#' @title Calculation of the values of the second derivation\n#' @param x_axis beliebige X-Achse (Skalar oder Vektor)\n#' @param cheb_coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)\n#' @return cheb_model_deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)\n#' @description\n#' cheb_deriv_2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung\n#' @export\ncheb_deriv_2nd <- function(x_axis, cheb_coeff) {\n n <- length(cheb_coeff) - 1\n # m <- n + 1\n l <- length(x_axis)\n cheb_t <- cheb_1st(x_axis, n)\n cheb_u <- cheb_2nd(x_axis, n)\n x_cheb <- cheb_scale(x_axis)\n\n cheb_t_deriv_2nd <- t((0:n) * t(t((0:n + 1) * t(cheb_t )) - cheb_u)) / (x_cheb ** 2 - 1)\n cheb_t_deriv_2nd[1,] <- (-1) ** (0:n) * ((0:n) ** 4 - (0:n) ** 2) / (3)\n cheb_t_deriv_2nd[l,] <- ((0:n) ** 4 - (0:n) ** 2) / (3)\n\n cheb_model_deriv_2nd <- cheb_t_deriv_2nd %*% cheb_coeff\n\n return(cheb_model_deriv_2nd)\n}\n\n\n##\n#' @title Curve Fitting with Chebyshev Polynomials\n#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)\n#' @param x_axis Beliebige X-Achse (Vektor)\n#' @param n Ordnung des Polynoms (Skalar)\n#' @return cheb_model Werte des gefilterten Modells\n#' @description\n#' \\code{cheb_fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren\n#' @export\ncheb_fit <- function(d, x_axis, n){\n ## Herausfiltern von fehlenden Werten (NAs)\n mss_ind <- which(is.na(d))\n\n # Fallunterscheidung fuer NAs im Datensatz\n if (length(mss_ind) >= 1) {\n cheb_t <- cheb_1st(x_axis[-mss_ind], n)\n } else {\n cheb_t <- cheb_1st(x_axis, n)\n }\n\n ## modell berechnungen\n # berechnung der koeffizienten des polyfits\n if (length(mss_ind) >= 1) {\n cheb_coeff <- solve(t(cheb_t) %*% cheb_t) %*% t(cheb_t) %*% d[-mss_ind]\n } else {\n cheb_coeff <- solve(t(cheb_t) %*% cheb_t) %*% t(cheb_t) %*% d\n }\n\n # berechnung des gefilterten modells\n x_cheb <- cheb_scale(x_axis)\n cheb_model <- cheb_model_filter(x_cheb, cheb_coeff)\n\n # uebergabe der Variablen\n return(cheb_model)\n}\n\n\n##\n#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots\n#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)\n#' @param x_axis Beliebige X-Achse (Vektor)\n#' @param n Ordnung des Polynoms (Skalar)\n#' @param roots_bound_lower Unterer Rand des Bereichs der Nullstellensuche\n#' @param roots_bound_upper Oberer Rand des Bereichs der Nullstellensuche\n#' @return cheb_list Liste berechneter Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte)\n#' @description\n#' \\code{cheb_fit.extr} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren\n#' @export\n#' @importFrom rootSolve uniroot.all\ncheb_find_extr <- function(d, x_axis, n, roots_bound_lower = NA, roots_bound_upper = NA){\n\n x_cheb <- cheb_scale(x_axis)\n cheb_t <- cheb_1st(x_axis, n)\n\n ## modell berechnungen\n # berechnung der koeffizienten des polyfits\n cheb_coeff <- solve(t(cheb_t) %*% cheb_t) %*% t(cheb_t) %*% d\n\n # Berechnung der Extrema ueber Nullstellen der ersten Ableitung\n extr <- uniroot.all(cheb_deriv_1st, cheb_coeff = cheb_coeff, lower = -1, upper = 1)\n # reskalierung der Extrema auf normale Lat- Achse\n extr_x <- if (length(extr) != 0) cheb_rescale(extr, x_axis = x_axis)\n\n # ueberpruefen, welche Extrema im gesuchten Bereich liegen\n if (!is.na(roots_bound_lower) | !is.na(roots_bound_upper)) {\n ind <- which(extr_x >= roots_bound_lower & extr_x <= roots_bound_upper)\n extr <- extr[ind]\n extr_x <- extr_x[ind]\n }\n extr.y <- if (length(extr_x) != 0) cheb_model_filter(x_axis = extr, cheb_coeff = cheb_coeff)\n extr_deriv_2nd <- if (length(extr) != 0) cheb_deriv_2nd(x_axis = extr, cheb_coeff = cheb_coeff)\n\n cheb_list <- list(extr_x = extr_x,\n extr.y = extr.y,\n extr_deriv_2nd = extr_deriv_2nd)\n return(cheb_list)\n}\n\n\n##\n#' @title Routine to find maximum values of a curve\n#' @param d Zu fittender Datensatz\n#' @param x_axis beliebiege X-Achse\n#' @param n Ordnung des Skalars\n#' @param maxima_bound_lower Unterer Rand des Bereichs der Maxima-Suche\n#' @param maxima_bound_upper Oberer Rand des Bereichs der Maxima-Suche\n#' @return max_list Positionen und Werte der Maxima als Liste\n#' @description\n#' \\code{cheb_find_max} fittet ein Polynom und sucht mittel dessen Ableitung die Maxima des Datensatzes\n#' @export\n#' @importFrom rootSolve uniroot.all\ncheb_find_max <- function(d, x_axis, n, maxima_bound_lower = NA, maxima_bound_upper = NA){\n x_cheb <- cheb_scale(x_axis)\n cheb_t <- cheb_1st(x_axis, n)\n\n ## modell berechnungen\n # koeffizienten d poly fits\n cheb_coeff <- solve(t(cheb_t) %*% cheb_t) %*% t(cheb_t) %*% d\n\n # berechnen d maxima\n # nullstellen d ableitung\n extr <- uniroot.all(cheb_deriv_1st, cheb_coeff = cheb_coeff, lower = -1, upper = 1)\n\n # reskalierung der Extrema auf normale Lat- Achse\n extr_x <- cheb_rescale(extr, x_axis = x_axis)\n\n # ueberpruefen, welche Extrema im gesuchten Bereich liegen\n if (!is.na(maxima_bound_lower) | !is.na(maxima_bound_upper)) {\n ind <- which(extr_x >= maxima_bound_lower & extr_x <= maxima_bound_upper)\n extr <- extr[ind]\n extr_x <- extr_x[ind]\n }\n\n # ueberpruefen, welche Extrema Maxima sind\n if (length(extr) != 0) {\n extr_deriv_2nd <- cheb_deriv_2nd(x_axis = extr, cheb_coeff = cheb_coeff)\n\n # filtern der maxima | wert d zweiten ableitung < 0\n ind_max <- which(extr_deriv_2nd < 0)\n if (length(ind_max) != 0) {\n max_x <- extr_x[ind_max]\n max_y <- cheb_model_filter(x_axis = extr[ind_max], cheb_coeff = cheb_coeff)\n } else {\n max_x <- NA; max_y <- NA\n }\n } else {\n max_x <- NA; max_y <- NA;\n }\n max_list <- list(max_x = max_x,\n max_y = max_y)\n return(max_list)\n}\n\n\n\n\n\n", "meta": {"hexsha": "2ed6afbefc7192a3103f0bff3286eb0f9da053c6", "size": 10939, "ext": "r", "lang": "R", "max_stars_repo_path": "01-code/03-pckg.cheb/R/functions-chebyshev.r", "max_stars_repo_name": "sebaki/climate-jet-stream", "max_stars_repo_head_hexsha": "6b07e4327a0c2edee13c112b2e6379032ff23042", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01-code/03-pckg.cheb/R/functions-chebyshev.r", "max_issues_repo_name": "sebaki/climate-jet-stream", "max_issues_repo_head_hexsha": "6b07e4327a0c2edee13c112b2e6379032ff23042", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01-code/03-pckg.cheb/R/functions-chebyshev.r", "max_forks_repo_name": "sebaki/climate-jet-stream", "max_forks_repo_head_hexsha": "6b07e4327a0c2edee13c112b2e6379032ff23042", "max_forks_repo_licenses": ["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.9488817891, "max_line_length": 162, "alphanum_fraction": 0.6910138038, "num_tokens": 3822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6163873555975535}} {"text": "if (tau < tauAlpha){\n AlphaE = 1\n \n}else{\n \n AlphaE = Alpha - ((Alpha - 1.0) * (1.0 - tau) / (1.0 - tauAlpha))\n} \nenergyLimitedEvaporation= (evapoTranspirationPriestlyTaylor / Alpha) * AlphaE * tau\n", "meta": {"hexsha": "163a237c3fc38e4a435e7516a35f8e385cb29dfe", "size": 216, "ext": "r", "lang": "R", "max_stars_repo_path": "test/data/energyBalance/crop2ml/Algo/R/ptsoil.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/data/energyBalance/crop2ml/Algo/R/ptsoil.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/data/energyBalance/crop2ml/Algo/R/ptsoil.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 24.0, "max_line_length": 83, "alphanum_fraction": 0.587962963, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.616362591530461}} {"text": "#data_url <- \"https://files.datapress.com/london/dataset/2011-boundary-files/2011_london_boundaries.zip\"\n#zip_fn <- \"london.zip\"\n#download.file(data_url, zip_fn)\n#unzip(zip_fn)\n\nlibrary(maptools)\nlibrary(rgdal)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(plyr)\nlibrary(gganimate)\n\n\nset.seed(33333334)\n\ncrswgs84=CRS(\"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\")\n\nlon <- maptools::readShapePoly(\"LSOA_2011_BFE_City_of_London.shp\")\ncam <- readShapePoly(\"LSOA_2011_BFE_Camden.shp\")\nlon <- rbind(lon, cam)\nplot(lon)\n\nlon_coords <- sp::coordinates(lon) # Coordinates of polygon centers\nlon_nbs <- spdep::poly2nb(lon) # Neighbour relationships based on a triangulation\n\nrownames(lon_coords) <- lon$LSOA11NM\nplot(lon)\npoints(lon_coords)\npoints(lon_coords[2,1], lon_coords[2,2], col=\"red\")\n\nlon_w_mat <- spdep::nb2mat(lon_nbs) # Weight matrix between the nodes.\ncolnames(lon_w_mat) <- rownames(lon_w_mat)\nhist(Filter(f = function(x) x > 0, x = as.vector(lon_w_mat)))\n\nnum_nbs <- length(lon_nbs)\nthreshold <- 0.16\nplot(lon)\npoints(lon_coords)\n\nadj_matrix <- lon_w_mat>threshold\ndimnames(adj_matrix) <- NULL\n\nedges <- which(adj_matrix, arr.ind = TRUE)\napply(edges, 1, function(r){\n lines(lon_coords[r,1], lon_coords[r,2], col=\"blue\")\n})\n\n#transmission rate\nbeta <- 3\n\n#recovery rate\ngamma <- 1\n\nn.nodes <- ncol(adj_matrix)\nstatus.vector <- rep(\"S\", n.nodes)\n\nstatus.vector[sample(length(status.vector), 1)] <- \"I\"\nnames(status.vector) <- 1:n.nodes\ncolnames(adj_matrix) <- rownames(adj_matrix) <- 1:n.nodes\n\n#matrix and vector to store results at each time step\ntime.steps <- rep(NA, 2*n.nodes)\nstatus.matrix <- matrix(NA, nrow = 2*n.nodes, ncol = n.nodes)\n\ntime.steps[[1]] <- 0\nstatus.matrix[1,] <- status.vector\n\n#run until\nstopping.time <- 10\n\n#initialise time\ncurrent.time <- 0\ntime.step <- 1\n\nwhile(current.time < stopping.time){\n # message for debugging\n # message(paste(c(\"time step:\", time.step, \"current time:\", current.time), collapse = \" \"))\n \n #calculate vector recovery rates for each infected person\n recovery.rates <- rep(gamma, sum(status.vector==\"I\"))\n names(recovery.rates) <- c(1:n.nodes)[status.vector==\"I\"]\n \n #infection rates for each suceptiable person\n infection.rates <- rowSums(adj_matrix[,status.vector==\"I\",drop=FALSE])[status.vector==\"S\"]\n infection.rates <- infection.rates*beta\n names(infection.rates) <- c(1:n.nodes)[status.vector==\"S\"]\n \n #sample event\n event.rate <- sum(recovery.rates, infection.rates)\n if(event.rate<=0){\n #we've reached the end of the simulation\n break\n }\n \n p <- c(recovery.rates, infection.rates)/event.rate\n event.num <- sample(names(p), 1, prob = p)\n \n #update status\n if(status.vector[event.num]==\"S\"){\n status.vector[event.num] <- \"I\"\n } else if (status.vector[event.num]==\"I\") {\n status.vector[event.num] <- \"R\"\n } else {\n stop(\"bad index!\")\n }\n \n #sample time to event\n current.time <- current.time + rexp(1, rate = event.rate)\n time.step <- time.step + 1\n \n #update results\n time.steps[[time.step]] <- current.time\n status.matrix[time.step, ] <- status.vector\n}\n\ntime.steps <- time.steps[1:time.step]\nstatus.matrix <- status.matrix[1:time.step,]\n\nresults.df <- data.frame(t(apply(status.matrix, 1, function(r){\n table(factor(r, levels = list(\"S\", \"I\", \"R\")))\n })), stringsAsFactors = FALSE)\n\nresults.df$time <- time.steps\nresults.df <- melt(results.df, id.vars=\"time\")\n\n# Plot\nggplot(results.df, aes(x=time, y=value, col=variable)) + geom_line()\n\nresults.df <- melt(status.matrix)\ncolnames(results.df) <- c(\"time step\", \"node\", \"status\")\nresults.df <- cbind(results.df, lon_coords[results.df$node,], rownames(lon_coords))\nresults.df$node <- rownames(lon_coords)[results.df$node]\ncolnames(results.df) <- c(\"time step\", \"node\", \"status\", \"lat\", \"long\", \"area\")\n\nlon@data$id = rownames(lon@data)\nlondon.points = fortify(lon, region=\"id\")\nlondon.df = join(london.points, lon@data, by=\"id\")\n\nplot.df <- do.call(rbind, lapply(unique(results.df$`time step`), function(t){\n temp.df <- results.df[results.df$`time step`==t,]\n london.df$status <- temp.df$status[match(as.character(london.df$LSOA11NM), temp.df$node)]\n london.df$time <- t\n return(london.df)\n}))\n\ngg <- ggplot(plot.df) + \n aes(long,lat, group=group, fill=status) + \n geom_polygon() +\n geom_path(color=\"white\") +\n coord_equal() + \n # Here comes the gganimate code\n transition_manual(time)\n\nanim_save(\"london.gif\",animate(gg))\n\ncontents <- base64enc::base64encode(\"london.gif\")\ntag <- ''\nIRdisplay::display_html(sprintf(tag, contents))\n", "meta": {"hexsha": "e3857f36a681908100e8d67168f8f187a7a3114f", "size": 4547, "ext": "r", "lang": "R", "max_stars_repo_path": "models/network_models/london_sir.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/network_models/london_sir.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/network_models/london_sir.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.5974842767, "max_line_length": 104, "alphanum_fraction": 0.6943039367, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6161188403835256}} {"text": "\n#' Curbe ball algorithm to generate random networks with given an igraph network\n#'\n#' This extract the adjacency matrix from an igraph object and generates a randomized version\n#' of the network with the same row and column totals, the results have the same in and out degree sequence\n#' than the original network. The diagonals are not avoided so it can generate self-links or cannibalism in\n#' the context of food-webs. In the case that the network has multiple components (or disconnected networks)\n#' the algorithm simulates around the same number of components, if the original network has 1 component\n#' the algorithm enforces that the results have all 1 component. If the edge attribute weight is present\n#' and istrength=TRUE then the weigth is additionally randomized keeping the column sum equal to the original matrix.\n#'\n#' Based on:\n#'\n#' @references Strona, G. et al. 2014. A fast and unbiased procedure to randomize ecological binary matrices with\n#' fixed row and column totals. -Nat. Comm. 5: 4114. doi: 10.1038/ncomms5114\n#'\n#' @aliases curveBall\n#' @param g igraph object to extract adjacency matrix\n#' @param nsim number of generated random networks\n#' @param istrength if TRUE the edge attribute weight is taken as interaction strength and randomized keeping the column sum equal to the original matrix.\n#'\n#' @return a list of randomized igraph objects\n#' @export\n#'\n#' @examples\n#'\n#' curve_ball(netData[[1]])\n#'\ncurve_ball<-function(g,nsim=1000,istrength=FALSE){\n stopifnot(class(g)==\"igraph\")\n\n m <- get.adjacency(g,sparse=FALSE)\n\n if(components(g)$no>1) {\n\n nets<- lapply(1:nsim, function (x) {\n # repeat {\n RC <- dim(m)\n R <- RC[1]\n C <- RC[2]\n hp <- list()\n for (row in 1:dim(m)[1]) {hp[[row]] <- (which(m[row,]==1))}\n l_hp <- length(hp)\n for (rep in 1:5*l_hp){\n AB <- sample(1:l_hp,2)\n a <- hp[[AB[1]]]\n b <- hp[[AB[2]]]\n ab <- intersect(a,b)\n l_ab <- length(ab)\n l_a <- length(a)\n l_b <- length(b)\n if ((l_ab %in% c(l_a,l_b))==FALSE){\n tot <- setdiff(c(a,b),ab)\n l_tot <- length(tot)\n tot <- sample(tot, l_tot, replace = FALSE, prob = NULL)\n L <- l_a-l_ab\n hp[[AB[1]]] <- c(ab,tot[1:L])\n hp[[AB[2]]] <- c(ab,tot[(L+1):l_tot])}\n\n }\n rm <- matrix(0,R,C)\n for (row in 1:R){rm[row,hp[[row]]] <- 1}\n\n g <- graph_from_adjacency_matrix(rm,mode=\"directed\")\n return(g)\n })\n } else { #if the the networks has only one component enforce that in the simulations\n\n nets<- lapply(1:nsim, function (x) {\n repeat {\n RC <- dim(m)\n R <- RC[1]\n C <- RC[2]\n hp <- list()\n for (row in 1:dim(m)[1]) {hp[[row]] <- (which(m[row,]==1))}\n l_hp <- length(hp)\n for (rep in 1:5*l_hp){\n AB <- sample(1:l_hp,2)\n a <- hp[[AB[1]]]\n b <- hp[[AB[2]]]\n ab <- intersect(a,b)\n l_ab <- length(ab)\n l_a <- length(a)\n l_b <- length(b)\n if ((l_ab %in% c(l_a,l_b))==FALSE){\n tot <- setdiff(c(a,b),ab)\n l_tot <- length(tot)\n tot <- sample(tot, l_tot, replace = FALSE, prob = NULL)\n L <- l_a-l_ab\n hp[[AB[1]]] <- c(ab,tot[1:L])\n hp[[AB[2]]] <- c(ab,tot[(L+1):l_tot])}\n\n }\n rm <- matrix(0,R,C)\n for (row in 1:R){rm[row,hp[[row]]] <- 1}\n\n g <- graph_from_adjacency_matrix(rm,mode=\"directed\")\n if(components(g)$no==1)\n break\n }\n return(g)\n })\n }\n\n if(istrength) {\n m <- get.adjacency(g,sparse=FALSE,attr=\"weight\")\n r <- dim(m)[1]\n c <- dim(m)[2]\n\n wnets<- lapply(nets, function (x) {\n m1 <- get.adjacency(x,sparse=FALSE)\n for(i in seq_len(c) ){\n ss <- sample(m[,i])\n ss <- ss[ss>0]\n k <- 1\n for( j in seq_len(r)){\n if(m1[j,i]>0 ) {\n m1[j,i] <- ss[k]\n k <- k+1\n }\n }\n }\n graph_from_adjacency_matrix(m1,mode=\"directed\",weighted = \"weight\")\n })\n } else {\n return(nets)\n }\n}\n\n#' @export\ncurveBall<-function(g,nsim=1000,istrength=FALSE){curve_ball(g,nsim,istrength)}\n\n\n\n#' Generate directed Erdos-Renyi random networks with at least 1 basal node and only one component\n#'\n#' This uses the igraph's function sample_gnm to generate nsim random networks with the same number of nodes\n#' and links than the parameter ig and two restrictions:\n#' 1) at least one basal species/node, that is a species that has no prey, 2) 1 connected component so there is no\n#' disconnected species or sub-community.\n#'\n#' @param ig igraph object with parameters to use in the random network simulations: number of species/nodes\n#' and number of links/edges\n#' @param nsim number of simulations\n#'\n#' @aliases generateERbasal\n#'\n#' @return a list with igraph objects\n#' @export\n#'\n#' @examples\n#'\n#' generateERbasal(netData[[1]])\ngenerate_er_basal <- function(ig,nsim=1000){\n if(!is_igraph(ig))\n stop(\"Parameter ig must be an igraph object\")\n\n size <- vcount(ig)\n\n links <- ecount(ig)\n\n er <- lapply(1:nsim, function (x) {\n e <- sample_gnm(size, links, directed = TRUE)\n basal <- length(V(e)[degree(e,mode=\"in\")==0])\n while(components(e)$no>1 | basal==0){\n e <- sample_gnm(size, links,directed = TRUE)\n basal <- length(V(e)[degree(e,mode=\"in\")==0])\n }\n return(e) })\n}\n\n#' @export\ngenerateERbasal <- function(ig,nsim=1000){generate_er_basal(ig,nsim)}\n", "meta": {"hexsha": "e5b16d5adcdf7cf1212dd536d2c37ccf7cf1a31a", "size": 5468, "ext": "r", "lang": "R", "max_stars_repo_path": "R/models.r", "max_stars_repo_name": "lsaravia/multiweb", "max_stars_repo_head_hexsha": "5f0c36c3b4c68ad3df69dcdc38057e926acbbedb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-03T02:45:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T02:45:15.000Z", "max_issues_repo_path": "R/models.r", "max_issues_repo_name": "lsaravia/EcoNetwork", "max_issues_repo_head_hexsha": "78e936476a902524e6fcf275930e2d2c8b5915d0", "max_issues_repo_licenses": ["MIT"], "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/models.r", "max_forks_repo_name": "lsaravia/EcoNetwork", "max_forks_repo_head_hexsha": "78e936476a902524e6fcf275930e2d2c8b5915d0", "max_forks_repo_licenses": ["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.4252873563, "max_line_length": 154, "alphanum_fraction": 0.5972933431, "num_tokens": 1615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6161188353316565}} {"text": "##' Vortex transform.\n##' \n##' Fringe analysis by Vortex aka Spiral Quadrature transform.\n##' \n##' @param imagedata matrix containing the interferogram data\n##' @param cp list with circle parameters describing interferogram location. Defaults to NULL\n##' @param filter size of filter to remove background\n##' @param fw.o size of gaussian blur to smooth orientation estimate\n##' @param options A list with general fitting and display options. See [psfit_options()].\n##' \n##' @return a list with wavefront estimates, wrapped phase, modulation, etc.\n##' \n##' @seealso This is one of two routines provided for analysis of single interferograms,\n##' along with [fftfit()]. This \\emph{may} be suitable for interferograms with\n##' closed fringes.\n##'\n##' @details Implements the Vortex or spiral phase quadrature transform method\n##' of Larkin et al. (2001) [https://doi.org/10.1364/JOSAA.18.001862] including the \n##' fringe orientation estimation approach in Larkin (2005) [https://doi.org/10.1364/OPEX.13.008097].\n##' Thanks to Steve Koehler for ideas on implementation details.\n##' \n##' @section Warning:\n##' This routine is offered as is with no license, as it may be in violation of one or more\n##' US and international patents.\n##'\n##' @examples\n##' require(zernike)\n##' fpath <- file.path(find.package(package=\"zernike\"), \"psidata\")\n##' fname <- \"Image197.jpg\"\n##' img <- load.images(file.path(fpath, fname))\n##' \n##' # parameters for this run\n##' \n##' source(file.path(fpath, \"parameters.txt\"))\n##' \n##' # target SA coefficients for numerical null.\n##' \n##' sa.t <- sconic(diam,roc,lambda=wavelength)\n##' zopt <- psfit_options()\n##' zopt$satarget <- sa.t\n##' \n##' # display an interferogram\n##' \n##' if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\n##' image(1:nrow(img), 1:ncol(img), img, col=grey256, asp=1,\n##' xlab=\"X\", ylab=\"Y\", useRaster=TRUE)\n##' mtext(\"Sample Interferogram\")\n##' \n##' if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\n##' vfit <- vortexfit(img, filter=15, fw.o=10, options=zopt)\nvortexfit <- function(imagedata, cp=NULL, filter=NULL, fw.o=10, options=psfit_options()) {\n \n nr <- nrow(imagedata)\n nc <- ncol(imagedata)\n npad <- nextn(max(nr,nc))\n xs <- (-npad/2):(npad/2-1)\n im <- padmatrix(imagedata, npad=npad, fill=mean(imagedata))\n im.fft <- fftshift(fft(im))\n if (is.null(filter)) {\n sldata <- pick.sidelobe(imagedata, logm=TRUE)\n filter <- sldata$filter\n }\n if (filter > 0) {\n xss <- 2*xs/filter\n rho2 <- outer(xss, xss, function(x,y) x^2+y^2)\n im.fft <- im.fft*(1-exp(-rho2/2))\n }\n theta <- function(x,y) atan2(y,x)\n phi <- outer(xs, xs, theta)\n im.nb <- Re(fft(fftshift(im.fft), inv=TRUE))/(npad^2)\n D <- fft(fftshift(exp(1i*phi)*im.fft), inv=TRUE)/(npad^2)\n D2 <- fft(fftshift(exp(2*1i*phi)*im.fft), inv=TRUE)/(npad^2)\n sx <- (D^2-im.nb*D2)[1:nr, 1:nc]\n if (fw.o > 0) {\n rsx <- gblur(Re(sx), fw=fw.o)\n isx <- gblur(Im(sx), fw=fw.o)\n sx <- rsx + 1i*isx\n }\n orient <- Arg(sx)\n mod.o <- Mod(sx)\n if (options$plots) {\n image(1:nr, 1:nc, orient, col=grey256, asp=1, xlab=\"X\", ylab=\"Y\", useRaster=TRUE)\n mtext(\"Orientation\")\n }\n dir <- wrap(pi * qpuw(orient, mod.o))\n if (options$plots) {\n image(1:nr, 1:nc, dir, col=grey256, asp=1, xlab=\"X\", ylab=\"Y\", useRaster=TRUE)\n mtext(\"Direction\")\n }\n Q <- Re(D[1:nr, 1:nc] * exp(-1i*dir))\n phase <- atan2(Q, im.nb[1:nr, 1:nc])\n mod <- sqrt(Q^2+(im.nb[1:nr, 1:nc])^2)\n mod <- (mod-min(mod))/(max(mod)-min(mod))\n if (is.null(cp)) {\n cp <- circle.pars(mod, plot=options$plots)\n }\n cp.orig <- cp\n if (options$crop) {\n mod <- crop(mod, cp)$im\n phase <- crop(phase, cp)\n cp <- phase$cp\n phase <- phase$im\n }\n nr <- nrow(phase)\n nc <- ncol(phase)\n prt <- pupil.rhotheta(nr, nc, cp)\n phase[is.na(prt$rho)] <- NA\n class(phase) <- \"pupil\"\n wf.raw <- switch(options$puw_alg,\n qual = qpuw(phase, mod),\n brcut = brcutpuw(phase),\n qpuw(phase, mod)\n )\n wf.raw <- options$fringescale*wf.raw\n class(wf.raw) <- \"pupil\"\n wf.nets <- wf_net(wf.raw, cp, options)\n outs <- list(im.bgclean=im.nb[1:nr, 1:nc], orient=orient, dir=dir, phi=phase, mod=mod, \n cp=cp, cp.orig=cp.orig,\n wf.net=wf.nets$wf.net, wf.smooth=wf.nets$wf.smooth, \n wf.residual=wf.nets$wf.residual, fit=wf.nets$fit, zcoef.net=wf.nets$zcoef.net)\n class(outs) <- append(class(outs), \"wf_fitted\")\n outs\n}\n \n", "meta": {"hexsha": "3e07ab6f552952f7d0e0cec8707cc236ebbf9ac7", "size": 4456, "ext": "r", "lang": "R", "max_stars_repo_path": "R/vortexfit.r", "max_stars_repo_name": "gmke/zernike", "max_stars_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/vortexfit.r", "max_issues_repo_name": "gmke/zernike", "max_issues_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_issues_repo_licenses": ["MIT"], "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/vortexfit.r", "max_forks_repo_name": "gmke/zernike", "max_forks_repo_head_hexsha": "0880b0ae43cbb051afb54aa5decc246252467a8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 35.648, "max_line_length": 102, "alphanum_fraction": 0.6229802513, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6160752754267991}} {"text": "## Ch06.확률분포 : 도수분포(frequency table)의 %\n\nabs <- c(0:4)\nstu.n <- c(40,35,15,7,3)\n\npro.stu <- data.frame(abs,stu.n)\n\nprop.stu1 <- prop.table(stu.n)\n\nbarplot(prop.stu1 ~ abs,\n main =\"확률분포\",\n xlab = \"결석일수\",\n ylab = \"학생수\")\n\n\n# 이산확률변수와 연속확률변수의 차이 이해 (특정수치(사건 수, 방문자 수 등) vs. 연속변수(몸무게, 체온, 통근시간 등)\n\n# 확률밀도함수: d~ 개별 건수에 대한 확률 확인\n# 누적분포함수(점수): p~ 점수(숫자)를 가지고 몇 %에 해당하는지를 파악\n# 누적분포함수(확률): q~ 확률을 가지고 몇 점에 해당하는지를 파악 \n\n## 01.이항분포\n# 이항분포 확률밀도 : 확률이 두 가지로 구분되어 있을 경우 활용하는 방법 \n# dbinom(성공회수, size(시행횟수(n)), prob(성공확률)\n\n# fortune 쿠키 성공사례 : 식당에서 쿠키를 나누어줌\n# 시행횟수: 3명\n# 성공확률: 90% (쿠키가 들어있을 확률)\n# P(X = a) 확률 계산\ndbinom(0, size=3, prob=0.9)\ndbinom(1, size=3, prob=0.9)\ndbinom(2, size=3, prob=0.9)\ndbinom(3, size=3, prob=0.9) \n\n# 이항분포 확률밀도 graph\ny <- dbinom(0:3, size=3, prob=0.9)\nplot(0:3, y, # x를 0부터 3까지 4개로 쪼개라 \n type='h', # 유형이 달라지면, 그래프의 모양도 달라짐. 옵션은 찾아봐야 함 \n lwd=10, \n col=\"red\", \n ylab=\"확률\", \n xlab=\"성공확률 X\",\n main = \"이항분포\")\n\n\n# 이항분포 누적확률계산\n# 이하 : P(X <= a) lower.tail = TRUE * 여기가 옵션 넣을 때 매우 중요한 부분임. R의 기본 옵션은 이하와 초과로 구분\n# 초과: P(X > a) lower.tail = FALSE\n# P(X <= 1)이하로 받을 확률 => 3번 중에 1번 이하로 성공할 확률(누적확률이므로 pbinom사용 )\npbinom(1, size=3, prob=0.9, lower.tail = TRUE)\n\n# 1명이상 받을 확률: P(X >= 1) 확률 계산, 초과이므로 최소 0을 넣어야 함. lowe.tail 옵션은 FALSE\npbinom(0, size=3, prob=0.9, lower.tail = FALSE)\n\n# 누적이항분포 graph\n\nplot(pbinom(0:3, size=3, prob=0.9), \n type='h', \n lwd=10, \n col=\"red\", \n main = \"누적이항분포\")\n\n\n## 퀴즈\n# 성공확률 0.7, 10명중 7명 이상: P(X >= 7) 확률 계산\n\npbinom(6, size=10, prob=0.7, lower.tail = FALSE)\n\n\n# 확률밀도 graph\ny <- dbinom(0:10, size=10, prob=0.7)\nplot(0:10, y, \n type='h', \n lwd=10, \n col=\"red\", \n ylab=\"확률\", \n xlab=\"성공확률 X\",\n main = \"이항분포\")\n\n# 누적이항분포 graph\nplot(pbinom(0:10, size=10, prob=0.7), \n type='h', \n lwd=10, \n col=\"red\", \n main = \"누적이항분포\")\n", "meta": {"hexsha": "dc7d75553ed0d1db54fd5921b0bf1072a3b3e419", "size": 1841, "ext": "r", "lang": "R", "max_stars_repo_path": "ch06 - 확률분포/01.이항분포.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": "ch06 - 확률분포/01.이항분포.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": "ch06 - 확률분포/01.이항분포.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": 21.4069767442, "max_line_length": 81, "alphanum_fraction": 0.5600217273, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465170505205, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.6158485221847875}} {"text": "# Benjamini-Hochberg with two-sided p-values\nBenjaminiHochberg = function(zscores, fdr_level) {\n# zscores is a vector of z scores\n# fdr_level is the desired level (e.g. 0.1) of control over FDR\n# returns a binary vector where 0=nofinding, 1=finding at given FDR level\n N = length(zscores)\n pval2 = 2*pmin(pnorm(zscores), 1- pnorm(zscores))\n cuts = (1:N)*fdr_level/N\n bhdiff = sort(pval2)-cuts\n bhcutind2 = max(which(bhdiff < 0))\n bhcut2 = sort(pval2)[bhcutind2]\n 0+{pval2 <= bhcut2}\n}\n\nargs <- commandArgs(trailingOnly = TRUE)\nz = as.numeric(t(as.matrix(read.csv(args[1], header=FALSE))))#testing\ndiscoveries = BenjaminiHochberg(z, 0.1)\nwrite.table(discoveries, args[2], row.names=FALSE, col.names=FALSE, sep=\",\")", "meta": {"hexsha": "ea56a33617a66b10c6d902eeed9774c17ece6fa3", "size": 734, "ext": "r", "lang": "R", "max_stars_repo_path": "test/run_bh.r", "max_stars_repo_name": "tansey/smoothfdr", "max_stars_repo_head_hexsha": "c5b693d0a66e83c9387433b33c0eab481bd4a763", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2016-02-26T23:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-13T16:14:47.000Z", "max_issues_repo_path": "test/run_bh.r", "max_issues_repo_name": "tansey/smoothfdr", "max_issues_repo_head_hexsha": "c5b693d0a66e83c9387433b33c0eab481bd4a763", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-09-23T16:59:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-29T13:19:44.000Z", "max_forks_repo_path": "test/run_bh.r", "max_forks_repo_name": "tansey/smoothfdr", "max_forks_repo_head_hexsha": "c5b693d0a66e83c9387433b33c0eab481bd4a763", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-07-04T12:25:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T00:10:33.000Z", "avg_line_length": 40.7777777778, "max_line_length": 76, "alphanum_fraction": 0.7029972752, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.615689710722258}} {"text": "[[[[[\n Show that a real r is Solovay random\n iff it is Martin-Lof random.\n\n An effective covering A_k of k is a function\n of k that enumerates bit strings s,\n which are the initial bits of the covered\n reals. We assume that no s in A_k is a\n proper prefix or extension of another.\n Thus the measure of the cover A_k of k is\n exactly Sum_{s in A_k} of 2^{-|s|},\n where |s| is the length of the bit string s.\n]]]]]\n\n[First part: not M-L random ===> not Solovay random] \n\n[\nThis is immediate. We are given coverings A_k such\nthat real r is in A_k for all k and the measure of A_k <= 2^{-k}.\nIt follows immediately that r is in infinitely many of the\nA_k and the sum of the measure of A_k summed over all k converges.\nThus r is not Solovay random.\n]\n\n[Second part: not Solovay random ===> not M-L random] \n\n[\nSuppose that a real r is in infinitely many of the \ncoverings A_n and that Sum_k mu A_n <= 2^c.\nConsider B_k defined as the set of all reals that are\nin at least 2^{k+c} of the A_n.\nThen r is in all of the B_k and the measure of \nB_k is <= 2^{-k}, so r is not Martin-Lof random.\n\nNow let's program this!\n\nInstead, I'll program B_k which is the set of all reals\nthat are in at least k of the A_n.\nThe proof then results from considering B_{2^{k+c}} .\n\nThe main function has two parameters, the stage n, and\nthe number of times something has to be repeated to\nbe taken into account. At stage n, with number \nof repeats r, we look at A_0 through A_n for time n,\nand put into our condensed result cover only subintervals\nthat are covered at least r times.\n\nThe key auxiliary function given n generates A_0 through A_n for time n,\nthen expands all intervals to the same max length and counts how\nmany times each is repeated. Then it is easy to select those that\nare covered the requisite number of times.\n\nFirst step is to run A_0 through A_n for time n and append the results.\nThen we get the max length and do a binary tree walk. We start with\ns and see if it's a prefix of at least r things.\nIf so, s will be in our result, and we backtrack.\nIf not, if s has max length, we stop recursion.\nOtherwise, we look at s0 and at s1.\nAnd we start with s = nil.\nThis gives our covering at stage n,\nthen we have to eliminate overlaps to\nget our final result.\n]\n\n[ \n Test case: A_n is defined to be the set of\n all natural numbers greater than n,\n where k is represented as k 1's followed by a 0.\n Then measure of A_n is 2^{-n-1}, and\n 1=10 is in one of the A_n, 2=110 is in two of them,\n 3=1110 is in three of them, etc.\n\n I.e., 1=10 is only in A_0,\n 2=110 is only in A_0 & A_1,\n 3=1110 is only in A_0 A_1 & A_2, etc.\n\n In this case the total measure of the A_n is \n 1/2 + 1/4 + 1/8 + ... = 1.\n For the proof in general, all we know is that\n this total measure converges to a finite sum, not 1.\n]\ndefine (A n) [displays infinite set 1^k 0, k > n] \n let (loop k)\n cons display \n append base10-to-2 - ^ 2 k 1 [2^k - 1 = k 1's]\n cons 0 nil [followed by a 0 bit]\n (loop + k 1)\n (loop + n 1)\n\ndefine A\nvalue (lambda (n) ((' (lambda (loop) (loop (+ n 1)))) ('\n (lambda (k) (cons (display (append (base10-to-2 (\n - (^ 2 k) 1)) (cons 0 nil))) (loop (+ k 1)))))))\n\n \n\n[now put together in one list stage n of A_0 through A_n]\ndefine (sum n)\n let (loop k sum)\n if > k n sum\n (loop + k 1 \n append caddr try n cons cons \"' cons A nil cons k nil nil\n sum)\n (loop 0 nil)\n\ndefine sum\nvalue (lambda (n) ((' (lambda (loop) (loop 0 nil))) (' (\n lambda (k sum) (if (> k n) sum (loop (+ k 1) (appe\n nd (car (cdr (cdr (try n (cons (cons ' (cons A nil\n )) (cons k nil)) nil)))) sum)))))))\n\n[\n (count x y) \n Now count how many times something x is contained in / \n is an extension of an element of y\n]\ndefine (count x y) \n if atom y 0\n if (is-prefix-of? car y x) + 1 (count x cdr y)\n (count x cdr y)\n\ndefine count\nvalue (lambda (x y) (if (atom y) 0 (if (is-prefix-of? (c\n ar y) x) (+ 1 (count x (cdr y))) (count x (cdr y))\n )))\n\ndefine (is-prefix-of? x y) [is bit string x a prefix of bit string y?]\n if atom x true\n if atom y false\n if = car x car y (is-prefix-of? cdr x cdr y)\n false\n\ndefine is-prefix-of?\nvalue (lambda (x y) (if (atom x) true (if (atom y) false\n (if (= (car x) (car y)) (is-prefix-of? (cdr x) (c\n dr y)) false))))\n\n[get maximum length of a list of bit strings]\ndefine (max-length list) \n if atom list 0\n let len1 length car list\n let len2 (max-length cdr list)\n if > len1 len2 \n [then] len1 \n [else] len2 \n\ndefine max-length\nvalue (lambda (list) (if (atom list) 0 ((' (lambda (len1\n ) ((' (lambda (len2) (if (> len1 len2) len1 len2))\n ) (max-length (cdr list))))) (length (car list))))\n )\n\n[\n Now we get what (sum n) covers with multiplicity >= k.\n The measure of the multiplicity k covering will\n be bounded by the finite total measure (here 1) divided by k.\n]\n\ndefine (exceeds-count n k)\n let sum-n (sum n)\n let max-length-sum-n (max-length sum-n)\n (look-at nil)\n\ndefine exceeds-count\nvalue (lambda (n k) ((' (lambda (sum-n) ((' (lambda (max\n -length-sum-n) (look-at nil))) (max-length sum-n))\n )) (sum n)))\n\n[\n This routine has free parameters sum-n, max-length-sum-n, k.\n It gets us the MINIMAL multiplicity >= k covering for (sum n)!\n]\ndefine (look-at x) [produces strings x covered with multiplicity >= k in (sum n)]\n if = length x max-length-sum-n\n let n (count x sum-n)\n if >= n k cons x nil [found an interval x that is covered >= k times]\n nil [didn't find an interval x that is covered >= k times]\n [otherwise break x into subintervals]\n let x0 append x cons 0 nil\n let x1 append x cons 1 nil\n let v append (look-at x0)\n (look-at x1)\n [consolidate subintervals?]\n if = v cons x0 cons x1 nil [yes!] cons x nil\n [no, leave covering as is] v\n\ndefine look-at\nvalue (lambda (x) (if (= (length x) max-length-sum-n) ((\n ' (lambda (n) (if (>= n k) (cons x nil) nil))) (co\n unt x sum-n)) ((' (lambda (x0) ((' (lambda (x1) ((\n ' (lambda (v) (if (= v (cons x0 (cons x1 nil))) (c\n ons x nil) v))) (append (look-at x0) (look-at x1))\n ))) (append x (cons 1 nil))))) (append x (cons 0 n\n il)))))\n\n[\n Now we put this all together into B_k, which is\n the limit as n goes to infinity of (exceeds-count n k),\n k fixed, n --> infinity.\n\n I.e., B_k is what A_0, A_1, A_2, ... covers with\n multiplicity >= k.\n\n Thus the measure of B_k will be bounded by the\n total measure of the A_n (if it exists) divided by k.\n\n The main problem is to avoid overlaps in B_k,\n which we do using a completely general algorithm.\n]\n\n[list of intervals in covering so far]\n[used to avoid overlapping intervals in covering]\ndefine intervals ()\n\ndefine intervals\nvalue ()\n\ndefine (process-all x) [process list of intervals x]\n if atom x intervals\n let intervals append (process car x) intervals\n (process-all cdr x)\n\ndefine process-all\nvalue (lambda (x) (if (atom x) intervals ((' (lambda (in\n tervals) (process-all (cdr x)))) (append (process \n (car x)) intervals))))\n\ndefine (process interval) [process individual interval]\n if (new-interval-covered-by-previous-one? interval intervals) \n [then don't need to repeat it]\n nil\n let holes (new-interval-covers-previous-ones interval intervals)\n if atom holes\n [then interval is fine as is]\n [output it with display!]\n cons display interval nil \n [get max granularity needed]\n let max (max-length holes) \n [convert everything to same granularity]\n let holes (extend-all holes max)\n [and remove overlap]\n [subtract will output residue with display]\n (subtract (extend interval max) holes)\n\ndefine process\nvalue (lambda (interval) (if (new-interval-covered-by-pr\n evious-one? interval intervals) nil ((' (lambda (h\n oles) (if (atom holes) (cons (display interval) ni\n l) ((' (lambda (max) ((' (lambda (holes) (subtract\n (extend interval max) holes))) (extend-all holes \n max)))) (max-length holes))))) (new-interval-cover\n s-previous-ones interval intervals))))\n\n[returns true/false]\ndefine (new-interval-covered-by-previous-one? interval intervals)\n if atom intervals false\n if (is-prefix-of? car intervals interval) true\n (new-interval-covered-by-previous-one? interval cdr intervals)\n\ndefine new-interval-covered-by-previous-one?\nvalue (lambda (interval intervals) (if (atom intervals) \n false (if (is-prefix-of? (car intervals) interval)\n true (new-interval-covered-by-previous-one? inter\n val (cdr intervals)))))\n\n[returns set of previous intervals covered by this one]\ndefine (new-interval-covers-previous-ones interval intervals)\n if atom intervals nil\n if (is-prefix-of? interval car intervals)\n [then] cons car intervals (new-interval-covers-previous-ones interval cdr intervals)\n [else] (new-interval-covers-previous-ones interval cdr intervals)\n\ndefine new-interval-covers-previous-ones\nvalue (lambda (interval intervals) (if (atom intervals) \n nil (if (is-prefix-of? interval (car intervals)) (\n cons (car intervals) (new-interval-covers-previous\n -ones interval (cdr intervals))) (new-interval-cov\n ers-previous-ones interval (cdr intervals)))))\n\n \n[produce set of all extensions of a given bit string to a given length]\n[(assumed >= to its current length)]\ndefine (extend bit-string len)\n if = len length bit-string \n [has correct length; return singleton set]\n cons bit-string nil\n append (extend append bit-string cons 0 nil len)\n (extend append bit-string cons 1 nil len)\n\ndefine extend\nvalue (lambda (bit-string len) (if (= len (length bit-st\n ring)) (cons bit-string nil) (append (extend (appe\n nd bit-string (cons 0 nil)) len) (extend (append b\n it-string (cons 1 nil)) len))))\n\n[extend all the bit strings in a given list to the same length]\ndefine (extend-all list len)\n if atom list nil\n append (extend car list len)\n (extend-all cdr list len)\n\ndefine extend-all\nvalue (lambda (list len) (if (atom list) nil (append (ex\n tend (car list) len) (extend-all (cdr list) len)))\n )\n\n[subtract set of intervals y from set of intervals x]\n[output residue with display!]\ndefine (subtract x y)\n if atom x nil \n if (is-in? car x y)\n [then] (subtract cdr x y)\n [else] cons display car x (subtract cdr x y)\n\ndefine subtract\nvalue (lambda (x y) (if (atom x) nil (if (is-in? (car x)\n y) (subtract (cdr x) y) (cons (display (car x)) (\n subtract (cdr x) y)))))\n\ndefine (is-in? x l) [is x an element of list l?]\n if atom l false\n if = x car l true\n (is-in? x cdr l)\n\ndefine is-in?\nvalue (lambda (x l) (if (atom l) false (if (= x (car l))\n true (is-in? x (cdr l)))))\n\n[\n Put it all together---Here is cover B_k,\n which is what is covered by A_0, A_1, A_2, ...\n with multiplicity >= k, and therefore has\n measure bounded by the total measure of the A_n\n divided by k.\n Supposing that this total measure is <= 2^c\n and considering B_{2^{k+c}}, \n we see that if a real r is in infinitely many of\n the A_n, then it will be in all of the \n B_{2^{k+c}}, each of which has measure <= 1/2^k.\n Hence if a real r is not Solovay random,\n it follows that it will not be M-L random.\n Here we write the code for B_k, not for\n B_{2^{k+c}}.\n]\ndefine (B k)\n let intervals nil\n let (stage n)\n if = n 6 stop! [to stop test run---remove if real thing]\n let exceed-count (exceeds-count n k)\n let intervals (process-all exceed-count) \n (stage + 1 n)\n [go!!!!!]\n (stage 0)\n\ndefine B\nvalue (lambda (k) ((' (lambda (intervals) ((' (lambda (s\n tage) (stage 0))) (' (lambda (n) (if (= n 6) stop!\n ((' (lambda (exceed-count) ((' (lambda (intervals\n ) (stage (+ 1 n)))) (process-all exceed-count)))) \n (exceeds-count n k)))))))) nil))\n\n[k = multiplicity = repeated/covered 2 or more times in the A_n]\n(B 2)\n\nexpression (B 2)\ndisplay (1 1 0)\ndisplay (1 1 1 0)\ndisplay (1 1 1 1 0)\ndisplay (1 1 1 1 1 0)\ndisplay (1 1 1 1 1 1 0)\ndisplay (1 1 1 1 1 1 1 0)\nvalue stop!\n", "meta": {"hexsha": "7e75adaa8f3178ed648a4cd0dc034c8588ff47c5", "size": 12715, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/solovay.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/solovay.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/solovay.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 34.0884718499, "max_line_length": 90, "alphanum_fraction": 0.6228077074, "num_tokens": 3634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6154669744415108}} {"text": "# Kvantitativni podaci\n\ntrajanje.posmatranja <- sum(faithful$eruptions) + sum(faithful$waiting)\ntrajanje.posmatranja\ntrajanje.posmatranja <- trajanje.posmatranja / c(60, 60*24, 60*24*7)\ntrajanje.posmatranja\n\ntrajanja <- faithful$eruptions\ntrajanja\nopseg <- range(trajanja)\nopseg\n# alternativni nacin\nopseg <- c( min(trajanja), max(trajanja))\nopseg\ndonja.granica <- 1.5\ngornja.granica <- 5.5\nbroj.podintervala <- 25\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\ngranice\nizrezano <- cut(trajanja, granice, right=FALSE)\nizrezano\nfrekfencija.trajanja <- table(izrezano)\nbarplot(frekfencija.trajanja)\n\ncekanja <- faithful$waiting\nopseg <- c( min(cekanja), max(cekanja))\ndonja.granica <- 45\ngornja.granica <- 100\nbroj.podintervala <- 125\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nizrezano <- cut(cekanja, granice, right=FALSE)\nbarplot(table(izrezano))\n\ntrajanja <- faithful$eruptions\nhist(trajanja, right = FALSE)\nhist(trajanja, breaks = 20, right = FALSE)\nhist(trajanja, \n breaks = c(1.5, 2, 2.5, 3, 4.7, 5, 5.5), \n right = FALSE)\nhist(trajanja, \n breaks = c(1.5, 2, 2.5, 3, 4.7, 5, 5.5), \n main = \"Histogram za trajanje\",\n xlab = \"trajanje erupcije\",\n col = c( \"purple\", \"red\", \"blue\"),\n right = FALSE)\n\ncekanja <- faithful$waiting\nhist(cekanja, \n breaks = 5, \n col = c( \"purple\", \"red\", \"blue\"),\n right = FALSE)\n\ntrajanja <- faithful$eruptions\ndonja.granica <- 1.5\ngornja.granica <- 5.5\nbroj.podintervala <- 10\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nizrezano <- cut(trajanja, granice, right=FALSE)\nfrekfencija.trajanja <- table(izrezano)\nfrekfencija.trajanja\nrelativna.frekfencija.trajanja <- frekfencija.trajanja / nrow(faithful)\nrelativna.frekfencija.trajanja\nrelativna.frekfencija.trajanja <- frekfencija.trajanja / length(trajanja)\nrelativna.frekfencija.trajanja\nrelativna.frekfencija.trajanja <- frekfencija.trajanja / sum(frekfencija.trajanja)\nrelativna.frekfencija.trajanja \n\ntrajanja <- faithful$eruptions\ndonja.granica <- 1.5\ngornja.granica <- 5.5\nbroj.podintervala <- 10\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nizrezano <- cut(trajanja, granice, right=FALSE)\nfrekfencija.trajanja <- table(izrezano)\nfrekfencija.trajanja\nkumulativna.frekfencija.trajanja <- cumsum(frekfencija.trajanja)\nkumulativna.frekfencija.trajanja\n\ncekanja <- faithful$waiting\ndonja.granica <- 45\ngornja.granica <- 100\nbroj.podintervala <- 15\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nfrekfencija.cekanja <- table(cut(cekanja, granice, right=FALSE))\nfrekfencija.cekanja\nkumulativna.frekfencija.cekanja <- cumsum(frekfencija.cekanja)\nkumulativna.frekfencija.cekanja\n\ntrajanja <- faithful$eruptions\ndonja.granica <- 1.5\ngornja.granica <- 5.5\nbroj.podintervala <- 10\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nizrezano <- cut(trajanja, granice, right=FALSE)\nfrekfencija.trajanja <- table(izrezano)\nkumulativna.frekfencija.trajanja <- cumsum(frekfencija.trajanja)\nkumulativna.frekfencija.trajanja\nplot(granice,c(0, kumulativna.frekfencija.trajanja) )\nlines(granice,c(0, kumulativna.frekfencija.trajanja) )\n\ncekanja <- faithful$waiting\ndonja.granica <- 40\ngornja.granica <- 110\nbroj.podintervala <- 45\ngranice <- seq(donja.granica,\n gornja.granica, \n (gornja.granica-donja.granica)/broj.podintervala )\nrelativna.frekfencija.cekanja <- \n table(cut(cekanja, granice, right=FALSE))/ length(cekanja)\nkumulativna.relativna.frekfencija.cekanja <- cumsum(relativna.frekfencija.cekanja)\nkumulativna.relativna.frekfencija.cekanja\nplot(granice,c(0, kumulativna.relativna.frekfencija.cekanja), \n xlab=\"cekanje(u minutama)\",\n ylab=\"deo populacije\")\nlines(granice,c(0, kumulativna.relativna.frekfencija.cekanja) )\n\ndonja.granica <- -4\ngornja.granica <- 4\nbroj.tacaka <- 40\nx <- seq(donja.granica, gornja.granica, \n by = (gornja.granica-donja.granica)/broj.tacaka )\ny <- sin (x)\nplot(x,y)\nlines(x,y)\n\ntrajanja <- faithful$eruptions\ncekanja <- faithful$waiting\nplot( trajanja, cekanja, xlab=\"trajanje\", ylab= \"cekanje\")\nmodel <- lm(cekanja ~ trajanja )\nabline(model)\n\ntrajanja <- faithful$eruptions\ncekanja <- faithful$waiting\nplot( cekanja, trajanja, xlab=\"cekanje\", ylab= \"trajanje\")\nmodel <- lm( trajanja ~ cekanja )\nabline(model)\n", "meta": {"hexsha": "0b43e9bdad2e38995ea1bd6263101a7e7e7fc494", "size": 4693, "ext": "r", "lang": "R", "max_stars_repo_path": "predavanja/primeri-r/007-kvatitativni-podaci.r", "max_stars_repo_name": "PmfBlPRB/PRB", "max_stars_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predavanja/primeri-r/007-kvatitativni-podaci.r", "max_issues_repo_name": "PmfBlPRB/PRB", "max_issues_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-05T11:49:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T07:53:58.000Z", "max_forks_repo_path": "predavanja/primeri-r/007-kvatitativni-podaci.r", "max_forks_repo_name": "PmfBlPRB/PRB", "max_forks_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4966442953, "max_line_length": 82, "alphanum_fraction": 0.7159599403, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6154669672210022}} {"text": "x = 3\nwhile(x != 1) {\n cat(x, \",\")\n if(x%%2 == 0) {\n x = x/2\n } else {\n x = x*3+1\n }\n}\ncat(1)", "meta": {"hexsha": "a045b99f224519633c7c76bc5d1e2ba6a0bdb94f", "size": 103, "ext": "r", "lang": "R", "max_stars_repo_path": "resolucao/r/collatz.r", "max_stars_repo_name": "rafaelbes/numericalAnalysis", "max_stars_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "resolucao/r/collatz.r", "max_issues_repo_name": "rafaelbes/numericalAnalysis", "max_issues_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resolucao/r/collatz.r", "max_forks_repo_name": "rafaelbes/numericalAnalysis", "max_forks_repo_head_hexsha": "31f2b9cd5fb62cee9a649ac0257024de757eede4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-12-15T00:31:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T14:52:19.000Z", "avg_line_length": 10.3, "max_line_length": 17, "alphanum_fraction": 0.3203883495, "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6152667000733922}} {"text": "#kvalitativni podaci\npainters\n\nprosecna.ocena.kompozicija <- mean(painters$Composition)\nprosecna.ocena.kompozicija\n\nprosecna.ocena.crtanje <- mean(painters$Drawing)\nprosecna.ocena.crtanje\n\nprosecna.ocena.boja <- mean(painters$Colour)\nprosecna.ocena.boja\n\nprosecna.ocena.izrazajnost <- mean(painters$Expression)\nprosecna.ocena.izrazajnost\n\nizrazajnosti <- painters$Expression\nizrazajnosti\nizrazajnosti.frekfencija <- table(izrazajnosti)\nizrazajnosti.frekfencija\n\nskole <- painters$School\nskole\nskole.frekfencija <- table(skole)\nskole.frekfencija\n\nskole <- painters$School\nskole\nskole.relativna.frekfencija <- table(skole) / length(skole) \nskole.relativna.frekfencija\n\nskole <- painters$School\nskole\nskole.frekfencija.procenat <- table(skole) / length(skole) * 100\nskole.frekfencija.procenat\n\nskole <- painters$School\nskole\nskole.frekfencija.procenat <- table(skole) / length(skole) * 100\ncbind(skole.frekfencija.procenat)\n\nskole <- painters$School\nskole\nskole.frekfencija.procenat <- table(skole) / length(skole) * 100\nskole.frekfencija.procenat\nstaro.podesavanje <- options(digits=3)\nskole.frekfencija.procenat\noptions(staro.podesavanje)\n\nskole <- painters$School\nskole\nskole.frekfencija <- table(skole)\nbarplot( skole.frekfencija)\n\nskole <- painters$School\nskole\nskole.frekfencija <- table(skole)\nboje <- c(\"red\",\"green\", \"yellow\", \"purple\", \"violet\")\nbarplot( skole.frekfencija,\n col = boje)\n\nocene.kompozicija <- painters$Composition\nocene.kompozicija.frekfencija <- table (ocene.kompozicija)\nboje <- c(\"red\",\"green\", \"yellow\", \"purple\", \"violet\")\nbarplot(ocene.kompozicija.frekfencija, col = boje)\n\nbarplot( table(painters$Composition), \n col = c(\"red\",\"green\", \"yellow\", \"purple\", \"violet\")\n )\n\nskole <- painters$School\nskole\nskole.frekfencija <- table(skole)\npie( skole.frekfencija)\n\npie( table(painters$School))\n\npie( table(painters$School),\n col = c(\"red\",\"green\", \"yellow\", \"purple\", \"violet\"))\n\nprosecna.ocena.kompozicija.svi <- mean(painters$Composition)\nprosecna.ocena.kompozicija.svi\n\n# prosecna.ocena.kompozicija.skola.A ???\nfilter.skola.A <- painters$School == \"A\"\nslikari.skola.A <- painters[filter.skola.A,]\nocena.kompozicija.skola.A <- slikari.skola.A$Composition\nprosecna.ocena.kompozicija.skola.A <- mean(ocena.kompozicija.skola.A)\nprosecna.ocena.kompozicija.skola.A\n\nprosecna.ocena.kompozicija.skola.A <- \n mean(painters[painters$School == \"A\",]$Composition)\nprosecna.ocena.kompozicija.skola.A\n\nprosecna.ocena.kompozicija.skola.B <- \n mean(painters[painters$School == \"B\",]$Composition)\nprosecna.ocena.kompozicija.skola.B\n\nsve.prosecne.ocene.kompozicija <- \n tapply(painters$Composition, painters$School, mean)\nsve.prosecne.ocene.kompozicija\n\nsve.prosecne.ocene.boja <- \n tapply(painters$Colour, painters$School, mean)\nsve.prosecne.ocene.boja", "meta": {"hexsha": "6e851aad3e6ba726a24442b05b7d4bbd42895d54", "size": 2798, "ext": "r", "lang": "R", "max_stars_repo_path": "predavanja/primeri-r/006-kvalitativni-podaci.r", "max_stars_repo_name": "PmfBlPRB/PRB", "max_stars_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predavanja/primeri-r/006-kvalitativni-podaci.r", "max_issues_repo_name": "PmfBlPRB/PRB", "max_issues_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-05T11:49:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-19T07:53:58.000Z", "max_forks_repo_path": "predavanja/primeri-r/006-kvalitativni-podaci.r", "max_forks_repo_name": "PmfBlPRB/PRB", "max_forks_repo_head_hexsha": "eba907dafc66837feccc06b500e3f72e1588277b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9038461538, "max_line_length": 69, "alphanum_fraction": 0.760185847, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.615163197975189}} {"text": "# portfolio.r\n# \n# Functions for portfolio analysis\n# to be used in Introduction to Computational Finance & Financial Econometrics\n# last updated: November 7, 2000 by Eric Zivot\n# Oct 15, 2003 by Tim Hesterberg\n# November 18, 2003 by Eric Zivot\n# November 9, 2004 by Eric Zivot\n#\t\t November 9, 2008 by Eric Zivot\n# August 11, 2011 by Eric Zivot\n#\n# Functions:\n#\t1. efficient.portfolio\t\t\tcompute minimum variance portfolio\n#\t\t\t\t\t\t\t subject to target return\n#\t2. globalMin.portfolio\t\t\tcompute global minimum variance portfolio\n#\t3. tangency.portfolio\t\t\t compute tangency portfolio\n#\t4. efficient.frontier\t\t\t compute Markowitz bullet\n#\t5. getPortfolio\t\t\t\t\t create portfolio object\n#\n\ngetPortfolio <-\nfunction(er, cov.mat, weights)\n{\n\t# contruct portfolio object\n\t#\n\t# inputs:\n\t# er\t\t\t\t N x 1 vector of expected returns\n\t# cov.mat \t\t N x N covariance matrix of returns\n\t# weights\t\t\t N x 1 vector of portfolio weights\n\t#\n\t# output is portfolio object with the following elements\n\t# call\t\t\t\toriginal function call\n\t# er\t\t\t\t portfolio expected return\n\t# sd\t\t\t\t portfolio standard deviation\n\t# weights\t\t\tN x 1 vector of portfolio weights\n\t#\n\tcall <- match.call()\n\t\n\t#\n\t# check for valid inputs\n\t#\n\tasset.names <- names(er)\n\tweights <- as.vector(weights)\n\tnames(weights) = names(er)\n \ter <- as.vector(er)\t\t\t\t\t# assign names if none exist\n\tif(length(er) != length(weights))\n\t\tstop(\"dimensions of er and weights do not match\")\n \tcov.mat <- as.matrix(cov.mat)\n\tif(length(er) != nrow(cov.mat))\n\t\tstop(\"dimensions of er and cov.mat do not match\")\n\tif(any(diag(chol(cov.mat)) <= 0))\n\t\tstop(\"Covariance matrix not positive definite\")\n\t\t\n\t#\n\t# create portfolio\n\t#\n\ter.port <- crossprod(er,weights)\n\tsd.port <- sqrt(weights %*% cov.mat %*% weights)\n\tans <- list(\"call\" = call,\n\t \"er\" = as.vector(er.port),\n\t \"sd\" = as.vector(sd.port),\n\t \"weights\" = weights) \n\tclass(ans) <- \"portfolio\"\n\tans\n}\n\nefficient.portfolio <-\nfunction(er, cov.mat, target.return)\n{\n # compute minimum variance portfolio subject to target return\n #\n # inputs:\n # er\t\t\t\t\t N x 1 vector of expected returns\n # cov.mat \t\t\t N x N covariance matrix of returns\n # target.return\t scalar, target expected return\n #\n # output is portfolio object with the following elements\n # call\t\t\t\t original function call\n # er\t\t\t\t\t portfolio expected return\n # sd\t\t\t\t\t portfolio standard deviation\n # weights\t\t\t N x 1 vector of portfolio weights\n #\n call <- match.call()\n\n #\n # check for valid inputs\n #\n asset.names <- names(er)\n er <- as.vector(er)\t\t\t\t\t# assign names if none exist\n cov.mat <- as.matrix(cov.mat)\n if(length(er) != nrow(cov.mat))\n stop(\"invalid inputs\")\n if(any(diag(chol(cov.mat)) <= 0))\n stop(\"Covariance matrix not positive definite\")\n # remark: could use generalized inverse if cov.mat is positive semidefinite\n\n #\n # compute efficient portfolio\n #\n ones <- rep(1, length(er))\n top <- cbind(2*cov.mat, er, ones)\n bot <- cbind(rbind(er, ones), matrix(0,2,2))\n A <- rbind(top, bot)\n b.target <- as.matrix(c(rep(0, length(er)), target.return, 1))\n x <- solve(A, b.target)\n w <- x[1:length(er)]\n names(w) <- asset.names\n\n #\n # compute portfolio expected returns and variance\n #\n er.port <- crossprod(er,w)\n sd.port <- sqrt(w %*% cov.mat %*% w)\n ans <- list(\"call\" = call,\n\t \"er\" = as.vector(er.port),\n\t \"sd\" = as.vector(sd.port),\n\t \"weights\" = w) \n class(ans) <- \"portfolio\"\n ans\n}\n\nglobalMin.portfolio <-\nfunction(er, cov.mat)\n{\n # Compute global minimum variance portfolio\n #\n # inputs:\n # er\t\t\t\tN x 1 vector of expected returns\n # cov.mat\t\tN x N return covariance matrix\n #\n # output is portfolio object with the following elements\n # call\t\t\toriginal function call\n # er\t\t\t\tportfolio expected return\n # sd\t\t\t\tportfolio standard deviation\n # weights\t\tN x 1 vector of portfolio weights\n call <- match.call()\n\n #\n # check for valid inputs\n #\n asset.names <- names(er)\n er <- as.vector(er)\t\t\t\t\t# assign names if none exist\n cov.mat <- as.matrix(cov.mat)\n if(length(er) != nrow(cov.mat))\n stop(\"invalid inputs\")\n if(any(diag(chol(cov.mat)) <= 0))\n stop(\"Covariance matrix not positive definite\")\n # remark: could use generalized inverse if cov.mat is positive semi-definite\n\n #\n # compute global minimum portfolio\n #\n cov.mat.inv <- solve(cov.mat)\n one.vec <- rep(1,length(er))\n# w.gmin <- cov.mat.inv %*% one.vec/as.vector(one.vec %*% cov.mat.inv %*% one.vec)\n w.gmin <- rowSums(cov.mat.inv) / sum(cov.mat.inv)\n w.gmin <- as.vector(w.gmin)\n names(w.gmin) <- asset.names\n er.gmin <- crossprod(w.gmin,er)\n sd.gmin <- sqrt(t(w.gmin) %*% cov.mat %*% w.gmin)\n gmin.port <- list(\"call\" = call,\n\t\t \"er\" = as.vector(er.gmin),\n\t\t \"sd\" = as.vector(sd.gmin),\n\t\t \"weights\" = w.gmin)\n class(gmin.port) <- \"portfolio\"\n gmin.port\n}\n\n\ntangency.portfolio <- \nfunction(er,cov.mat,risk.free)\n{\n # compute tangency portfolio\n #\n # inputs:\n # er\t\t\t\t N x 1 vector of expected returns\n # cov.mat\t\t N x N return covariance matrix\n # risk.free\t\t scalar, risk-free rate\n #\n # output is portfolio object with the following elements\n # call\t\t\t captures function call\n # er\t\t\t\t portfolio expected return\n # sd\t\t\t\t portfolio standard deviation\n # weights\t\t N x 1 vector of portfolio weights\n call <- match.call()\n\n #\n # check for valid inputs\n #\n asset.names <- names(er)\n if(risk.free < 0)\n stop(\"Risk-free rate must be positive\")\n er <- as.vector(er)\n cov.mat <- as.matrix(cov.mat)\n if(length(er) != nrow(cov.mat))\n stop(\"invalid inputs\")\n if(any(diag(chol(cov.mat)) <= 0))\n stop(\"Covariance matrix not positive definite\")\n # remark: could use generalized inverse if cov.mat is positive semi-definite\n\n #\n # compute global minimum variance portfolio\n #\n gmin.port <- globalMin.portfolio(er,cov.mat)\n if(gmin.port$er < risk.free)\n stop(\"Risk-free rate greater than avg return on global minimum variance portfolio\")\n\n # \n # compute tangency portfolio\n #\n cov.mat.inv <- solve(cov.mat)\n w.t <- cov.mat.inv %*% (er - risk.free) # tangency portfolio\n w.t <- as.vector(w.t/sum(w.t))\t# normalize weights\n names(w.t) <- asset.names\n er.t <- crossprod(w.t,er)\n sd.t <- sqrt(t(w.t) %*% cov.mat %*% w.t)\n tan.port <- list(\"call\" = call,\n\t\t \"er\" = as.vector(er.t),\n\t\t \"sd\" = as.vector(sd.t),\n\t\t \"weights\" = w.t)\n class(tan.port) <- \"portfolio\"\n tan.port\n}\n\nefficient.frontier <- \nfunction(er, cov.mat, nport=20, alpha.min=-0.5, alpha.max=1.5)\n{\n # Compute efficient frontier with no short-sales constraints\n #\n # inputs:\n # er\t\t\t N x 1 vector of expected returns\n # cov.mat\t N x N return covariance matrix\n # nport\t\t scalar, number of efficient portfolios to compute\n #\n # output is a Markowitz object with the following elements\n # call\t\t captures function call\n # er\t\t\t nport x 1 vector of expected returns on efficient porfolios\n # sd\t\t\t nport x 1 vector of std deviations on efficient portfolios\n # weights \tnport x N matrix of weights on efficient portfolios \n call <- match.call()\n\n #\n # check for valid inputs\n #\n asset.names <- names(er)\n er <- as.vector(er)\n cov.mat <- as.matrix(cov.mat)\n if(length(er) != nrow(cov.mat))\n stop(\"invalid inputs\")\n if(any(diag(chol(cov.mat)) <= 0))\n stop(\"Covariance matrix not positive definite\")\n\n #\n # create portfolio names\n #\n port.names <- rep(\"port\",nport)\n ns <- seq(1,nport)\n port.names <- paste(port.names,ns)\n\n #\n # compute global minimum variance portfolio\n #\n cov.mat.inv <- solve(cov.mat)\n one.vec <- rep(1,length(er))\n port.gmin <- globalMin.portfolio(er,cov.mat)\n w.gmin <- port.gmin$weights\n\n #\n # compute efficient frontier as convex combinations of two efficient portfolios\n # 1st efficient port: global min var portfolio\n # 2nd efficient port: min var port with ER = max of ER for all assets\n #\n er.max <- max(er)\n port.max <- efficient.portfolio(er,cov.mat,er.max)\n w.max <- port.max$weights \n a <- seq(from=alpha.min,to=alpha.max,length=nport)\t\t\t# convex combinations\n we.mat <- a %o% w.gmin + (1-a) %o% w.max\t# rows are efficient portfolios\n er.e <- we.mat %*% er\t\t\t\t\t\t\t# expected returns of efficient portfolios\n er.e <- as.vector(er.e)\n names(er.e) <- port.names\n cov.e <- we.mat %*% cov.mat %*% t(we.mat) # cov mat of efficient portfolios\n sd.e <- sqrt(diag(cov.e))\t\t\t\t\t# std devs of efficient portfolios\n sd.e <- as.vector(sd.e)\n names(sd.e) <- port.names\n dimnames(we.mat) <- list(port.names,asset.names)\n\n # \n # summarize results\n #\n ans <- list(\"call\" = call,\n\t \"er\" = er.e,\n\t \"sd\" = sd.e,\n\t \"weights\" = we.mat)\n class(ans) <- \"Markowitz\"\n ans\n}\n\n#\n# print method for portfolio object\nprint.portfolio <- function(x, ...)\n{\n cat(\"Call:\\n\")\n print(x$call, ...)\n cat(\"\\nPortfolio expected return: \", format(x$er, ...), \"\\n\")\n cat(\"Portfolio standard deviation: \", format(x$sd, ...), \"\\n\")\n cat(\"Portfolio weights:\\n\")\n print(round(x$weights,4), ...)\n invisible(x)\n}\n\n#\n# summary method for portfolio object\nsummary.portfolio <- function(object, risk.free=NULL, ...)\n# risk.free\t\t\trisk-free rate. If not null then\n#\t\t\t\tcompute and print Sharpe ratio\n# \n{\n cat(\"Call:\\n\")\n print(object$call)\n cat(\"\\nPortfolio expected return: \", format(object$er, ...), \"\\n\")\n cat( \"Portfolio standard deviation: \", format(object$sd, ...), \"\\n\")\n if(!is.null(risk.free)) {\n SharpeRatio <- (object$er - risk.free)/object$sd\n cat(\"Portfolio Sharpe Ratio: \", format(SharpeRatio), \"\\n\")\n }\n cat(\"Portfolio weights:\\n\")\n print(round(object$weights,4), ...)\n invisible(object)\n}\n# hard-coded 4 digits; prefer to let user control, via ... or other argument\n\n#\n# plot method for portfolio object\nplot.portfolio <- function(object, ...)\n{\n asset.names <- names(object$weights)\n barplot(object$weights, names=asset.names,\n\t xlab=\"Assets\", ylab=\"Weight\", main=\"Portfolio Weights\", ...)\n invisible()\n}\n\n#\n# print method for Markowitz object\nprint.Markowitz <- function(x, ...)\n{\n cat(\"Call:\\n\")\n print(x$call)\n xx <- rbind(x$er,x$sd)\n dimnames(xx)[[1]] <- c(\"ER\",\"SD\")\n cat(\"\\nFrontier portfolios' expected returns and standard deviations\\n\")\n print(round(xx,4), ...)\n invisible(x)\n}\n# hard-coded 4, should let user control\n\n#\n# summary method for Markowitz object\nsummary.Markowitz <- function(object, risk.free=NULL)\n{\n call <- object$call\n asset.names <- colnames(object$weights)\n port.names <- rownames(object$weights)\n if(!is.null(risk.free)) {\n # compute efficient portfolios with a risk-free asset\n nport <- length(object$er)\n sd.max <- object$sd[1]\n sd.e <- seq(from=0,to=sd.max,length=nport)\t\n names(sd.e) <- port.names\n\n #\n # get original er and cov.mat data from call \n er <- eval(object$call$er)\n cov.mat <- eval(object$call$cov.mat)\n\n #\n # compute tangency portfolio\n tan.port <- tangency.portfolio(er,cov.mat,risk.free)\n x.t <- sd.e/tan.port$sd\t\t# weights in tangency port\n rf <- 1 - x.t\t\t\t# weights in t-bills\n er.e <- risk.free + x.t*(tan.port$er - risk.free)\n names(er.e) <- port.names\n we.mat <- x.t %o% tan.port$weights\t# rows are efficient portfolios\n dimnames(we.mat) <- list(port.names, asset.names)\n we.mat <- cbind(rf,we.mat) \n }\n else {\n er.e <- object$er\n sd.e <- object$sd\n we.mat <- object$weights\n }\n ans <- list(\"call\" = call,\n\t \"er\"=er.e,\n\t \"sd\"=sd.e,\n\t \"weights\"=we.mat)\n class(ans) <- \"summary.Markowitz\"\t\n ans\n}\n\nprint.summary.Markowitz <- function(x, ...)\n{\n\txx <- rbind(x$er,x$sd)\n\tport.names <- names(x$er)\n\tasset.names <- colnames(x$weights)\n\tdimnames(xx)[[1]] <- c(\"ER\",\"SD\")\n\tcat(\"Frontier portfolios' expected returns and standard deviations\\n\")\n\tprint(round(xx,4), ...)\n\tcat(\"\\nPortfolio weights:\\n\")\n\tprint(round(x$weights,4), ...)\n\tinvisible(x)\n}\n# hard-coded 4, should let user control\n\n#\n# plot efficient frontier\n#\n# things to add: plot original assets with names\n# tangency portfolio\n# global min portfolio\n# risk free asset and line connecting rf to tangency portfolio\n#\nplot.Markowitz <- function(object, plot.assets=FALSE, ...)\n# plot.assets\t\tlogical. If true then plot asset sd and er\n{\n if (!plot.assets) {\n y.lim=c(0,max(object$er))\n x.lim=c(0,max(object$sd))\n plot(object$sd,object$er,type=\"b\",xlim=x.lim, ylim=y.lim,\n xlab=\"Portfolio SD\", ylab=\"Portfolio ER\", \n main=\"Efficient Frontier\", ...)\n }\n else {\n\t call = object$call\n\t mu.vals = eval(call$er)\n\t sd.vals = sqrt( diag( eval(call$cov.mat) ) )\n\t y.lim = range(c(0,mu.vals,object$er))\n\t x.lim = range(c(0,sd.vals,object$sd))\n\t plot(object$sd,object$er,type=\"b\", xlim=x.lim, ylim=y.lim,\n xlab=\"Portfolio SD\", ylab=\"Portfolio ER\", \n main=\"Efficient Frontier\", ...)\n text(sd.vals, mu.vals, labels=names(mu.vals))\n }\n invisible()\n}\n", "meta": {"hexsha": "9b13d1cbaa9284c55d2c5d07820f1c20ae773710", "size": 12884, "ext": "r", "lang": "R", "max_stars_repo_path": "Reproducible Finance/portfolio.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": "Reproducible Finance/portfolio.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": "Reproducible Finance/portfolio.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": 29.018018018, "max_line_length": 87, "alphanum_fraction": 0.6391648556, "num_tokens": 3669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6151631961929156}} {"text": "#' @title Compute turnover components.\n#'\n#' @description Compute the a, b, c turnover components. Given two vectors, v1\n#' and v2, of species names or interactions, component \"a\" is the number of\n#' elements (species or interactions) present in both vectors v1 and v2, \"b\"\n#' is the number of elements present only in v1 and \"c\" only in v2. See the\n#' section \"Beta diversity estimates\" in Novotny, V. (2009). Beta diversity\n#' of plant–insect food webs in tropical forests: a conceptual framework.\n#' Insect Conservation and Diversity, 2(1), 5-9.\n#'\n#' @param vect A list of two vectors with species names or interactions.\n#'\n#' @return A list with the 3 components a, b, c. The elements of the list are\n#' numeric vectors of length 1.\n#'\n#' @examples\n#'\n#' library(bootdissim)\n#' library(bipartite)\n#'\n#' net1 <- reshape_net(vazarr, seed = 1)\n#' net2 <- reshape_net(vazcer, seed = 1)\n#' vect <- get_interactions(net1, net2)\n#' abc <- get_abc(vect)\n#'\n#' @export\n#'\n#' @md\nget_abc <- function(vect){\n v1 <- vect[[1]]\n v2 <- vect[[2]]\n\n # Fast testing if elements of a vector are present in a second vector. The\n # index position doesn't matter. What matters is if for a given element from\n # the first vector, the match() function returns a value of zero or above\n # zero. A zero indicates that the respective element from the first vector\n # doesn't exist in the second vector. A positive value indicates that the\n # respective element from the first vector exists in the second vector. The\n # value itself indicates the first position where that element is encountered\n # in the second vector, but this information is not important for our\n # purposes. We used match() function because is fast.\n match_v1_in_v2 <- match(v1, v2, nomatch = 0)\n match_v2_in_v1 <- match(v2, v1, nomatch = 0)\n\n # Get the a, b and c components.\n\n # \"a\" is the number of elements present in both vectors v1 and v2\n a <- sum(match_v2_in_v1 > 0) # same as sum(match_v1_in_v2 > 0)\n # \"b\" is the number of elements present only in v1\n b <- sum(!(match_v1_in_v2 > 0))\n # \"c\" is the number of elements present only in v2\n c <- sum(!(match_v2_in_v1 > 0))\n\n return(list(a = a, b = b, c = c))\n}\n\n\n#' @title Compute dissimilarity index.\n#'\n#' @description Compute various dissimilarity indices.\n#'\n#' @param abc A list with the turnover components a, b and c.\n#'\n#' @param index The name of the desired index, e.g.: \"whittaker\", \"jaccard\",\n#' \"sorensen\". Character type.\n#'\n#' @return A dissimilarity index. Numeric vector of length one.\n#'\n#' @examples\n#'\n#' library(bootdissim)\n#' library(bipartite)\n#'\n#' net1 <- reshape_net(vazarr, seed = 1)\n#' net2 <- reshape_net(vazcer, seed = 1)\n#' vect <- get_interactions(net1, net2)\n#' abc <- get_abc(vect)\n#' get_beta(abc, index = \"whittaker\")\n#' get_beta(abc, index = \"jaccard\")\n#' get_beta(abc, index = \"sorensen\")\n#'\n#' @export\n#'\n#' @md\n\nget_beta <- function(abc, index){\n a <- abc[[\"a\"]]\n b <- abc[[\"b\"]]\n c <- abc[[\"c\"]]\n\n switch(index,\n whittaker = 2*(a+b+c)/(2*a+b+c) - 1, # sometimes written as ( (a + b + c) / ((2*a + b + c)/2) ) - 1\n jaccard = a/(a+b+c),\n sorensen = (2*a)/(2*a+b+c),\n stop(\"Your index is not recognised or available. Typo? Check help for options.\",\n call. = FALSE))\n # Switch is generally faster than if statements.\n # https://stackoverflow.com/a/7826352/5193830\n}\n\n", "meta": {"hexsha": "8a7b928d39a3a2bb7354b03cb177abfbe6e0178d", "size": 3398, "ext": "r", "lang": "R", "max_stars_repo_path": "R/indices.r", "max_stars_repo_name": "valentinitnelav/bootstrapturnover", "max_stars_repo_head_hexsha": "86c27b46be0d3d63100ea695b4724175f703e823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-03-22T19:14:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T17:01:52.000Z", "max_issues_repo_path": "R/indices.r", "max_issues_repo_name": "valentinitnelav/bootstrapturnover", "max_issues_repo_head_hexsha": "86c27b46be0d3d63100ea695b4724175f703e823", "max_issues_repo_licenses": ["MIT"], "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/indices.r", "max_forks_repo_name": "valentinitnelav/bootstrapturnover", "max_forks_repo_head_hexsha": "86c27b46be0d3d63100ea695b4724175f703e823", "max_forks_repo_licenses": ["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.6435643564, "max_line_length": 108, "alphanum_fraction": 0.6630370806, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6151631933210809}} {"text": "# Implementation of the Douglas-Peucker algorithm for line thinning\n# http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\nsimplify_rec <- function(points, tol = 0.01) {\n n <- nrow(points)\n if (n <= 2) return() # c(1, n))\n dist <- with(points, point_line_dist(x, y, x[1], y[1], x[n], y[n]))\n \n if (max(dist, na.rm = T) > tol) {\n furthest <- which.max(dist)\n c(\n simplify_rec(points[1:(furthest - 1), ], tol),\n furthest,\n simplify_rec(points[(furthest + 1):n, ], tol) + furthest \n )\n } else {\n c()\n } \n}\n\n# From http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html\npoint_line_dist <- function(px, py, lx_1, ly_1, lx_2, ly_2) {\n abs((lx_2 - lx_1) * (ly_1 - py) - (lx_1 - px) * (ly_2 - ly_1)) /\n sqrt((lx_2 - lx_1) ^ 2 + (ly_2 - ly_1) ^ 2)\n}\n\n# Precompute all tolerances so that we can post-select quickly\ncompute_tol <- function(points, offset = 0) {\n n <- nrow(points)\n if (n <= 2) {\n c()\n } else if (n == 3) {\n with(points,\n point_line_dist(long[2], lat[2], long[1], lat[1], long[3], lat[3]))\n } else {\n dist <- with(points, \n point_line_dist(long[2:(n-1)], lat[2:(n-1)], long[1], lat[1], long[n], lat[n])\n )\n \n furthest <- which.max(dist)\n if (length(furthest) == 0) browser()\n c(\n compute_tol(points[1:(furthest + 1), ], offset),\n dist[furthest],\n compute_tol(points[(furthest + 1):n, ], furthest + offset)\n )\n }\n}", "meta": {"hexsha": "edbf20b3138c8f8fc93ddb53695948b70d8deb6c", "size": 1431, "ext": "r", "lang": "R", "max_stars_repo_path": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_stars_repo_name": "maxim5/code-inspector", "max_stars_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-01-03T06:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T13:15:29.000Z", "max_issues_repo_path": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_issues_repo_name": "maxim5/code-inspector", "max_issues_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "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": "data/r/4d3b204f419e13c711e427f1e3aae40b_thin.r", "max_forks_repo_name": "maxim5/code-inspector", "max_forks_repo_head_hexsha": "14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-04T02:54:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-24T17:50:46.000Z", "avg_line_length": 30.4468085106, "max_line_length": 84, "alphanum_fraction": 0.5828092243, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6150240754915592}} {"text": "##### Chapter 9: Clustering with k-means -------------------\n\n# 군집화는 데이터를 cluster로 자동 분리하는 머신 러닝 작업이다.\n# 찾고 있는 것이 무엇인지 모르기 때문에, 군집화는 예측보다는 지식의 발견에 사용된다.\n\n# 모델은 데이터 내에 존재하는 패턴을 설명한다.\n# 이와 대조적으로 군집화는 새로운 데이터를 생성한다.\n\n# 주목할 점은 자율 분류기(=군집기)에서 얻은 클래스 레이블은 본질적인 의미가 없다는 것이다.\n # 군집화는 어떤 예시 그룹이 긴밀하게 연관되어 있는지는 말해 주지만,\n # 실행 가능하고 의미 있는 레이블을 적용하는 것은 사람의 책임이다.\n\n# k- 평균 알고리즘은 n개의 예시를 k개의 클러스터 중 하나에 할당하는데, 이 때 k는 사전에 결정됨\n # 이 알고리즘의 목표는 클러스터 내의 차이를 최소화하고, 클러스터 간의 차이를 최대화하는 것이다.\n\n# k-평균 알고리즘은 클러스터 중심의 출발 위치에 매우 민감하다.\n # k-평균의 초기 중심을 선택하는 방법을 다르게 할 수 있다. 거리는 보통 유클리드 거리를 사용한다.\n\n# k를 크게 설정하면 클러스터의 동질성이 향상 but overfitting 위험 커진다.\n # 이상적으로는 실제 그룹에 대한 선험적(a priori)지식이 있을 것이며, 이 정보를 클러스터 개수를 선택하는데 적용가능\n # 사전 지식이 없다면 k를 n/2의 제곱근과 동일하도록 설정해보자.\n # 엘보법\n # 다양한 k값에 대해 클러스터 내의 동질성과 이질성이 어떠헥 변하는지를 측정한다.\n## Example: Finding Teen Market Segments ----\n## Step 2: Exploring and preparing the data ----\nsetwd(\"D:/R_LAB/MlwR/Chapter 09\")\nteens <- read.csv(\"snsdata.csv\")\nstr(teens)\n\n# look at missing data for female variable\ntable(teens$gender)\ntable(teens$gender, useNA = \"ifany\")\n\n# look at missing data for age variable\nsummary(teens$age)\n\n# eliminate age outliers\nteens$age <- ifelse(teens$age >= 13 & teens$age < 20,\n teens$age, NA)\n\nsummary(teens$age)\n\n# reassign missing gender values to \"unknown\"\nteens$female <- ifelse(teens$gender == \"F\" &\n !is.na(teens$gender), 1, 0)\nteens$no_gender <- ifelse(is.na(teens$gender), 1, 0)\n\n# check our recoding work\ntable(teens$gender, useNA = \"ifany\")\ntable(teens$female, useNA = \"ifany\")\ntable(teens$no_gender, useNA = \"ifany\")\n\n# finding the mean age by cohort\nmean(teens$age) # doesn't work\nmean(teens$age, na.rm = TRUE) # works\n\n# age by cohort\n# aggregate() 함수는 데이터의 하위 그룹에 대한 통계를 계산한다.\naggregate(data = teens, age ~ gradyear, mean, na.rm = TRUE)\n\n# create a vector with the average age for each gradyear, repeated by person\n# ave() 함수는 결과가 원 벡터의 길이와 같아지게 그룹의 평균이 반복되는 벡터를 반환한다.\nave_age <- ave(teens$age, teens$gradyear,\n FUN = function(x) mean(x, na.rm = TRUE))\n\n\nteens$age <- ifelse(is.na(teens$age), ave_age, teens$age) # 결측치에 ave_age 넣\n\n# check the summary results to ensure missing values are eliminated\nsummary(teens$age)\n\n## Step 3: Training a model on the data ----\ninterests <- teens[5:40]\ninterests_z <- as.data.frame(lapply(interests, scale))\n\nset.seed(13123313)\nteen_clusters <- kmeans(interests_z, 5)\n\n## Step 4: Evaluating model performance ----\n# look at the size of the clusters\nteen_clusters$size\n\n# look at the cluster centers :각 클러스터의 동질성을 살펴보자. 중심점의 좦를 알아보자.\nteen_clusters$centers\n# 양수는 모든 십대에 대한 전체 평균 이상, 음수는 전체 평균 이하.\n# 클러스터가 각 관심 범주에 대해 평균 이상인지 이앟인지 검토 > 클러스터는 서로 구별하는 패턴 인식.\n\n\n## Step 5: Improving model performance ----\n# apply the cluster IDs to the original data frame\n\n# 이 클러스터를 전체 데이터셋에 역을 ㅗ적용하자.\n# kmeans() 함수에 의해 생성된 teen_cluster객체는 cluster라는 이름의 component를 포함한다.\n# cluster component에는 전체 30000명 개인에 대한 클러스터 할당이 포함되어 있다.\n# 다음 명령으로 cluster component를 teens 데이터 프레임의 열로 추가할 수 있다.\nteens$cluster <- teen_clusters$cluster\n\n# look at the first five records\nteens[1:5, c(\"cluster\", \"gender\", \"age\", \"friends\")]\n\n# mean age by cluster # aggregate()로 인구통계학적 특성 살펴보\naggregate(data = teens, age ~ cluster, mean)\n\n# proportion of females by cluster\naggregate(data = teens, female ~ cluster, mean) # 여성 비율은 상당한 차이가 있다(성별 데이터 사용 않았음에도)\n\n# mean number of friends by cluster\naggregate(data = teens, friends ~ cluster, mean) # 공주, 범죄자, 그리고 무력한 사람\n\n# k-평균 알고리즘 뿐만 아니라, 작업에 고유한 편향과 휴리스틱을 제공하는 다른 여러 군집 알고리즘 변형이 있다.", "meta": {"hexsha": "1ce49097c91bd4aef5fe761080fb5f227b5fe7a8", "size": 3520, "ext": "r", "lang": "R", "max_stars_repo_path": "MLwR/Chapter 09/MLwR_v2_09(Clustering).r", "max_stars_repo_name": "BeginnerJay/R_STUDYING", "max_stars_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MLwR/Chapter 09/MLwR_v2_09(Clustering).r", "max_issues_repo_name": "BeginnerJay/R_STUDYING", "max_issues_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MLwR/Chapter 09/MLwR_v2_09(Clustering).r", "max_forks_repo_name": "BeginnerJay/R_STUDYING", "max_forks_repo_head_hexsha": "4dcca5a781cf550c8c40edc636c247357c95a296", "max_forks_repo_licenses": ["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.0, "max_line_length": 84, "alphanum_fraction": 0.6914772727, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6150098352123314}} {"text": "#!/usr/bin/Rscript\n\n########################################################################################\n# script name: calculate_probabilities.r\n# developed by: Haris Zafeiropoulos, Savvas Paragkamian\n# framework: PREGO - WP4\n########################################################################################\n# GOAL:\n# this script aims to calculate PREGO association scores\n########################################################################################\n#\n# usage: Rscript calculate_probabilities.r\n#\n########################################################################################\n\n\n# Dependencies\nlibrary(Rfast)\n\n######################################################\n### Regarding the NCBI IDs and their probabilities\n######################################################\n\n# read the background file\nx<- read.csv(\"/data/databases/scripts/gathering_data/mgnify/ncbi_background.tsv\", header = FALSE, sep = \"\\t\")\n\n# keep the values of each id occurence\nmydata_x <- x$V2\n\n# build a model using the negative binomial distribution\nmod_x <- negbin.mle(mydata_x)\n\n# calculate the probability of each ncbi id to come with respect to the non binomial distribution we built\nx$new_x <- dnbinom(x = mydata_x, size = mod_x$param[2], prob = mod_x$param[1])\n\n# write an output file with the probabilities of each NCBI ID to come \nwrite.table(x, file='/data/databases/scripts/gathering_data/mgnify/probabilities_ncbi.tsv', quote=FALSE, sep='\\t', row.names = FALSE, col.names = FALSE)\n\n\n########################################################\n### Regarding the metadata terms and their probabilities\n########################################################\n\n# read the background file\ny <- read.csv(\"/data/databases/scripts/gathering_data/mgnify/metadata_background.tsv\", header = FALSE, sep = \"\\t\")\n\n# keep the values of each id occurence\nmydata_y <- y$V2\n\n# build a model using the negative binomial distribution\nmod_y <- negbin.mle(mydata_y)\n\n# calculate the probability of each ncbi id to come with respect to the non binomial distribution we built\ny$new_y <- dnbinom(x = mydata_y, size = mod_y$param[2], prob = mod_y$param[1])\n\n# write an output file with the probabilities of each metadata ter to come \nwrite.table(y, file='/data/databases/scripts/gathering_data/mgnify/probabilities_metadata.tsv', quote=FALSE, sep='\\t', row.names = FALSE, col.names = FALSE)\n", "meta": {"hexsha": "0b69880f2ac92e27dc812308ef8fe9398bd8b92d", "size": 2381, "ext": "r", "lang": "R", "max_stars_repo_path": "mgnify/calculate_probabilities.r", "max_stars_repo_name": "lab42open-team/prego_gathering_data", "max_stars_repo_head_hexsha": "f882bf7220afcf6d68a45825c22dd88e4e325abe", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mgnify/calculate_probabilities.r", "max_issues_repo_name": "lab42open-team/prego_gathering_data", "max_issues_repo_head_hexsha": "f882bf7220afcf6d68a45825c22dd88e4e325abe", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mgnify/calculate_probabilities.r", "max_forks_repo_name": "lab42open-team/prego_gathering_data", "max_forks_repo_head_hexsha": "f882bf7220afcf6d68a45825c22dd88e4e325abe", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0517241379, "max_line_length": 156, "alphanum_fraction": 0.5728685426, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.614882945561938}} {"text": "# A general Brownian motion with mean non necessarily 0\n# and non-necessarily unit variance.\n# 23-04-2015\n# Killian Martin--Horgassan\n\ngeneralBM = function(mu, sigma,h) {\n\t\n\t# Number of time steps\n\tt <- ceiling(1/h)\n\t\n\t# Generating a t-uplet Gaussian vector and taking the sum\n\tvect <- cumsum(rnorm(t, mu*h, sigma*h))\n\t\n\treturn(vect)\n}", "meta": {"hexsha": "89917d66a02fb043a3e8eee9e8c78d30c122d11a", "size": 335, "ext": "r", "lang": "R", "max_stars_repo_path": "r_files_buildingBM/MvtBrownienCasParticulier/generalBM.r", "max_stars_repo_name": "CillianMH/pdmExtremeValueTheory", "max_stars_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r_files_buildingBM/MvtBrownienCasParticulier/generalBM.r", "max_issues_repo_name": "CillianMH/pdmExtremeValueTheory", "max_issues_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_files_buildingBM/MvtBrownienCasParticulier/generalBM.r", "max_forks_repo_name": "CillianMH/pdmExtremeValueTheory", "max_forks_repo_head_hexsha": "f7a7504c2eca0c6be665bcfc3d98dfee6c02de41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3333333333, "max_line_length": 58, "alphanum_fraction": 0.7074626866, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.6148829396203435}} {"text": "#' pGLS model comparison using phylogenetic analysis of covariance (gls.ancova)\n#'\n#' Computes F-ratio test of GLS models that include different sets of indicator variables.\n#' @param form Model formula. \n#' @param Sigma Matrix describing the covariance among data points. For the phylogenetic regression, this is based on a phylogeny (vcv(tree)). \n#' @param ReducedModel The GLS model that includes the fewest indicator variables. \n#' @param FullModel The GLS model that includes the fewest indicator variables. \n#' @return Anova table.\n#' @references Smaers & Rohlf (2016) Testing species' deviations from allometric preductions using the phylogenetic regression. Evolution. 70 (5): 1145-1149.\n#' @examples see https://smaerslab.com/software/ \n#' @export\n\ngls.ancova<-function (form, Sigma, ReducedModel, FullModel) \n{\n Y<-c(data[,which(colnames(data)==all.vars(form)[1])])\n n <- length(Y); tr <- sum(diag(Sigma)); Sigma <- n * Sigma/tr; invSigma <- solve(Sigma)\n df_ReducedModel <- c(length(ReducedModel[1, ])); df_FullModel <- c(length(FullModel[1, ]))\n\n C <- solve(t(ReducedModel) %*% invSigma %*% ReducedModel)\n B <- C %*% t(ReducedModel) %*% invSigma %*% Y\n SS_unexpl_ReducedModel <- (t(Y - (ReducedModel %*% B)) %*% invSigma %*% (Y - (ReducedModel %*% B)))\n MS_unexpl_ReducedModel <- SS_unexpl_ReducedModel/c(n-df_ReducedModel)\n\n C <- solve(t(FullModel) %*% invSigma %*% FullModel)\n B <- C %*% t(FullModel) %*% invSigma %*% Y\n SS_unexpl_FullModel <- (t(Y - (FullModel %*% B)) %*% invSigma %*% (Y - (FullModel %*% B)))\n MS_unexpl_FullModel <- SS_unexpl_FullModel/c(n-df_FullModel)\n\n Fs <- ((SS_unexpl_ReducedModel - SS_unexpl_FullModel)/(c(n-df_ReducedModel) - c(n-df_FullModel)))/(SS_unexpl_FullModel/c(n-df_FullModel))\n P <- 1 - pf(Fs, (c(n-df_ReducedModel) - c(n-df_FullModel)), c(n-df_FullModel))\n\n Output <- as.data.frame(cbind(rbind(df_FullModel, df_ReducedModel), \n rbind(round(SS_unexpl_FullModel, 4), round(SS_unexpl_ReducedModel, 4)), rbind(round(MS_unexpl_FullModel, 4), round(MS_unexpl_ReducedModel, 4)), rbind(round(Fs, 4), \"\"), rbind(round(P, 4), \"\")))\n colnames(Output) <- c(\"df\", \"Sum Sq\", \"Mean Sum Sq\", \"F value\", \"Pr(>F)\")\n rownames(Output) <- c(\"FullModel\", \"ReducedModel\")\n return(Output)\n}\n\n\n", "meta": {"hexsha": "d03d311346c4ece224cbe92f544c77438e6ca5d8", "size": 2279, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gls.ancova.r", "max_stars_repo_name": "JeroenSmaers/evomap", "max_stars_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-01-07T04:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-15T19:42:12.000Z", "max_issues_repo_path": "R/gls.ancova.r", "max_issues_repo_name": "JeroenSmaers/evomap", "max_issues_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/gls.ancova.r", "max_forks_repo_name": "JeroenSmaers/evomap", "max_forks_repo_head_hexsha": "dfa7dfdc560d1fd04414dffedab7b6be765d8175", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2015-10-14T18:26:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-10T04:57:55.000Z", "avg_line_length": 56.975, "max_line_length": 201, "alphanum_fraction": 0.6858271172, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.614882935656246}} {"text": "# Test de hipótesis (t test), errores Tipo I y II, significancia estadística (p-values).\n#################################################################\ncat(\"\\014\")\nrm(list=ls())\ngraphics.off()\n\n#################################################################\n# Motivacion\n#################################################################\n\n# Hasta el momento sabemos interpretar las primeras dos columnas de nuestra tabla de regresion.\n# Es decir, (a) los betas (Estimadores o Coeficientes) y (b) el error estandard. \n# Tambien sabemos (c) que son los intervalos de confianza y cual es su relacion con los \n# errores estandard. Sin embargo, hasta el momento no sabemos que son esas estrellas\n# que aparecen en nuestra tabla.\n\n# Esto es lo que aprenderemos hoy. El coeficiente nos dice el tamano del efecto.\n# Sin embargo, hay una posibildiad de que estemos equivocados. Recuerda,\n# nuestra logica es frecuentista. El 95% de confianza significa que si \n# el mismo fenomeno se repitiera 100 veces, 95 veces sucederia lo que estamos\n# prediciendo. \n\n# Como hacemos este calculo? Esto esta muy relacionado a los intervalos de confianza. \n# Para esto, necesitamos hacer tests de hipotesis y CALCULAR\n# CUAN CERCANOS O LEJANOS ESTAMOS DE QUE NUESTROS BETAS SEAN LO QUE NOSOTROS\n# CREEMOS QUE SON.\n\n\n#################################################################\n# Estimemos un modelo\n#################################################################\n\n# Cargar paquete para cargar bases que no son de R.\n# install.packages(\"foreign\")\nlibrary(foreign) # significa \"foraneo\"\noptions(scipen = 1000000) # apagar notacion cientifica.\ndat = read.dta(\"https://github.com/hbahamonde/OLS/raw/master/Datasets/cow.dta\")\n\n\n# Hoy pensaremos en que factores ayudan a subir la poblacion en los paises.\n\n# (1) Que relacion podria haber entre poblacion y democracia?\n# (2) Que relacion podria haber entre poblacion y represion politica?\n\n# Modelo\nmodelo.1 = lm(pop ~ democracy + repression, dat)\n\n# resumen del modelo\noptions(scipen = 1000000) # apagar notacion cientifica.\nsummary(modelo.1)\n\n# (1) Que podemos deducir de nuestro modelo? (Interpreta la tabla)\n\n# Checklist: (SIEMPRE EJECUTAR ESTE CHECKLIST)\n## (1) Interpretar estimadores.\nsummary(modelo.1)\n\n## (2) Observar los errores estandard.\nsummary(modelo.1)\n\n## (3) Checkear normalidad de los residuos: y' con residuos.\nplot(modelo.1$fitted.values, modelo.1$residuals)\n\n## (4) Checkear significancia estadistica (asunto de hoy).\nsummary(modelo.1)\n\n\n#################################################################\n# Significancia Estadistica: p-values\n#################################################################\n\n## Significancia: en simple, es la probabilidad de que nuestros betas sean 0.\n## Es decir, la probabilidad de que, por ej., beta(1) no sea 2345, si no que 0.\n## En este caso, hay un 69,84% de probabilidad de que el efecto sea 0. \n## Asi mismo, hay un 24.41% de que beta(2) no sea 18707, si no que sea 0.\n\n## (1) Hasta que punto debieramos rechazar la idea de que b1=0? Cual es el \n## % \"magico\" que nos diga \"ok, estoy segur@ de que b1=0 y no b1=2345?\n\n## Estrellas denotan significancia. \n### * = la probabilidad de que el beta sea 0 es igual/menor al 1%\n### ** = la probabilidad de que el beta sea 0 es igual/menor al 0.1%\n### *** = la probabilidad de que el beta sea 0 es igual a 0%\n\n## Otros niveles:\n### . = la probabilidad de que el beta sea 0 es igual al 5%\n\n## (4) Checkear significancia estadistica: \n### Que podemos decir de la significancia estadistica de nuestros coeficientes?\n\n#################################################################\n# Apliquemos lo que sabemos respecto a Intervalos de Confianza\n#################################################################\n\n# p-values e intervalos de confianza estan altamente relacionados.\n\n# Plotear modelo\n# install.packages(\"coefplot\")\nlibrary(coefplot)\ncoefplot(modelo.1, strict = T) # plot de coeficientes\n\n# mostrar el detalle de los intervalos de confianza\nconfint(modelo.1, strict = T)\n\n\n#################################################################\n# Pero ocurre algo muy raro aqui....?\n#################################################################\n\n# (1) Que similitudes encontramos entre nuestra tabla de regresion, \n# \"confint\" y \"coefplot\"? Las tres herramientas nos estan comunicando el mismo\n# mensaje de alerta.... o no?\n\n# (2) Pero que diferencias encontramos entre la tabla, coefplot/confint?\n\n# Veamos mas en detalle el problema...\n# install.packages(\"effects\")\nlibrary(effects)\nplot(allEffects(modelo.1))\n\n# otro ejemplo\noptions(scipen = 999999) # apagar notacion cientifica.\nlibrary(ggeffects)\nmydf <- ggpredict(modelo.1)\n\nmydf # ve los resultados.\n\nplot(mydf$democracy)\nplot(mydf$repression)\n\n# (3) Que podemos concluir? \n\n#################################################################\n# OK, misterio resuelto. Y es por esto que necesitamos pensar en P-values\n#################################################################\n\n# En nuestra tabla de regresion, el \"p-value\" esta dado por la probabildiad de que\n# el \"valor t\" (\"t value\") sea mayor al numero absoluto de t (en la tabla,\n# esta denotado por \"Pr(>|t|)\").\n\n# Volvamos a mirar la tabla\nsummary(modelo.1)\n\n# Vamos por parte.\n# Primero, veamos lo que el p-value es (los numeros en la columna \"Pr(>|t|)\").\n\n# (1) Un p-value es la probabilidad de que nuestro efecto sea \"falso\".\n# Esto en matematicas significa que nuestro efecto sea realmente \"0\".\n\n# (2) Como es una probabilidad, el p-value (o valor \"p\") es una escala\n# que va de 0 a 1. \n\n# (3) En ciencias sociales, existe la convencion de que un p-value \n# superior al 5%, se cuenta como \"falso.\" Es decir, cuando nuestro p-value,\n# que es nuestra probabilidad de que nuestro efecto sea falso/cero, es mayor a 5%,\n# concluimos que el efecto es \"realmente\" cero. Ahora, si el p-value es menor \n# a 5%, consideramos que la probabilidad de que sea falso es chica, y podemos\n# creer que nuestro efecto en realidad es \"verdadero\" o mas bien \"no-cero\" o \"no falso\".\n\n\n# Recuerda: 5% significa 5/100=0.05. Entonces, un p-value menor a 0.05 indica que \n# nuestro efecto es verdadero o \"no-falso\", y un p-value mayor a 0.05 indica que nuestro efecto es falso/0. Es por esto que los p-values de los coeficientes que son iguales o menores a 0.05 tienen estrellas, y los que son mayores no tienen. \n\n\n#################################################################\n# Estadistico T\n#################################################################\n\n# Lo siguiente es el \"t value\" o \"valor t\" (o \"estadistico t\").\n# El t value es el coeficiente/error estandard.\n\n48303/19052\n2345/6036\n18707/15973\n\n# Esto significa que cuando el error estandard es grande (lo que es \"malo\"), \n# t value se vuelve mas chico. Nosotros queremos lo contrario. Ojala t values\n# que son cercanos a dos. En general, esos t values tienen un p-value < 0.05.\n\n# En otras palabras, el t value es una medida de dispersion de nuestra estimacion.\n# Mientras mas dispersa, mas alta es la probabilidad de que--en su dispersion--\n# nuestra estimacion toque el cero. \n\n#################################################################\n# Al pensar en los p-values y los intervalos de confianza,\n# hemos tratado de minimizar nuestros Errores Tipo 1 y 2.\n#################################################################\n\n# La logica en investigacion en ciencias sociales tiene que ver con la idea de \n# ver si hay suficiente evidencia en contra de la \"hipotesis nula\" (es decir, no hay efecto). En otras palabras, un@ no trata de buscar \"verdades\" (o estimaciones estadisticamente\n# significativas). Un@ trabaja con estimaciones que son hasta 5% falsas (o 95% verdaderas).\n\n# En concreto, un@ trata de minimizar la posibildiad del error \"Tipo 1\".\n\n# Error Tipo 2: falsos negativos.\n# Error Tipo 1: falsos positivos.\n\n# Definir ambos.\n\n\n#################################################################\n# Pensamiento Critico\n#################################################################\n\n# P-values.\n#----\n\n## (1) Criticas al p-value. Por que 5% y no 3% por ejemplo?\n## (2) Comunicando resultados: tablas con CI en vez de estrellas.\n\n\n# install.packages(\"texreg\")\nlibrary(texreg)\nscreenreg(modelo.1, ci.force = F)\n\n\n### Tabla que incorpora estas criticas\n# install.packages(\"texreg\")\nlibrary(texreg)\nscreenreg(modelo.1, ci.force = T) # nuestro paquete \"screenreg\" que ya conocemos,\n# pero ahora, forzando los intervalos de confianza (\"confidence intervals\"), por \n# eso, \"ci.force = T\" (\"T\" por \"true\").\n\n\n\n# Asintotica \n#----\n\n## Asintotica, recordemos, es la idea frecuentista de tener \n## una base de datos infinita. Como esto es imposible,\n## \"el mal menor\" es tener la mayor cantidad de datos: mientras mas, mejor.\n\n### Demostrar en la pizarra que esto puede llegar a conducir a otros problemas.\n### Mas datos, varianza es mas chica, el valor esperado mas preciso.\n\n\n#### (1) Mientras mas datos tenemos, nuestras distribuciones se ponen mas perfectas, \n#### delgadas, y precisas. Eso hace que encontremos independencia estadistica mas facil.\n#### (2) Falsos positivos! \n\nhist(rnorm(10,0,1))\nhist(rnorm(50,0,1))\nhist(rnorm(250,0,1))\nhist(rnorm(2500000,0,1))\n\n\n\n", "meta": {"hexsha": "1bbc8ca4c73ec61a7f6a1d774d57924b36b782d5", "size": 9189, "ext": "r", "lang": "R", "max_stars_repo_path": "Lectures/Clase13/Clase13.r", "max_stars_repo_name": "hbahamonde/OLS", "max_stars_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Clase13/Clase13.r", "max_issues_repo_name": "hbahamonde/OLS", "max_issues_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Clase13/Clase13.r", "max_forks_repo_name": "hbahamonde/OLS", "max_forks_repo_head_hexsha": "439cc5aac95a7fe1e57224732982a36d74a20f67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0524193548, "max_line_length": 241, "alphanum_fraction": 0.6339101099, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6146568577804765}} {"text": "#optim function minimizes 'f'; c vector are starting values; lower is the\n#constraint; I choose a null gradient because it was easiest to get up and running\n#note that here the beta parameter is hard coded in as equal to 1\nrm(list = ls())\n#ap5 = .17\n#a0 = ap5 + .5\n#anp5 = ap5 + 1\n\nap5 = 1.27\na0 = 1.27\nanp5 = 1.27\n\nh <- function(WB,al) {\n\nsy=1\nsz=1\n \nf <- function(B,WB,al) {\n Bp5 <- B[1]\n B0 <- B[2]\n Bnp5 <- B[3]\n -WB*((1/(1+exp(al - B0 + a0)))*(1/(1+exp((al - .5 - Bnp5 + anp5)/sy))) + (1/(1+exp(al - B0 + a0)))*(1/(1+exp((al + .5 - Bp5 + ap5)/sz))) + (1/(1+exp((al + .5 - Bp5 + ap5)/sz)))*(1/(1+exp((al - .5 - Bnp5 + anp5)/sy))) - 2*(1/(1+exp(al - B0 + a0)))*(1/(1+exp((al - .5 - Bnp5 + anp5)/sy)))*(1/(1+exp((al + .5 - Bp5 + ap5)/sz)))) + B0 + Bp5 + Bnp5\n} \n\no <- optim(c(1,1,1,WB,al),function(B) f(B,WB,al),gr=NULL,method = \"L-BFGS-B\", lower = c(0,0,0), control = list(maxit=100000))\n#o <- constrOptim(c(0.01,0.01,0.01,WB,al),function(B) f(B,WB,al),gr=NULL,method = \"Nelder-Mead\", ui = rbind(c(1,0,0),c(0,1,0),c(0,0,1)),ci=c(0,0,0))\n\nX = round(- al -a0 + o$par[2], digits = 2) #B0 these are shorthand variables for the exponents\nY = round(.5 - al -anp5 + o$par[3], digits = 2) #Bnp5 in the logistic CDFs; I don't use them in the function\nZ = round(-.5 - al - ap5 + o$par[1], digits=2) #Bp5 but I've pasted in values here to check\n\npos <- c(Z,X,Y)\nbribes <- c(o$par,-o$value)\n#note I haven't fixed the win probability to include a's bribes\nwin <- c(((1/(1+exp(-X)))*(1/(1+exp(-Y/sy))) + (1/(1+exp(-X)))*(1/(1+exp(-Z/sz))) + (1/(1+exp(-Z/sz)))*(1/(1+exp(-Y/sy))) - 2*(1/(1+exp(-X)))*(1/(1+exp(-Y/sy)))*(1/(1+exp(-Z/sz)))))\nout <- list(\"solns\" = o$par[1:3], \"pos\" = pos, \"objMax\" = -o$value, \"a\" = al, \"wb\" = WB, \"winProb\" = win)\nreturn(out)\n}\n\n# Create a dataframe of parameter values\nwb_vector <- 5:20 \na_vector <- seq(0.0, 0.0, 0.0)\nparams <- expand.grid(\"wb\" = wb_vector, \"a\" = a_vector)\n\n# Use \"Map\" to evaluate the \"h\" function at each pair of parameter values\nresults <- Map(h, al = params$a, WB = params$wb)\n\n# Extract positions and bind to the parameter values\n# WOULD LIKE TO HAVE BOTH SOLUTIONS AND POSITIONS IN OUTPUT VECTOR BUT DON'T KNOW HOW\nsolns <- lapply(seq_along(results), function(x) results[[x]]$solns)\nnetpos <- lapply(seq_along(results), function(x) results[[x]]$pos)\nval <- lapply(seq_along(results), function(x) results[[x]]$objMax)\nwinProb <- lapply(seq_along(results), function(x) results[[x]]$winProb)\nsolns <- do.call(\"rbind\", solns)\nnetpos <- do.call(\"rbind\", netpos)\nval <- do.call(\"rbind\", val)\nwinProb <- do.call(\"rbind\", winProb)\ncolnames(solns) <- c(\"foe\", \"middle\", \"friend\")\ncolnames(netpos) <- c(\"Z\", \"X\", \"Y\")\ncolnames(val) <- c(\"value\")\ncolnames(winProb) <- c(\"winProb\")\nsolns <- cbind(params, solns,netpos,val,winProb)\nView(solns)", "meta": {"hexsha": "05559f854b2d9c2cfa0976fdbd26f6e789365b95", "size": 2796, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/code/constrained-optimization.r", "max_stars_repo_name": "JorgeValdebenito/political-uncertainty", "max_stars_repo_head_hexsha": "6308432a4099facb236634d675b781d26d7fd12c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/code/constrained-optimization.r", "max_issues_repo_name": "JorgeValdebenito/political-uncertainty", "max_issues_repo_head_hexsha": "6308432a4099facb236634d675b781d26d7fd12c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/code/constrained-optimization.r", "max_forks_repo_name": "JorgeValdebenito/political-uncertainty", "max_forks_repo_head_hexsha": "6308432a4099facb236634d675b781d26d7fd12c", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 345, "alphanum_fraction": 0.6051502146, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6145151569331455}} {"text": "########################################################################\n# #\n# finite-set.rb #\n# #\n########################################################################\n=begin\n[(())] \n[(())] \n(())\n/\n(())\n\n= Algebra::Set\n((*集合のクラス*))\n\n集合を表現するクラスです。2つの集合 ((|s|)), ((|t|)) に関して、\n((|s|)) が ((|t|)) に含まれる事は (()) を使って、\n\n s.all?{|x| t.member?(x)}\n\nで表現されます。\n\n== ファイル名:\n* ((|finite-set.rb|))\n\n== スーパークラス:\n* ((|Object|))\n\n== インクルードしているモジュール:\n\n* ((|Enumerable|))\n\n== クラスメソッド:\n\n--- ::[]([obj0, [obj1, [obj2, ...]]])\n 引数の列から ((|Set|)) オブジェクトを生成します。\n \n 例: 全て {\"a\", [1, 2], 0} を生成する。\n require \"finite-set\"\n p Algebra::Set[0, \"a\", [1, 2]]\n p Algebra::Set.new(0, \"a\", [1, 2])\n p Algebra::Set.new_a([0, \"a\", [1, 2]])\n p Algebra::Set.new_h({0=>true, \"a\"=>true, [1, 2]=>true})\n \n--- ::new([obj0, [obj1, [obj2, ...]]])\n 引数の列から ((|Set|)) オブジェクトを生成します。\n\n--- ::new_a(a)\n 配列 ((|a|)) から ((|Set|)) オブジェクトを生成します。\n\n--- ::new_h(h)\n ((|Hash|)) から ((|Set|)) オブジェクトを生成します。\n\n--- self.empty_set\n 空集合を生成する。\n\n--- ::phi\n--- ::null\n ((<::empty_set>)) のエイリアスです。\n\n\n--- ::singleton(x)\n ((|x|)) 一元のみで構成される集合を生成します。\n\n== メソッド:\n\n--- empty_set\n 空集合を生成する。\n\n--- phi\n--- null\n (()) のエイリアスです。\n\n--- empty?\n 空集合であるとき真を返します。\n\n--- phi?\n--- empty_set?\n--- null?\n (()) のエイリアスです。\n\n--- singleton(x)\n ((|x|)) 一元のみで構成される集合を生成します。\n\n--- singleton?\n 一元のみで構成される集合であるとき真を返します。\n\n--- size\n 集合の大きさを返します。\n\n--- each\n 集合の各要素に関して繰り返します。繰り返しの順番は不定です。\n\n 例: \n require \"finite-set\"\n include Algebra\n Set[0, 1, 2].each do |x|\n p x #=> 1, 0, 2\n end\n\n--- separate\n 集合の各要素をブロックパラメータに渡し、ブロックの値を真にする\n もので構成される集合を返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n p Set[0, 1, 2, 3].separate{|x| x % 2 == 0} #=> {2, 0}\n\n--- select_s\n--- find_all_s\n (()) のエイリアスです。\n\n--- map_s\n 集合の各要素をブロックパラメータに渡し、ブロックの値によって\n 構成される集合を返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n p Set[0, 1, 2, 3].map_s{|x| x % 2 + 1} #=> {2, 1}\n\n--- pick\n 集合の要素から一つ選んで値とします。どの要素が選ばれるかは\n 不定です。空集合に対しては ((|nil|)) を返します。\n\n--- shift\n 集合の要素から一つ選んで取り出し値とします。どの要素が選ばれる\n かは不定です。\n\n 例: \n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3]\n p s.shift #=> 2\n p s #=> {0, 1, 3}\n\n--- dup\n 集合の複製を返します。(内部の Hash の複製によります。)\n\n--- append!(x)\n 集合に要素 ((|x|)) を付け加えます。返り値は ((|self|)) です。\n\n--- push\n--- <<\n ((|append!|)) のエイリアスです。\n\n--- append(x)\n 集合に要素 ((|x|)) を付け加えた複製を返します。\n\n--- concat(other)\n 集合に別の集合 ((|other|)) の要素を付け加えます。\n (((|+|)) の破壊版です。)\n\n--- rehash\n 内部の ((|Hash|)) オブジェクトを ((|rehash|)) します。\n\n--- eql?(other)\n 集合 ((|other|)) と等しいとき、真を返します。\n (({ self >= other and self <= other})) と同値です。\n\n--- ==\n (()) のエイリアスです。\n\n--- hash\n 自身が ((|Hash|)) あるいは ((|Set|)) の要素となるときに利用される\n ハッシュ値関数です。\n\n--- include?(x)\n 集合が ((|x|)) を要素としているとき、真を返します。\n\n--- member?\n--- has?\n--- contains?\n (()) のエイリアスです。\n\n--- superset?(other)\n 集合が他の集合 ((|other|)) を包含するとき真を返します。\n (({other.all{|x| member?(x)}})) と同値です。\n\n--- >=\n--- incl?\n (({superset?})) のエイリアスです。\n\n--- subset?(other)\n 集合が他の集合 ((|other|)) の部分集合であるとき真を返します。\n (({self.all{|x| other.member?(x)}})) と同値です。\n\n--- <=\n--- part_of?\n ((|subset?|)) のエイリアスです。\n\n--- <(other)\n ((|self|)) が ((|other|)) の真部分集合の時真を返します。\n\n--- >(other)\n ((|self|)) が ((|other|)) を真に含む時真を返します。\n\n--- union([other])\n ((|self|)) と ((|other|)) の合併集合を返します。\n ((|other|)) が省略された場合、自身を集合の集合とみなし、全ての\n 要素の合併を返します。\n \n 例:\n require \"finite-set\"\n include Algebra\n p Set[0, 2, 4].cup Set[1, 3] #=> {0, 1, 2, 3, 4}\n s = Set[*(0...15).to_a]\n s2 = s.separate{|x| x % 2 == 0}\n s3 = s.separate{|x| x % 3 == 0}\n s5 = s.separate{|x| x % 5 == 0}\n p Set[s2, s3, s5].union #=> {1, 7, 11, 13}\n\n--- |\n--- +\n--- cup\n ((|union|)) のエイリアスです。\n\n--- intersection([other])\n ((|self|)) と ((|other|)) の交わりの集合を返します。\n ((|other|)) が省略された場合、自身を集合の集合とみなし、全ての\n 要素の共通部分を返します。\n\n 例:\n require \"finite-set\"\n include Algebra\n p Set[0, 2, 4].cap(Set[4, 2, 0]) #=> {0, 2, 4}\n s = Set[*(0..30).to_a]\n s2 = s.separate{|x| x % 2 == 0}\n s3 = s.separate{|x| x % 3 == 0}\n s5 = s.separate{|x| x % 5 == 0}\n p Set[s2, s3, s5].cap #=> {0, 30}\n\n--- &\n--- cap\n ((|intersection|)) のエイリアスです。\n\n\n--- difference(other)\n ((|self|)) から ((|other|)) に含まれる要素を取り除いたものを返します。\n\n--- -\n ((|difference|)) のエイリアスです。\n\n\n--- each_pair\n 集合から異なる2つの要素を取り出して、ブロックパラメータに\n 代入して繰り返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_pair do |x, y|\n s.push [x, y]\n end\n p s == Set[[0, 1], [0, 2], [1, 2]] #=> true\n\n--- each_member(n)\n 集合から異なる ((|n|)) 個の要素を取り出して、ブロックパラメータに\n 代入して繰り返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_member(2) do |x, y|\n s.push [x, y]\n end\n p s == Set[[0, 1], [0, 2], [1, 2]] #=> true\n\n--- each_subset\n 集合の全ての部分集合をブロックパラメータに代入して繰り返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n s = Set.phi\n Set[0, 1, 2].each_subset do |t|\n s.append! t\n end\n p s.size = 2**3 #=> true\n\n--- each_non_trivial_subset\n 集合の空集合でない真部分集合をブロックパラメータに代入して繰り返します。\n\n--- power_set\n 集合の全ての部分集合の集合を返します。\n\n--- each_product(other)\n ((|self|)) と ((|other|)) の全ての要素 ((|x|)), ((|y|)) に\n ついて、繰り返します。\n\n 例:\n require \"finite-set\"\n include Algebra\n Set[0, 1].each_prodct(Set[0, 1]) do |x, y|\n p [x, y] #=> [0,0], [0,1], [1,0], [1,1]\n end\n\n--- product(other)\n ((|self|)) と ((|other|)) の積集合を返します。積集合の各元\n は配列 (({[x, y]})) です。ブロックが与えられた時は、ブロック\n を評価した値で構成される集合を返します。\n\n 例: \n require \"finite-set\"\n include Algebra\n p Set[0, 1].product(Set[0, 1]) #=> {[0,0], [0,1], [1,0], [1,1]}\n p Set[0, 1].product(Set[0, 1]){|x, y| x + 2*y} #=> {0, 1, 2, 3]\n\n--- *\n (()) のエイリアスです。\n\n--- equiv_class([equiv])\n 集合を同値関係で割った商集合を返します。同値関係の与え方は次の3通りあります。\n \n (1) ブロックの評価値を真にする同値関係\n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3, 4, 5]\n p s.equiv_class{|a, b| (a - b) % 3 == 0} #=> {{0, 3}, {1, 4}, {2, 5}}\n (2) 引数に与えられたオブジェクトに対するメソッド ((|call(x, y)|)) \n の真偽値による同値関係\n require \"finite-set\"\n include Algebra\n o = Object.new\n def o.call(x, y)\n (x - y) % 3 == 0\n end\n s = Set[0, 1, 2, 3, 4, 5]\n p s.equiv_class(o) #=> {{0, 3}, {1, 4}, {2, 5}}\n (3) 引数に与えられた ((|Symbol|)) に応じたメソッドによる同値関係\n require \"finite-set\"\n include Algebra\n s = Set[0, 1, 2, 3, 4, 5]\n def q(x, y)\n (x - y) % 3 == 0\n end\n p s.equiv_class(:q) #=> {{0, 3}, {1, 4}, {2, 5}}\n\n--- /\n (()) のエイリアスです。\n\n--- to_a\n 集合を配列にして返します。要素の並びの順は不定です。\n\n--- to_ary\n (()) のエイリアスです。\n\n--- sort\n (()) の値をソートして返します。\n\n--- power(other)\n ((|other|)) から ((|self|)) への写像全ての集合を返します。\n 写像は (()) の元として表現されます。\n \n 例: \n require \"finite-map\"\n include Algebra\n a = Set[0, 1, 2, 3]\n b = Set[0, 1, 2]\n s = \n p( (a ** b).size ) #=> 4 ** 3 = 64\n p b.surjections(a).size #=> S(3, 4) = 36\n p a.injections(b).size #=> 4P3 = 24\n\n--- **\n (()) のエイリアスです。\n\n--- identity_map\n 自分への恒等写像を返します。\n\n--- surjections(other)\n ((|other|)) から ((|self|)) への全射全ての集合を返します。\n\n#--- injections0(other)\n\n--- injections(other)\n ((|other|)) から ((|self|)) への単射全ての集合を返します。\n\n\n--- bijections(other)\n ((|other|)) から ((|self|)) への全単射全ての集合を返します。\n\n\n#--- monotonic_series #what is this?\n\n= Enumerable\n\n== ファイル名:\n* ((|finite-set.rb|))\n\n== メソッド:\n\n--- any?\n ブロックを真にする要素があるとき、真を返します。\n ((|Enumerable#find|)) の別名です。(built-in of ruby-1.8)\n\n--- all?\n 全ての要素についてブロックが真であるとき、真を返します。\n\n !any?{|x| !yield(x)}\n\n と定義されています。(built-in of ruby-1.8)\n\n=end\n\n", "meta": {"hexsha": "ff9475f22721c677fda7f8ee13ef5069659cb3c3", "size": 8231, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/finite-set-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/finite-set-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/finite-set-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1246943765, "max_line_length": 79, "alphanum_fraction": 0.4819584498, "num_tokens": 4024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6144790987997497}} {"text": "require(nleqslv)\r\nrequire(xlsx)\r\nlibrary(rgl)\r\n\r\n# Aaia?e?oai aoiaiua aaiiua\r\ngenerate <- function(n, tet, sigma1=0.05, sigma2=0.5, sigma3=0.05, sigma4=0.8) {\r\n m <- length(tet)\r\n c(runif(n, -1, 1)) -> ksi\r\n eta <- apply(sapply(1:m, function(i) ksi^(i-1)), 1, function(r) sum(r * tet))\r\n\r\n rbinom(n, 1, 0.05) -> rb1\r\n rbinom(n, 1, 0.05) -> rb2\r\n\r\n sapply(rb1, function(x) rnorm(1, 0, switch(x + 1, sigma1, sigma2))) -> delta\r\n sapply(rb2, function(x) rnorm(1, 0, switch(x + 1, sigma3, sigma4))) -> eps\r\n X <- cbind(rep(1,n), apply(sapply(2:m, function(i) ksi^(i-1)), 2, function(r) r + delta))\r\n list(X = matrix(X, nrow = n, ncol = m), y = eta + eps, outliersX = rb1, outliersY = rb2)\r\n}\r\n\r\nmnk <- function (X, y) {\r\n c(solve(t(X) %*% (X)) %*% t(X) %*% matrix(y)) \r\n}\r\n\r\n# Au?eneyai aaooa\r\nrcr <- function(X, y, tet.init, g0=0.001, h=0.001, eps=1.e-8, g=NULL) {\r\n b0 <- tet.init[2:length(tet.init)]\r\n p <- length(tet.init) - 1\r\n\r\n r <- sqrt(apply(sapply(1:p, function(i) (X[,i+1] - mean(X[,i+1]))^2), 1, sum) + (y - mean(y))^2)\r\n fSxx <- function (i, j) sum((X[,i+1]-mean(X[,i+1])) * (X[,j+1]-mean(X[,j+1])) / r^2)\r\n fSxy <- function (j) sum((X[,j+1]-mean(X[,j+1])) * (y - mean(y)) / r^2)\r\n Syy <- sum((y-mean(y))^2 / r^2)\r\n \r\n Sxx <- matrix(0, nrow = p, ncol = p)\r\n Sxy <- numeric(p)\r\n for (i in 1:p) {\r\n for (j in 1:p) {\r\n Sxx[i,j] <- fSxx(i, j)\r\n }\r\n Sxy[i] <- fSxy(i)\r\n }\r\n\r\n\r\n SS <- function(b, gamma) {\r\n #gamma0 <- 1 - sum(gamma)\r\n gamma0 <- gamma[1]\r\n gamma.other <- gamma[2:length(gamma)]\r\n Sxx.sum <- 0\r\n Sxy.sum <- 0\r\n for (i in 1:p) {\r\n for (j in 1:p) {\r\n Sxx.sum <- Sxx.sum + b[i] * b[j] * Sxx[i, j]\r\n }\r\n Sxy.sum <- Sxy.sum + b[i] * Sxy[i]\r\n }\r\n #sum(sapply(1:5, function (j) sum(sapply(1:5, Sxx, j=j))))\r\n (gamma0 + sum(gamma.other / b^2)) * (Syy + Sxx.sum - 2 * Sxy.sum)\r\n }\r\n# f <- function(v) SS(v[1:p], v[(p+1):(2*p)])\r\n fg <- function(b) function(g) SS(b, g)\r\n fb <- function(g) function(b) SS(b, g)\r\n df <- function(f) {\r\n function (v) {\r\n l <- length(v)\r\n grad <- numeric(l)\r\n for (i in 1:l) {\r\n v.plus.h <- v\r\n v.plus.h[i] <- v.plus.h[i] + h \r\n grad[i] <- (f(v.plus.h) - f(v)) / h\r\n }\r\n grad\r\n }\r\n }\r\n norm <- function(x) sqrt(sum(x^2))\r\n basis <- function(n, i) {\r\n \ta <- numeric(n)\r\n \ta[i] <- 1\r\n \ta\r\n }\r\n\r\n g.init <- rep(g0, p)\r\n b.init <- b0\r\n calc_b <- function (g, b.init=b0) {\r\n \tres <- nleqslv(b.init, df(fb(g)), method = \"Newton\")\r\n \tres$x\r\n }\r\n \r\n F <- function(g.p) {\r\n \tg <- c((1-sum(g.p)), g.p)\r\n b <- calc_b(g, b.init)\r\n b.init <- b\r\n #for (i in 1:(p+1)) if (g[i] < 0 || g[i] > 1) return(1000000.0)\r\n -sum(sapply(1:(p+1), function(i) SS(calc_b(basis(p+1, i), b.init), basis(p+1, i)) / SS(b, basis(p+1, i))))\r\n }\r\n\r\n theta <- function(gamma) {\r\n \tb <- calc_b(gamma)\r\n \talpha <- mean(y) - sum(b * sapply(1:p, function(i) (mean(X[,i+1]))))\r\n c(alpha, b)\r\n }\r\n\r\n # plot ((1:100) / 100, sapply((1:100) / 100, F))\r\n # x <- (1:100) / 100\r\n # xn = length(x)\r\n # z <- matrix(0, nrow = xn, ncol = xn)\r\n # for (i in 1:xn){\r\n # for (j in 1:xn){\r\n # z[i,j] <- f(x[i], x[j])\r\n # \t}\r\n\t# }\r\n # persp3d(z)\r\n if (!is.null(g)) return(theta(g))\r\n \r\n res <- optim(par=g.init, F)\r\n #res <- optimize(F, interval=c(0,1))\r\n g <- c((1-sum(res$par)), res$par)\r\n #g <- c((1-res$minimum), res$minimum)\r\n print(c(g, sum(g)))\r\n #print(c(-F(res$minimum),F(numeric(p)), theta(g)))\r\n print(c(-F(res$par), -F(numeric(p))))\r\n theta(g)\r\n \r\n\r\n\r\n # repeat {\r\n # f <- fg(b)\r\n # plot (sapply((0:100) / 100, f), (0:100) / 100)\r\n\r\n # res <- nleqslv(g, df(fg(b)), method = \"Newton\")\r\n # g <- res$x\r\n # print (g)\r\n # res <- nleqslv(b, df(fb(g)), method = \"Newton\")\r\n # b_new <- res$x\r\n # if (norm(b_new - b) / norm(b) <= eps) {\r\n # break\r\n # }\r\n # b <- b_new\r\n # }\r\n\r\n\r\n # psi <- function (gamma) {\r\n # t <- theta(gamma)\r\n # sum((t - te)^2 / te^2)\r\n # }\r\n\r\n\r\n # for (g in (1:100) / 100) {\r\n # print(c(g, psi(c(1-g,g)), -F(g), theta(c(1-g,g))))\r\n # }\r\n\r\n\t# for (g1 in (0:100) / 100) {\r\n\t# \tfor (g2 in (0:10) / 10) {\r\n\t# \t\tg <- c(1-g1-g2, g1, g2)\r\n\t# \t\tprint(c(g, psi(g), -F(c( g1, g2)), theta(g)))\r\n\t# \t}\r\n\t# }\r\n \r\n\r\n\r\n\r\n #plot(psi, 0, 1)\r\n\r\n # g <- \r\n # p <- sapply(g, psi)\r\n # a <- sapply(g, \r\n\r\n # x <- data.frame(g = g, psi = p)\r\n # write.table(x, file = \"rcr.csv\", sep = \",\", qmethod = \"double\")\r\n\r\n # for (g1 in (0:10) / 50) {\r\n # for (g2 in (0:10) / 50) {\r\n # g <- c(g1, g2)\r\n # print(c(g, psi(g), theta(g)))\r\n # }\r\n # }\r\n\r\n\r\n\r\n# F <- function(gamma) {\r\n# t <- theta(gamma)\r\n# b <- t[2]\r\n# ((Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy) - gamma)^2\r\n# }\r\n\r\n# o = optimize(F, interval=c(-1, 100000))\r\n# o$minimum\r\n\r\n# repeat {\r\n\r\n# gamma_new <- (Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy)\r\n\r\n\r\n# f <- function(b) (gamma0 + gamma_new / b^2) * (Syy + b^2 * Sxx - 2 * b * Sxy)\r\n# df <- function(b) (f(b + h) - f(b)) / h\r\n# res <- nleqslv(b0, df, method = \"Newton\")\r\n# b_new <- res$x\r\n\r\n# print(gamma)\r\n# if (abs(b_new - b) / abs(b) <= eps || k > 100) {\r\n# break \r\n# }\r\n# #print(k)\r\n# #print(abs(b_new - b) / abs(b))\r\n# b <- b_new\r\n# gamma <- gamma_new\r\n# #k = k+1\r\n\r\n# }\r\n}\r\n\r\n\r\nrcr_err <- function(X, y, tet.init, g0=0.001, h=0.001, eps=1.e-8, g=NULL) {\r\n b0 <- tet.init[2:length(tet.init)]\r\n p <- length(tet.init) - 1\r\n n <- length(y)\r\n \r\n r <- sqrt(apply(sapply(1:p, function(i) (X[,i+1] - mean(X[,i+1]))^2), 1, sum) + (y - mean(y))^2)\r\n fSxx <- function (i, j) sum((X[,i+1]-mean(X[,i+1])) * (X[,j+1]-mean(X[,j+1])) / r^2)\r\n fSxy <- function (j) sum((X[,j+1]-mean(X[,j+1])) * (y - mean(y)) / r^2)\r\n Syy <- sum((y-mean(y))^2 / r^2)\r\n \r\n Sxx <- matrix(0, nrow = p, ncol = p)\r\n Sxy <- numeric(p)\r\n for (i in 1:p) {\r\n for (j in 1:p) {\r\n Sxx[i,j] <- fSxx(i, j)\r\n }\r\n Sxy[i] <- fSxy(i)\r\n }\r\n \r\n \r\n SS <- function(b, gamma) {\r\n #gamma0 <- 1 - sum(gamma)\r\n gamma0 <- gamma[1]\r\n gamma.other <- gamma[2:length(gamma)]\r\n Sxx.sum <- 0\r\n Sxy.sum <- 0\r\n for (i in 1:p) {\r\n for (j in 1:p) {\r\n Sxx.sum <- Sxx.sum + b[i] * b[j] * Sxx[i, j]\r\n }\r\n Sxy.sum <- Sxy.sum + b[i] * Sxy[i]\r\n }\r\n (gamma0 + sum(gamma.other / b^2)) * (Syy + Sxx.sum - 2 * Sxy.sum)\r\n }\r\n\r\n fg <- function(b) function(g) SS(b, g)\r\n fb <- function(g) function(b) SS(b, g)\r\n df <- function(f) {\r\n function (v) {\r\n l <- length(v)\r\n grad <- numeric(l)\r\n for (i in 1:l) {\r\n v.plus.h <- v\r\n v.plus.h[i] <- v.plus.h[i] + h \r\n grad[i] <- (f(v.plus.h) - f(v)) / h\r\n }\r\n grad\r\n }\r\n }\r\n norm <- function(x) sqrt(sum(x^2))\r\n basis <- function(n, i) {\r\n a <- numeric(n)\r\n a[i] <- 1\r\n a\r\n }\r\n \r\n g.init <- rep(g0, p)\r\n b.init <- b0\r\n calc_b <- function (g, b.init=b0) {\r\n res <- nleqslv(b.init, df(fb(g)), method = \"Newton\")\r\n res$x\r\n }\r\n \r\n \r\n theta <- function(gamma) {\r\n b <- calc_b(gamma)\r\n alpha <- mean(y) - sum(b * sapply(1:p, function(i) (mean(X[,i+1]))))\r\n c(alpha, b)\r\n }\r\n \r\n F <- function(g.p) {\r\n g <- c((1-sum(g.p)), g.p)\r\n b <- calc_b(g, b.init)\r\n y.est <- X %*% matrix(theta(g))\r\n for (i in 1:(p+1)) if (g[i] < 0 || g[i] > 1) return(1000000.0)\r\n sum(abs(y - y.est)) / n\r\n }\r\n\r\n res <- optim(par=g.init, F)\r\n #res <- optimize(F, interval=c(0,1))\r\n g <- c((1-sum(res$par)), res$par)\r\n #g <- c((1-res$minimum), res$minimum)\r\n print(c(g, sum(g)))\r\n #print(c(-F(res$minimum),F(numeric(p)), theta(g)))\r\n print(c(F(res$par), F(numeric(p))))\r\n theta(g)\r\n}\r\n\r\nrcr_g0 <- function(X, y, tet.init) {\r\n m <- length(tet.init)\r\n g <- numeric(m)\r\n g[1] <- 1\r\n rcr(X, y, tet.init, g=g)\r\n}\r\n\r\nrcr2 <- function(x, y, b0=0.001, h=0.001, eps=1.e-8, k=0) {\r\n r <- sqrt((x-mean(x))^2 + (y - mean(y))^2)\r\n Sxx <- sum((x-mean(x))^2 / r^2)\r\n Sxy <- sum((x-mean(x)) * (y - mean(y)) / r^2)\r\n Syy <- sum((y-mean(y))^2 / r^2)\r\n my <- mean(y)\r\n mx <- mean(x)\r\n\r\n theta <- function() {\r\n f <- function(b) ((1 - (Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy)) + ((Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy)) / b^2) * (Syy + b^2 * Sxx - 2 * b * Sxy)\r\n df <- function(b) (f(b + h) - f(b)) / h\r\n res <- nleqslv(b0, df, method = \"Newton\")\r\n b <- res$x\r\n c(my - b * mx, b)\r\n }\r\n\r\n# for (g in (1:100) / 100) {\r\n# print(c(g, theta(g)))\r\n# }\r\n\r\n theta()\r\n# repeat {\r\n\r\n# gamma_new <- (Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy)\r\n\r\n\r\n# f <- function(b) (gamma0 + gamma_new / b^2) * (Syy + b^2 * Sxx - 2 * b * Sxy)\r\n# df <- function(b) (f(b + h) - f(b)) / h\r\n# res <- nleqslv(b0, df, method = \"Newton\")\r\n# b_new <- res$x\r\n\r\n# print(gamma)\r\n# if (abs(b_new - b) / abs(b) <= eps || k > 100) {\r\n# break \r\n# }\r\n# #print(k)\r\n# #print(abs(b_new - b) / abs(b))\r\n# b <- b_new\r\n# gamma <- gamma_new\r\n# #k = k+1\r\n\r\n# }\r\n}\r\n\r\nrcr3 <- function(x, y, gamma_init=0.1, b0=0.001, h=0.001, eps=1.e-8) {\r\n\r\n r <- sqrt((x-mean(x))^2 + (y - mean(y))^2)\r\n Sxx <- sum((x-mean(x))^2 / r^2)\r\n Sxy <- sum((x-mean(x)) * (y - mean(y)) / r^2)\r\n Syy <- sum((y-mean(y))^2 / r^2)\r\n\r\n gamma <- gamma_init\r\n gamma0 <- 1 - gamma\r\n f <- function(b) (gamma0 + gamma / b^2) * (Syy + b^2 * Sxx - 2 * b * Sxy)\r\n df <- function(b) (f(b + h) - f(b)) / h\r\n res <- nleqslv(b0, df, method = \"Newton\")\r\n b <- res$x\r\n\r\n repeat {\r\n \r\n gamma_new <- (Syy - b * Sxy) / (Syy - b * Sxy + b^4 * Sxx - b^3 * Sxy)\r\n\r\n gamma0 <- 1 - gamma_new\r\n f <- function(b) (gamma0 + gamma_new / b^2) * (Syy + b^2 * Sxx - 2 * b * Sxy)\r\n df <- function(b) (f(b + h) - f(b)) / h\r\n res <- nleqslv(b0, df, method = \"Newton\")\r\n b_new <- res$x\r\n\r\n #print(gamma)\r\n if (abs(b_new - b) / abs(b) <= eps) {\r\n break\r\n }\r\n b <- b_new\r\n gamma <- gamma_new\r\n }\r\n c(mean(y) - b * mean(x), b)\r\n}\r\n\r\nals <- function(X, y, tet.init, sigma_init=0.01, eps=1.e-8) {\r\n m <- length(tet.init)\r\n n <- length(y)\r\n matrix(1, nrow=n, ncol=2*m) -> t\r\n matrix(0, nrow=m, ncol=m) -> P\r\n rep(1,m) -> R\r\n\r\n t[,2] <- X[,2]\r\n\r\n theta <- function(sd2) {\r\n for (i in 3:(2*m)) { t[,i] <- X[,2] * t[,i-1] - (i - 2) * sd2 * t[,i-2] }\r\n for (i in 1:m) { R[i] <- sum(t[,i] * y) }\r\n for (i in 1:m) { for (j in 1:m) { P[i,j] <- sum(t[,i+j-1]) } }\r\n c(solve(P) %*% matrix(R))\r\n }\r\n # F <- function(sd2) {\r\n # tet <- theta(sd2)\r\n # #((n * sd2)/(sum(y^2) - sum(R * tet)) - (var(x) / var(y)))^2\r\n # #y.est <- apply(sapply(1:m, function(i) x^(i-1) * tet[i]), 1, sum)\r\n # y.est <- apply(sapply(1:m, function(i) x^(i-1)), 1, function(r) sum(r * tet))\r\n # (((n-m) * sd2)/sum((y - y.est)^2) - var(x)/var(y))^2\r\n # #(((n-m) * sd2)/sum((y - sum(R * tet))^2) - 1)^2\r\n # }\r\n\r\n tet <- tet.init\r\n\r\n norm <- function(x) sqrt(sum(x^2))\r\n\r\n theta(0.01^2)\r\n\r\n #g <- var(x) / var(y)\r\n # g <- 1\r\n\r\n # print (c(var(x) / var(y), 1))\r\n # repeat {\r\n \r\n # y.est <- apply(sapply(1:m, function(i) x^(i-1)), 1, function(r) sum(r * tet))\r\n\r\n # # print (c(y- y.est))\r\n # # break\r\n # sd2 <- g * sum((y - y.est)^2) / (n - m)\r\n # tet_new <- theta(sd2)\r\n # nev <- norm(tet_new - tet) / norm(tet)\r\n # print(c(nev, sd2))\r\n # if (nev < eps) {\r\n # break\r\n # }\r\n # tet <- tet_new\r\n # }\r\n # tet\r\n\r\n # o = optimize(F, interval=c(0, 10))\r\n # #o = BBoptim(par=0, fn=F)\r\n # sd2 <- o$minimum\r\n # print(sd2)\r\n # print(F(sd2))\r\n # #plot(F, 0, 10)\r\n # theta(0.0001)\r\n}\r\n\r\nerr <- function (data, tet) {\r\n m <- length(tet)\r\n n <- length(data$y)\r\n y.est <- apply(sapply(1:m, function(i) data$X[,i]), 1, function(r) sum(r * tet))\r\n c(sum((data$y - y.est)^2) / n, sum(abs(data$y - y.est)) / n)\r\n}\r\n\r\nreport <- function (N, te) {\r\n psi <- function (tet) sum((tet - te)^2 / te^2)\r\n m <- length(te)\r\n out <- matrix(0, nrow=N, ncol=(m+2)*4)\r\n for (i in 1:N) {\r\n data <- generate(500, te)\r\n tet.mnk <- mnk(data$X, data$y)\r\n tet.als <- als(data$X, data$y, tet.init=tet.mnk)\r\n tet.rcr <- rcr(data$X, data$y, tet.init=tet.mnk)\r\n tet.rcr_g0 <- rcr_g0(data$X, data$y, tet.init=tet.mnk)\r\n out[i,] <- c(tet.mnk, err(data, tet.mnk), tet.als, err(data, tet.als), tet.rcr, err(data, tet.rcr), tet.rcr_g0, err(data, tet.rcr_g0))\r\n }\r\n x <- data.frame(out)\r\n write.xlsx(x, file = \"report.xlsx\")\r\n}\r\n\r\nmodel <- function(tet) {\r\n m <- length(tet)\r\n Vectorize(function (x) sum(sapply(1:m, function(i) x^(i-1)) * tet))\r\n}\r\n\r\nresearch <- function(f, m=3) {\r\n dx <- read.table(sprintf(\"data/x_%s.txt\", f))\r\n dy <- read.table(sprintf(\"data/y_%s.txt\", f))\r\n data <- list(X = sapply(1:m, function(i) dx$V1^(i-1)), y = dy$V1)\r\n\r\n tet.mnk <- mnk(data$X, data$y)\r\n print(sprintf(\"tet.mnk = (%s), err = %f\", paste(tet.mnk, collapse=\", \"), err(data, tet.mnk)[2]))\r\n plot(model(tet.mnk), 0, 1)\r\n \r\n tet.als <- als(data$X, data$y, tet.init=tet.mnk)\r\n print(sprintf(\"tet.als = (%s), err = %f\", paste(tet.als, collapse=\", \"), err(data, tet.als)[2]))\r\n plot(model(tet.als), 0, 1)\r\n \r\n tet.rcr <- rcr(data$X, data$y, tet.init=tet.mnk)\r\n print(sprintf(\"tet.rcr = (%s), err = %f\", paste(tet.rcr, collapse=\", \"), err(data, tet.rcr)[2]))\r\n plot(model(tet.rcr), 0, 1)\r\n \r\n tet.rcr_err <- rcr_err(data$X, data$y, tet.init=tet.mnk)\r\n print(sprintf(\"tet.rcr_err = (%s), err = %f\", paste(tet.rcr_err, collapse=\", \"), err(data, tet.rcr_err)[2]))\r\n plot(model(tet.rcr_err), 0, 1)\r\n \r\n tet.rcr_g0 <- rcr_g0(data$X, data$y, tet.init=tet.mnk)\r\n print(sprintf(\"tet.rcr_g0 = (%s), err = %f\", paste(tet.rcr_g0, collapse=\", \"), err(data, tet.rcr_g0)[2]))\r\n plot(model(tet.rcr_g0), 0, 1)\r\n}\r\n\r\n\r\noutliersPlot <- function(te) {\r\n data <- generate(50, te)\r\n X.clean = data$X[data$outliersX == 0 & data$outliersY == 0,]\r\n y.clean = data$y[data$outliersX == 0 & data$outliersY == 0]\r\n X.outliers = data$X[data$outliersX == 1 | data$outliersY == 1,]\r\n y.outliers = data$y[data$outliersX == 1 | data$outliersY == 1]\r\n \r\n tet.mnk <- mnk(data$X, data$y)\r\n tet.als <- als(data$X, data$y, tet.init=tet.mnk)\r\n tet.als.clean <- als(X.clean, y.clean, tet.init=tet.mnk)\r\n \r\n plot(X.clean[,2], y.clean, col=\"black\")\r\n plot(model(tet.als), -1, 1, col=\"red\", lwd=2, add=TRUE)\r\n plot(model(tet.als.clean), -1, 1, col=\"black\", lwd=2, add=TRUE)\r\n points(X.outliers[,2], y.outliers, col=\"red\")\r\n}\r\n\r\nte <- c(1.3, 2.1, 0.4)\r\n#report(1, te)\r\n\r\n#research(\"2_year_421\")\r\noutliersPlot(te)\r\n\r\n#data <- generate(500, te)\r\n# plot(data$X[,2], data$y)\r\n#b0 <- mnk(data$x, data$y, te=te)\r\n#tet <- rcr(data$x, data$y, te=te, tet.init=b0)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "bad5fd9f07273b5b628d3f328c093547aca37e15", "size": 14476, "ext": "r", "lang": "R", "max_stars_repo_path": "main.r", "max_stars_repo_name": "EArkhipenko/diplom", "max_stars_repo_head_hexsha": "a413913340c3426401c2460e95ff0dff779c9a7a", "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": "main.r", "max_issues_repo_name": "EArkhipenko/diplom", "max_issues_repo_head_hexsha": "a413913340c3426401c2460e95ff0dff779c9a7a", "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": "main.r", "max_forks_repo_name": "EArkhipenko/diplom", "max_forks_repo_head_hexsha": "a413913340c3426401c2460e95ff0dff779c9a7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3132075472, "max_line_length": 189, "alphanum_fraction": 0.4782398453, "num_tokens": 5846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.614454527445426}} {"text": "x = seq(-1,1,0.01)\nfs = 1.8\nfsc = 1.8\n\n\n#complEx simple box, on differences\npdf(\"complex_simple_box.pdf\",width=7,height=7)\nop <- par(mar = c(5,5.5,2,2) +0.1)\ncontour(x,x,outer(x,x, function(x,y) pmax(0,x) + pmax(x,abs(y))),nlevels=10,cex.lab=fs+0.4, cex.axis=fs, cex.main=fs, cex.sub=fs, labcex=fsc, xlab=expression(Re(theta['b, i']- theta['r, i'])), ylab=expression(Im(theta['b, i'] - theta['r, i'])))\ndev.off()\n\n\n#complex simple sphere\npdf(\"complex_simple_sphere.pdf\",width=7,height=7)\nop <- par(mar = c(5,5.5,2,2) +0.1)\ncontour(x,x,outer(x,x, function(x,y) sqrt(x*x + y*y)),nlevels=10,cex.lab=fs+0.4, cex.axis=fs, cex.main=fs, cex.sub=fs, labcex=fsc, xlab=expression(Re(theta['b, i'] - theta['r, i'])), ylab=expression(Im(theta['b, i'] - theta['r, i'])))\ndev.off()\n\n", "meta": {"hexsha": "5426158fe594d582503a0ff28937fd5446191b18", "size": 769, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/synth/loss_complex.r", "max_stars_repo_name": "issca/inferbeddings", "max_stars_repo_head_hexsha": "80492a7aebcdcac21e758514c8af403d77e8594a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33, "max_stars_repo_stars_event_min_datetime": "2017-07-25T14:31:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T09:18:00.000Z", "max_issues_repo_path": "scripts/synth/loss_complex.r", "max_issues_repo_name": "issca/inferbeddings", "max_issues_repo_head_hexsha": "80492a7aebcdcac21e758514c8af403d77e8594a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-22T13:49:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-22T13:49:30.000Z", "max_forks_repo_path": "scripts/synth/loss_complex.r", "max_forks_repo_name": "issca/inferbeddings", "max_forks_repo_head_hexsha": "80492a7aebcdcac21e758514c8af403d77e8594a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2017-10-05T08:50:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T12:40:56.000Z", "avg_line_length": 40.4736842105, "max_line_length": 244, "alphanum_fraction": 0.6371911573, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.6144193677635472}} {"text": " DPBEQU Example Program Results\n\n Matrix A\n 1 2 3 4\n 1 5.4900E+00 2.6800E+10\n 2 5.6300E+20 -2.3900E+10\n 3 2.6000E+00 -2.2200E+00\n 4 5.1700E+00\n\n SCOND = 6.8E-11, AMAX = 5.6E+20\n\n Diagonal scaling factors\n 4.3E-01 4.2E-11 6.2E-01 4.4E-01\n\n Scaled matrix\n 1 2 3 4\n 1 1.0000 0.4821\n 2 1.0000 -0.6247\n 3 1.0000 -0.6055\n 4 1.0000\n", "meta": {"hexsha": "7851b2d1d04b1a00fb74d532ed5d0200a11f8d7b", "size": 614, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/dpbequ_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/dpbequ_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/dpbequ_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 29.2380952381, "max_line_length": 55, "alphanum_fraction": 0.348534202, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6142920445709599}} {"text": "/*\n\n\n here's what you can expect to learn. The characteristics of binomial outcome variables, such as buys versus doesn't buy, \n and recovers or get worse, any kind of situation which you might have to make a decision between two or more alternatives\n is an appropriate kind of context for this course. You'll also learn about the reasons that binomial outcome variables create\n problems for standard analysis procedures such as simple and multiple regression.\n\nYou'll see how simple transformations that involve odds ratios and logarithms can solve the problems that binomial outcomes\nbring to regression analysis. Now I use Excel in this course mainly to show you what goes on inside logistic regression's \nblack box. You'll be able to see the intermediate calculations involving those odds and those logarithms, and I use R to show \nyou how to reach the end point of the analysis quickly so that you can skip over those intermediate kinds of calculations.\n\n\n\n*/\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "8723db003313faa442155a89580a5a5df6727f8a", "size": 974, "ext": "r", "lang": "R", "max_stars_repo_path": "LogisticRegression/00 Intro.r", "max_stars_repo_name": "iitjee/SteppinsR", "max_stars_repo_head_hexsha": "c4a6feafeb9a324c0f9a54b10ba0e0990ebcc11a", "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": "LogisticRegression/00 Intro.r", "max_issues_repo_name": "iitjee/SteppinsR", "max_issues_repo_head_hexsha": "c4a6feafeb9a324c0f9a54b10ba0e0990ebcc11a", "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": "LogisticRegression/00 Intro.r", "max_forks_repo_name": "iitjee/SteppinsR", "max_forks_repo_head_hexsha": "c4a6feafeb9a324c0f9a54b10ba0e0990ebcc11a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4615384615, "max_line_length": 126, "alphanum_fraction": 0.795687885, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6142920135874256}} {"text": "########## tento skript je nasim uvodnim seznamenim s Rkem ##########\r\n#####################################################################\r\n# povsimnete si, ze v tomto softwaru jsou komentare opatreny (alespon jednim) dvojitym krizkem\r\n# a nezapomente, ze Rko rozeznava velka a mala pismena\r\n\r\n### ulozeni cisla do promenne: \r\n##############################\r\npocet<-30 ## to je pocet studentu zapsanych na pondelni cviceni\r\n\r\n### vypsani hodnoty promenne na obrazovku:\r\n##########################################\r\npocet\r\n\r\n### SAMI: a) do promenne VEK ulozte svuj vek (v rocich)\r\n### b) vypiste promennou VEK\r\nVEK <- 21\r\nVEK\r\n\r\n### prace s promennymi... jako by to byla konkretni cisla\r\n#########################################################\r\n\r\nXX<-13 ## pocet devcat na cvicenich\r\nXY<-17 ## pocet kluku na cvicenich\r\n\r\nXX+XY ## (by se melo rovnat \"poctu\")\r\n\r\n### SAMI: a) vytvorte promennou NOVA a dosadte do ni podil promennych XX a XY\r\n### b) vypiste promennou NOVA \r\n### c) spoctete rozdil mezi promennymi pocet a NOVA\r\n\r\nNOVA <- XX/XY\r\nNOVA\r\npocet - NOVA\r\n\r\n######## dalsi dulezita vec pro nas bude prace s vektory ########\r\n#################################################################\r\n\r\n### vektor zadany primo\r\n#######################\r\n\r\nhele <- c(1, 5, 4, 9, 0)\r\nlength(hele) ## funkce, vypise delku (dimenzi, pocet souradnic) vektoru hele\r\n\r\ndelka<-length(hele) ## i funkcni hodnota muze byt ulozena do promenne \r\ndelka\r\n\r\n### vektor zadany operatorem (muze se hodit)\r\n############################################\r\n\r\nx <- 1:7\r\nx\r\n\r\ny <- 2:-2\r\ny\r\n### vektor jako konecna posloupnost (i to se hodi)\r\n##################################################\r\n\r\nseq(1, 3, by=0.2) # urcen pocatkem, koncem a velikosti kroku\r\nseq(1, 5, length.out=4) # urcen a poctem elementu\r\n\r\n### SAMI: a) vytvorte vektor VEKT_1 s prvky -1,0,0.25,11\r\n### b) vytvorte vektor VEKT_2 jehoz prvky jsou cisla -2...23\r\n### c) kolik prvku ma (jak je dlouhy) VEKT_2?\r\n\r\nVEKT_1 <- c(-1,0,0.25,11)\r\nVEKT_1\r\n\r\nVEKT_2 <- -2:23\r\nVEKT_2\r\nlength(VEKT_2)\r\n\r\n### prace s prvky vektoru\r\n#########################\r\n\r\nx<-c(0,2,4,6,8,10)\r\nx[3] # vypise 3. prvek\r\n\r\nx[c(2, 4)] # vypise 2. a 4. prvek\r\ny<-x[c(2,4)] # vytvori vektor z 2. a 4. prvku vektoru x\r\ny\r\n\r\nx[-1] # vsechny prvky krome 1.\r\ny<-x[-1] # vektor, ktery vznikne z x vynechanim 1. prvku\r\ny\r\n\r\nx[c(2, -4)] # zahlasi chybu, pozice prvku jsou kladna cisla\r\nx[c(2.4, 3.54)] # zaokrouhli index dolu!!\r\n\r\n### SAMI: uvazujte svuj vektor VEKT_2:\r\n### a) vypiste 10. prvek\r\n### b) sectete 13. a 18. prvek\r\n### c) vydelte 20. prvek prvkem 6.\r\n### d) do vektoru VEKT_3 ulozte 3.,11., 13. a 20. prvek vektoru VEKT_2\r\n\r\nVEKT_2[10]\r\nVEKT_2[13] + VEKT_2[13]\r\nVEKT_2[20] / VEKT_2[6]\r\n\r\nVEKT_3 <- VEKT_2[c(3, 11, 13, 20)]\r\nVEKT_3\r\n\r\n#uprava vektoru\r\nx[2]<- -10 # prepise druhou souradnici\r\n\r\nx[-c(2,4)] # vypise vsechny prvky vektoru x BEZ 2. a 4. prvku\r\nx[c(-2,-4)]\r\n\r\nx<-x[-c(2,4)] # PRIMO z promene x vymaze druhy a ctvrty element\r\nlength(x)\r\nx\r\nx<-NULL # vymaze \"vnitrek\" promenne x\r\n\r\n### SAMI: a) z vektoru VEKT_2 vytvorte VEKT_4 odebranim 3., 10, a 14. prvku\r\n### b) jak je dlouhy vektor VEKT_4?\r\n\r\nVEKT_4 <- VEKT_2[-c(3, 10, 14)]\r\nVEKT_4\r\nlength(VEKT_4)\r\n\r\n### ooperace s vektory\r\n\r\ny<-c(-3,-2,-1,0,1,2)\r\n\r\nx+y ## soucet po souradnicich\r\nx*y ## soucin po souradnicich\r\nx-y ## rozdil po souradnicich\r\nx/y ## podil po souradnicich, pozor na deleni nulou!!!!\r\n\r\n### funkce na vektorech\r\n#######################\r\n\r\nlength(x) ## delka vektoru x (uz jsme si ukazali)\r\nsum(x) ## soucet prvku vektoru x\r\nmean(x) ## prumer z hodnot ulozenych v x\r\n\r\n### spojeni vektoru\r\n###################\r\nnovy_vektor<-c(x,y) ## spoji vektory x a y do jednoho \r\nnovy_vektor2<-c(novy_vektor,x) ## vytvori vektor obsahujici prvky vektoru \r\n ## novy_vektor a x\r\n\r\n### SAMI: a) vytvorte vektor VEKT_5 spojenim vektoru y a novy_vektor\r\n b) urcete delku VEKT_5\r\n c) soucet prvku vektoru VEKT_5 a jejich prumer\r\n\r\nVEKT_5 <- c(y, novy_vektor)\r\nVEKT_5\r\nlength(VEKT_5)\r\nsum(VEKT_5)\r\nmean(VEKT_5)\r\n", "meta": {"hexsha": "f0544cde05e4903abdecc019ba4a0982ba87b464", "size": 4250, "ext": "r", "lang": "R", "max_stars_repo_path": "informatics/computational_math/applied_statistics/seminars/cviceni1_2_solved.r", "max_stars_repo_name": "langer-jaros/learning", "max_stars_repo_head_hexsha": "446c0b4c425bda9077f222558817a2adf6a98b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "informatics/computational_math/applied_statistics/seminars/cviceni1_2_solved.r", "max_issues_repo_name": "langer-jaros/learning", "max_issues_repo_head_hexsha": "446c0b4c425bda9077f222558817a2adf6a98b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "informatics/computational_math/applied_statistics/seminars/cviceni1_2_solved.r", "max_forks_repo_name": "langer-jaros/learning", "max_forks_repo_head_hexsha": "446c0b4c425bda9077f222558817a2adf6a98b5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1456953642, "max_line_length": 95, "alphanum_fraction": 0.5430588235, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.6141763498237263}} {"text": "## Function file to fit discrete Lee-Carter with Newton-Raphson\n## Modified by Giancarlo Camarda 25-11-2009 for teaching purposes\n## (EDSD 220)\n\n\n###################################################\n## Update Alpha\nUpdate.alpha <- function(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit){\n difD <- Dth - D.fit\n Alpha <- Alpha + difD %*% One / (D.fit %*% One)\n Eta <- Alpha %*% t(One) + Beta %*% t(Kappa)\n D.fit <- Exp * exp(Eta)\n list(Alpha = Alpha, D.fit = D.fit)\n}\n\n###################################################\n## Update Beta\nUpdate.beta <- function(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit){\n difD <- Dth - D.fit\n Kappa2 <- Kappa * Kappa\n Beta <- Beta + difD %*% Kappa / (D.fit %*% Kappa2)\n Eta <- Alpha %*% t(One) + Beta %*% t(Kappa)\n D.fit <- Exp * exp(Eta)\n list(Beta = Beta, D.fit = D.fit)\n}\n\n###################################################\n## Update Kappa\nUpdate.kappa <- function(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit){\n difD <- Dth - D.fit\n Beta2 <- Beta * Beta\n Kappa <- Kappa + t(difD) %*% Beta / (t(D.fit) %*% Beta2)\n Kappa <- Kappa - mean(Kappa)\n Kappa <- Kappa / sqrt(sum(Kappa * Kappa))\n Kappa <- matrix(Kappa, ncol = 1)\n Eta <- Alpha %*% t(One) + Beta %*% t(Kappa)\n D.fit <- Exp * exp(Eta)\n list(Kappa = Kappa, D.fit = D.fit)\n}\n\n###################################################\n## MAIN FUNCTION for fitting the Lee-Carter\nLCpoi <- function(Dth, Exp){\n # dimensions\n m <- nrow(Dth)\n n <- ncol(Dth)\n # Initialise\n One <- matrix(1, nrow=n, ncol = 1) \n Fit.init <- log((Dth + 1)/(Exp + 2))\n Alpha <- Fit.init %*% One / n\n Beta <- matrix(1 * Alpha, ncol = 1)\n sum.Beta <- sum(Beta) \n Beta <- Beta / sum.Beta\n Kappa <- matrix(seq(n, 1, by = -1), nrow = n, ncol = 1)\n Kappa <- Kappa - mean(Kappa)\n Kappa <- Kappa / sqrt(sum(Kappa * Kappa))\n Kappa <- Kappa * sum.Beta\n # Iteration\n D.fit <- Exp * exp(Fit.init)\n for (iter in 1:50){\n Alpha.old <- Alpha\n Beta.old <- Beta\n Kappa.old <- Kappa\n #\n temp <- Update.alpha(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit)\n D.fit <- temp$D.fit\n Alpha <- temp$Alpha\n #\n temp <- Update.beta(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit)\n D.fit <- temp$D.fit\n Beta <- temp$Beta\n #\n temp <- Update.kappa(Alpha, Beta, Kappa,\n One, Dth, Exp, D.fit)\n D.fit <- temp$D.fit\n Kappa <- temp$Kappa\n crit <- max(max(abs(Alpha - Alpha.old)),\n max(abs(Beta - Beta.old)),\n max(abs(Kappa - Kappa.old)))\n if(crit < 1e-04) break\n }\n # constraints\n sum.Beta <- sum(Beta) \n Beta <- Beta / sum.Beta\n Kappa <- Kappa * sum.Beta\n # output\n out <- list(Alpha=Alpha, Beta=Beta, Kappa=Kappa)\n}\n", "meta": {"hexsha": "3d9818e6db81070d78dc8c717a4838b001fe357a", "size": 2793, "ext": "r", "lang": "R", "max_stars_repo_path": "MortalityExamples/FUNCTIONSleecarter.r", "max_stars_repo_name": "jmaburto/FertMort_forecast", "max_stars_repo_head_hexsha": "f2f1bf289688ee93e04cf2b1c3134e5ad9323719", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MortalityExamples/FUNCTIONSleecarter.r", "max_issues_repo_name": "jmaburto/FertMort_forecast", "max_issues_repo_head_hexsha": "f2f1bf289688ee93e04cf2b1c3134e5ad9323719", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MortalityExamples/FUNCTIONSleecarter.r", "max_forks_repo_name": "jmaburto/FertMort_forecast", "max_forks_repo_head_hexsha": "f2f1bf289688ee93e04cf2b1c3134e5ad9323719", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-13T10:30:30.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-13T10:30:30.000Z", "avg_line_length": 29.7127659574, "max_line_length": 65, "alphanum_fraction": 0.4991049051, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.614133005728262}} {"text": "# Create case study figures\n\n#########################################################################\n# Pull PWT into dataframe\ndata(\"pwt9.1\")\n\n# Basic calculations\np <- pwt9.1 # copy dataframe for manipulation\np$lngdppc <- round(log(p$rgdpna) - log(p$pop),digits=2) # create log GDP per capita\np$lntfp <- log(p$rtfpna)\np$ky <- round(p$rnna/p$rgdpna,digits=2) # create K/Y ratio\np$phil <- round(p$labsh*p$rgdpna/(p$labsh*p$rgdpna+.05*p$rnna),digits=2) # create kludge cost share of labor\n\n# Calculate growth rate of population\np <- \n p %>%\n group_by(isocode) %>%\n mutate(lag1.pop = dplyr::lag(pop, n = 1, default = NA))\np$g1.pop <- (log(p$pop) - log(p$lag1.pop))/1\np$si<- round(p$csh_i,digits=2)\n\n# subset PWT into stable and catchup groups\nusa <- p[which(p$isocode %in% c(\"USA\")),]\ndeu <- p[which(p$isocode %in% c(\"DEU\")),]\nkor <- p[which(p$isocode %in% c(\"KOR\")),]\nchn <- p[which(p$isocode %in% c(\"CHN\")),]\ncomp <- p[which(p$isocode %in% c(\"USA\",\"CHN\",\"KOR\")),]\n\n#########################################################################\n# Simple TS regressions for fitted BGP for USA\n#########################################################################\nm1 <- lm(usa$lngdppc~usa$year, data=usa)\nm2 <- lm(usa$lngdppc~usa$year, data=usa, subset=(year<2001))\nusa$fitted <- predict(m2,usa)\n\nfig <- plot_ly(usa, x = ~year, y = ~lngdppc, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = fitted(m1), name = 'BGP All',mode = 'lines')\nfig <- fig %>% add_trace(y = ~fitted, name = 'BGP 20th',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for United States', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita', range=c(9,12)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-usa\")\n\n#########################################################################\n# Simple TS regressions for fitted BGP for DEU\n#########################################################################\nm2 <- lm(deu$lngdppc~deu$year, data=deu, subset=(year>1990))\ndeu$fitted <- predict(m2,deu)\n\nfig <- plot_ly(deu, x = ~year, y = ~lngdppc, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~fitted, name = 'BGP',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for Germany', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita', range=c(7,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-deu\")\n\nfig <- plot_ly(deu, x = ~year, y = ~ky, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Capital/output for Germany', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Capital/output ratio', range=c(3,5)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply--ky-deu\")\n\n#########################################################################\n# Simple TS regressions for fitted BGP for KOR\n#########################################################################\nm1 <- lm(kor$lngdppc~kor$year, data=kor, subset=(year<1963))\nkor$fitted1 <- predict(m1,kor)\nm2 <- lm(kor$lngdppc~kor$year, data=kor, subset=(year>2009))\nkor$fitted2 <- predict(m2,kor)\n\nfig <- plot_ly(kor, x = ~year, y = ~lngdppc, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~fitted1, name = 'BGP before',mode = 'lines')\nfig <- fig %>% add_trace(y = ~fitted2, name = 'BGP after',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for South Korea', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita', range=c(6.5,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-kor\")\n\nfig <- plot_ly(kor, x = ~year, y = ~csh_i, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Capital formation share of GDP for South Korea', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Capital formation share of GDP', range=c(0,0.6)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-si-kor\")\n\nfig <- plot_ly(kor, x = ~year, y = ~g1.pop, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Population growth for South Korea', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Population growth rate', range=c(0,0.05)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-gl-kor\")\n\n#########################################################################\n# Simple TS regressions for fitted BGP for China\n#########################################################################\nm1 <- lm(chn$lngdppc~chn$year, data=chn, subset=(year<1970))\nchn$fitted1 <- predict(m1,chn)\nchn$fitted2 <- predict(m2,chn) # use Korea's current BGP as comparison\n\nfig <- plot_ly(chn, x = ~year, y = ~lngdppc, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~fitted1, name = 'BGP before',mode = 'lines')\nfig <- fig %>% add_trace(y = ~fitted2, name = 'S. Korea BGP',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for China', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita', range=c(6.5,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-chn\")\n\nfig <- plot_ly(chn, x = ~year, y = ~csh_i, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Capital formation share of GDP for China', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Capital formation share of GDP', range=c(0,0.6)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-si-chn\")\n\nfig <- plot_ly(chn, x = ~year, y = ~g1.pop, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Population growth for China', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Population growth rate', range=c(-.01,0.05)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-gl-chn\")\n\n#########################################################################\n# Comparison of GDP p.c. in USA, China, Korea\n#########################################################################\nfig <- plot_ly(comp, x = ~year, y = ~lngdppc, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Log GDP per capita ', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log GDP per capita', range=c(6.5,12)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-comp\")\n\n#########################################################################\n# Simple TS regressions for TFP path in China\n#########################################################################\nf <- p[which(p$isocode %in% c(\"CHN\")),] # re-grab initial data\nf <- f[which(f$year>1960),]\n\nm2 <- lm(f$lntfp~f$year, data=f, subset=(year>1960 & year<2000))\nm3 <- lm(f$lntfp~f$year, data=f, subset=(year>2013))\nf$fitted2 <- predict(m2,f)\nf$fitted3 <- predict(m3,f)\n\nfig <- plot_ly(f, x = ~year, y = ~lntfp, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~fitted2, name = 'Early BGP?',mode = 'lines')\nfig <- fig %>% add_trace(y = ~fitted3, name = 'New BGP?',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Level of productivity', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log productivity'),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-gtfp-chn\")\n\n#########################################################################\n# Simple TS regressions for TFP path in Japan\n#########################################################################\nf <- p[which(p$isocode %in% c(\"JPN\")),]\nm1 <- lm(f$lntfp~f$year, data=f, subset=(year<1995))\nm3 <- lm(f$lntfp~f$year, data=f, subset=(year>2000))\nf$fitted1 <- predict(m1,f)\nf$fitted3 <- predict(m3,f)\nfig <- plot_ly(f, x = ~year, y = ~lntfp, linetype = ~isocode, type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~fitted1, name = 'Pre-1995 BGP',mode = 'lines')\nfig <- fig %>% add_trace(y = ~fitted3, name = 'Post-2000 BGP',mode = 'lines')\nfig <- layout(fig, title = list(text = 'Level of productivity', x=0),\n xaxis = list(title = 'Year', tick0=1950, dtick=10),\n yaxis = list (title = 'Log productivity', range=c(-.75,.25)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-apply-gtfp-jpn\")", "meta": {"hexsha": "b9e780fe3d960c0f9bd48fcb3b1903b4036be65c", "size": 9141, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_PWT_Apply.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_PWT_Apply.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_PWT_Apply.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 53.1453488372, "max_line_length": 108, "alphanum_fraction": 0.5399846844, "num_tokens": 2652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6140655425454673}} {"text": "#------------------------------------------------------------------------------\r\n#Copyright (c) 2017 Tijana Vujcic\r\n\r\nsource(\"DBDA2E-utilities.R\")\r\n\r\n#===============================================================================\r\n \r\n require(rstan)\r\n #-----------------------------------------------------------------------------\r\n # THE DATA.\r\n myData = read.table(file=\"BloodDataGeneratorOutput.txt\",header=T,sep=\" \")\r\n yName = \"HeartAttack\"\r\n xName = c( \"Systolic\", \"Diastolic\", \"Weight\", \"Cholesterol\",\r\n \"Height\", \"Age\" )\r\n y = myData[,yName]\r\n x = myData[,xName]\r\n # Do some checking that data make sense:\r\n if ( any( !is.finite(y) ) ) { stop(\"All y values must be finite.\") }\r\n #if ( any( !is.finite(x) ) ) { stop(\"All x values must be finite.\") }\r\n #Ntotal = length(y)\r\n # Specify the data in a list, for later shipment to JAGS:\r\n dataList = list(\r\n x = x ,\r\n y = y ,\r\n N = length(y) ,\r\n\tp = 7,\r\n\tsystolic = x[,1],\r\n\tdias = x[,2],\r\n\tweight = x[,3],\r\n\tcholesterol = x[,4],\r\n\theight = x[,5],\r\n\tage = x[,6]\r\n )\r\n\r\n #-----------------------------------------------------------------------------\r\n # THE MODEL.\r\n modelString = \"\r\n\tdata {\r\n\t\tint N;\r\n\t\tint p;\r\n\t\tint y[N];\r\n\t\tint systolic[N];\r\n\t\tint dias[N];\r\n\t\treal weight[N];\r\n\t\tint cholesterol[N];\r\n\t\treal height[N];\r\n\t\tint age[N];\r\n\t}\r\n\r\n\tparameters {\r\n\t\treal beta[p];\r\n\t}\r\n\t\r\n\ttransformed parameters {\r\n\r\n\treal odds[N];\r\n\treal prob[N];\r\n\r\n\tfor (i in 1:N) {\r\n\t\todds[i] = exp(beta[1] + beta[2]*systolic[i] + beta[3]*dias[i] + beta[4]*weight[i] + beta[5]*cholesterol[i] + beta[6]*height[i] + beta[7]*age[i]);\r\n\t\tprob[i] = odds[i] / (odds[i] + 1);\r\n\t}\r\n\t}\r\n\t\r\n\tmodel {\r\n\t\ty ~ bernoulli(prob);\r\n\t}\r\n \r\n \r\n \" # close quote for modelString\r\n # Write out modelString to a text file\r\n \r\nresStan <- stan(model_code = modelString, data = dataList,\r\n chains = 3, iter = 20000/3, warmup = 1000, thin = 1)\r\n\r\n", "meta": {"hexsha": "9ef4cf65eace85d4124526cd5d66de9eaaf5c836", "size": 2027, "ext": "r", "lang": "R", "max_stars_repo_path": "MultipleLogisticR.r", "max_stars_repo_name": "vujicictijana/bayes", "max_stars_repo_head_hexsha": "1f6cdba557f7c14eb05f6bf5c49924b237a50034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-14T18:45:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:45:57.000Z", "max_issues_repo_path": "MultipleLogisticR.r", "max_issues_repo_name": "vujicictijana/bayes", "max_issues_repo_head_hexsha": "1f6cdba557f7c14eb05f6bf5c49924b237a50034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MultipleLogisticR.r", "max_forks_repo_name": "vujicictijana/bayes", "max_forks_repo_head_hexsha": "1f6cdba557f7c14eb05f6bf5c49924b237a50034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-18T08:48:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T18:45:58.000Z", "avg_line_length": 26.6710526316, "max_line_length": 149, "alphanum_fraction": 0.4632461766, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.6139435770103164}} {"text": "\n# Clear environment\nrm(list = ls()) \n\n# Clear console\ncat(\"\\014\") # ctrl+L\n\nlibrary(devtools)\n# import digest library to hash the value as sha256\nlibrary(\"digest\")\n\n\n# to use sample digest function, you can run this line:\n# digest(\"this is an example string\" ,\"sha256\")\n\n# Before you start building your blockchain, \n# you need to start the chain somewhere. This is done \n# using a so-called Genesis Block. It contains no data and \n# arbitrary values for proof and previous hash (as there is no previous block).\n\n# Define Genesis Block (index 1 and arbitrary previous hash)\n# in other words, first block(dummy node).\nblock_genesis <- list(index = 1,\n timestamp = Sys.time(),\n data = \"Genesis Block\",\n previous_hash = \"0\",\n proof = 1)\n\n#Function that creates a hashed \"block\"\nhash_block <- function(block){\n block$new_hash <- digest(c(block$index,\n block$timestamp,\n block$data,\n block$previous_hash), \"sha256\")\n return(block)\n}\n\n### Simple Proof of Work Algorithm\nproof_of_work <- function(last_proof){\n proof <- last_proof + 1\n \n # Increment the proof number until a number is found that is divisable by 99 and by the proof of the previous block\n while (!(proof %% 99 == 0 & proof %% last_proof == 0 )){\n proof <- proof + 1\n }\n \n return(proof)\n}\n\n#A function that takes the previous block and normally some data\n# (in our case the data is a string indicating which block in the chain it is)\ngen_new_block <- function(previous_block){\n \n #Proof-of-Work\n new_proof <- proof_of_work(previous_block$proof)\n \n #Create new Block\n new_block <- list(index = previous_block$index + 1,\n timestamp = Sys.time(),\n data = paste0(\"this is block \", previous_block$index +1),\n previous_hash = previous_block$new_hash,\n proof = new_proof)\n \n #Hash the new Block\n new_block_hashed <- hash_block(new_block)\n \n return(new_block_hashed)\n}\n\n# create a list named blockchain whose first node is block_genesis\nblockchain <- list(block_genesis)\nprevious_block <- blockchain[[1]]\n\n# How many blocks should we add to the chain after the genesis block\nnum_of_blocks_to_add <- 5\n\n# Add blocks to the chain with generated data.\nfor (i in 1: num_of_blocks_to_add){\n block_to_add <- gen_new_block(previous_block) \n blockchain[i+1] <- list(block_to_add)\n previous_block <- block_to_add\n \n print(cat(paste0(\"Block \", block_to_add$index, \" has been added\", \"\\n\",\n \"\\t\", \"Proof: \", block_to_add$proof, \"\\n\",\n \"\\t\", \"Hash: \", block_to_add$new_hash)))\n}\n\nblockchain\nbuild(\"~/Desktop/adsız klasör/blockchain_R\")\n", "meta": {"hexsha": "472c4f0cafb882455f7162005eb648be2749f017", "size": 2789, "ext": "r", "lang": "R", "max_stars_repo_path": "script.r", "max_stars_repo_name": "socodes/blockchain_R", "max_stars_repo_head_hexsha": "3097851ade0789fe115ef8085d80676d3bc5c22e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script.r", "max_issues_repo_name": "socodes/blockchain_R", "max_issues_repo_head_hexsha": "3097851ade0789fe115ef8085d80676d3bc5c22e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script.r", "max_forks_repo_name": "socodes/blockchain_R", "max_forks_repo_head_hexsha": "3097851ade0789fe115ef8085d80676d3bc5c22e", "max_forks_repo_licenses": ["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.9888888889, "max_line_length": 117, "alphanum_fraction": 0.6443169595, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.613894730674631}} {"text": "model_ptsoil <- function (evapoTranspirationPriestlyTaylor = 120.0,\n Alpha = 1.5,\n tau = 0.9983,\n tauAlpha = 0.3){\n #'- Name: PtSoil -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: PtSoil EnergyLimitedEvaporation Model\n #' * Author: Pierre Martre\n #' * Reference: Modelling energy balance in the wheat crop model SiriusQuality2:\n #' Evapotranspiration and canopy and soil temperature calculations\n #' * Institution: INRA Montpellier\n #' * ExtendedDescription: Evaporation from the soil in the energy-limited stage \n #' * ShortDescription: Evaporation from the soil in the energy-limited stage\n #'- inputs:\n #' * name: evapoTranspirationPriestlyTaylor\n #' ** description : evapoTranspiration Priestly Taylor\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 120\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: Alpha\n #' ** description : Priestley-Taylor evapotranspiration proportionality constant\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 1.5\n #' ** min : 0\n #' ** max : 100\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: tau\n #' ** description : plant cover factor\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** default : 0.9983\n #' ** min : 0\n #' ** max : 100\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: tauAlpha\n #' ** description : Fraction of the total net radiation exchanged at the soil surface when AlpaE = 1\n #' ** parametercategory : soil\n #' ** datatype : DOUBLE\n #' ** default : 0.3\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #'- outputs:\n #' * name: energyLimitedEvaporation\n #' ** description : energy Limited Evaporation \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n if (tau < tauAlpha)\n {\n AlphaE <- 1.0\n }\n else\n {\n AlphaE <- Alpha - ((Alpha - 1.0) * (1.0 - tau) / (1.0 - tauAlpha))\n }\n energyLimitedEvaporation <- evapoTranspirationPriestlyTaylor / Alpha * AlphaE * tau\n return (list('energyLimitedEvaporation' = energyLimitedEvaporation))\n}", "meta": {"hexsha": "0a1a431e687ffe48b939dc7f4f2aed12315bba38", "size": 3917, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Energy_Balance/Ptsoil.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_stars_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/SQ_Energy_Balance/Ptsoil.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_issues_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "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": "src/r/SQ_Energy_Balance/Ptsoil.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Energy_Balance", "max_forks_repo_head_hexsha": "db6a8ba30940b6527e3ae82c325319454ff8a224", "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": 52.9324324324, "max_line_length": 129, "alphanum_fraction": 0.4097523615, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6137803504113072}} {"text": " ZHEGV Example Program Results\n\n Eigenvalues\n -5.9990 -2.9936 0.5047 3.9990\n Eigenvectors\n 1 2 3 4\n 1 1.7405 -0.6626 0.2835 1.2378\n 0.0000 0.2258 -0.5806 0.0000\n \n 2 -0.4136 -0.1164 -0.3769 -0.5608\n -0.4689 -0.0178 -0.3194 -0.3729\n \n 3 -0.8404 0.9098 -0.3338 -0.6643\n -0.2483 0.0000 -0.0134 -0.1021\n \n 4 0.3021 -0.6120 0.6663 0.1589\n 0.6103 -0.5348 0.0000 0.8366\n\n Estimate of reciprocal condition number for B\n 2.5E-03\n\n Error estimates for the eigenvalues\n 6.7E-13 4.1E-13 1.9E-13 5.0E-13\n\n Error estimates for the eigenvectors\n 1.2E-12 1.1E-12 8.5E-13 9.4E-13\n", "meta": {"hexsha": "70922d173005652920f8ea8d6830be507162175f", "size": 784, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/baseresults/zhegv_example.r", "max_stars_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_stars_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2018-01-28T15:48:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:26:43.000Z", "max_issues_repo_path": "examples/baseresults/zhegv_example.r", "max_issues_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_issues_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/baseresults/zhegv_example.r", "max_forks_repo_name": "numericalalgorithmsgroup/LAPACK_examples", "max_forks_repo_head_hexsha": "0dde05ae4817ce9698462bbca990c4225337f481", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 18, "max_forks_repo_forks_event_min_datetime": "2019-04-19T12:22:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T03:32:12.000Z", "avg_line_length": 29.037037037, "max_line_length": 48, "alphanum_fraction": 0.4897959184, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6136678799231047}} {"text": "#This takes a matrix of x values, fits c/p/s hierarchically.\n#clear environment, load runjags.\nrm(list = ls())\nlibrary(runjags)\n\n#10 sites, 10 plots per site, 10 observations per plot. \nn.site <- 10\nn.plot <- 9\nn.core <- 10\nsiteID <- sort(rep(LETTERS[1:n.site],n.plot*n.core))\nplotID <- rep(1:n.plot,n.site*n.core)\nplotID <-paste(siteID,plotID,sep = '_')\nsite.means <- runif(n.site,10,25)\nplot.means <- list()\nfor(i in 1:length(site.means)){\n plot.means[[i]] <- rnorm(n.plot,site.means[i],2)\n}\nplot.means <- unlist(plot.means)\n\n#get observations for each plot, based on a mean, and a sd of 2\nobs <- list()\nfor(i in 1:length(plot.means)){\n obs[[i]] <- rnorm(n.core, mean = plot.means[i], sd = 2)\n}\nx1 <- unlist(obs)\nobs <- list()\nfor(i in 1:length(plot.means)){\n obs[[i]] <- rnorm(n.core, mean = plot.means[i], sd = 2)\n}\nx2 <- unlist(obs)\n\n#create true data frame.\ndat <- data.frame(siteID,plotID)\ndat <- dat[order(plotID),]\ndat$x1 <- x1\ndat$x2 <- x2\nX <- as.matrix(dat[,c('x1','x2')])\n\n#indexing.\nplotindex <- as.factor(dat$plotID)\nsiteindex <- list()\nfor(i in 1:n.site){\n siteindex[[i]] <- rep(LETTERS[i],n.plot)\n}\nsiteindex <- as.factor(unlist(siteindex))\n\njags.model = \"\nmodel {\n #priors\n for(m in 1:n.X){\n global[m] ~ dnorm(0,1.0E-4) #global level parameter prior.\n site.tau[m] ~ dgamma(0.1,0.1)\n plot.tau[m] ~ dgamma(0.1,0.1)\n core.tau[m] ~ dgamma(0.1,0.1)\n }\n \n #estimate means\n for(m in 1:n.X){\n for(i in 1:N.site){ site[i,m] ~ dnorm(global[m], site.tau[m])} ## estimate global mean\n for(j in 1:N.plot){ plot[j,m] ~ dnorm(site[siteindex[j],m],plot.tau[m])} ## estimate site means\n for(k in 1:N.core){ core[k,m] ~ dnorm(plot[plotindex[k],m],core.tau[m])} ## estimate plot means\n }\n\n} #end model\n\"\n#specify data object.\njags.data <- list(core = X, n.X = ncol(X), \n N.site = length(unique(dat$siteID)),\n N.plot = length(unique(dat$plotID)),\n N.core = nrow(dat),\n plotindex = plotindex, siteindex=siteindex)\n#fit model.\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('plot','site'))\nout <- summary(jags.out)\n#compare estimate plot/site means to true values. All w/in 95% credible interval.\npar(mfrow = c(2,2))\nfit.plot.means <- out[grep('plot',rownames(out)),][,4]\nfit.site.means <- out[grep('site',rownames(out)),][,4]\nplot(plot.means ~ fit.plot.means[1:90], main = 'plot-level fit x1'); abline(0,1,lwd=2, lty=2)\nplot(plot.means ~ fit.plot.means[91:180], main = 'plot-level fit x2'); abline(0,1,lwd=2, lty=2)\nplot(site.means ~ fit.site.means[1:10], main = 'site-level fit x1'); abline(0,1,lwd=2, lty=2)\nplot(site.means ~ fit.site.means[11:20], main = 'site-level fit x2'); abline(0,1,lwd=2, lty=2)\n\n#check uncertainty values\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('core.tau','plot.tau','site.tau','global'))\nsummary(jags.out)\n\n\n#create data with missing observations.\nmissing <- dat\n#remove 3 observations within a plot in site A.\nmissing[2:4,3] <- NA\nmissing[4:7,4] <- NA\n#remove an entire plot in site B.\nmissing[missing$plotID == 'B_1',3] <- NA\nmissing[missing$plotID == 'B_2',4] <- NA\n#remove all observations in site C.\nmissing[missing$siteID == 'C' ,3] <- NA\nmissing[missing$siteID == 'B' ,4] <- NA\n\nX <- as.matrix(missing[,3:4])\n\n#creat new jags data object.\njags.data <- list(core = X, n.X = ncol(X), \n N.site = length(unique(dat$siteID)),\n N.plot = length(unique(dat$plotID)),\n N.core = nrow(dat),\n plotindex = plotindex, siteindex=siteindex)\n\n#fit, see what the model estimates for core level values.\njags.out <- runjags::run.jags(jags.model,\n data = jags.data,\n n.chains = 3,\n monitor = c('core','plot','site'))\n\nout <- summary(jags.out)\ncomp <- dat\n\n\n###FROM here on has not been modded for multivariate case.\ncomp$pred <- out[grep('core',rownames(out)),4]\ncomp$removed <- missing$x\nz <- comp[is.na(comp$removed),]\n\n#how are the core level predcitions compared to true values? in range.\ncbind(out[2:4,],dat$x[2:4])\n\n#how about the missing plot?\nzz <- cbind(out[grep('core',rownames(out)),],missing,dat$x)\nzz[zz$plotID == 'B_1',]\n\n#how about the missing site?\nzz[zz$siteID == 'C',]\n", "meta": {"hexsha": "3f3b62faf22737d073c6b7397a3a02560b4b968d", "size": 4535, "ext": "r", "lang": "R", "max_stars_repo_path": "testing_development/implement_missing_data_ddirch/matrix of missing data.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing_development/implement_missing_data_ddirch/matrix of missing data.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "testing_development/implement_missing_data_ddirch/matrix of missing data.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 32.3928571429, "max_line_length": 100, "alphanum_fraction": 0.5944873208, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6136169289796118}} {"text": "\npca.analyse.data = function( X, t0=NULL, t1=NULL,\n fname=\"sorted.anomalies\", title=\"Years\", vars=NULL, newnames=NULL,\n colscheme=\"redgreen\", addscores=TRUE, sortdecreasing=FALSE, scaledata=TRUE, plotdata=TRUE) {\n\n if (!is.null(vars)) X = X[, vars ]\n if (!is.null(newnames) ) names(X) = newnames\n\n if (!is.null(t0) & !is.null(t1)) {\n X = X[ which( rowSums( X, na.rm=T) !=0 ) ,]\n X = X[ which( as.numeric(rownames(X)) >= t0 ) ,]\n X = X[ which( as.numeric(rownames(X)) <= t1 ) ,]\n }\n\n if (scaledata) X = scale( X, center=TRUE, scale=TRUE )\n\n yvals=rownames(X)\n vars =colnames(X)\n years= as.numeric(yvals)\n yrange = range(years)\n\n of1 = paste(fname, \"PC1.pdf\", sep=\".\")\n of2 = paste(fname, \"PC2.pdf\", sep=\".\")\n of3 = paste(fname, \"anomalies.pdf\", sep=\".\")\n\n cm = cor( X, use=\"pairwise.complete.obs\" ) # set up a correlation matrix ignoring NAs\n cm[ is.na(cm) ] = 0\n\n s = svd(cm) # eigenanalysis via singular value decomposition\n evec = s$v # eigenvectors\n eval = s$d # eigenvalues\n \n # i.e., X %*% evec .. force a multiplication ignoring NAs\n nfac = 2 \n ndat = dim(X)[1]\n scores = matrix(0, nrow=ndat, ncol = nfac)\n for (j in 1:nfac) { \n for (i in 1:ndat) { \n scores[i,j] = sum ( X[i,] * t(evec[,j]), na.rm=T )\n } \n }\n\n x = cbind( scores[,1] / sqrt(eval[1] ), scores[,2] / sqrt( eval[2]) )\n y = cbind( evec[,1] * sqrt(eval[1] ) , evec[,2] * sqrt( eval[2]) )\n\n outscores = data.frame(x)\n outscores$yr = as.numeric(yvals)\n\n X.stats = list( id=yvals, vars=vars, correlation.matrix=cm,\n eigenvectors=evec, eigenvalues=eval, projections.id=x, projections.vars=y )\n\n print( str( X.stats))\n\n if (plotdata) {\n\n par(cex=2, lty=2)\n\n plot.new()\n plot( yvals, x[,1], xlab=\"Years\", ylab=paste(\"PCA1 (\", round(eval[1]/sum(eval)*100, 1), \"%)\", sep=\"\") )\n lines( lowess(yvals, x[,1], f=1/5 ) )\n dev.print ( pdf, file=of1, width=12, height=8 )\n dev.off()\n\n plot.new()\n plot( yvals, x[,2], xlab=\"Years\", ylab=paste(\"PCA2 (\", round(eval[2]/sum(eval)*100, 1), \"%)\", sep=\"\" ) )\n lines( lowess(yvals, x[,2], f=1/5) )\n dev.print ( pdf, file=of2, width=12, height=8 )\n dev.off()\n\n # form residual variations figure based upon a sorting of ordination scores\n varloadings = NULL\n varloadings = as.data.frame( cbind( y, vars ) )\n\n q = as.data.frame( t( as.matrix( X ) ) )\n q$vars = rownames( q )\n q = merge( x=q, y=varloadings, by.x=\"vars\", by.y=\"vars\", all=T )\n ordered = sort( as.numeric( as.character( q$V1 ) ), index.return=T, decreasing=sortdecreasing )\n qq = q[ ordered$ix, ]\n\n if (addscores) {\n varnames = paste(qq$vars, \" {\", round(as.numeric(as.character(qq$V1)),2), \", \",\n round(as.numeric(as.character(qq$V2)),2), \"}\", sep=\"\")\n } else {\n varnames = qq$vars\n }\n\n qq$vars = qq$V1 = qq$V2 = NULL\n qq = as.data.frame( t( qq ) )\n colnames( qq ) = varnames\n Z = as.matrix( qq )\n\n a = max( abs( min(Z, na.rm=T) ), abs( max( Z, na.rm=T) ) )\n br = seq( -a, a, .1)\n\n plot.new()\n par( mai=c(2, 6, 1, 0.5), cex=2 )\n\n if (colscheme==\"rainbow\") {\n cols=rainbow(length(br)-1, start=0, end=1/3)\n } else if (colscheme==\"redgreen\") {\n cols=rev(green.red(length(br)))\n } else if (colscheme==\"bluered\") {\n cols=rev(blue.red(length(br)))\n } else if (colscheme==\"heat\") {\n cols=rev(heat.colors(length(br)-1))\n } else {\n cols=colscheme\n }\n\n image(z=Z, x=years, breaks=br, col=cols, xlab=title, ylab=\"\", axes=F )\n\n for (i in seq(range(yrange)[1], range(yrange)[2], by=10)) abline( v=i-0.5, col=\"slategray\")\n for (i in seq(range(yrange)[1], range(yrange)[2], by=1)) abline( v=i-0.5, col=\"slategray1\")\n\n z = 1/(dim(Z)[2] - 1)\n for (i in seq(0, 1, by=z*10)) abline( h=i-(z/2), col=\"slategray\")\n for (i in seq(0, 1, by=z)) abline( h=i-(z/2), col=\"slategray1\")\n\n par(las=1)\n axis( 1 )\n\n vars = colnames(Z)\n par(cex=1.4)\n axis( 2, at=seq(0,1,length=length(vars)), labels=vars)\n write.table(Z, file=\"anomalies.dat\", quote=F, sep=\";\")\n dev.print (pdf, file=of3, width=20, height=20)\n dev.off()\n }\n\n return( X.stats )\n}\n", "meta": {"hexsha": "18f112f2e91a127d7cd86f48fd4cb8e38c856f28", "size": 4130, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pca.analyse.data.r", "max_stars_repo_name": "PEDsnowcrab/aegis", "max_stars_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/pca.analyse.data.r", "max_issues_repo_name": "PEDsnowcrab/aegis", "max_issues_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/pca.analyse.data.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 31.2878787879, "max_line_length": 108, "alphanum_fraction": 0.5711864407, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6136152485029064}} {"text": "##########################################################################\n# github : https://github.com/jiankaiwang/DetailScience\n# classification : math\n# description : calculate the network in matrix\n#\n# class description :\n# - networkAfterRemoveNodesRetData\n#\t\t(1) net : perserve the network after removing nodes recursively\n#\t\t(2) sel : perserve the origin nodes for absolutely deletion\n#\t\t(3) rmv : perserve nodes for deletion finally\n# \n# function description :\n# - networkAfterRemoveNodes\n# (1) directed : row is the source and column is the target (or destination)\n#\t\t(2) return : returned object is \"networkAfterRemoveNodesRetData\" data type\n#\n# function usage :\n# - networkAfterRemoveNodesRetData networkAfterRemoveNodes(matrix originNetwork, vector selectedNodes, logical isDirected)\n# (1) originNetwork (as matrix) : a matrix conserving edge information\n# (2) selectedNodes (as vector) : a vector listing all nodes are removed\n# (3) isDirected (as boolean) : whether the matrix is directed or not\n#\n# function example :\n# - leftNetwork <- networkAfterRemoveNodes(net,selected,TRUE)\n#\n# > net\n# A B C D E F G H I\n# A 0 0 1 1 0 0 0 1 0\n# B 0 0 0 0 0 0 0 0 0\n# C 0 0 0 0 0 1 0 0 0\n# D 0 1 0 0 1 0 0 0 0\n# E 0 0 0 0 0 0 0 1 0\n# F 0 0 0 0 0 0 1 0 0\n# G 0 0 0 1 1 0 0 0 0\n# H 0 0 0 0 0 0 0 0 0\n# I 0 0 0 0 0 0 0 0 0\n#\n# > leftNetwork\n# An object of class \"classNetAfterNodeRevData\"\n#\tSlot \"net\":\n#\t\tA B C D E F G H I\n#\tA 0 0 0 1 0 0 0 1 0\n#\tB 0 0 0 0 0 0 0 0 0\n#\tC 0 0 0 0 0 0 0 0 0\n#\tD 0 0 0 0 0 0 0 0 0\n#\tE 0 0 0 0 0 0 0 0 0\n#\tF 0 0 0 0 0 0 0 0 0\n#\tG 0 0 0 0 0 0 0 0 0\n#\tH 0 0 0 0 0 0 0 0 0\n#\tI 0 0 0 0 0 0 0 0 0\n\n#\tSlot \"sel\":\n#\t[1] \"B\" \"C\" \"E\"\n\n#\tSlot \"rmv\":\n#\t[1] \"B\" \"C\" \"E\" \"F\" \"G\"\n##########################################################################\n\nnetworkAfterRemoveNodesRetData <- setClass(\n # Set the name for the class\n \"classNetAfterNodeRevData\",\n \n # Define the slots\n slots = c(\n net = \"matrix\",\n sel = \"vector\",\n rmv = \"vector\"\n ),\n \n # Set the default values for the slots. (optional)\n prototype=list(\n net = matrix(c(1:4),nrow=2,ncol=2,dimnames = list(c(\"A\",\"B\"),c(\"A\",\"B\"))),\n sel = c(\"A\"),\n rmv = c(\"A\")\n ),\n \n # Make a function that can test to see if the data is consistent.\n # This is not called if you have an initialize function defined!\n validity=function(object)\n {\n if((length(object@net) < 1) || (length(object@sel) < 1) || (length(object@rmv) < 1)) {\n return(\"Either one of net, selected or removed is not empty.\")\n }\n return(TRUE)\n }\n)\n\nnetworkAfterRemoveNodes <- function(originNetwork, selectedNodes, isDirected) {\n \n # continuously reconstruct the network\n net <- originNetwork\n \n # construct mask network\n maskOperated <- originNetwork\n \n # selected items\n selected <- selectedNodes\n \n # initial flag\n continueFlag = 1\n \n while(continueFlag == 1) {\n \n # initial mask matrix\n maskOperated[,] <- 0\n \n # drug would cause edge missing\n maskOperated[selected,] <- 1\n if(! isDirected) {\n maskOperated[,selected] <- 1\n }\n \n left <- matrix(\n bitwAnd(net,maskOperated),\n nrow=nrow(net),\n ncol=ncol(net),\n dimnames = list(\n rownames(net),\n colnames(net)\n )\n )\n \n fetNew <- which(left[,] == 1)\n sourceName <- rownames(net)\n itemName <- colnames(net)\n newSelect <- selected\n \n # check whether new node is found\n for(item in fetNew) {\n # r default is column-based, not row-based\n sourceNode <- sourceName[item %% nrow(net)]\n checkNode <- itemName[ceiling(item / nrow(net))]\n \n if(length(which(net[,checkNode] == 1)) > 1) {\n # there are others existing source\n # origin Network must be modified to remove the edge singlely\n # but the node does not be removed\n net[sourceNode,checkNode] <- 0\n next\n }\n \n # no matter whether node is removed, edge must be removed\n net[sourceNode,checkNode] <- 0\n\n # there are no other source, this node should be added for removing\n if(checkNode %in% newSelect) {\n next\n } else {\n # add new selected nodes\n newSelect <- c(newSelect,checkNode)\n }\n\n }\n \n if(length(newSelect) != length(selected)) {\n # new nodes are added\n selected <- newSelect\n } else {\n # not found new nodes\n continueFlag <- 0\n } \n \n #print(newSelect) \n }\n \n # restore the network\n mask <- originNetwork\n mask[,] <- 1\n mask[selected,] <- 0\n # if the destination node is removed\n # the edge between the source and the destination is also removed\n mask[,selected] <- 0\n leftNet <- matrix(\n bitwAnd(originNetwork,mask),\n nrow=nrow(originNetwork),\n ncol=ncol(originNetwork),\n dimnames = list(\n rownames(originNetwork),\n colnames(originNetwork)\n )\n )\n\n return(networkAfterRemoveNodesRetData(net=leftNet,sel=selectedNodes,rmv=selected))\n}\n", "meta": {"hexsha": "5ba0ddc4a68f96386783eea2486eb3959143da5d", "size": 4952, "ext": "r", "lang": "R", "max_stars_repo_path": "r/network.r", "max_stars_repo_name": "jiankaiwang/seed", "max_stars_repo_head_hexsha": "b4c1438267a604503819983ef56d52567df2a5ff", "max_stars_repo_licenses": ["MIT"], "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/network.r", "max_issues_repo_name": "jiankaiwang/seed", "max_issues_repo_head_hexsha": "b4c1438267a604503819983ef56d52567df2a5ff", "max_issues_repo_licenses": ["MIT"], "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/network.r", "max_forks_repo_name": "jiankaiwang/seed", "max_forks_repo_head_hexsha": "b4c1438267a604503819983ef56d52567df2a5ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-02T11:02:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-02T11:02:58.000Z", "avg_line_length": 26.7675675676, "max_line_length": 122, "alphanum_fraction": 0.6039983845, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6136152409066878}} {"text": "#testing calculating DIC from deviance scores vs. dic.samples()\n#clear environment, load packages\nrm(list=ls())\nlibrary(runjags)\n\n#generate a linear relatioship\nset.seed(1234)\nn <- 100\nx <- rnorm(n)\ny <- x + rnorm(n)\n\n#make JAGS data object\njags.data <- list(n = n, x = x, y = y)\n\n#write JAGS model\njags.model = \"\nmodel {\n #parameter priors\n m ~ dnorm(0, 1E-3)\n tau <- pow(sigma, -2)\n sigma ~ dunif(0, 100)\n \n #model\n for(i in 1:n){\n y[i] ~ dnorm(y.hat[i], tau)\n y.hat[i] <- x[i]*m\n }\n} #end model loop.\n\"\n\n#model for running with fixed parameter values.\nfix.model = \"\nmodel {\n #model\n for(i in 1:n){\n y[i] ~ dnorm(y.hat[i], tau)\n y.hat[i] <- x[i]*m\n }\n} #end model loop.\n\"\n\njags.out <- run.jags(model = jags.model,\n data = jags.data,\n n.chains = 3,\n adapt = 100,\n burnin = 100,\n sample = 1000,\n monitor = c('m','deviance','tau'))\njags.sum <- summary(jags.out)\n\n#grab mean deiviance and parameter means.\njags.deviance.mu <- jags.sum[2,4]\n m <- jags.sum[1,4]\n tau <- jags.sum[3,4]\n\n#new jags data\njags.data <- list(y=y, x=x, n=n, m=m, tau = tau)\n\n#get pD which is deviance at mean parameter values.\npD.out <- run.jags(model = fix.model,\n data = jags.data,\n n.chains = 3,\n adapt = 100,\n burnin = 100,\n sample = 1000,\n monitor = c('deviance'))\npD.sum <- summary(pD.out)\npD <- pD.sum[1,3]\n\n#Calculate DIC.\ndic_A <- 2*jags.deviance.mu - pD\n\n#get deviance using dic.samples\ndic_B <- extract(jags.out,'DIC')\n\n#compare calculated DIC scores.\ndic_A #deviance calculated by rerunning model with parameters set to their mean values.\ndic_B #deviance calculated from dic.samples()", "meta": {"hexsha": "5f1b92f4cf64782f45bbc308334ae79a90d37115", "size": 1857, "ext": "r", "lang": "R", "max_stars_repo_path": "testing_development/dic_comparison/dic.samples_vs._hand.calc_dic.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing_development/dic_comparison/dic.samples_vs._hand.calc_dic.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "testing_development/dic_comparison/dic.samples_vs._hand.calc_dic.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 23.8076923077, "max_line_length": 87, "alphanum_fraction": 0.5519655358, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6136152276513931}} {"text": "wtd.t.test <- function(x, y=0, weight=NULL, weighty=NULL, samedata=TRUE){\n if(is.null(weight)){\n weight <- rep(1, length(x))\n }\n if(length(y)!=length(x) & length(y)>1){\n samedata <- FALSE\n warning(\"Treating data for x and y separately\")\n if(is.null(weighty)){\n warning(\"y has no weights\")\n }\n }\n if(is.null(weighty) & samedata==TRUE){\n weighty <- weight\n }\n if(is.null(weighty) & samedata==FALSE){\n weighty <- rep(1, length(y))\n }\n require(Hmisc)\n n <- sum(!is.na(x))\n mx <- wtd.mean(x, weight, na.rm=TRUE)\n vx <- wtd.var(x, weight, na.rm=TRUE)\n if(length(y)==1){\n dif <- mx-y\n sx <- sqrt(vx)\n se <- sx/sqrt(n)\n t <- (mx-y)/se\n df <- n-1\n p.value <- (1-pt(abs(t), df))*2\n coef <- c(t, df, p.value)\n out2 <- c(dif, mx, y, se)\n names(coef) <- c(\"t.value\", \"df\", \"p.value\")\n names(out2) <- c(\"Difference\", \"Mean\", \"Alternative\", \"Std. Err\")\n out <- list(\"One Sample Weighted T-Test\", coef, out2)\n names(out) <- c(\"test\", \"coefficients\", \"additional\")\n }\n if(length(y)>1){\n n2 <- sum(!is.na(y))\n my <- wtd.mean(y, weighty, na.rm=TRUE)\n vy <- wtd.var(y, weighty, na.rm=TRUE)\n dif <- mx-my\n sxy <- sqrt((vx/n)+(vy/n2))\n df <- (((vx/n)+(vy/n2))^2)/((((vx/n)^2)/(n-1))+((vy/n2)^2/(n2-1)))\n t <- (mx-my)/sxy\n p.value <- (1-pt(abs(t), df))*2\n coef <- c(t, df, p.value)\n out2 <- c(dif, mx, my, sxy)\n names(coef) <- c(\"t.value\", \"df\", \"p.value\")\n names(out2) <- c(\"Difference\", \"Mean.x\", \"Mean.y\", \"Std. Err\")\n out <- list(\"Two Sample Weighted T-Test (Welch)\", coef, out2)\n names(out) <- c(\"test\", \"coefficients\", \"additional\")\n }\n out\n}\n", "meta": {"hexsha": "cc78c857fe6dac5aaa6034978b1ca72d3e74260a", "size": 1649, "ext": "r", "lang": "R", "max_stars_repo_path": "functions/weights_071/wtd.t.test.r", "max_stars_repo_name": "shui5/SpecVis", "max_stars_repo_head_hexsha": "724f9b68b85948c2bffccb86422bed3aa895ad90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T09:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:20:59.000Z", "max_issues_repo_path": "functions/weights_071/wtd.t.test.r", "max_issues_repo_name": "shui5/SpecVis", "max_issues_repo_head_hexsha": "724f9b68b85948c2bffccb86422bed3aa895ad90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/weights_071/wtd.t.test.r", "max_forks_repo_name": "shui5/SpecVis", "max_forks_repo_head_hexsha": "724f9b68b85948c2bffccb86422bed3aa895ad90", "max_forks_repo_licenses": ["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.537037037, "max_line_length": 73, "alphanum_fraction": 0.5312310491, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6135795295410956}} {"text": "# 3.2. land use regression\nmod.min <- lm(pm25 ~ 1, data=mon.data)\nmod.full <- lm(pm25 ~ long + lat + log10.m.to.a1 + log10.m.to.a2 + log10.m.to.a3\n + log10.m.to.road + km.to.coast + s2000.pop.div.10000, data=mon.data)\n\nstep(mod.min, direction=\"both\", scope=list(lower = ~1, upper = mod.full), test=\"F\")\n\n# output of step has the coefficients. Can use that to get the list??\n\nmod <- lm(pm25 ~ km.to.coast + log10.m.to.a1 + log10.m.to.a2 + lat, data=mon.data)\n\n# 3.2.1. leave-one-out cross-validation\nfor(i in 1:nrow(mon.data)){\n train <- mon.data[-i,]\n test <- mon.data[i,]\n train.lm <- lm(pm25 ~ km.to.coast + log10.m.to.a1 + log10.m.to.a2 + lat, data=train)\n X <- cbind(1,matrix(unlist(test[,names(train.lm$model)[-1]]),nrow=1))\n pred.1 <- X %*% train.lm$coef\n if(i==1) pred <- pred.1 else pred <- c(pred,pred.1)\n}\n\nmse.lur <- mean( (mon.data$pm25 - pred)^2 )\nr2.lur <- 1 - mse.lur/var(mon.data$pm25)\nmse.lur\nr2.lur\n", "meta": {"hexsha": "f1a9f69193accbce4d33f667d922883db4ade2f8", "size": 940, "ext": "r", "lang": "R", "max_stars_repo_path": "stepwise and cvLS.r", "max_stars_repo_name": "liannesheppard/envh556", "max_stars_repo_head_hexsha": "0be4522b32ca9f96b2127638fdddefbe737336f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stepwise and cvLS.r", "max_issues_repo_name": "liannesheppard/envh556", "max_issues_repo_head_hexsha": "0be4522b32ca9f96b2127638fdddefbe737336f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stepwise and cvLS.r", "max_forks_repo_name": "liannesheppard/envh556", "max_forks_repo_head_hexsha": "0be4522b32ca9f96b2127638fdddefbe737336f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-21T19:33:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T19:33:57.000Z", "avg_line_length": 36.1538461538, "max_line_length": 86, "alphanum_fraction": 0.620212766, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6135795130427094}} {"text": "###################################################################################\n# R-script submitted as Supplementary Information to Seebens et al. (2016) No \n# saturation in the accumulation of alien species worldwide. Nature Communications ....\n#\n# The script is called by the file Rcode_Seebens-etal_InvasionModel_PropPress_MAIN.r\n# which reproduces the modelling results shown in Supplementary Fig. 5 of the article.\n#\n# This file simulates the model scenario: linear increase.\n#\n# The model implemented here describes the temporal development of the \n# accumulation of alien species on an island, which were randomly depicted\n# from an arbitrary mainland community. The probability of depicting a species\n# may change during the simulation depending on the scenario to account for increases\n# in propagule and colonisation pressures due to e.g. increases of trade volumes.\n# For further details, consult the article.\n# Five scenarios were simulated assuming different increases in the rate of \n# introduction (constant, linear or exponential increase, related to import \n# volumes or the number of founded botanic gardens).\n#\n# The code is free of use as long as the article is properly cited.\n#\n# Author of code: Hanno Seebens, Frankfurt, Germany\n# 25. August, 2016\n###################################################################################\n\n\n##### Defintion of objects/variables for simulation ###########################################################\n\nn_spec <- 50000 # number of species of the mainland community\nt_max <- 202000 # max simulation time\n\nn_bins <- 1000 # number of steps abundances of the mainland community are stored\n\nadd <- \"lininc\" # type of increase in propagule pressure, required for output file; here: linear increase\n\n## Define temporal development of propagule pressure ###########################################################\nm <- seq(0,mean(m)*2,length.out=t_max) # linear increase\ntimeaxis <- seq(1,t_max/1000,length.out=t_max) # for plotting\n\n\n# define basic characteristics of community size #############################################################\nmlog <- seq(-3,1,length.out=5) # size of communities (defined as mean of log-normal distribution) for different model scenarios\nsdlog <- 300 # standard deviation of log-normal distribution, constant\nrun_tot <- length(mlog)*length(sdlog) # number of model scenarios\n\n\n######### SIMULATION #########################################################################################\n\nisland <- matrix(0,nr=t_max,nc=run_tot+1) # results file\nisland[,1] <- 1:t_max # include time axis in first column \nall_main <- matrix(0,nr=n_bins,nc=run_tot) # store communities (abundances and species)\nx <- 0 # counter\nfor (j in 1:length(mlog)){# loop through model scenarios depending on the number of defined means\n for (i in 1:length(sdlog)){# loop through model scenarios depending on the number of defined standard deviations\n x <- x + 1 # increase counter\n \n ## define mainland community ###############################################\n specabund <- dlnorm((seq(0.1,2,length.out=n_bins)),meanlog=mlog[j],sdlog=1)*10000\n axis1 <- seq(10,10000,length.out=n_bins) # steps of storing individuals per species (for plotting)\n specabund <- ceiling(specabund) # avoid decimals in abundances\n specabund <- round(specabund/sum(specabund)*n_spec) # rescale numbers\n \n tot_spec <- sum(specabund) # number of species\n abundances <- rep(axis1,round(specabund)) # set abundances\n tot_abund <- sum(abundances) # number of individuals\n all_main[,x] <- specabund # store community\n print(tot_spec)\n print(tot_abund)\n \n #### simulation ############################################################################\n for (t in 1:t_max){ # loop through time steps\n \n ## select individual from mainland community and transfer it on the island\n if (runif(1)= 13 & teens$age < 20,\r\n teens$age, NA)\r\n\r\nsummary(teens$age)\r\n\r\n# reassign missing gender values to \"unknown\"\r\nteens$female <- ifelse(teens$gender == \"F\" &\r\n !is.na(teens$gender), 1, 0)\r\nteens$no_gender <- ifelse(is.na(teens$gender), 1, 0)\r\n\r\n# check our recoding work\r\ntable(teens$gender, useNA = \"ifany\")\r\ntable(teens$female, useNA = \"ifany\")\r\ntable(teens$no_gender, useNA = \"ifany\")\r\n\r\n# finding the mean age by cohort\r\nmean(teens$age) # doesn't work\r\nmean(teens$age, na.rm = TRUE) \r\n\r\n# age by cohort\r\naggregate(data = teens, age ~ gradyear, mean, na.rm = TRUE)\r\n\r\n# calculating the expected age for each person\r\nave_age <- ave(teens$age, teens$gradyear,\r\n FUN = function(x) mean(x, na.rm = TRUE))\r\n\r\n\r\nteens$age <- ifelse(is.na(teens$age), ave_age, teens$age)\r\n\r\n# check the summary results to ensure missing values are eliminated\r\nsummary(teens$age)\r\n\r\n## Step 3: Training a model on the data ----\r\ninterests <- teens[5:40]\r\ninterests_z <- as.data.frame(lapply(interests, scale))\r\n\r\nteen_clusters <- kmeans(interests_z, 5)\r\n\r\n## Step 4: Evaluating model performance ----\r\n# look at the size of the clusters\r\nteen_clusters$size\r\n\r\n# look at the cluster centers\r\nteen_clusters$centers\r\n\r\n## Step 5: Improving model performance ----\r\n# apply the cluster IDs to the original data frame\r\nteens$cluster <- teen_clusters$cluster\r\n\r\n# look at the first five records\r\nteens[1:5, c(\"cluster\", \"gender\", \"age\", \"friends\")]\r\n\r\n# mean age by cluster\r\naggregate(data = teens, age ~ cluster, mean)\r\n\r\n# proportion of females by cluster\r\naggregate(data = teens, female ~ cluster, mean)\r\n\r\n# mean number of friends by cluster\r\naggregate(data = teens, friends ~ cluster, mean)\r\n", "meta": {"hexsha": "9d6bffde01a6fd118f7c2d5d28bffb0c654b55b5", "size": 2161, "ext": "r", "lang": "R", "max_stars_repo_path": "Training/MachineLearning/code/chapter 9/2148_09.r", "max_stars_repo_name": "davidmeza1/NASADatanauts", "max_stars_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2017-10-05T16:45:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-25T16:23:31.000Z", "max_issues_repo_path": "Training/MachineLearning/code/chapter 9/2148_09.r", "max_issues_repo_name": "davidmeza1/NASADatanauts", "max_issues_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Training/MachineLearning/code/chapter 9/2148_09.r", "max_forks_repo_name": "davidmeza1/NASADatanauts", "max_forks_repo_head_hexsha": "084ce551d47317bb9513dae1e473ba91ddfdee7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-04-27T11:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-05T19:22:24.000Z", "avg_line_length": 28.4342105263, "max_line_length": 68, "alphanum_fraction": 0.6649699213, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6134609321527055}} {"text": "\n## Library loading\nlibrary(reshape2); \nlibrary(vegan); \nlibrary(dplyr)\nlibrary(ade4); \nlibrary(plotly)\nlibrary(compositions); \nlibrary(pracma); \nlibrary(DESeq2); \nlibrary(fpc); \nlibrary(tidyverse)\nlibrary(purrr)\nlibrary(cluster)\nlibrary(RColorBrewer)\nlibrary(ape)\n\n# Migrate to location of repository and downloaded test data:\n# setwd($PATH/analyzing_microbiome_timeseries/module1_clustering/)\nload(\"TESTDATA_DIEL18S.RData\",verbose=T)\n\n# To address ecological questions, you may need to perform some quality \n# control on your OTU data. (1) Below, first global singletons are removed.\n# This is unwanted noise in the form of OTUs which only have one sequence \n# in the entired dataset. \n# (2) Then, any OTUs assigned a Metazoan taxonomic identity are removed. This\n# is because the methods used to generate this 18S data are not suitable\n# to capture the metazoan community.\n# (3) Finally, while we are mainly working with OTU.IDs throughout this tutorial\n# we want to eventually add back in the taxonomic identities. So we make a taxonomy\n# key dataframe ('tax_key')\n#\n# (1) Remove global singletons (where a single OTU appears with only 1 sequence in the entire dataset)\nrowsum<-apply(test_data[2:20],1,sum) # sum numerics in OTU table by row\ncounts.no1 = test_data[ rowsum>1, ] # remove rows that sum to 1 or less\ndim(test_data)[1] - dim(counts.no1)[1] # report total number of singletons removed\n#\n# (2) Filter out OTUs which belong to the metazoa:\ncounts.filtered<-counts.no1[-(which(counts.no1$Level3 %in% \"Metazoa\")),] # Remove from counts\ndim(counts.no1);dim(counts.filtered) # Test data should be left with 1984 total OTUs\n#\n# (3) Create taxonomy key:\nnames(counts.filtered)\nseq_counts<-counts.filtered[1:20]\ntax_key<-counts.filtered[c(1,21:31)]; head(tax_key[1:2,])\n# Modify seq_counts data frame so row.names = OTU.ID and all values are numeric\nrow.names(seq_counts)<-seq_counts$OTU.ID\nseq_counts$OTU.ID<-NULL; head(seq_counts[1:2,])\n\n# Because these data are compositional, they are on a simplex. \n# The data being on a simplex means, if we know the abundances of all of the OTUs except for one, we still have the \n# same amount of information as if we knew all of the OTUs. \n# Evidence:\n# Estimate covariance matrix for OTUs\ncovariance_matrix<-as.matrix(seq_counts)%*%t(seq_counts)\n# Evaluate determinant of covariance matrix\ncov_determinant<-det(covariance_matrix)\ncov_determinant #0\n# The determinant of the covariance matrix (what we just calculated) is equivalent to the product of the\n# proportion of variance explained by every PCA axis. If the determinant is 0, that means there is an axis which\n# explains 0 variance that we can't separate from the other axes. The data need to be transformed to be suitable\n# for PCA. \n\n## Another approach to PCA ordination w/Compositional Data: Log-Ratio Transformations\n# Log-ratio\nlog_rats<-data.frame(compositions::ilr(t(seq_counts)))\n# These are complicated to interpret however because you move from D simplex to D-1 euclidean\n# But using these we can see we are now in invertible covariance regime\n\n## Checking the difference the log-ratio made on the data characteristics\nnew_covdet<-det(as.matrix(log_rats)%*%t(log_rats))\ncov_determinant #Original Count Data\nnew_covdet # After doing a log ratio, you see that none of the axes are equal to 0\n\n# AND change command so its the same.\nlograt_pca<-prcomp(log_rats)\n# Look at this\nlograt_variances<-lograt_pca$sdev^2/sum(lograt_pca$sdev^2)\nbarplot(lograt_variances,\n main='Log-Ratio PCA Screeplot',\n xlab='PC Axis',\n ylab='% Variance',\n col=c(rep('black',1),rep('grey',18)),\n cex.names=1.5,cex.axis=1.5,cex.lab=1.5,cex.main=1.5)\nlegend('topright',fill=c('black','grey'),c('Should Present','??? Judgment Call'))\n\n## We conclude a more faithful representation is to plot this ordination in 2D because the 3rd and 4th axes appear\n## very similar, and we can't construct a 4D plot\npca_lograt_frame<-data.frame(lograt_pca$x,\n time_of_day=gsub('^.*_','',rownames(lograt_pca$x)))\nggplot(pca_lograt_frame)+\n geom_point(aes(x=PC1,y=PC2,col=time_of_day))+\n ylab(paste0('PC2 ',round(lograt_variances[2]*100,2),'%'))+\n xlab(paste0('PC1 ',round(lograt_variances[1]*100,2),'%'))+\n scale_color_brewer(palette='Set1',name='Time of Day')+\n ggtitle('Log-Ratio PCA Ordination')+\n coord_fixed(ratio=lograt_variances[2]/lograt_variances[1])+\n theme_bw()\n\n# So let's start by looking at PCoA. PCoA is doing a PCA on a distance matrix constructed from the data. \n# We then need a distance matrix. \n# Different distance metrics emphasize separate attributes/factors in microbial community comparison\n# For instance, if we want to prioritize differences in presence/absence between samples\njac_dmat<-vegdist(t(seq_counts),method=\"jaccard\") # p/a example\npcoa_jac<-ape::pcoa(jac_dmat) #perform PCoA\n# Now we need to inspect how the PCoA turned out. We look at a Screeplot for this.\n# The screeplot shows the amount of variance explained by each axis\nsamp_no<-dim(seq_counts)[2]\njac_variances<-pcoa_jac$values$Relative_eig\npar(mar=c(5,6,4,1)+.1)\nbarplot(jac_variances,\n xlab='Principal Coordinate Axis',\n ylab='% Variance',\n col=c(rep('black',2),'darkgrey',rep('lightgrey',16)),\n cex.names=2,cex.axis=2,cex.lab=2,cex.main=1,\n names.arg=as.character(1:18))\nlegend('topright',fill=c('black','darkgrey','lightgrey'),c('Should Present','Judgment Call','Unnecessary to Present'),cex=2)\n# How to read this plot: Before we plot the actual ordination, we need to decide which axes to present.\n# We need to select as few axes as possible (so we can visualize) which capture large amounts of variance.\n# In this example, we see the first axis captures most of the variance, so we definitely will show that one.\n# Then the next two axes show less, but a similar amount, and the remaining all show way less in comparison. \n# Therefore, we can exclude everything after the 3rd axis. Because axes 2 and 3 capture similar amounts of variance,\n# if we show one, we need to show the other one to be faithful to the data.\n\n\n# Performing the log-ratio transformation makes the data all occupy a similar dynamic range, so we can use\n# magnitude-sensitive distances like euclidean distance\n\neuc_dmat<-dist(log_rats) \n\n\n## Conduct ordination w/distance matrix\npcoa_euc<-ape::pcoa(euc_dmat)\n#euc_variances<-pcoa_euc$sdev^2/sum(pcoa_euc$sdev^2)\neuc_variances<-pcoa_euc$values$Relative_eig\npar(mar=c(5,6,4,1)+.1)\nbarplot(euc_variances,\n xlab='Principal Coordinate Axis',\n ylab='% Variance',\n col=c(rep('black',2),rep('darkgrey',2),rep('lightgrey',17)),\n cex.names=2,cex.axis=2,cex.lab=2,cex.main=1,\n names.arg=as.character(1:18))\nlegend('topright',fill=c('black','darkgrey','lightgrey'),c('Should Present','Judgment Call','Unnecessary'),cex=2)\n#\n# By trying 2 different metrics, we see a differences in ordination output.\n# For Jaccard distance, we see we need 3 axes to present the ordination. Using euclidean distance,\n# because of the complex covariance structure of the relative compositions, the data do not easily\n# ordinate into 2 or 3 dimensions.\n\n\n# How dissimilar are my samples with respect to diversity?\n## P/A is recommended when asking questions about the ENTIRE community\n# Does the active microbial community change depending on time of day?\n# To emphasize changes in presence/absence, we elect to use Jaccard distance for ordination.\n# Our ordination indicates the data are most suitably summarized\n# with 3 dimensions. \n#pcoa_jac_frame<-data.frame(pcoa_jac$x,\n# time_of_day=gsub('^.*_','',rownames(pcoa_jac$x)))\npcoa_jac_frame<-data.frame(pcoa_jac$vectors,time_of_day=gsub('^.*_','',rownames(pcoa_jac$vectors)))\neigenvalues<-round(jac_variances,4)*100\nplot_ly(pcoa_jac_frame,type='scatter3d',mode='markers',\n x=~Axis.2,y=~Axis.3,z=~Axis.1,colors=~brewer.pal(6,'Set1'),color=~time_of_day)%>%\n layout(font=list(size=18),\n #title='PCoA Jaccard Distance',\n scene=list(xaxis=list(title=paste0('Co 2 ',eigenvalues[2],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n yaxis=list(title=paste0('Co 3 ',eigenvalues[3],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n zaxis=list(title=paste0('Co 1 ',eigenvalues[1],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n aspectratio = list(x=3*eigenvalues[2]/eigenvalues[1])), y=3*eigenvalues[3]/eigenvalues[1], z=3)\n\n## To compare with the euclidean distance ordination representing differences in relative composition\n#pcoa_euc_frame<-data.frame(pcoa_euc$x,\n# time_of_day=gsub('^.*_','',rownames(pcoa_euc$x)))\npcoa_euc_frame<-data.frame(pcoa_euc$vectors,time_of_day=gsub('^.*_','',rownames(pcoa_euc$vectors)))\neuc_eigenvalues<-round(euc_variances,4)*100\nplot_ly(pcoa_euc_frame,type='scatter3d',mode='markers',\n x=~Axis.3,y=~Axis.2,z=~Axis.1,colors=~brewer.pal(6,'Set1'),color=~time_of_day)%>%\n layout(font=list(size=18),\n #title='PCoA Euclidean Distance',\n scene=list(xaxis=list(title=paste0('Co 3 ',euc_eigenvalues[3],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n yaxis=list(title=paste0('Co 2 ',euc_eigenvalues[2],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n zaxis=list(title=paste0('Co 1 ',euc_eigenvalues[1],'%'),\n showticklabels=FALSE,zerolinecolor='black'),\n aspectratio = list(x=3*euc_eigenvalues[3]/euc_eigenvalues[1], \n y=3*euc_eigenvalues[2]/euc_eigenvalues[1], \n z=3)))\n## Further note: If your ordination has data which align in a 'T' or '+' shape perpendicular to the axes\n## this is often diagnostic of covariance attributed to the higher dimensions which are not plotted\n\n# To corroborate the 3-D plot, use a simple average \n## hierarchical clustering and plot the dendrogram.\n## Some of the same pattern emerge, but it is not as \n## clear as the 3-D representation.\ncluster_ex<-hclust(vegdist(t(seq_counts),method='jaccard'),method=\"complete\") #Using Jaccard distance so apples to apples\nplot(cluster_ex,main='Jaccard Hierarchical Agglomerative Clustering',xlab='',sub='')\n\n# Although our statistical ordinations appear to require at least 3 dimensions to communicate the data.\n# However, we don't always have the budget for a 3D plot. So we may want to impose the condition on an ordination\n# technique that the answer MUST go in 2D. We turn to NMDS here. \n#\nset.seed(071510) # setting random seed to assure NMDS comes out the same every time\n## So we can compare the relative composition based distance metric to the presence/absence based distance metric\neuc_nmds<-metaMDS(euc_dmat,k=2,autotransform=FALSE)\njac_nmds<-metaMDS(jac_dmat,k=2,autotransform=FALSE)\n\n# Take a look at stress - overall this value is not extremely informative, but know that the\n# closer stress is to 1 the less representative of your actual data the NMDS is\neuc_nmds$stress #Stress ~0.075\njac_nmds$stress #Stress ~0.073 So the Jaccard NMDS is a ***slightly*** more parsimonious ordination.\n\n# Additionally, the axes for NMDS are totally arbitrary, so axis scaling does not matter\n# and data can be rotated/reflected about axes and the NMDS is still the same\neuc_frame<-data.frame(euc_nmds$points,\n time_of_day=gsub('^.*_','',rownames(log_rats)))\njac_frame<-data.frame(jac_nmds$points,\n time_of_day=gsub('^.*_','',rownames(log_rats)))\n## Plotting euclidean distance NMDS\nggplot(euc_frame,aes(x=MDS1,y=MDS2,col=time_of_day))+\n geom_point(size=2)+\n scale_color_brewer(palette='Set1',name='Time of Day')+\n theme_bw()+ggtitle('Euclidean Distance NMDS')\n## Plotting Jaccard distance NMDS\nggplot(jac_frame,aes(x=MDS1,y=MDS2,col=time_of_day))+\n geom_point(size=2)+\n scale_color_brewer(palette='Set1',name='Time of Day')+\n theme_bw()+ggtitle('Jaccard Distance NMDS')\n## For paper figures\neuc_fig<-ggplot(euc_frame,aes(x=MDS1,y=MDS2,col=time_of_day))+\n geom_point(size=10)+\n scale_color_brewer(palette='Set1',name='Time of Day')+\n theme_bw()+theme(legend.position='none',text=element_text(size=24))+\nxlab('NMDS 1')+ylab('NMDS 2')\njac_fig<-ggplot(jac_frame,aes(x=MDS1,y=MDS2,col=time_of_day))+\n geom_point(size=10)+\n scale_color_brewer(palette='Set1',name='Time of Day')+\n theme_bw()+theme(legend.position='none',text=element_text(size=24))+\nxlab('NMDS1')+ylab('NMDS2')\neuc_fig\njac_fig\n\n## Before we can cluster temporal dynamics, we must make sure species are intercomparable. \n## We need to perform normalization steps to ensure intercomparability between species.\n## Put another way, the count data are heteroskedastic -- \n## the mean is correlated with the variance.\nwithin_seq_means<-apply(t(seq_counts),2,mean)\nwithin_seq_vars<-apply(t(seq_counts),2,var)\nplot(within_seq_means,within_seq_vars,log='xy',\n main='Heteroskedastic Data',\n xlab='Mean # Counts',\n ylab='Var # Counts')\n# Variance (in the amount of times an OTU shows up) is correlated to average count. \n# This attribute (common to count data) violates the assumption of constant variance in errors\n# which is necessary for standard linear modeling. To use z-scores for comparisons and to detrend our timeseries \n#(a kind of linear model), we have to deal with this.\n\n## We stabilize the variances so that they are no longer correlated to the species abundances.\ntransformed_counts<-DESeq2::varianceStabilizingTransformation(as.matrix(seq_counts))\n\n## Check to see how the transformation did\nwithin_trans_means<-apply(transformed_counts,1,mean)\nwithin_trans_vars<-apply(transformed_counts,1,var)\n# Plot:\nplot(within_trans_means,within_trans_vars)\n# See how now most of the variances are the same between otus? \n# This means the data are more intercomparable using a z-score transformation + detrending\n\n# Since the goal is to identify repeating day/night patterns, we need to remove trends we are not considering,\n# i.e., linear trends\n#?pracma::detrend() for more information\ntransformed_detrended<-apply(transformed_counts,1,pracma::detrend)\n# Now we rescale so numbers are again intercomparable and now overdispersion has been\n# dealt with\ntrans_dt_scaled<-apply(transformed_detrended,2,scale)\n## We lost rownames so tack those back on\nrownames(trans_dt_scaled)<-colnames(transformed_counts)\n#\n## Comparing the distribution of the data along every step of the pipeline -- notice how by the time we get to the \n## z-scores we're looking more like a standard normal\nhist(transformed_counts,\n main='VST Sequence Count Observations',\n xlab='# Total Observations',\n ylab='Frequency')\nhist(transformed_detrended,\n main='VST+Detrended Data',\n xlab='Total Observations Accounting for Linear Trends',\n ylab='Frequency')\nhist(trans_dt_scaled,\n main='VST+Detrended+Scaled Data (Z-scores)',\n xlab='Expression Level Relative to per-OTU Avg',\n ylab='Frequency')\n\n# Now we're ready to generate a distance matrix for clustering\n# Recall what we previously learned about different distance metrics.\n# We use euclidean distance below:\ntemporal_dmat<-dist(t(trans_dt_scaled))\nn_clusts<-2:20 # This sets the range of # clusters we divide the data into\n# First, the classic hierarchical agglomerative clustering\nhc_full_cluster<-hclust(temporal_dmat)\nhc_clusts<-lapply(n_clusts,function(x) cutree(hc_full_cluster,x))\n## Now we try k-medoids, also a very popular clustering method\n## This particular implementation is not optimized for speed, so this may take a minute or so\nkmed_clusts<-lapply(n_clusts, function(x) cluster::pam(temporal_dmat,k=x))\n\n## Comparing cluster outcomes\nhc_stats<-lapply(hc_clusts,function(x) fpc::cluster.stats(temporal_dmat,\n clustering=x))\nkmed_stats<-lapply(kmed_clusts, function(x) fpc::cluster.stats(temporal_dmat,\n clustering=x$clustering))\n\n## We write a helper function to be less redundant\nripping_stats<-function(list,func){\n ## Essentially all this function does is implements a function (func) on a list\n ## and coerces the output to a column vector (this will be handy when we want to make a data frame)\n output<-do.call(rbind,lapply(list,func))\n return(output)\n}\nfunc_list<-rep(list(function(x) x$cluster.number,\n function(x) x$within.cluster.ss,\n function(x) x$avg.silwidth,\n function(x) x$ch),2)\nstats_list<-rep(list(hc_stats,kmed_stats),each=4)\ncollected_stats<-purrr::map2(stats_list,func_list,ripping_stats)\nnclusts<-rep(n_clusts,length(collected_stats))\nmethod<-rep(c('hc_agg','kmed'),each=length(n_clusts)*length(collected_stats)/2)\nind_name<-rep(c('n','ss','sil','ch'),each=length(n_clusts)) %>%\n rep(2)\n \n## Collecting outputs for plotting \nindex_frame<-data.frame(index=do.call(rbind,collected_stats),\n nc=nclusts,\n Method=method,\n ind=ind_name)\nindex_frame %>%\n filter(ind=='ss') %>%\n ggplot(aes(x=nc,y=index,col=Method)) +\n geom_point() +\n geom_line(aes(group=Method)) +\n ylab('Within Cluster Sum Square Error') +\n xlab('Number Clusters')+\n theme_bw()\n## Interpretation of plots: \n# As we add more clusters (yaxis), we want the sum square error to decrease\n# As we allow for more clusters, we are able to describe more of the variability in the data\n# so the sum square error decreases.\n## trade-off - it will always decrease when you add clusters, but we want to \n## add as fewer clusters as possible, hence in this example kmed > hc\n# for any given amount of clusters, kmed has less error. So we will continue using kmed approach. \n\n## Plotting out the calinski-harabasz indices for each clustering\n## We want this number to be high\nindex_frame %>%\n filter(ind=='ch') %>%\n ggplot(aes(x=nc,y=index,col=Method)) +\n geom_point() +\n geom_line(aes(group=Method)) +\n ylab('C-H Stat') +\n xlab('Number Clusters')+\ntheme_bw()\n\n## Silhouette profile: Looking at species variability w/in our 8 clusters\n## Extract silhouette profile for the clustering we select\nsilhouette_profile_kmed8<-cluster::silhouette(kmed_clusts[[7]])\n## Reformat for easier plotting\nsilhouette_frame<-data.frame(cluster=silhouette_profile_kmed8[,1],\n neighbor=silhouette_profile_kmed8[,2],\n dist=silhouette_profile_kmed8[,3],\n otu_id=rownames(silhouette_profile_kmed8))\n\n## Sorting by cluster and ranking by silhouette width\nnew_silframe<-silhouette_frame %>%\n arrange(dist) %>%\n group_by(cluster) %>%\n mutate(idno=1:n(),\n tot_num=n())\n\n## Plotting silhouette profile of OTUs for each cluster\nggplot(new_silframe,aes(x=idno,y=dist))+\n geom_bar(stat='identity') +\n coord_flip() +\n ggtitle('Silhouette Profiles for Individual Clusters') +\n facet_wrap(~cluster)\n\n## In order to interpret the silhouette profiles, we can compare the width (x-axis) and height (y-axis) of each\n## profile. For instance, comparing cluster #3 vs #8: Cluster 3 is much taller (has more species in it) compared to \n# cluster 8, but also is much broader (there are more species with intermediate values on the x-axis). This means\n# on the whole cluster 3 is less coherent than cluster 8. \n## Also keep an eye out for species w/negative silhouette distances -- this means that they have a nearby neighbor\n## who belongs in a different cluster and therefore may be only marginally similar to their cluster on the whole\n\n# What is the taxonomic composition of each of the 8 clusters?\n## To make ecological sense of the temporal clusters,\n## we can pull out a representative species and use their signal over time\n## to summarize the temporal trends across the whole cluster\nmedoid_otus<-kmed_clusts[[7]]$medoids\n## Extracting those time series\nmedoid_dynamics<-trans_dt_scaled[,medoid_otus]\n\n# Using the output from:\nhead(silhouette_frame)\n# We can re-build what the taxonomic composition of each \n## of these clusters is.\nrange(silhouette_frame$cluster) # n=8 clusters with test data\n\n# Join cluster information with taxonomic information\ncolnames(tax_key)[1]<-\"otu_id\"\ntax_bycluster<-left_join(silhouette_frame, tax_key, by=\"otu_id\") # Recall the taxonomy key we made from above?\nhead(tax_bycluster[1:2,])\n\n# Summarize taxa with cluster information\ntax_bycluster_sum<-tax_bycluster %>%\n group_by(cluster, Taxa) %>%\n summarise(richness = n()) %>% #Get richness information\n group_by(Taxa) %>%\n mutate(n_per_tax=sum(richness)) %>% #Figure out total number of OTUs assigned to each taxon\n as.data.frame\ntax_bycluster_sum$Taxa[which(tax_bycluster_sum$Taxa=='Opisthokonts')]<-'Opisthokont' # Cleaning this up\nhead(tax_bycluster_sum)\n\n# Plot cluster-to-cluster taxonomic differences\n## Values are equal to the total number of OTUs \n## belonging to each taxonomic group\n#\ntax_color<-c(\"#67000d\",\"#e31a1c\",\"#dd3497\",\"#fcbba1\",\"#fed976\",\"#fc8d59\",\"#a63603\",\"#addd8e\",\"#7f2704\",\"#238b45\",\"#a1d99b\",\"#081d58\",\"#1f78b4\",\"#a6cee3\",\"#8c6bb1\",\"#9e9ac8\",\"#984ea3\",\"#081d58\",\"#662506\",\"#ffffff\",\"#969696\",\"#525252\",\"#000000\")\n#\nggplot(tax_bycluster_sum, aes(x=cluster, y=richness, fill=Taxa))+\n geom_bar(color=\"black\", stat=\"identity\")+\n coord_flip()+\n scale_fill_brewer(palette='Set3')+\n theme_minimal()+\n scale_x_continuous(breaks=1:8,labels=as.character(1:8),name='Cluster #')+\n scale_y_continuous(name='# Species')+\ntheme(legend.position='bottom',text=element_text(size=18))+ ## Make the cluster #s happen\nguides(fill=guide_legend(nrow=3,byrow=TRUE))\n\n## Demonstrating medoid dynamics for each cluster\nmedoid_dyn_long<-as.data.frame(t(medoid_dynamics)) %>%\nmutate(otu_id=colnames(medoid_dynamics),\n clust_num=1:8) %>%\ngather(timepoint,z_score,'1_6PM':'19_6PM') %>%\nmutate(time_numeric=as.numeric(gsub('_.*$','',timepoint)),\n plotting_timepoint=paste('Day',ceiling(time_numeric/6),gsub('^.*_','',timepoint))) \n#\n## We're plotting the y axis as z-scores so that transcripts with different baseline levels are \n# more readily intercomparable. Read a z-score y-axis this like this:\n# 0 is the average transcript level\n# negative numbers are below-average numbers of transcripts\n# positive numbers are above-average levels of transcripts\n# 1 unit is 1 standard deviation away from the mean (So a value of 1 corresponds to mean+1sd, -1 is mean-1sd)\n\nggplot()+\ngeom_point(size=4,\n shape=21, \n color=\"white\", \n aes(fill=factor(clust_num),\n x=time_numeric,\n y=z_score),\n data=medoid_dyn_long)+\ngeom_line(data=medoid_dyn_long,\n aes(x=time_numeric,\n y=z_score,\n group=otu_id,\n col=factor(clust_num)),size=1.25,linetype=5)+\nfacet_wrap(~clust_num,ncol=2)+\nscale_color_brewer(palette='Set2',name='Cluster #')+\nscale_fill_brewer(palette='Set2',guide=FALSE)+\nscale_x_continuous(breaks=seq(1,19,by=6),labels=unique(medoid_dyn_long$plotting_timepoint)[c(1,7,13,19)])+\nscale_y_continuous(name='Z-score Expression',limits=c(-2,4.5))+\ntheme(axis.text.x=element_text(angle=90,hjust=0.5,size=18),\n panel.background=element_rect(fill='white'),\n panel.grid.major=element_line(color='gray'),\n axis.title.x=element_blank(),\n text=element_text(size=18))+\ngeom_rect(data=data.frame(ymin=rep(-2,4),\n ymax=rep(4.5,4),\n xmin=seq(1,19,by=6),\n xmax=c(seq(4,19,by=6),19)),\n aes(xmin=xmin,ymin=ymin,xmax=xmax,ymax=ymax),\n col='gray',\n alpha=0.25)\n", "meta": {"hexsha": "75c180d72fa338a10d87638f2b003b56d4b1679f", "size": 23697, "ext": "r", "lang": "R", "max_stars_repo_path": "module_clustering/clustering_tutorial.r", "max_stars_repo_name": "shu251/analyzing_microbiome_timeseries", "max_stars_repo_head_hexsha": "f8713f63b8f7ee316c24f3b24383345a210d7cbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-07T12:13:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T00:58:15.000Z", "max_issues_repo_path": "module_clustering/clustering_tutorial.r", "max_issues_repo_name": "shu251/analyzing_microbiome_timeseries", "max_issues_repo_head_hexsha": "f8713f63b8f7ee316c24f3b24383345a210d7cbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module_clustering/clustering_tutorial.r", "max_forks_repo_name": "shu251/analyzing_microbiome_timeseries", "max_forks_repo_head_hexsha": "f8713f63b8f7ee316c24f3b24383345a210d7cbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-07-22T16:49:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T19:52:51.000Z", "avg_line_length": 48.9607438017, "max_line_length": 243, "alphanum_fraction": 0.7219479259, "num_tokens": 6405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6134604115268946}} {"text": "\n#install.packages(\"nlrwr\")\n#install.packages(\"minpack.lm\")\n#install.packages(\"leaps\")\n#install.packages(\"mgcv\")\n\nlibrary(\"minpack.lm\")\nrequire(\"foreign\")\nrequire(\"data.table\")\nrequire(\"MASS\")\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Fitting a logistic function similar to that of Preston (1976) a/(1+exp(B+exp(lnC*GDP))\n# output: alpha, beta & C [model: alpha/(1+exp(beta + exp(ln(C)*dgp))) ], BIC and AIC\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nlogfnS<-function(gdp.pc,alpha,beta,C){\n alpha / (1 + exp( beta + exp(log(C) * gdp.pc )))\t\n }\n\n # Logistic fitting\nlog.fnS<-function(data){\n datos<-na.omit(data)\n # estimating starting values for the parameters. Assume alpha=1, then estimate logit(yvar)=beta+gamma^GDP\n yvar <- datos$yvar/(1.05 * max(datos$yvar)) # scale to within unit height\n datos$z <- log(yvar/(1 - yvar)) # logit transformation\n\t pars<- nls(z ~ beta+exp(log(C)*gdp.pc),\n data=datos,\n start=list(beta=1,C=1))\n nlsFormula <- \"yvar ~ logfnS(gdp.pc,alpha,beta,C)\"\n nlsInitial <- c(alpha=max(datos$yvar),coef(pars)[1],coef(pars)[2])\n mod1<-nlsLM(formula = nlsFormula,\n data=datos,\n start=nlsInitial,\n control=nls.lm.control(maxiter=1000))\n #,lower=c(30,-1000,-1000),upper=c(90,1000,1000))\n MSE.p <- mean(residuals(mod1)^2)\n return(data.frame(\n alpha=coef(mod1)[1],\n beta=coef(mod1)[2],\n C=coef(mod1)[3],\n alpha.se=summary(mod1)$coefficients[1,2],\n beta.se=summary(mod1)$coefficients[2,2],\n C.se=summary(mod1)$coefficients[3,2],\n MSE=MSE.p))\n}\n# foo<-datos[,c(\"gdp.pc\",\"year\",\"median\")];setnames(foo,colnames(foo),c(\"gdp.pc\",\"year\",\"yvar\"))\n# foo<-subset(foo,year>1950)\n#example: log.fnS(data=foo)\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Predicting values from a logistic function\n# pars: alpha,gamma,beta [model: alpha/(1+exp((dgp-gamma)*beta)) ]\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\npred.log.fnS<-function(pars,newX){\n\talpha<-pars[1]\n\tbeta<-pars[2]\n\tC<-pars[3]\n\tout<-unlist(apply(rbind(newX),2,FUN=function(x) alpha/(1 + exp(beta+exp(log(C)*x)))))\n return(out)\n}\n#example:\n# pred.log.fnS(pars=log.fnS(data=dat2),newX=quantile(dat2$gdp.pc,probs=seq(0,1,0.25),na.rm=T))\n\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Fitting a logistic function\n# output: alpha, gamma & beta [model: alpha/(1+exp((dgp-gamma)*beta)) ], BIC and AIC\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nlogfn<-function(gdp.pc,alpha,gamma,beta){\n alpha/(1 + exp((gdp.pc-gamma)*beta))\n }\n # Logistic fitting\nlog.fn<-function(data){\n datos<-na.omit(data)\n nlsFormula <- \"yvar ~ logfn(gdp.pc,alpha,gamma,beta)\"\n nlsInitial <- c(alpha=max(datos$yvar),gamma=mean(datos$gdp.pc),beta=1/mean(datos$year))\n mod1<-nlsLM(formula = nlsFormula, data=datos,start=nlsInitial,control=nls.lm.control(maxiter=1000))\n MSE.p <- mean(residuals(mod1)^2)\n return(data.frame(alpha=coef(mod1)[1],gamma=coef(mod1)[2],beta=coef(mod1)[3],\n \t alpha.se=summary(mod1)$coefficients[1,2],gamma.se=summary(mod1)$coefficients[2,2],beta.se=summary(mod1)$coefficients[3,2],\n \t MSE=MSE.p))\n}\n# foo<-datos[,c(\"gdp.pc\",\"year\",\"median\")];setnames(foo,colnames(foo),c(\"gdp.pc\",\"year\",\"yvar\"))\n# foo<-subset(foo,year>1950)\n#example: log.fn(data=foo)\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Predicting values from a logistic function\n# pars: alpha,gamma,beta [model: alpha/(1+exp((dgp-gamma)*beta)) ]\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\npred.log.fn<-function(pars,newX){\n\talpha<-pars[1]\n\tgamma<-pars[2]\n\tbeta<-pars[3]\n\tout<-unlist(apply(rbind(newX),2,FUN=function(x) alpha/(1 + exp((x-gamma)*beta))))\n return(out)\n}\n#example:\n# pred.log.fn(pars=log.fn(datos=dat2),newX=quantile(dat2$gdp.pc,probs=seq(0,1,0.25),na.rm=T))\n\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Fitting a Box-Cox function\n# output: lambda (for Box-Cox), alpha & beta [model: Box-Cox(Y) = alpha+beta*log(dgp)], BIC and AIC\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\n# Box-Cox with free lambda, lambda -> (0,3), if lambda=0 --> log(yvar)= alpha + beta*log(gdp)\nfree.bx.fn<-function(datos){\nfoo<-boxcox(yvar~log(gdp.pc),data=datos,plotit=F,lambda=seq(0,3,0.01))\n lambda1<-foo$x[foo$y==max(foo$y)]\n if(lambda1==0) datos$yvar2<-log(datos$yvar)\n if(lambda1>0) datos$yvar2<-(datos$yvar^lambda1 -1)/lambda1\n mod1<-lm(yvar2~log(gdp.pc),data=datos)\n\tpred<-pred.free.bx.fn(pars=data.frame(lambda=lambda1,alpha=coef(mod1)[1],beta=coef(mod1)[2]),newX=datos$gdp.pc)\n\tMSE.p<-sum((datos$yvar-pred)^2,na.rm=T)/dim(datos)[1]\nreturn(data.frame(lambda=lambda1,alpha=coef(mod1)[1],beta=coef(mod1)[2],alpha.se=summary(mod1)$coefficients[1,2],beta.se=summary(mod1)$coefficients[2,2],\n MSE=MSE.p))\n}\n#example: free.bx.fn(datos=foo)\n\n# Box-Cox with lambda=0 so the model is log(yvar)= alpha + beta*log(gdp)\nbx.fn<-function(datos){\n mod1<-lm(log(yvar)~log(gdp.pc),data=datos)\n\tpred<-pred.bx.fn(pars=data.frame(alpha=coef(mod1)[1],beta=coef(mod1)[2]),newX=datos$gdp.pc)\n\tMSE.p<-sum((datos$yvar-pred)^2,na.rm=T)/dim(datos)[1]\n return(data.frame(alpha=coef(mod1)[1],beta=coef(mod1)[2],alpha.se=summary(mod1)$coefficients[1,2],beta.se=summary(mod1)$coefficients[2,2],\n\t MSE=MSE.p))\n}\n#example: bx.fn(datos=foo)\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Predicting values from a linear model using Box-Cox transformation\n# pars: lambda [Box-Cox], alpha,beta [model: alpha+beta*log(dgp) ]\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\n# Box-Cox with free lambda, if lambda=0 --> log(yvar)= alpha + beta*log(gdp)\npred.free.bx.fn<-function(pars,newX){#pars=coeff1,newX=q1\n\tlambda<-pars[1]\n\talpha<-pars[2]\n\tbeta<-pars[3]\n\tbxcx.y<-unlist(tapply(as.vector(newX),1:length(newX),FUN=function(x) alpha+beta*log(x)))\n\tif(lambda==0) out<-unlist(tapply(as.vector(bxcx.y),1:length(bxcx.y),FUN=function(x) exp(x)))\n\tif(lambda>0) out<-unlist(tapply(as.vector(bxcx.y),1:length(bxcx.y),FUN=function(x) (x*lambda + 1)^(1/lambda)))\n return(out)\n}\n\n# Box-Cox with lambda=0\npred.bx.fn<-function(pars,newX){\n\talpha<-pars[1]\n\tbeta<-pars[2]\n\tbxcx.y<-unlist(tapply(as.vector(newX),1:length(newX),FUN=function(x) alpha+beta*log(x)))\n\tout<-unlist(tapply(as.vector(bxcx.y),1:length(bxcx.y),FUN=function(x) exp(x)))\n return(out)\n}\n#example:\n# pred.bx.fn(pars=bx.fn(datos=dat1),newX=quantile(dat1$gdp.pc,probs=seq(0,1,0.25),na.rm=T))\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Function that takes predicts life exp between the lowest and highest quartile of income\n# with respect to the median. It uses a logistic or free Box-Cox fitting\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nex.pred<-function(data,fitting,indices){\n\ttmp<-data\n\ttmp<-tmp[indices,]\n\tq1<-quantile(tmp$gdp.pc,probs=seq(0.25,0.75,0.25),na.rm=T)\n if(fitting==\"logistic\") {\n \tcoeff1<-log.fn(data=tmp)#;print(coeff1)\n \tp1<-pred.log.fn(pars=coeff1,newX=q1)\n diff1<-p1[2]-p1[1]\n diff2<-p1[3]-p1[2]\n out<-c(diff1,diff2); names(out)<-c(\"median.minus.q1\",\"q3.minus.median\")\n }\n if(fitting==\"free-boxcox\") {\n \tcoeff1<-free.bx.fn(datos=tmp)#;print(coeff1)\n \tp1<-pred.free.bx.fn(pars=coeff1,newX=q1)\n diff1<-p1[2]-p1[1]\n diff2<-p1[3]-p1[2]\n out<-c(diff1,diff2); names(out)<-c(\"median.minus.q1\",\"q3.minus.median\")\n }\n return(out)\n}\n#example: tmp<-datos[,c(\"year\",\"gdp.pc\",\"median\")]\n#nms<-colnames(tmp);nms[nms==\"median\"]<-\"yvar\";colnames(tmp)<-nms\n#ex.pred(data=subset(tmp,year>=1950),fitting=\"free-boxcox\")\n#tmp<-boot(data=subset(tmp,year<1950),fitting=\"free-boxcox\",statistic=ex.pred,R=5)\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Function that takes a dataset and estimates a logistic or Box-Cox, it then selects the best model as min(MSE)\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nbest.fit<-function(data){\n bx1<-free.bx.fn(datos=data);bxn<-c(\"lambda\",\"alpha\",\"beta\",\"MSE\") #BX: lambda, alpha, beta\n log1<-log.fn(data=data) ;lon<-c(\"alpha\",\"gamma\",\"beta\",\"MSE\") #log: alpha, gamma, beta\n log1S<-log.fnS(data=data) ;lsn<-c(\"alpha\",\"beta\",\"C\",\"MSE\") #logS: alpha, beta, C\n coef<-rep(NA,length(bxn)+length(lon)+length(lsn)); names(coef)<-c(paste(\"FB\",bxn,sep=\".\"),paste(\"Lg\",lon,sep=\".\"),paste(\"LS\",lsn,sep=\".\"))\n min1<-min(bx1$MSE,log1$MSE,log1S$MSE)\n if(bx1$MSE==min1) { coef[1:4]<-bx1[bxn] }\n\tif(log1$MSE==min1) { coef[5:8]<-log1[lon] }\n if(log1S$MSE==min1) { coef[9:12]<-log1S[lsn] }\n return(unlist(coef))\n}\n#example: best.fit(data=dat1)\n\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Function that takes the two datasets and estimates \\Delta(i) using a logistic or Box-Cox fitting\n# fitting: logistic, Sam.logistic, free-boxcox, constraint-boxcox\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nDelta.fn<-function(datos1,datos2,yvar,fitting){\n\tdat1<-datos1\n\tdat2<-datos2\n nms<-colnames(dat1);nms[nms==yvar]<-\"yvar\";setnames(dat1,colnames(dat1),nms)\n nms<-colnames(dat2);nms[nms==yvar]<-\"yvar\";setnames(dat2,colnames(dat2),nms)\n q1<-quantile(dat1$gdp.pc,probs=seq(0.25,0.75,0.25),na.rm=T)\n q2<-quantile(dat2$gdp.pc,probs=seq(0.25,0.75,0.25),na.rm=T)\n if(fitting==\"logistic\") {\n \tcoeff1<-log.fn(data=dat1)#;print(coeff1)\n \tcoeff2<-log.fn(data=dat2)#;print(coeff2)\n \tp1<-pred.log.fn(pars=coeff1,newX=q1)\n p2<-pred.log.fn(pars=coeff2,newX=q2)\n\tpi1<-pred.log.fn(pars=coeff2,newX=q1)\n\tpi2<-pred.log.fn(pars=coeff1,newX=q2)\n\tdelta1<- (pi1-p1)/(p2-p1)\n\tdelta2<- (p2-pi2)/(p2-p1)\n\tDelta<-(1/(2*length(q1)))*(sum(delta1)+sum(delta2))\n setnames(coeff1,colnames(coeff1),paste(colnames(coeff1),1,sep=\".\")) #adding label 1 for parameters estimated <1950\n\tsetnames(coeff2,colnames(coeff2),paste(colnames(coeff2),2,sep=\".\")) #adding label 2 for parameters estimated >=1950\n\tout<-data.frame(Delta=Delta,coeff1,coeff2)\n }\n if(fitting==\"Sam.logistic\") {\n \tcoeff1<-log.fnS(data=dat1)#;print(coeff1)\n \tcoeff2<-log.fnS(data=dat2)#;print(coeff2)\n \tp1<-pred.log.fnS(pars=coeff1,newX=q1)\n p2<-pred.log.fnS(pars=coeff2,newX=q2)\n\tpi1<-pred.log.fnS(pars=coeff2,newX=q1)\n\tpi2<-pred.log.fnS(pars=coeff1,newX=q2)\n\tdelta1<- (pi1-p1)/(p2-p1)\n\tdelta2<- (p2-pi2)/(p2-p1)\n\tDelta<-(1/(2*length(q1)))*(sum(delta1)+sum(delta2))\n setnames(coeff1,colnames(coeff1),paste(colnames(coeff1),1,sep=\".\")) #adding label 1 for parameters estimated <1950\n\tsetnames(coeff2,colnames(coeff2),paste(colnames(coeff2),2,sep=\".\")) #adding label 2 for parameters estimated >=1950\n\tout<-data.frame(Delta=Delta,coeff1,coeff2)\n }\n if(fitting==\"constraint-boxcox\") {\n \tcoeff1<-bx.fn(datos=dat1)\n \tcoeff2<-bx.fn(datos=dat2)\n \tp1<-pred.bx.fn(pars=coeff1,newX=q1)\n p2<-pred.bx.fn(pars=coeff2,newX=q2)\n\tpi1<-pred.bx.fn(pars=coeff2,newX=q1)\n\tpi2<-pred.bx.fn(pars=coeff1,newX=q2)\n\tdelta1<- (pi1-p1)/(p2-p1)\n\tdelta2<- (p2-pi2)/(p2-p1)\n\tDelta<-(1/(2*length(q1)))*(sum(delta1)+sum(delta2))\n setnames(coeff1,colnames(coeff1),paste(colnames(coeff1),1,sep=\".\")) #adding label 1 for parameters estimated <1950\n setnames(coeff2,colnames(coeff2),paste(colnames(coeff2),2,sep=\".\")) #adding label 2 for parameters estimated >=1950\n\tout<-data.frame(Delta=Delta,coeff1,coeff2)\n }\n if(fitting==\"free-boxcox\") {\n coeff1<-free.bx.fn(datos=dat1)\n \tcoeff2<-free.bx.fn(datos=dat2)\n \tp1<-pred.free.bx.fn(pars=coeff1,newX=q1)\n p2<-pred.free.bx.fn(pars=coeff2,newX=q2)\n\tpi1<-pred.free.bx.fn(pars=coeff2,newX=q1)\n\tpi2<-pred.free.bx.fn(pars=coeff1,newX=q2)\n\tdelta1<- (pi1-p1)/(p2-p1)\n\tdelta2<- (p2-pi2)/(p2-p1)\n\tDelta<-(1/(2*length(q1)))*(sum(delta1)+sum(delta2))\n setnames(coeff1,colnames(coeff1),paste(colnames(coeff1),1,sep=\".\")) #adding label 1 for parameters estimated <1950\n setnames(coeff2,colnames(coeff2),paste(colnames(coeff2),2,sep=\".\")) #adding label 2 for parameters estimated >=1950\n\tout<-data.frame(Delta=Delta,coeff1,coeff2)\n }\nreturn(out)\n}\n\n\n\n#/\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\./\\.\n#\n# Function that takes the best fitting model in terms of lowest MSE in each period, <1950, 1950+ and then\n# estimates \\Delta(i) using the best model in each period\n# fitting: logistic or boxcox\n#\n#\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\\/.\nDelta.best.fn<-function(coef1,coef2,p1,p2,pi1,pi2,q1){\n\tdelta1<- (pi1-p1)/(p2-p1)\n\tdelta2<- (p2-pi2)/(p2-p1)\n\tDelta<-(1/(2*length(q1)))*(sum(delta1)+sum(delta2)); names(Delta)<-\"Delta\"\n\treturn(unlist(c(Delta,as.vector(coef1),as.vector(coef2))))\n}\n\n#DeltaK.fn<-function(dattos,indices){\t#\nDeltaK.fn<-function(dattos){\t#\n\ttmp<-na.omit(dattos)\n#\ttmp<-tmp[indices,]#these indices are used for the bootstrap\n dat1<-tmp[tmp$year<1950,]; dat2<-tmp[tmp$year>=1950,]\n\n\tq1<-quantile(dat1$gdp.pc,probs=seq(0.25,0.75,0.25),na.rm=T)\n q2<-quantile(dat2$gdp.pc,probs=seq(0.25,0.75,0.25),na.rm=T)\n\n log1<-log.fn(data=dat1); log1S<-log.fnS(data=dat1); bx12<-free.bx.fn(datos=dat1); bx1<-bx.fn(datos=dat1)\n log2<-log.fn(data=dat2); log2S<-log.fnS(data=dat2); bx22<-free.bx.fn(datos=dat2); bx2<-bx.fn(datos=dat2)\n if(log1$MSE>100) log1$MSE<-100;if(log1S$MSE>100) log1S$MSE<-100;if(bx1$MSE>100) bx1$MSE<-100;if(bx12$MSE>100) bx12$MSE<-100\n if(log2$MSE>100) log2$MSE<-100;if(log2S$MSE>100) log2S$MSE<-100;if(bx2$MSE>100) bx2$MSE<-100;if(bx22$MSE>100) bx22$MSE<-100\n\n min1<-min(log1$MSE,log1S$MSE,bx1$MSE,bx12$MSE)#\n min2<-min(log2$MSE,log2S$MSE,bx2$MSE,bx22$MSE)#\n\n\tbxn<-c(\"lambda\",\"alpha\",\"beta\",\"MSE\");lon<-c(\"alpha\",\"gamma\",\"beta\",\"MSE\");lsn<-c(\"alpha\",\"beta\",\"C\",\"MSE\"); cont.bx<-c(\"alpha\",\"beta\",\"MSE\")\n\tcoef1<-rep(NA,length(bxn)+length(lon)+length(lsn));coef2<-rep(NA,length(bxn)+length(lon)+length(lsn))\n\tnames(coef1)<-names(coef2)<-c(paste(\"FB\",bxn,sep=\".\"),paste(\"Lg\",lon,sep=\".\"),paste(\"LS\",lsn,sep=\".\"))\n\n if(log1$MSE==min1) { coeff1<-log1; coef1[5:8]<-coeff1[lon]; p1<-pred.log.fn(pars=coeff1,newX=q1); pi2<-pred.log.fn(pars=coeff1,newX=q2) }\n if(log1S$MSE==min1) { coeff1<-log1S;coef1[9:12]<-coeff1[lsn]; p1<-pred.log.fnS(pars=coeff1,newX=q1); pi2<-pred.log.fnS(pars=coeff1,newX=q2) }\n\tif(bx12$MSE==min1) { coeff1<-bx12; coef1[1:4]<-coeff1[bxn]; p1<-pred.free.bx.fn(pars=coeff1,newX=q1);pi2<-pred.free.bx.fn(pars=coeff1,newX=q2) }\n if(bx1$MSE==min1) { coeff1<-bx1; coef1[1:4]<-c(0,coeff1[cont.bx]); p1<-pred.bx.fn(pars=coeff1,newX=q1); pi2<-pred.bx.fn(pars=coeff1,newX=q2) }\n\n\tif(log2$MSE==min2) { coeff2<-log2; coef2[5:8]<-coeff2[lon]; p2<-pred.log.fn(pars=coeff2,newX=q2); pi1<-pred.log.fn(pars=coeff2,newX=q1) }\n if(log2S$MSE==min2) { coeff2<-log2S;coef2[9:12]<-coeff2[lsn]; p2<-pred.log.fnS(pars=coeff2,newX=q2); pi1<-pred.log.fnS(pars=coeff2,newX=q1) }\n if(bx22$MSE==min1) { coeff2<-bx12; coef2[1:4]<-coeff2[bxn]; p2<-pred.free.bx.fn(pars=coeff2,newX=q2);pi1<-pred.free.bx.fn(pars=coeff2,newX=q1) }\n if(bx2$MSE==min2) { coeff2<-bx2; coef2[1:4]<-c(0,coeff2[cont.bx]); p2<-pred.bx.fn(pars=coeff2,newX=q2); pi1<-pred.bx.fn(pars=coeff2,newX=q1) }\n\n #setnames(coeff1,colnames(coeff1),paste(colnames(coeff1),1,sep=\".\"));setnames(coeff2,colnames(coeff2),paste(colnames(coeff2),2,sep=\".\"))\n\tnames(coef1)<-paste(names(coef1),1,sep=\".\")\n names(coef2)<-paste(names(coef2),2,sep=\".\")\n\treturn(Delta.best.fn(coef1=coef1,coef2=coef2,p1=p1,p2=p2,pi1=pi1,pi2=pi2,q1=q1))\n}\n# example:\n#foo<-na.omit(data.frame(yvar=N.samples[[1]],gdp.pc=datos$gdp.pc,year=datos$year))\n# DeltaK.fn(dattos=foo)\n", "meta": {"hexsha": "1eaf2fca39b238d649908b558b9d6edf1d0cbe7c", "size": 15916, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/bootstrap_code/function_decomp.r", "max_stars_repo_name": "sdaza/lambda", "max_stars_repo_head_hexsha": "551389be42256342cdb7078a4cf83215e56f0fa5", "max_stars_repo_licenses": ["AFL-3.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": "docs/bootstrap_code/function_decomp.r", "max_issues_repo_name": "sdaza/lambda", "max_issues_repo_head_hexsha": "551389be42256342cdb7078a4cf83215e56f0fa5", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/bootstrap_code/function_decomp.r", "max_forks_repo_name": "sdaza/lambda", "max_forks_repo_head_hexsha": "551389be42256342cdb7078a4cf83215e56f0fa5", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3447293447, "max_line_length": 153, "alphanum_fraction": 0.5995853229, "num_tokens": 6562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.612615009789777}} {"text": "tanimoto_traits <- function(resource_x, resource_y, trait_x, trait_y, trait_weight) {\n # The Tanimoto similarity with traits measures the similarity between vectors of traits as well as similarity between vectors of resources\n # tanimotot(x; y;wt) = wttanimoto(xt; yt) + (1 􀀀 wt)tanimoto(xi; yi);\n # If trait_weight == 1, only traits are used for similarity measurement\n # If trait_weight == 0, only shared resources measures the similarity between species\n\n # !!! Does it make sense to measure taxonomic proximity linearly like this? I need to look into taxonomic proximity measurements in packages like rphylo !!!\n\n\n return(trait_weight * tanimoto(trait_x, trait_y) + (1 - trait_weight) * tanimoto(resource_x, resource_y))\n}\n", "meta": {"hexsha": "1be66db129ecf7691bf6a61605662bdc3141234b", "size": 745, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/tanimoto_traits.r", "max_stars_repo_name": "david-beauchesne/predicting_interactions", "max_stars_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-08-12T11:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-09T18:16:12.000Z", "max_issues_repo_path": "Script/tanimoto_traits.r", "max_issues_repo_name": "david-beauchesne/predicting_interactions", "max_issues_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-12T14:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T15:25:21.000Z", "max_forks_repo_path": "Script/tanimoto_traits.r", "max_forks_repo_name": "david-beauchesne/predicting_interactions", "max_forks_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-12T10:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-12T10:46:53.000Z", "avg_line_length": 62.0833333333, "max_line_length": 160, "alphanum_fraction": 0.7476510067, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6125653199774197}} {"text": "allele.imbalance<- function(rna, dna, rna.err, dna.err){\n \n #Step1\n # estimate sequencing error, dispersion DNA counts and dispersion RNA counts\n # optimization function 1\n mtmp <- function(par, dna.x, dna.n, rna.x, rna.n, ge, rna.err, dna.err){\n \n # define parameters\n # seq.err <- par[1]\n disp.dna <- par[1]\n disp.rna <- par[2]\n \n # likelihood given genotype err (not actually het)\n term1<- 0.5 * dbetabinom(dna.x, dna.n, m= dna.err/3, s= disp.dna) * dbetabinom(rna.x, rna.n, m= rna.err/3, s= disp.rna)\n term2<- 0.5 * dbetabinom(dna.n-dna.x, dna.n, m= dna.err/3, s= disp.dna) * dbetabinom(rna.n-rna.x, rna.n, m= rna.err/3, s= disp.rna)\n err.like <- (ge)*(term1 + term2)\n \n # likelihood given het sites (actually het)\n het.like = (1-ge)*(dbetabinom(dna.x, dna.n, m= 0.5, s= disp.dna)) * dbetabinom(rna.x, rna.n, m= 0.5, s= disp.rna)\n \n # log likelihood\n ll<- -sum(log(err.like + het.like))\n \n return(ll)\n }\n \n # optimize\n m0<- optim(par= c(1, 1), mtmp, \n dna.x=dna$ref.matches, dna.n= dna$N, \n rna.x= rna$ref.matches, rna.n = rna$N,\n ge= dna$genotype.error,dna.err= dna.err, rna.err= rna.err, \n method=\"L-BFGS-B\",lower = c(1e-5, 1e-5), \n upper = c(100, 100))\n \n # get parameter\n disp.dna = m0$par[1]\n disp.rna = m0$par[2]\n \n # get genes\n genes= as.character(unique(rna$gene))\n \n # allelic.imbalance is how far proportion is away from 0.5\n # first site : L( x | allelic.imbalance)=het.like* P( x | 0.5 + allelic.imbalance) + err.like\n # subsequent sites : L( x | allelic.imbalance) = het.like(0.5 * Pr(x | 0.5 - d) + 0.5 * Pr( x | 0.5 + d))) + err.like\n # chi-square test against null hypothesis of allelic.imbalance = 0\n \n myfunc<- function(i){\n #Step 1 subset by gene\n # rna\n rna= rna[rna$gene %in% genes[i],]\n rna= rna[order(rna$start),]\n \n # dna\n dna= dna[(dna$rsID %in% rna$rsID) & (dna$gene %in% genes[i]),]\n dna= dna[order(dna$start),]\n \n # step 2 likelihood estimate\n # likelihood function estimate for ase\n ll<- function(allelic.imbalance, dna.x, dna.n, rna.x, rna.n, ge, dna.err, rna.err, disp.dna, disp.rna){\n \n # for 1st site\n # likelihood of allelic imbalance (d1)\n d1= dbetabinom(rna.x[1], rna.n[1], m= 0.5+ allelic.imbalance, s= disp.rna) \n \n # likelihood given genotype err (not actually het)\n term1<- 0.5 * dbetabinom(dna.x[1], dna.n[1], m= dna.err/3, s= disp.dna) * dbetabinom(rna.x[1], rna.n[1], m= rna.err/3, s= disp.rna)\n term2<- 0.5 * dbetabinom(dna.n[1]-dna.x[1], dna.n[1], m= dna.err/3, s= disp.dna) * dbetabinom(rna.n[1]-rna.x[1], rna.n[1], m= rna.err/3, s= disp.rna)\n err.like <- (ge[1])*(term1 + term2)\n \n # likelihood given het sites (actually het)\n het.like= (1-ge[1])*(dbetabinom(dna.x[1], dna.n[1], m= 0.5, s= disp.dna))\n \n # likelihood of 1st sites\n p1= het.like*d1+ err.like\n \n # for subsequent sites\n len= nrow(rna)\n \n if(len >1){\n \n # likelihood of allelic imbalance of n+1, n+2....n+k sites\n d2= 0.5 * dbetabinom(rna.x[2:len], rna.n[2:len], 0.5+ allelic.imbalance, disp.rna) \n d3= 0.5 * dbetabinom(rna.x[2:len], rna.n[2:len], 0.5- allelic.imbalance, disp.rna) \n \n # likelihood given genotype err (not actually het)\n term1<- 0.5 * dbetabinom(dna.x[2:len], dna.n[2:len], m= dna.err/3, s= disp.dna) * \n dbetabinom(rna.x[2:len], rna.n[2:len], m= rna.err/3, s= disp.rna)\n \n term2<- 0.5 * dbetabinom(dna.n[2:len]-dna.x[2:len], dna.n[2:len], m= dna.err, s= disp.dna) * \n dbetabinom(rna.n[2:len]-rna.x[2:len], rna.n[2:len], m= rna.err, s= disp.rna)\n \n err.like <- (ge[2:len])*(term1 + term2)\n \n # likelihood given het sites (actually het)\n het.like= (1-ge[2:len])*(dbetabinom(dna.x[2:len], dna.n[2:len], m= 0.5, s= disp.dna))\n \n p2= het.like*(d2 + d3) + err.like\n \n return(-sum(log(c(p1,p2))))}else{\n return(-sum(log(p1)))\n }}\n \n # optimize allelic.imbalance\n m1= optimize(ll, c(-0.5, 0.5), \n rna.x= rna$ref.matches, rna.n= rna$N, \n dna.x= dna$ref.matches, dna.n= dna$N, ge= dna$genotype.error, \n dna.err= dna.err, rna.err= rna.err, disp.dna= disp.dna, disp.rna= disp.rna)\n \n # estimates of allelic.imbalance\n alt.ll <- m1$objective\n estimate <- m1$minimum\n \n # NULL hypothesis\n null.ll= ll(allelic.imbalance = 0, \n rna.x= rna$ref.matches, rna.n= rna$N, \n dna.x= dna$ref.matches, dna.n= dna$N, \n ge= dna$genotype.error, dna.err= dna.err, rna.err= rna.err, \n disp.dna= disp.dna, disp.rna= disp.rna)\n \n # likelihood ratio test\n lrt.stat <- 2 * (null.ll - alt.ll)\n pval <- pchisq(lrt.stat, df=1, lower.tail=F)\n result= data.frame(gene= genes[i], pval =pval, d= estimate)\n return(result)\n }\n rlist= llply(1:length(genes), myfunc)\n res= do.call(rbind,rlist)\n res$fdr= p.adjust(res$pval, \"fdr\")\n return(res)\n}", "meta": {"hexsha": "189eee279f958978f4b67260b49db1d731ed7bc3", "size": 5419, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/allele_imbalance.r", "max_stars_repo_name": "aryarm/as_analysis", "max_stars_repo_head_hexsha": "570bd160449c8eba1a67cb65fc52f91cda0b27bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-01-11T09:27:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T14:39:09.000Z", "max_issues_repo_path": "scripts/allele_imbalance.r", "max_issues_repo_name": "aryam7/as_analysis", "max_issues_repo_head_hexsha": "570bd160449c8eba1a67cb65fc52f91cda0b27bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60, "max_issues_repo_issues_event_min_datetime": "2018-06-04T18:04:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-22T04:58:07.000Z", "max_forks_repo_path": "scripts/allele_imbalance.r", "max_forks_repo_name": "aryarm/as_analysis", "max_forks_repo_head_hexsha": "570bd160449c8eba1a67cb65fc52f91cda0b27bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-01-06T21:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T07:46:54.000Z", "avg_line_length": 41.6846153846, "max_line_length": 158, "alphanum_fraction": 0.5336778003, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.6124308788267735}} {"text": "# CS422 Data Mining\n# Vijay K. Gurbani, Ph.D.\n# Illinois Institute of Technology\n#\n# Demonstration of k-means clustering. Algorithm below is for demonstration \n# purpose only; lot's of hard-coded stuff. Don't assume it will work for all\n# sorts of data and clustering strategies!!\n\nrm(list=ls())\n\n# Main entry point. To run, give the coordinates of the cluster centroids.\n#\n# > kmeans.demo.main(data.frame(x=c(9,10,11), y=c(2,3,4)))\n# or\n# > kmeans.demo.main(data.frame(x=c(1,6,10), y=c(10,6,8)))\n#\n# The following cluster centroid will result in only 2 clusters: red and black.\n# (Some warnings are thrown as the code does not handle corner cases\n# approriately.)\n#\n# > kmeans.demo.main(data.frame(x=c(1,2,3), y=c(10,10,10)))\n#\n# Other centroids: data.frame(x=c(1,12,6), y=c(1,10,6))\n\nkmeans.demo.main <- function(centroids) {\n\n x <- c(4,7,4,6,3,2,5,10,12,11,9,12)\n y <- c(10,10,8,8,4,2,2,5,6,4,3,3)\n df <- data.frame(x,y)\n \n cluster.centroids <- centroids\n \n old.cluster.centroids <- cluster.centroids\n for (i in 1:100) {\n kmeans.demo.plot(df, cluster.centroids)\n readline(prompt=\"Press to continue\")\n cluster.centroids <- kmeans.demo.training(df, cluster.centroids)\n readline(prompt=\"Press to continue\")\n if (identical(cluster.centroids, old.cluster.centroids)) { break }\n old.cluster.centroids <- cluster.centroids\n }\n cat(paste(\"Iterations to converge: \", i, \"\\n\"))\n}\n\n# Plot the data points and the centroids\nkmeans.demo.plot <- function(df, cluster.centroids) {\n plot(df, xlim=c(0,13), ylim=c(0,11), cex=3)\n points(cluster.centroids[1,1], cluster.centroids[1,2], col=\"green\", pch=8, cex=3)\n points(cluster.centroids[2,1], cluster.centroids[2,2], col=\"red\", pch=8, cex=3)\n points(cluster.centroids[3,1], cluster.centroids[3,2], col=\"black\", pch=8, cex=3)\n}\n\n# \"Train\" the dataset by seeing which points belong to which cluster\nkmeans.demo.training <- function(df, cluster.centroids) {\n green.df <- data.frame(); \n red.df <- data.frame(); \n black.df <- data.frame();\n for (i in 1:dim(df)[1]) {\n paint <- kmeans.demo.which.cluster(df[i,1], df[i,2], cluster.centroids)\n points(df[i,1], df[i,2], col=paint, pch=20, cex=4)\n if (paint == \"green\") { green.df <- rbind(green.df, df[i,])}\n if (paint == \"red\") { red.df <- rbind(red.df, df[i,])}\n if (paint == \"black\") { black.df <- rbind(black.df, df[i,])}\n }\n cluster.centroids <- kmeans.demo.update.centroids(green.df, \n red.df, \n black.df, \n cluster.centroids)\n cluster.centroids\n}\n\n# Determine which point to paint with which color\nkmeans.demo.which.cluster <- function(x, y, cluster.centroids) {\n df <- data.frame(c(x, cluster.centroids[1,1]), c(y, cluster.centroids[1,2]))\n d1 <- dist(df) # green\n df <- data.frame(c(x, cluster.centroids[2,1]), c(y, cluster.centroids[2,2]))\n d2 <- dist(df) # red\n df <- data.frame(c(x, cluster.centroids[3,1]), c(y, cluster.centroids[3,2]))\n d3 <- dist(df) # black\n indx <- which.min(c(d1,d2,d3))\n if (indx == 1) {\n paint = \"green\"\n } else if (indx == 2){\n paint = \"red\"\n } else {\n paint = \"black\"\n }\n paint\n}\n\n# Update the centroids to their new location.\nkmeans.demo.update.centroids <- function(green.df, \n red.df, \n black.df, \n cluster.centroids) {\n \n cluster.centroids <- data.frame(x = c(mean(green.df$x), \n mean(red.df$x), \n mean(black.df$x)),\n y = c(mean(green.df$y), \n mean(red.df$y), \n mean(black.df$y)))\n cluster.centroids\n}\n", "meta": {"hexsha": "9ec197dd5a2fe87247a6b1e242cac7b49c6f2256", "size": 3895, "ext": "r", "lang": "R", "max_stars_repo_path": "hw8/kmeans-algo-simple.r", "max_stars_repo_name": "liwenlongonly/cs422_hw", "max_stars_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw8/kmeans-algo-simple.r", "max_issues_repo_name": "liwenlongonly/cs422_hw", "max_issues_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw8/kmeans-algo-simple.r", "max_forks_repo_name": "liwenlongonly/cs422_hw", "max_forks_repo_head_hexsha": "6d696ab75d86987c52fb167cea5d0dd50abb6f2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0952380952, "max_line_length": 83, "alphanum_fraction": 0.5735558408, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6123979290374514}} {"text": "### Generate data base simulations\n## Use: Generate data for four functional forms\n## Author: Mark Verhagen\n\nlibrary(tidyverse)\nlibrary(randomForest)\nlibrary(xgboost)\n\nset.seed(1704)\n\n## Set n and X variable\nn <- 100\nX <- runif(n, -4, 4)\n\n## Generate y outcome based on four functional forms\ny0 <- -1 + .9 * X\ny1 <- -2 * ifelse(X < -3, 1, 0) + 2.55 * ifelse(X > -2, 1, 0) -\n 2 * ifelse(X > 0, 1, 0) + 4 * ifelse(X > 2, 1, 0) - 1 * ifelse(X > 3, 1, 0)\ny2 <- 6 + 0.4 * X - 0.36 * X^2 + 0.005 * X^3\ny3 <- 2.83 * sin(pi / 2 * X)\n\n## Generate white noise such that overall variance is fixed\nvar0 <- 5 - var(y0)\nvar1 <- 5 - var(y1)\nvar2 <- 5 - var(y2)\nvar3 <- 5 - var(y3)\n\nepsilon0 <- rnorm(n, 0, sqrt(var0))\nepsilon1 <- rnorm(n, 0, sqrt(var1))\nepsilon2 <- rnorm(n, 0, sqrt(var2))\nepsilon3 <- rnorm(n, 0, sqrt(var3))\n\n## Generate outcome plus noise and store in dataframe\ndf <- data.frame(\n X = X,\n y_0 = y0 + epsilon0,\n y_1 = y1 + epsilon1,\n y_2 = y2 + epsilon2,\n y_3 = y3 + epsilon3\n)\n\nreturn_oos_r2 <- function(actual, predict) {\n return(1 - sum((actual - predict)^2) / sum((actual - mean(actual))^2))\n}\n\n## Generate ids for every row\ndf_analysis <- df %>%\n mutate(id = 1:n())\n\ntrain_set <- df_analysis\n\nobs_vars <- c(\"y_0\", \"y_1\", \"y_2\", \"y_3\")\n\n## Obtian outcome value per functional form for trainset\ntrain_ys <- lapply(obs_vars, FUN = function(x) {\n train_set[, x]\n})\n\n## Obtain train and test version of feature set\nX_train <- train_set %>%\n select(X)\n\n## Estimate true linear effects\ntrue_vars <- list(y0, y1, y2, y3)\nlms <- lapply(true_vars, FUN = function(x) {\n lm(y ~ 1 + X, data = df_analysis %>% mutate(y = x))\n})\n\n## Estimate random forest models on train set\nrfs <- lapply(train_ys, FUN = function(x) {\n randomForest(x = X_train, y = x)\n})\n\n## Estimate gradient boosting models\ngbs <- lapply(train_ys, FUN = function(x) {\n xgboost(data = as.matrix(X_train), label = x, nrounds = 200)\n})\n\n## Plotting\npred_df <- data.frame(X = seq(-4, 4, 8 / 100))\n\n## True association\npred_df$lm_0 <- predict(lms[[1]], pred_df)\npred_df$lm_1 <- predict(lms[[2]], pred_df)\npred_df$lm_2 <- predict(lms[[3]], pred_df)\npred_df$lm_3 <- predict(lms[[4]], pred_df)\n\n## Implied association\npred_df$rf_0 <- predict(gbs[[1]], as.matrix(pred_df$X))\npred_df$rf_1 <- predict(rfs[[2]], as.matrix(pred_df$X))\npred_df$rf_2 <- predict(rfs[[3]], as.matrix(pred_df$X))\npred_df$rf_3 <- predict(rfs[[4]], as.matrix(pred_df$X))\n\npred_df$gb_0 <- predict(gbs[[1]], as.matrix(pred_df$X))\npred_df$gb_1 <- predict(gbs[[2]], as.matrix(pred_df$X))\npred_df$gb_2 <- predict(gbs[[3]], as.matrix(pred_df$X))\npred_df$gb_3 <- predict(gbs[[4]], as.matrix(pred_df$X))\n\nmelt_pred_df <- reshape2::melt(pred_df, id.vars = c(\"X\")) %>%\n mutate(model = ifelse(grepl(\"rf\", variable), \"RF\",\n ifelse(grepl(\"gb\", variable), \"GB\",\n ifelse(grepl(\"lm\", variable), \"LM\", NA)\n )\n ), data = gsub(\"rf_|gb_|lm_\", \"\", variable))\n\nmelt_observed <- df %>%\n reshape2::melt(id.vars = (\"X\")) %>%\n mutate(model = \"Simulated\", data = gsub(\"y_\", \"\", variable))\n\ndf_true <- data.frame(\n X = X, y_0 = y0, y_1 = y1,\n y_2 = y2, y_3 = y3\n)\n\nmelt_true <- df_true %>%\n reshape2::melt(id.vars = (\"X\")) %>%\n mutate(model = \"True\", data = gsub(\"y_\", \"\", variable))\n\ntotal_melt <- rbind(melt_pred_df, melt_observed, melt_true) %>%\n mutate(data = ifelse(data == \"0\", \"Linear\",\n ifelse(data == \"1\", \"Step\",\n ifelse(data == \"2\", \"Quadratic\",\n ifelse(data == \"3\", \"Sine\", NA)\n )\n )\n ))\n\n \nggplot(total_melt, aes(y = value, x = X)) +\n geom_point(data = total_melt %>% filter(!(model %in% c(\"True\", \"LM\", \"GB\", \"RF\"))), alpha = 0.3, aes(color = model)) +\n geom_line(data = total_melt %>% filter(model == \"True\"), aes(linetype = model)) +\n geom_line(data = total_melt %>% filter(model == \"LM\"), aes(linetype = model)) +\n facet_wrap(~data) +\n xlab(\"X\") +\n ylab(\"Y\") +\n scale_color_manual(\n name = \"\", values = c(ggsci::pal_aaas(\"default\")(3)[3:1], ggsci::pal_aaas(\"default\")(10)[10]),\n labels = c(\"Simulated data\")\n ) +\n scale_linetype_manual(name = \"\", values = c(\"dashed\", \"solid\"), labels = c(\"Linear Model\", \"True effect\")) +\n cowplot::theme_cowplot() +\n theme(\n # panel.grid.minor.y = element_line(size = 0.25, linetype = \"dotted\"),\n # panel.grid.major.y = element_line(size = 0.25, linetype = \"dotted\"),\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.5),\n legend.position = \"top\",\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n text = element_text(size = 20)\n ) +\n guides(color = guide_legend(override.aes = list(fill = NA)))\n\nggsave(\"../tex/figs/fig1_base.pdf\", last_plot(), width = 10, height = 8)\n\nggplot(total_melt, aes(y = value, x = X)) +\n geom_point(data = total_melt %>% filter(!(model %in% c(\"True\", \"LM\"))), alpha = 0.3, aes(color = model)) +\n geom_line(data = total_melt %>% filter(model == \"True\"), aes(linetype = model)) +\n facet_wrap(~data) +\n xlab(\"X\") +\n ylab(\"Y\") +\n scale_color_manual(\n name = \"\", values = c(ggsci::pal_aaas(\"default\")(3)[1:3], ggsci::pal_aaas(\"default\")(10)[10]),\n labels = c(\"Gradient Boosting\", \"Random Forest\", \"Simulated data\")\n ) +\n scale_linetype_manual(name = \"\", values = c(\"solid\"), labels = c(\"True effect\")) +\n cowplot::theme_cowplot() +\n theme(\n # panel.grid.minor.y = element_line(size = 0.25, linetype = \"dotted\"),\n # panel.grid.major.y = element_line(size = 0.25, linetype = \"dotted\"),\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.5),\n legend.position = \"top\",\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n text = element_text(size = 20)\n ) +\n guides(color = guide_legend(override.aes = list(fill = NA)))\n\nggsave(\"../tex/figs/fig1_base2.pdf\", last_plot(), width = 10, height = 8)\n", "meta": {"hexsha": "d045c6c9c54ba79628b4ebb9d3a012e2acbaf624", "size": 6142, "ext": "r", "lang": "R", "max_stars_repo_path": "base_simuls/00_gen.r", "max_stars_repo_name": "MarkDVerhagen/functional_form_complexity", "max_stars_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "base_simuls/00_gen.r", "max_issues_repo_name": "MarkDVerhagen/functional_form_complexity", "max_issues_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base_simuls/00_gen.r", "max_forks_repo_name": "MarkDVerhagen/functional_form_complexity", "max_forks_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_forks_repo_licenses": ["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.312849162, "max_line_length": 122, "alphanum_fraction": 0.5970367958, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.6123487878767665}} {"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)\nlibrary(quantmod)\n\n## Get risk-free rates\nrf.tickers <- c(\"FRED/DGS3MO\", \"BOC/V39065\", \"BUNDESBANK/BBK01_WT3210\",\n \"SNB/RENDOBLID\", \"RBA/F17_0\", \"MOFJ/INTEREST_RATE_JAPAN\")\nrf.columns <- c(1,1,1,1,2,1)\nrf.ids <- c(\"USD3M\", \"CAD3M\",\"EUR6M\",\"CHF1Y\",\"AUD3M\",\"JPY1Y\",\"HKD3M\")\n## loop through tickers and columns\nrf <- Quandl(rf.tickers[1], type=\"xts\")[,rf.columns[1]]/100\nfor (i in 2:length(rf.tickers)) {\n rf.tmp <- Quandl(rf.tickers[i], type=\"xts\")[,rf.columns[i]]/100\n rf <- cbind(rf, rf.tmp)\n}\n\n## Getting HKMA data is not straightforward, so...\n## ...these are from the Hong Kong Monetary Authority\nhkma.exfund.3M.rates <-\n c(0.09,0.10,0.10,0.11,0.26,0.62,0.27,0.18,0.24,0.25,0.30,0.28, # 2010\n 0.16,0.19,0.20,0.11,0.13,0.06,0.07,0.10,0.11,0.10,0.17,0.22, # 2011\n 0.18,0.11,0.10,0.12,0.10,0.08,0.15,0.17,0.23,0.09,0.07,0.05, # 2012\n 0.11,0.08,0.06,0.08,0.09,0.15,0.16,0.15,0.17,0.13,0.12,0.11, # 2013\n 0.14,0.14,0.14,0.10,0.07,0.09,0.07,0.04,0.09,0.03,0.03,0.04, # 2014\n 0.03,0.01,0.02,0.01,0.01,0.00,0.01,-0.01,-0.01,0.00,-0.01,0.04, # 2015\n 0.24,0.07,0.07,0.06,0.20,0.17,0.28,0.30,0.31,0.30,0.28,0.67, # 2016\n 0.54,0.41,0.27,0.40,0.29,0.31,0.35,0.28,0.45,0.85,0.75,1.02, # 2017\n 0.66,0.56) # 2018\nrf.subset <- rf[\"201001/201802\"]\nhkma.3M <- xts(hkma.exfund.3M.rates,\n order.by = index(rf.subset[xts:::startof(rf.subset, \"months\")]))\nrf <- cbind(rf, hkma.3M)\nrf <- na.locf(rf)\ncolnames(rf) <- rf.ids\n\n# Get indices and stock prices\nadj.close <- 6 # 6th field is adjusted close\nequity.tickers <- c(\"^GSPC\",\"^GSPTSE\",\"^STOXX50E\",\"^SSMI\",\"^AORD\",\"^HSI\",\"^N225\",\n \"CTC-A.TO\",\"F\",\"HSBC\",\"PFE\",\"SVNDY\",\"TM\",\"EDF.PA\",\"NOVN.VX\",\n \"SIE.DE\",\"VOW.DE\",\"BRG.AX\",\"MQG.AX\",\"J36.SI\",\"0019.HK\")\nequity.ids <- c(\"SPX\",\"TSXCOMP\",\"ESX50\",\"SMI\",\"AORD\",\"HS\",\"N225\",\n \"CATIRE\",\"FORD\",\"HSBC\",\"PFIZER\",\"SEVENANDI\",\"TOY\",\"EDF\",\"NOVARTIS\",\n \"SIEMENS\",\"VW\",\"BREVILLE\",\"MACQUARIE\",\"JARDINES\",\"SWIRE\")\nprices <- getSymbols(equity.tickers[1], source=\"yahoo\", auto.assign=FALSE,\n return.class=\"xts\")[,adj.close]\nfor (i in 2:length(equity.tickers)) {\n prices.tmp <- getSymbols(equity.tickers[i], source=\"yahoo\",\n auto.assign=FALSE, return.class=\"xts\")[,adj.close]\n prices <- cbind(prices, prices.tmp)\n}\n## We often get errors here since international stocks are not always\n## traded on our home days, so there are some NAs. No worries; fill\n## forward and returns will be zero on non-trading days. (Might be a\n## minor bias on volatility estimates; we will probably survive.\nprices <- na.locf(prices)\ncolnames(prices) <- equity.ids\nreturns <- diff(log(prices))\n\n## Now we join all of the datasets together and trim to recent\nalldata <- cbind(rf, returns)[\"2010/\"]\n\n## create excess returns\nequity.names.xs <- paste(equity.names, \".xs\", sep=\"\")\n## now in a for loop subtract off a daily risk-free rate, FOR EXAMPLE:\nalldata$SPX.xs <- alldata$SPX - alldata$T3M/250\n## Only oddity: use HKD rf for Jardines.\n\n# If your ticker were DAL and you wanted to model returns\n# (not excess returns) using ESTOX and SMI, you would do like so:\nsimple.wrong.model <- lm(DAL ~ ESTOX + SMI, data=alldata)\nsummary(simple.wrong.model)\n# NOTE that this is not the model you are supposed to do\n", "meta": {"hexsha": "125f1e6021470ac5ee82f07964339e491c4e990e", "size": 3665, "ext": "r", "lang": "R", "max_stars_repo_path": "Quantitative Primer/samples/ch17-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/ch17-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/ch17-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": 46.3924050633, "max_line_length": 83, "alphanum_fraction": 0.6365620737, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6123316377613405}} {"text": "# If you use this code or parts of it, please cite the following paper\n# Bruhin A., E. Fehr, D. Schunk (2018): \"The Many Faces of Human Sociality: Uncovering the Distribution and Stability of Social Preferences\",\n# Journal of the European Economic Association, forthcoming.\n# ===========================================================================================================================================\n\nlibrary(compiler)\n\n# Log Likelihood\nfdummy.ll <- function(v,y,self_x, other_x, self_y, other_y,indicators_x, indicators_y) {\n\tbeta <- v[1:(length(v)-1)]\n\tgamma <- exp(v[length(v)])\n\n\tlli <- indicators_x%*%beta\n\trli <- indicators_y%*%beta\n\tuleft <- gamma*((1-lli)*self_x+lli*other_x)\n\turight <- gamma*((1-rli)*self_y+rli*other_y)\n\n\tprobs <- (exp(uleft)/(exp(uleft)+exp(uright)))^y * (exp(uright)/(exp(uleft)+exp(uright)))^(1-y)\n\n\tsum(log(probs))\n}\nf.ll <- cmpfun(fdummy.ll)\n\n# Log Likelihood of a model without indicators\nfdummy.ll.nopar <- function(v,y,self_x,self_y) {\n\tgamma <- exp(v)\n\n\tuleft <- gamma*self_x\n\turight <- gamma*self_y\n\n\tprobs <- (exp(uleft)/(exp(uleft)+exp(uright)))^y * (exp(uright)/(exp(uleft)+exp(uright)))^(1-y)\n\n\tsum(log(probs))\n}\nf.ll.nopar <- cmpfun(fdummy.ll.nopar)\n\n# Gradient of Log Likelihood\nfdummy.ll.gr <- function(v, y, self_x, other_x, self_y, other_y, indicators_x, indicators_y) {\n\tbeta <- v[1:(length(v)-1)]\n\tgamma <- exp(v[length(v)])\n\n\tlli <- indicators_x%*%beta\n\trli <- indicators_y%*%beta\n\tutl <- gamma*((1-lli)*self_x+lli*other_x)\n\tutr <- gamma*((1-rli)*self_y+rli*other_y)\n\tprobs <- (exp(utl)/(exp(utl)+exp(utr)))^y * (exp(utr)/(exp(utl)+exp(utr)))^(1-y)\n\tprobsm <- matrix(probs, nrow(indicators_x), ncol(indicators_x))\n\n\tu <- matrix(exp(utl) , nrow(indicators_x), ncol(indicators_x))\n\tw <- matrix(exp(utl) + exp(utr) , nrow(indicators_x), ncol(indicators_x))\n\tup <- gamma * indicators_x * matrix(other_x-self_x, nrow(indicators_x), ncol(indicators_x)) * u\n\twp <- up + gamma * indicators_y * matrix((other_y-self_y)*exp(utr), nrow(indicators_x), ncol(indicators_x))\n\n\tprebgrad <- (-1)^(1-y)*((up*w - u*wp)/w^2)/probsm\n\tbgrad <- colSums(prebgrad)\n\n\tup2 <- utl * u[,1]\n\twp2 <- up2 + utr * exp(utr)\n\n\tggrad <- sum((-1)^(1-y) * (((up2*w[,1] - u[,1]*wp2)/w[,1]^2)/probs))\n\n\tc(bgrad, ggrad)\n}\nf.ll.gr <- cmpfun(fdummy.ll.gr)\n\n# Gradient of Log Likelihood of a model without indicators\nfdummy.ll.gr.nopar <- function(v, y, self_x,self_y) {\n\tgamma <- exp(v)\n\n\tutl <- gamma*self_x\n\tutr <- gamma*self_y\n\tprobs <- (exp(utl)/(exp(utl)+exp(utr)))^y * (exp(utr)/(exp(utl)+exp(utr)))^(1-y)\n\n\tu <- exp(utl)\n\tw <- exp(utl) + exp(utr)\n\tup2 <- utl * u\n\twp2 <- up2 + utr * exp(utr)\n\n\tggrad <- sum((-1)^(1-y) * (((up2*w - u*wp2)/w^2)/probs))\n\tggrad\n}\nf.ll.gr.nopar <- cmpfun(fdummy.ll.gr.nopar)\n\n# Function to compute cluster robust standard errors\nf.clusterse <- function(estobj, dat, label_choice_x, label_self_x, label_other_x, label_self_y, label_other_y, label_indicators_x, label_indicators_y, clustervar) {\n\ty <- as.vector(dat[,label_choice_x])\n\tself_x <- as.matrix(dat[,label_self_x])\n\tother_x <- as.matrix(dat[,label_other_x])\n\tself_y <- as.matrix(dat[,label_self_y])\n\tother_y <- as.matrix(dat[,label_other_y])\n\tindicators_x <- as.matrix(dat[,label_indicators_x])\n\tindicators_y <- as.matrix(dat[,label_indicators_y])\n\tclusters <- as.vector(dat[,clustervar])\n\n\tll1 <- f.ll(estobj$retobj$par, y, self_x, other_x, self_y, other_y, indicators_x, indicators_y)\n\tif (abs(ll1 - estobj$retobj$value)>0.001) stop(paste(\"Saved loglik\", ll1, \"and computed loglik\", estobj$retobj$value, \"differ\"))\n\n\tsandwich <- f.sandwich(estobj$retobj$par, y, self_x, other_x, self_y, other_y,indicators_x, indicators_y, clusters) # sandwich part; see function below\n\n\tk <- length(estobj$retobj$par)\n\n\tvcm <- solve(-estobj$retobj$hessian)\n\tvcm <- sandwich$qc * (vcm %*% sandwich$sandwich %*% vcm)\n\n\tse <- sqrt(diag(vcm))\n\tse[k] <- sqrt( exp(estobj$retobj$par[k])^2 * se[k]^2 )\n\n\tpe <- estobj$retobj$par\n\tpe[k] <- exp(pe[k])\n\tout <- matrix(c(pe, se, pe/se, 2*(1-pnorm(abs(pe)/se))), k, 4, dimnames=list(c(paste(label_indicators_x,\"label_idicators_y\"),\"choicesens\"),c(\"point_estimates\",\"se_cluster\",\"z-stat_cluster\",\"p-val_cluster\")));\n\n\tcat(\"\\nNumber of clusters\", sandwich$j,\"\\n\")\n\tprint(round(out,3))\n\n\tlist(out=out, vcm=vcm[1:(k-1), 1:(k-1)])\n}\n\n# Sandwitch part for calculating cluster robust standard errors\nf.sandwich <- function(v, y, self_x, other_x, self_y, other_y,indicators_x, indicators_y, clusters) {\n\n\t#compute individual gradient contributions\n\tbeta <- v[1:(length(v)-1)]\n\tgamma <- exp(v[length(v)])\n\n\tlli <- indicators_x%*%beta;\n\trli <- indicators_y%*%beta;\n\tutl <- gamma*((1-lli)*self_x+lli*other_x)\n\tutr <- gamma*((1-rli)*self_y+rli*other_y)\n\tprobs <- (exp(utl)/(exp(utl)+exp(utr)))^y * (exp(utr)/(exp(utl)+exp(utr)))^(1-y);\n\tprobsm <- matrix(probs, nrow(indicators_x), ncol(indicators_x))\n\n\tu <- matrix(exp(utl) , nrow(indicators_x), ncol(indicators_x))\n\tw <- matrix(exp(utl) + exp(utr) , nrow(indicators_x), ncol(indicators_x))\n\tup <- gamma * indicators_x * matrix(other_x-self_x, nrow(indicators_x), ncol(indicators_x)) * u\n\twp <- up + gamma * indicators_y * matrix((other_y-self_y)*exp(utr), nrow(indicators_x), ncol(indicators_x))\n\n\tbgradi <- (-1)^(1-y)*((up*w - u*wp)/w^2)/probsm\n\n\tup2 <- utl * u[,1]\n\twp2 <- up2 + utr * exp(utr)\n\n\tggradi <- (-1)^(1-y) * (((up2*w[,1] - u[,1]*wp2)/w[,1]^2)/probs)\n\n\tgradi <- cbind(bgradi, ggradi)\n\n\t#Sandwich part of the sandwich VC estimator\n\tcl <- unique(clusters)\n\tj <- length(cl)\n\tk <- ncol(gradi)\n\n\tsandwich <- matrix(0, k, k)\n\tfor (i in 1:j) {\n\t\tsel <- clusters == cl[i]\n\t\tgradsel <- colSums(gradi[sel, ])\n\t\tsandwich <- sandwich + (gradsel %o% gradsel)\n\t}\n\n\tqc <- (length(y)-1) / (length(y)-k) * j/(j-1) #df adjustment\n\n\tlist(qc=qc, sandwich=sandwich, j=j)\n}\n\n# Estimation Function (to be called directly for aggregate estimations and by f.indivest for individual estimations)\nfdummy.estim <- function(dat, label_choice_x, label_indicators_x, label_indicators_y, label_self_x, label_other_x, label_self_y, label_other_y, silent=F, comp.se=T, v0=NULL) {\n\ty <- as.vector(dat[,label_choice_x])\n\tself_x <- as.matrix(dat[,label_self_x])\n\tother_x <- as.matrix(dat[,label_other_x])\n\tself_y <- as.matrix(dat[,label_self_y])\n\tother_y <- as.matrix(dat[,label_other_y])\n\tindicators_x <- as.matrix(dat[,label_indicators_x])\n\tindicators_y <- as.matrix(dat[,label_indicators_y])\n\n\tk <- length(label_indicators_x)+1\n\n\tif (is.null(v0)) {v0 <- c(rep(0,k-1), log(runif(1,.05,.8)/mean(c(mean(self_x),mean(other_x),mean(self_y),mean(other_y)))))} # Random start values if start values are not provided\n\tret <- optim(v0, f.ll, f.ll.gr, method=\"BFGS\", control=list(maxit=100000,trace=as.numeric(silent==F),REPORT=50, fnscale=-1), hessian=comp.se, y=y, self_x=self_x, other_x=other_x, self_y=self_y, other_y=other_y, indicators_x=indicators_x, indicators_y=indicators_y)\n\n\trawpe <- ret$par\n\tpe <- rawpe\n\tpe[k] <- exp(rawpe[k]) # Choice sensitivity > 0\n\n\tse <- rep(NA, k)\n\toverall.pval <- NA\n\tif(comp.se) {\n\t\trawse <- sqrt(diag( solve(-ret$hessian) ))\n\t\tse <- rawse\n\t\tse[k] <- sqrt( exp(rawpe[k])^2 * rawse[k]^2 ) #Delta method\n\n\t\tret2 <- optim(log(0.5/1000), f.ll.nopar, f.ll.gr.nopar, method=\"BFGS\", control=list(maxit=100000,trace=F,REPORT=50, fnscale=-1), hessian=F, y=y, self_x=self_x, self_y=self_y)\n\t\toverall.pval <- 1-pchisq(2*(ret$value-ret2$value),4)\n\t}\n\n\tout <- matrix(c(pe, se, pe/se, 2*(1-pnorm(abs(pe)/se))), k, 4, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"),c(\"point_estimates\",\"se_noCluster\",\"z-stat_noCluster\",\"p-val_noCluster\")))\n\n\tif (silent==F) {\n\t\tprint(paste(\"LogLik:\",ret$value), quote=F)\n\t\tprint(round(out,4))\n\t}\n\n\tlist(out=out, retobj=ret, overall.pval=overall.pval)\n}\nf.estim <- cmpfun(fdummy.estim)\n\n\n# Function for running individual estimations\nf.indivest <- function(dat){\n\n\t# Set up grid of start values (individual estimations are more fragile than pooled ones => test a lot of start values for each subject)\n\tv01 <- c(0,0,0,0)\n\tv02 <- c(.1,-.1,0,0)\n\tv03 <- c(.1,-.1,.01,-.01)\n\tv04 <- c(.1,-.1,-.01,.01)\n\tv05 <- c(-.1,.1,0,0)\n\tv06 <- c(-.1,.1,.01,-.01)\n\tv07 <- c(-.1,.1,-.01,.01)\n\tv00 <- matrix(c(v01,v02,v03,v04,v05,v06,v07),7,4,byrow=T)\n\terrv0 <- log(seq(0.0001, .001, length.out=20))\n\tirps <- 7*20 #140 estimation per subject with varying start values\n\n\tids <- sort(unique(dat$sid)) #Individual IDs\n\tj <- length(ids) #Number of individuals\n\n\tparset <- c(\"beta\", \"alpha\", \"gamma\", \"delta\", \"choicesens\")\n\tparmatrix <- matrix(NA, j, length(parset)+2, dimnames=list(ids, c(parset, \"loglik\", \"success\"))) # Matrix for saving the final estimation results for every subject\n\tparsubmatrix <- matrix(NA, irps, length(parset)+2, dimnames=list(NULL,c(parset, \"loglik\", \"success\"))) # Matrix for saving the estimation results for every start value combination in the grid of start values\n\n\t# Run the individual Estimations including all irps subreplications\n\tfor (i in 1:j) {\n\t\tidat <- dat[dat$sid == ids[i], ]\n\t\tcat(\"\\nEstimating individual:\", i,\"/\",j)\n\n\t\t# Cycle through all 140 start value combinations\n\t\tfor (s in 1:irps) {\n\t\t\tverr <- errv0[((s-1) %% 20) + 1] #start values for the choice sensitivity\n\t\t\tv <- v00[((s-1) %/% 20) +1,] #start values of the parameters\n\n\t\t\t#estimtion\n\t\t\tpe <- f.estim(idat, \"choice_x\", c(\"r_x\",\"s_x\",\"q\",\"v\"), c(\"r_y\",\"s_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", silent=T, comp.se=F, v0=c(v,verr))\n\t\t\tipar <- pe$out[,1]\n\t\t\till <- pe$retobj$value\n\t\t\tisuc <- as.numeric(pe$retobj$convergence == 0)\n\t\t\tparsubmatrix[s,] <- c(ipar, ill, isuc)\n\t\t}\n\n\t\t# Extract start values that led to the best estimation (i.e. the estimation with the highest log likelihood)\n\t\tv0 <- as.matrix(parsubmatrix[order(parsubmatrix[,\"loglik\"], decreasing=T),])[1,1:length(parset)]\n\t\tv0[length(v0)] <- log(v0[length(v0)]) # Choice sensitivty (last parameter in v0) is > 0\n\n\t\t# Redo best estimation\n\t\tpe <- f.estim(idat, \"choice_x\", c(\"r_x\",\"s_x\",\"q\",\"v\"), c(\"r_y\",\"s_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", silent=T, comp.se=F, v0=v0)\n\n\t\tparmatrix[i, 1:length(parset)] <- pe$out[,1] # save point estimates\n\t\tparmatrix[i, length(parset)+1] <- pe$retobj$value # save log likelihood\n\t\tparmatrix[i, length(parset)+2] <- as.numeric(pe$retobj$convergence == 0) # save success indicator\n\t}\n\n\tparmatrix\n}\n\n# Funtion that identifies subjects that behaved erraticly and exhibit individual parameter estimates outside the identifiable range\nf.droperratic <- function(par1, par2) {\n\n\trange <- c(-3,1) # Identifiable parameter range\n\n\tdrop <- matrix(NA, nrow(par1), 4, dimnames=list(rownames(par1),c()))\n\tfor (i in 1:4) {\n\t\tdrop[,i] <- (par1[,i] < range[1]) | (par1[,i] > range[2]) | (par2[,i] < range[1]) | (par2[,i] > range[2])\n\t}\n\n\trowSums(drop)\n}\n", "meta": {"hexsha": "f0ed6dd7bf915d65dfc67cbf0e61691252810b00", "size": 10838, "ext": "r", "lang": "R", "max_stars_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/99_estim_functions_aggregate_individual.r", "max_stars_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_stars_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-11-16T12:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:01:32.000Z", "max_issues_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/99_estim_functions_aggregate_individual.r", "max_issues_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_issues_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/99_estim_functions_aggregate_individual.r", "max_forks_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_forks_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-11-16T12:31:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T14:40:37.000Z", "avg_line_length": 39.8455882353, "max_line_length": 265, "alphanum_fraction": 0.6512271637, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6122964316446529}} {"text": "# Pull PWT into dataframe\ndata(\"pwt9.1\")\n\np <- pwt9.1 # copy dataframe for manipulation\np$lngdppc <- round(log(p$rgdpna) - log(p$pop),digits=2) # create log GDP per capita\np$lnpop <- round(log(p$pop),digits=2) # create log population\np$ky <- round(p$rnna/p$rgdpna,digits=2) # create K/Y ratio\np$phil <- round(p$labsh*p$rgdpna/(p$labsh*p$rgdpna+.05*p$rnna),digits=2) # create kludge cost share of labor\np <- \n p %>%\n group_by(isocode) %>%\n mutate(lag10.lngdppc = dplyr::lag(lngdppc, n = 10, default = NA))\np <- \n p %>%\n group_by(isocode) %>%\n mutate(lag10.lnpop = dplyr::lag(lnpop, n = 10, default = NA))\np$g10.lngdppc <- (p$lngdppc - p$lag10.lngdppc)/10\np$g10.lnpop <- (p$lnpop - p$lag10.lnpop)/10\np$lagyear <- p$year-10\np$csh_trade <- p$csh_x - p$csh_m\np$csh_mabs <- -1*p$csh_m\n\n# subset PWT into stable and catchup groups\nstable <- p[which(p$isocode %in% c(\"USA\", \"CAN\", \"MEX\", \"GBR\", \"AUS\")),]\ncatchup <- p[which(p$isocode %in% c(\"USA\", \"DEU\", \"JPN\", \"KOR\", \"CHN\",\"NGA\")),]\ntest <- p[which(p$isocode %in% c(\"ETH\", \"ZAF\",\"BWA\")),]\nusa <- p[which(p$isocode %in% c(\"USA\")),]\nall <- p[which(p$isocode %in% c(\"USA\", \"MEX\", \"DEU\",\"JPN\",\"KOR\",\"CHN\")),]\n\nfig <- plot_ly(usa, x = ~lagyear, y = ~g10.lnpop, color = ~country, type = 'scatter', mode='lines+markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Population growth rate', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = '10-year population growth rate', range=c(0,.02)))\napi_create(fig, filename = \"pwt-usa-pop-growth\")\n\nfig <- plot_ly(all, x = ~csh_g, y = ~g10.lngdppc, color = ~country, type = 'scatter', mode='markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Government and growth', x=0),\n xaxis = list(title = 'Gov. spending share of GDP'),\n yaxis = list (title = '10-year growth rate'))\napi_create(fig, filename = \"pwt-all-cshg-growth\")\n\nfig <- plot_ly(all, x = ~csh_g, y = ~lngdppc, color = ~country, type = 'scatter', mode='markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Government and level of GDP per capita', x=0),\n xaxis = list(title = 'Gov. spending share of GDP'),\n yaxis = list (title = 'Log GDP per capita'))\napi_create(fig, filename = \"pwt-test-chsg-level\")\n\nus <- p[which(p$isocode %in% c(\"USA\")),]\nfig <- plot_ly(us, x = ~lagyear, y = ~g10.lngdppc, type = 'scatter', mode='lines+markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = '10-year growth rate', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = '10-year growth rate', range=c(0,.04)))\napi_create(fig, filename = \"pwt-usa-growth-rate\")\n\nfig <- plot_ly(all, x = ~csh_trade, y = ~lngdppc, color = ~country, type = 'scatter', mode='markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Trade and level of GDP per capita', x=0),\n xaxis = list(title = '(Exports+Imports) as share of GDP'),\n yaxis = list (title = 'Log GDP per capita'))\napi_create(fig, filename = \"pwt-all-trade-level\")\n\nfig <- plot_ly(all, x = ~csh_x, y = ~lngdppc, color = ~country, type = 'scatter', mode='markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Exports and level of GDP per capita', x=0),\n xaxis = list(title = 'Exports as share of GDP'),\n yaxis = list (title = 'Log GDP per capita'))\napi_create(fig, filename = \"pwt-all-export-level\")\n\nfig <- plot_ly(all, x = ~csh_mabs, y = ~lngdppc, color = ~country, type = 'scatter', mode='markers', colors = \"Set1\")\nfig <- layout(fig, title = list(text = 'Imports and level of GDP per capita', x=0),\n xaxis = list(title = 'Imports as share of GDP'),\n yaxis = list (title = 'Log GDP per capita'))\napi_create(fig, filename = \"pwt-all-imports-level\")\n\n\n############################\n# Figures for log GDP per capita\n############################\nfig <- plot_ly(test, x = ~year, y = ~lngdppc, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Log GDP per capita', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Log GDP per capita', range=c(6,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-test-lngdppc\")\n\nfig <- plot_ly(stable, x = ~year, y = ~lngdppc, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for stable growth countries', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Log GDP per capita', range=c(6,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-stable-lngdppc\")\n\nfig <- plot_ly(catchup, x = ~year, y = ~lngdppc, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Log GDP per capita for catch-up growth countries', x=0), \n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Log GDP per capita', range=c(6,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-catchup-lngdppc\")\n\n############################\n# Figures of labor share\n############################\n\nfig <- plot_ly(stable, x = ~year, y = ~labsh, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Compensation/GDP for stable growth countries', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Compensation share of GDP', range=c(0,1)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-stable-labsh\")\n\nfig <- plot_ly(catchup, x = ~year, y = ~labsh, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Compensation/GDP for catch-up growth countries', x=0), \n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Compensation share of GDP', range=c(0,1)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-catchup-labsh\")\n\n############################\n# Figures of labor cost share\n############################\n\nfig <- plot_ly(stable, x = ~year, y = ~phil, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Compensation/Total Costs', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'W/(W+RK)', range=c(0,1)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-stable-phil\")\n\nfig <- plot_ly(catchup, x = ~year, y = ~phil, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Compensation/Total Costs', x=0), \n xaxis = list(title = 'Year'),\n yaxis = list (title = 'W/(W+RK)', range=c(0,1)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-catchup-phil\")\n\n############################\n# Figures of convergence\n############################\n# get 10-year lagged value of log gdppc, by country\np <- \n p %>%\n group_by(isocode) %>%\n mutate(lag10.lngdppc = dplyr::lag(lngdppc, n = 10, default = NA))\np$g10.lngdppc <- (p$lngdppc - p$lag10.lngdppc)/10\n\n# just need the catchup group\ncatchup <- p[ which(p$isocode %in% c(\"USA\", \"DEU\", \"JPN\", \"KOR\", \"CHN\",\"NGA\")),]\n\npal <- c('#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#ffff33')\npal <- setNames(pal, c(\"CHN\", \"DEU\", \"JPN\",\"KOR\",\"NGA\",\"USA\"))\nfig <- plot_ly(catchup, x = ~lag10.lngdppc, y = ~g10.lngdppc, text=~year,\n color = ~isocode, \n colors = pal, \n type = 'scatter',\n mode = 'markers',\n hovertemplate = paste(\"%{text}
\",\n \"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\"),\n marker = list(size = 7)\n )\nfig <- layout(fig, title=list(text = 'Convergence and non-convergence', x= 0),\n xaxis = list(title = 'Initial log GDP per capita',range=c(6,11)),\n yaxis = list (title = '10-year growth rate')\n )\napi_create(fig, filename = \"pwt-catchup-convergence\")\n\n############################\n# Figures of K/Y ratio\n############################\np1960 <- p[which(p$year >1959),] # drop 50-59 b/c of PWT initial ky guess\nstable <- p1960[ which(p1960$isocode %in% c(\"USA\", \"CAN\", \"MEX\", \"GBR\", \"AUS\")),]\ncatchup <- p1960[ which(p1960$isocode %in% c(\"USA\", \"DEU\", \"JPN\", \"KOR\", \"CHN\",\"NGA\")),]\n\nfig <- plot_ly(stable, x = ~year, y = ~ky, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Capital/output ratio for stable countries', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Capital/output ratio',range=c(0,7)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-stable-ky\")\n\nfig <- plot_ly(catchup, x = ~year, y = ~ky, linetype = ~country, type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Capital/output ratio for catch-up countries', x=0),\n xaxis = list(title = 'Year'),\n yaxis = list (title = 'Capital/output ratio',range=c(0,7)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"pwt-catchup-ky\")\n\n", "meta": {"hexsha": "05fa9912d31e2e2be47d121c254332a154056caa", "size": 9264, "ext": "r", "lang": "R", "max_stars_repo_path": "dump/Guide_PWT_Facts.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "dump/Guide_PWT_Facts.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dump/Guide_PWT_Facts.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 49.8064516129, "max_line_length": 124, "alphanum_fraction": 0.572970639, "num_tokens": 2804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6122085143329247}} {"text": "# James Rekow\r\n\r\n## Contains several simple functions used in the DOC analysis.\r\n\r\noverlapSet = function(x, y){\r\n xPresent = x > 0\r\n yPresent = y > 0\r\n return(xPresent & yPresent)\r\n} # end overlapSet\r\n\r\nnormalize = function(x){\r\n return(x / sum(x))\r\n} # end normalize\r\n\r\n# This function does not assume the data is normalized\r\noverlap = function(x, y){\r\n \r\n x = normalize(x)\r\n y = normalize(y)\r\n \r\n bothPresent = overlapSet(x, y)\r\n return(0.5 * sum(x[bothPresent] + y[bothPresent]))\r\n \r\n} # end overlap\r\n\r\n# This function does not assume the data is normalized\r\nDrJSD = function(x, y){\r\n \r\n bothPresent = overlapSet(x, y)\r\n x = normalize(x[bothPresent])\r\n y = normalize(y[bothPresent])\r\n m = 0.5 * (x + y)\r\n \r\n if(sum(m) == 0){\r\n return(0)\r\n }\r\n \r\n return(sqrt(0.5 * (sum(x * log(x / m) + y * log(y / m)))))\r\n \r\n} # end DrJSD\r\n", "meta": {"hexsha": "3aa01aacd55839c8fc1338de94254dccd01a468c", "size": 860, "ext": "r", "lang": "R", "max_stars_repo_path": "universality_functions.r", "max_stars_repo_name": "JamesRekow/GLV_Model", "max_stars_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "universality_functions.r", "max_issues_repo_name": "JamesRekow/GLV_Model", "max_issues_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-08T20:21:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T20:21:25.000Z", "max_forks_repo_path": "universality_functions.r", "max_forks_repo_name": "JamesRekow/GLV_Model", "max_forks_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9756097561, "max_line_length": 64, "alphanum_fraction": 0.5895348837, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6120149692393171}} {"text": "metrop_hastings<-function(x_0, iter=1, log_post_density,\n proposal_dist = function(x, prop_sigma){ \n MASS::mvrnorm(1, mu = x, Sigma = prop_sigma )\n }, \n lower=-Inf, upper=Inf, prop_sigma,\n ... ){\n for(i in 1:iter){\n # draw from proposal distribution\n x_star <- proposal_dist(x_0, prop_sigma) \n \n # calculate ratio of conditional posterior densities\n r_num <- do.call(log_post_density, c(list(x_star), list(...)) )\n r_denom <- do.call(log_post_density, c(list(x_0), list(...)) )\n r <- exp(r_num - r_denom)\n rmin<-min(r,1)\n if(is.na(rmin)) browser()\n # accept / reject proposal\n if(rbinom(1,1,rmin)==1){ \n x_0<-x_star\n }\n }\n \n res<-list(x_0 = x_0, accept_prob = rmin )\n return(res)\n}", "meta": {"hexsha": "ba91e7298c9ba3c6dda459a1ea17c4cd13613495", "size": 854, "ext": "r", "lang": "R", "max_stars_repo_path": "R/metropolis_hastings.r", "max_stars_repo_name": "lagvier/ChiRP", "max_stars_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-02-26T03:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T09:19:11.000Z", "max_issues_repo_path": "R/metropolis_hastings.r", "max_issues_repo_name": "lagvier/ChiRP", "max_issues_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-02-24T19:32:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-22T01:26:40.000Z", "max_forks_repo_path": "R/metropolis_hastings.r", "max_forks_repo_name": "lagvier/ChiRP", "max_forks_repo_head_hexsha": "48504130a909a5b46105ba13da8e0d50405d5beb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2019-03-03T19:25:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T18:03:51.000Z", "avg_line_length": 34.16, "max_line_length": 73, "alphanum_fraction": 0.5351288056, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440397949314, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.6119598237388434}} {"text": "BBOD <- function(B,By,y,max_price, OD){\n if(OD == \"o\"){\n func = 0.2*B+By*y\n } else{\n func = max_price-0.3072734*B+0.5*By*y\n func[func>max_price] = max_price\n }\n return(func)\n}\n\nBBPlot <- function(input,output,values){\n bonds = seq(0,200,length.out = 100)\n to_plot = data.frame(bonds = bonds)\n\n eq_Pb = BBOD(values$eq$B,input$by,values$eq$y,input$max_price, \"o\")\n fig = plot_ly(to_plot, x = ~bonds)\n fig = fig %>% add_trace(y = BBOD(bonds,input$by,values$eq$y,input$max_price,\"o\"), type = \"scatter\", mode = \"lines\", name = \"$$B^s(N)$$\", line = list(color = \"blue\"),\n hovertemplate = paste(\"Bs=%{x:.0f}\",\"
Pb=%{y:.0f}\",\"\"))\n fig = fig %>% add_trace(y = BBOD(bonds,input$by,values$eq$y,input$max_price,\"d\"), type = \"scatter\", mode = \"lines\", name = \"$$B^d(N)$$\", line = list(color = \"red\"),\n hovertemplate = paste(\"Bd=%{x:.0f}\",\"
Pb=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(0,eq_Pb,max(bonds),eq_Pb, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"B*=%{x:.0f}\",\"
Pb*=%{y:.0f}\",\"\")) \n fig = fig %>% add_segments(values$eq$B,0,values$eq$B,eq_Pb, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"B*=%{x:.0f}\",\"
Pb*=%{y:.0f}\",\"\"))\n \n eq_label = list(\n x = values$eq$B,\n y = eq_Pb,\n text = paste0(\"B*=\",round(values$eq$B),\", Pb*=\",round(eq_Pb))\n )\n fig = fig %>% layout(annotations = eq_label)\n \n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n empLevel <- list(\n title = \"Nombre de titres en circulation, B\",\n titlefont = f\n )\n salReels <- list(\n title = \"Prix des titres, Pb (inverse de r)\",\n titlefont = f,\n range = c(70,110)\n )\n fig = fig %>% layout(xaxis = empLevel, yaxis = salReels)\n}\n\nRPBPlot <- function(input,output,values){\n r = seq(0,20,length.out = 1000)\n to_plot = data.frame(interest = r)\n\n eq_Pb = BBOD(values$eq$B,input$by,values$eq$y,input$max_price, \"o\")\n eq_R = values$eq$r\n fig = plot_ly(to_plot, x = ~interest)\n fig = fig %>% add_trace(y = 100/(r/100+1), type = \"scatter\", mode = \"lines\", name = \"$$\\\\frac{100}{r+1}$$\", line = list(color = \"gold\"),\n hovertemplate = paste(\"r=%{x:.1f}\",\"
Pb=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(0,eq_Pb,eq_R,eq_Pb, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"B*=%{x:.0f}\",\"
Pb*=%{y:.0f}\",\"\"))\n fig = fig %>% add_segments(eq_R,0,eq_R,eq_Pb, line = list(color = 'rgb(200, 0, 0)', width = 1, dash = 'dash'), showlegend = FALSE,\n hovertemplate = paste(\"B*=%{x:.0f}\",\"
Pb*=%{y:.0f}\",\"\"))\n\n eq_label = list(\n x = eq_R,\n y = eq_Pb,\n text = paste0(\"r*=\",round(eq_R,1),\", Pb*=\",round(eq_Pb))\n )\n fig = fig %>% layout(annotations = eq_label)\n\n f <- list(\n family = \"Courier New, monospace\",\n size = 18,\n color = \"#7f7f7f\"\n )\n empLevel <- list(\n title = \"Taux d'intérêt, r\",\n titlefont = f\n )\n salReels <- list(\n title = \"Prix des titres, Pb\",\n titlefont = f\n )\n fig = fig %>% layout(xaxis = empLevel, yaxis = salReels)\n}\n", "meta": {"hexsha": "243b73e9a96895607a440be033ea9360f8e3cc4e", "size": 3412, "ext": "r", "lang": "R", "max_stars_repo_path": "src/BB_functions.r", "max_stars_repo_name": "placardo/macro_monetaire", "max_stars_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BB_functions.r", "max_issues_repo_name": "placardo/macro_monetaire", "max_issues_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BB_functions.r", "max_forks_repo_name": "placardo/macro_monetaire", "max_forks_repo_head_hexsha": "d43c7cd0ee766a6da2b36a51ff26380be3bf4c4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6744186047, "max_line_length": 167, "alphanum_fraction": 0.5486518171, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6116207380986377}} {"text": "png(\"pdqr.png\",width = 1250,height = 500)\r\npar(xpd = TRUE,mfrow = c(1,2), mar = c(4,2,0,3))\r\n## Normal dist.\r\nset.seed(1234)\r\nx <- sort(rnorm(1000))\r\nplot(x,dnorm(x),type = \"l\",axes = FALSE,xlab = \"\",ylab = \"\",lwd = 3)\r\nn <- 200\r\np <- x[n]\r\n## rnorm\r\ncol <- grey.colors(1,alpha = 0.1)\r\nh <- hist(x,add = TRUE,freq = FALSE,border = col,cex = 2,col = col)\r\ntext(h$breaks[14],h$density[10],cex = 2,\"rnorm\")\r\narrows(h$breaks[13],h$density[10],h$breaks[11],h$density[10],col = 'lightgrey',lwd = 3)\r\n## pnorm\r\npolygon(c(x[x <= p],rev(x[x <= p])),c(rep(0,length(x[x<=p])),dnorm(rev(x[x<=p]))),col = \"grey\")\r\ntext(x[n/2],dnorm(x[n/2])/2,\"pnorm\",cex = 2)\r\n## qnorm\r\narrows(p,0,p,dnorm(p),lwd = 3,lty = 2,code = 0)\r\ntext(p,0 - 0.025,\"qnorm\",cex = 2)\r\n## dnorm\r\narrows(min(x),dnorm(p),p,dnorm(p),code = 0, lwd = 3,lty = 3)\r\ntext(min(x) - 0.5,dnorm(p),\"dnorm\",cex = 2,srt = 90)\r\n## redo dnorm\r\nlines(x,dnorm(x),lwd = 3)\r\n\r\n## Poisson\r\nset.seed(4321)\r\nlam <- 2.5\r\nx <- sort(rpois(1000,lam))\r\nb <- barplot(dpois(unique(x),lam),axes = FALSE,col = col,border = col,\r\n ylim = c(-0.03,max(dpois(unique(x),lam))) + 0.02)\r\npoints(b[,1],dpois(unique(x),lam),cex = 3,pch = 20)\r\n## rpois\r\ntext(b[8,1],dpois(unique(x)[5],lam),\"rpois\",cex = 2)\r\narrows(b[8,1],dpois(unique(x)[5],lam) - 0.01,\r\n b[6,1] + 0.5,dpois(unique(x)[7],lam) + 0.01,col = \"lightgrey\",lwd = 3)\r\n## dpois\r\ntext(b[8,1],dpois(unique(x)[4],lam),\"dpois\",cex = 2)\r\narrows(b[7,1],dpois(unique(x)[4],lam),b[4,1],dpois(unique(x)[4],lam),code = 0,lwd = 3, lty = 3)\r\n## qpois\r\ntext(b[4,1],-0.01,\"qpois\",cex = 2)\r\narrows(b[4,1],dpois(unique(x)[4],lam),b[4,1],0,code = 0,lwd = 3, lty = 2)\r\n## ppois\r\nbarplot(dpois(unique(x)[1:2],lam),col = \"grey\",add = TRUE,border = \"grey\",axes = FALSE)\r\ntext(mean(b[1:2,1]),dpois(unique(x)[1],lam)/2,\"ppois\",cex = 2)\r\n## redo dpois\r\npoints(b[,1],dpois(unique(x),lam),cex = 3,pch = 20)\r\ndev.off()\r\n", "meta": {"hexsha": "74709ab031bbc581554e5bf271cfd4e7eceb92d8", "size": 1882, "ext": "r", "lang": "R", "max_stars_repo_path": "r_scripts/pdqr.r", "max_stars_repo_name": "statbiscuit/swots", "max_stars_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-02-22T02:58:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-22T03:01:46.000Z", "max_issues_repo_path": "r_scripts/pdqr.r", "max_issues_repo_name": "cmjt/statbiscuits", "max_issues_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r_scripts/pdqr.r", "max_forks_repo_name": "cmjt/statbiscuits", "max_forks_repo_head_hexsha": "005da6fdb980e6cbb40f407e059623256f9c0626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4081632653, "max_line_length": 96, "alphanum_fraction": 0.5733262487, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6113057003986777}} {"text": "#' Gradient function for negative binomial regression\n#'\n#' The following variables need to be available to the function in order to\n#' be able to call `optim` using this as a gradient function:\n#'\n#' x - Regression coefficients matrix\n#' beta - Regressors, such that beta * x = y\n#' y - Observed count values\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 direction of steepest descent (the gradient)\ngradient = 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 (all(mu >= 0)) {\n grc = drop(.y - mu * (.y + theta)/(mu + theta))\n grt = digamma(.y + theta) - digamma(theta) +\n log(theta) + 1 - log(mu + theta) - (.y + theta)/(mu + theta)\n gr = -colSums(weights * cbind(grc * .x, grt * theta))\n } else {\n gr = c(-beta, 0) # trivial solution for mu=0\n }\n\n if (.verbose)\n message(\"gr: \", paste(sprintf(\"%.2f\", gr), collapse=\", \"))\n gr\n}\n", "meta": {"hexsha": "3c96720ea3d2d226e3e569e160ff26f4a61cc714", "size": 1337, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gradient.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/gradient.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/gradient.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": 37.1388888889, "max_line_length": 83, "alphanum_fraction": 0.6043380703, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6112023819921616}} {"text": "# Enter your code here. Read input from STDIN. Print output to STDOUT\r\ngirlprob <- 1 / 2.09\r\nanswer <- pbinom(3, size = 6, prob = girlprob)\r\nwrite(round(answer, 3), stdout())", "meta": {"hexsha": "e230bb9bc7dcee1e580df6604f47b0b59a014627", "size": 174, "ext": "r", "lang": "R", "max_stars_repo_path": "binomial-distribution-2/accepted_solutions/18989241.r", "max_stars_repo_name": "hermes-jr/my-hackerrank-solutions", "max_stars_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "binomial-distribution-2/accepted_solutions/18989241.r", "max_issues_repo_name": "hermes-jr/my-hackerrank-solutions", "max_issues_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "binomial-distribution-2/accepted_solutions/18989241.r", "max_forks_repo_name": "hermes-jr/my-hackerrank-solutions", "max_forks_repo_head_hexsha": "29508ad9f2afe6977b1b00f30449a6192d72b3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5, "max_line_length": 70, "alphanum_fraction": 0.683908046, "num_tokens": 55, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6112023756232791}} {"text": "# R program - Linear Regression and Lasso Regression\n\n# Read the datasets\ndata_train <- read.csv(\"/Project data analysis for business/train.csv\")\ndata_test <- read.csv(\"/Project data analysis for business/test.csv\")\n\n# Split Train and Test using sample()\ntrain <- sample(1:nrow(data_train), nrow(data_train)/2)\ntest <- (-train)\n\n# Exploratory Data Analysis: verify correlation between the response SalePrice and every other predictor\npdf(\"my_plot.pdf\")\npar(mfrow = c(4,3))\nfor(i in 1:ncol(data_train)){\nplot(data_train[,i], data_train$SalePrice, xlab=names(data_train[i]),\nylab=\"SalePrice\", pch=20)\n}\ndev.off()\n\n# Print how many NAs there are inside each predictor column\nfor (i in 1:ncol(data_train)){\n n <- sum(is.na(data_train[,i]))\n if (n > 100){\n cat(\"[\", i, \"]: \", n, \"\\n\")\n }\n}\n\n# Remove predictors that shows a number of NAs > 500.\nindexes_NA <- c() #boolean vector: TRUE means that\npredictor i has NA values\nfor (i in 1:ncol(data_train)){\n n <- sum(is.na(data_train[,i]))\n if (n > 500){\n indexes_NA <- c(indexes_NA, TRUE)\n }\n else{ indexes_NA <- c(indexes_NA, FALSE) }\n}\n#remove:\ndata_train <- data_train[,!indexes_NA]\n\n# Remove the predictor \"Utilities\", which contains only one level of factor.\ndata_train$Utilities <- NULL\n\n# Solve other NAs issues\ndata_train$GarageFinish <- as.character(data_train$GarageFinish)\ndata_train$GarageFinish[is.na(data_train$GarageFinish)] <- \"No\"\ndata_train$GarageFinish <- as.factor(data_train$GarageFinish)\ndata_train$GarageQual <- as.character(data_train$GarageQual) > data_train$GarageQual[is.na(data_train$GarageQual)] <- \"No\"\ndata_train$GarageQual <- as.factor(data_train$GarageQual)\ndata_train$GarageYrBlt[is.na(data_train$GarageYrBlt)] <- 0\ndata_train$MasVnrArea[is.na(data_train$MasVnrArea)] <- mean(data_train$MasVnrArea, na.rm = TRUE) #substitute with mean\ndata_train$LotFrontage[is.na(data_train$LotFrontage)] <- mean(data_train$LotFrontage, na.rm = TRUE)\ndata_train$Electrical[is.na(data_train$Electrical)] <- \"SBrkr\"\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++\n# MODEL 1 - Fitting a Linear Regression\n\nlm.fit <- lm(SalePrice~., data=data_train[train,])\nsummary(lm.fit)\n\n# Compute \"studentized residuals\" to identify outliers\nout <- abs(rstudent(lm.fit))\nfor(i in 1:length(out)){\n if(out[i] > 3){ print(out[i]) }\n}\n\nlm.fit <- lm(SalePrice ~ KitchenQual + X2ndFlrSF + X1stFlrSF + BsmtQual\n+ MasVnrArea + OverallQual + OverallCond + LotArea + HouseStyle +\nLotFrontage + YearBuilt +TotalBsmtSF, data = data_train[train,])\n\n# Compute the Variance Inflaction Factor (VIF) to detect collinearity\nlibrary(car)\nvif(lm.fit)\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++\n# K-Fold Cross-Validation\n\nmse.lm <- rep(0,10)\nfor(i in 1:10){\n set.seed(i)\n train <- sample(1:nrow(data_train), nrow(data_train)/2)\n test <- (-train)\n y <- data_train[test,]$SalePrice\n lm.fit <- lm(SalePrice ~ KitchenQual + X2ndFlrSF + X1stFlrSF +\nBsmtQual + MasVnrArea + OverallQual + OverallCond + LotArea +\nHouseStyle + LotFrontage + YearBuilt +TotalBsmtSF, data =\ndata_train[train,])\n pred <- predict(lm.fit, data_train[test,])\n mse.lm[i] <- mean((y - pred)^2)\n}\nprint(sqrt(mean(mse.lm)))\n# Average RMSE is 29,826.37\n\n\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++\n# MODEL 2 - Fitting the Lasso\n\ninstall.packages(\"glmnet\")\nlibrary(glmnet)\n\nmse.lasso <- rep(0,10)\nfor (i in 1:10){\n x <- model.matrix(SalePrice~., data_train)[,-1] #Predictors\n y <- data_train$SalePrice #Response\n set.seed(i)\n train <- sample(1:nrow(x), nrow(x)/2) #split train and test\n test <- (-train)\n y.test = y[test]\n lasso.mod <- glmnet(x[train,], y[train], alpha=1) #fitting a lasso model\n cv.out <- cv.glmnet(x[train,], y[train], alpha=1) #find best lambda\n bestlam <- cv.out$lambda.min\n lasso.pred <- predict(lasso.mod, s=bestlam, newx=x[test,])\n mse.lasso[i] <- mean((y.test - lasso.pred)^2)\n}\nprint(sqrt(mean(mse.lasso)))\n# Average MSE is 26,409.52\n\n\n\n\n# R-squared\nrsq <- function(predicted, actual){\n mean <- mean(actual)\n tss <- 0\n rss <- 0\n for(i in 1:length(predicted)){\n tss <- tss + (actual[i] - mean)^2\n rss <- rss + (actual[i] - predicted[i])^2\n}\n rs <- 1 - rss/tss\n}\n\n\n# Compute R-squared among 10 different dataset splits\nrs.lasso <- rep(0,10)\nfor (i in 1:10){\n x <- model.matrix(SalePrice~., data_train)[,-1] #Predictors\n y <- data_train$SalePrice #Response\n set.seed(i)\n train <- sample(1:nrow(x), nrow(x)/2) #split train and test\n test <- (-train)\n y.test = y[test]\n lasso.mod <- glmnet(x[train,], y[train], alpha=1) #fitting a lasso model\n cv.out <- cv.glmnet(x[train,], y[train], alpha=1) #find best lambda\n bestlam <- cv.out$lambda.min\n lasso.pred <- predict(lasso.mod, s=bestlam, newx=x[test,])\n rs.lasso[i] <-rsq(lasso.pred, y.test)\n}\nprint(sqrt(mean(rs.lasso)))\n# R2 is 0.94\n\n\n\n", "meta": {"hexsha": "886d385a95bfdf243d29a5556e0edeb08332ef00", "size": 4975, "ext": "r", "lang": "R", "max_stars_repo_path": "predict-price.r", "max_stars_repo_name": "paglia22/predict-house-price", "max_stars_repo_head_hexsha": "b7bc1d0e1c0dfc933ba73b8cc249c857ab1dd7ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "predict-price.r", "max_issues_repo_name": "paglia22/predict-house-price", "max_issues_repo_head_hexsha": "b7bc1d0e1c0dfc933ba73b8cc249c857ab1dd7ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predict-price.r", "max_forks_repo_name": "paglia22/predict-house-price", "max_forks_repo_head_hexsha": "b7bc1d0e1c0dfc933ba73b8cc249c857ab1dd7ba", "max_forks_repo_licenses": ["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.09375, "max_line_length": 122, "alphanum_fraction": 0.6436180905, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6110246588328252}} {"text": "#Napoved ekoloških izdatkov Slovenije v prihodnjih letih =======================================\neko.potrosnja.slovenija <- eko.potrosnja %>%\n filter(Drzava == 'Slovenia') %>%\n transform(Izdatki.za.ekologijio = Izdatki.za.ekologijio / 1000)\n\nnapoved <- lm(data=eko.potrosnja.slovenija, eko.potrosnja.slovenija$Izdatki.za.ekologijio ~Leto)\ndodatna.leta <- data.frame(Leto=seq(2017,2021,1))\nnapoved.potrosnje <- mutate(dodatna.leta, Izdatki.za.ekologijio=predict(napoved, dodatna.leta))\n\ngraf.napovedi.praga.slo <- ggplot(eko.potrosnja.slovenija, aes(x=Leto, y=Izdatki.za.ekologijio)) + \n geom_smooth(method=lm, fullrange=TRUE, color='yellow') + \n geom_point(data=napoved.potrosnje, inherit.aes=TRUE, colour=\"red\") + \n geom_point() + \n scale_x_continuous('Leto', breaks=seq(2008, 2021, 1), limits=c(2008, 2021)) +\n ggtitle('Napoved izdatkov za ekologijo Slovenije v letih 2017-2021') + \n theme(plot.title=element_text(hjust=0.5, size=15, face=\"bold\")) +\n theme_bw() +\n xlab(\"Leto\") + \n ylab(\"Izdatki za ekologijo v milijardah €\")\n\n# plot(graf.napovedi.praga.slo)\n\n\n##Napoved ekoloških izdatkov Nemčije v prihodnjih letih =======================================\neko.potrosnja.nemcija <- eko.potrosnja %>% \n filter(Drzava == 'Germany') %>% \n transform(Izdatki.za.ekologijio = Izdatki.za.ekologijio / 1000)\n\nnapoved <- lm(data=eko.potrosnja.nemcija, eko.potrosnja.nemcija$Izdatki.za.ekologijio ~Leto)\ndodatna.leta <- data.frame(Leto=seq(2017,2021,1))\nnapoved.potrosnje <- mutate(dodatna.leta, Izdatki.za.ekologijio=predict(napoved, dodatna.leta))\n\ngraf.napovedi.praga.nem <- ggplot(eko.potrosnja.nemcija, aes(x=Leto, y=Izdatki.za.ekologijio)) + \n geom_smooth(method=lm, fullrange=TRUE, color=\"yellow\") + \n geom_point(data=napoved.potrosnje, inherit.aes=TRUE, colour=\"red\") + \n geom_point() + \n scale_x_continuous('Leto', breaks = seq(2008, 2021, 1), limits=c(2008, 2021)) +\n ggtitle('Napoved izdatkov za ekologijo Nemčije v letih 2016-2020') + \n theme(plot.title=element_text(hjust=0.5, size=15, face=\"bold\")) +\n theme_bw() +\n xlab(\"Leto\") + \n ylab(\"Izdatki za ekologijo v milijardah €\")\n\n# plot(graf.napovedi.praga.nem)\n", "meta": {"hexsha": "8088849763b7b31deea6a481c9190e96d28b331d", "size": 2138, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "matejske/APPR-2019-20", "max_stars_repo_head_hexsha": "e8613c28623733815a6e47675ff2b5f516aec2b8", "max_stars_repo_licenses": ["MIT"], "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": "matejske/APPR-2019-20", "max_issues_repo_head_hexsha": "e8613c28623733815a6e47675ff2b5f516aec2b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-10-12T15:42:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-07T18:07:23.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "matejske/APPR-2019-20", "max_forks_repo_head_hexsha": "e8613c28623733815a6e47675ff2b5f516aec2b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5111111111, "max_line_length": 99, "alphanum_fraction": 0.7011225444, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.6109807320023353}} {"text": "# COVID-19\n#\n# Estimación de los parametros de una exponecial/ logistica, el factor de crecimiento\n# También para los casos de contacto directo\n#\n# Fuente @msalnacion \n#\n\nrequire(dplyr)\nrequire(readr)\nrequire(lubridate)\ncor <- read_csv(\"/home/leonardo/Academicos/GitProjects/covid19/coronavirus_ar.csv\") %>% dplyr::select(fecha:comunitarios)\ncor <- cor %>% mutate(fecha=ymd(fecha), dias =as.numeric( fecha - min(fecha))) \n#\n# OJO, los casos en estudio = ? comunitarios no estan acumulados\n#\n\nrequire(ggplot2)\n\n# g0 <- ggplot(cor,aes(x=dias,y=casos)) + geom_point() + theme_bw() + geom_smooth(method=\"glm\",family=gaussian(link=\"log\")) \n# g1 <- g0 + expand_limits(x=c(0,240))+\n# geom_smooth(method=\"glm\",family=gaussian(link=\"log\"),\n# fullrange=TRUE)\n\n# Comparación de distintos modelos utilizando el criterio de Akaike (lineal y exponencial nomas)\n#\nexpmdl <- lm(log(casos)~ dias,data=cor)\nsummary(expmdl)\nlinmdl <- lm(casos~ dias,data=cor)\nsummary(linmdl)\nAIC(linmdl,expmdl)\n\n# Ajuste no-lineal del los parametros del modelo exponencial\n#\nmodel <- nls(casos ~ alpha * exp(beta * dias) , data =cor , start=list(alpha=0.6,beta=0.4))\n# Ajuste del modelo logístico\nrequire(drc)\n#\n# f(x) = d / (1+exp(b(x - e)))\n#\nmodel1 <- drm(casos ~ dias, fct=L.3() , data = cor)\nsummary(model1)\ncapacidadcarga <- round(coef(model1)[2])\nAIC(model,model1)\n# Despues del dia 21 El ajuste del modelo logístico es mejor \n# En el dia 21 todavia ajustaba mejor el modelo exponencial\n#\n\n# Extraigo los coeficientes para ponerlos en el gráfico\n#\nmodel <- nls(casos ~ alpha * exp(beta * dias) , data = filter(cor, dias<22) , start=list(alpha=0.6,beta=0.4))\n\na <- round(coef(model)[1],2)\nb <- round(coef(model)[2],2)\nsummary(model)\n# Tiempo de duplicacion\n#\ntau <- round(log(2)/b,2)\n\n# Prediccion hasta 12/04\n#\nldia <- as.numeric(ymd(\"2020-04-12\") - min(cor$fecha))\npredexp <-data.frame(pred=predict(model,newdata=data.frame(dias=0:ldia)),predlog = predict(model1,newdata=data.frame(dias=0:ldia))) %>% mutate(dias=0:ldia, fecha=min(cor$fecha)+dias)\npredexp\n# Estimación de R0\n#\n#\n# Generation time from\n# https://github.com/midas-network/COVID-19/tree/master/parameter_estimates/2019_novel_coronavirus\n# \nrequire(R0)\nmGT<-generation.time(\"gamma\", c(7.5, 3.4))\nest.R0.EG(cor$casosdia,mGT,begin = 1,end=22)\n\ntl <- est.R0.ML(cor$casosdia,mGT,begin = 1,end=22)\n#plotfit(tl)\nr <- round(tl$R,2)\nr0 <- round(tl$conf.int,2)\n\ncol <- viridisLite::viridis(2)\n# Casos totales\n#\nggplot(cor, aes(x = fecha, y = casos) ) +\n geom_point() +\n# geom_ribbon( aes(ymin = lwr, ymax = upr), alpha = .15) +\n geom_line(data=predexp, aes(x=fecha,y = pred), size = .5, color= col[1]) + \n geom_line(data=predexp, aes(x=fecha,y = predlog), size = .5, color= col[2]) + theme_bw() + \n annotate(\"text\",x=ymd(\"20200330\"), y=1, label=\"Fuente @msalnacion\\n by @larysar\",color=\"red\",size=2) + scale_y_log10() + \n annotate(\"text\", x=ymd(\"20200325\"), y=3,label=paste(\"R0 =\", r, \"[\", r0[1], \",\", r0[2],\"]\"),size=3) + \n annotate(\"text\", x=ymd(\"20200325\"), y=2,label=paste(\"Capacidad de carga =\", capacidadcarga),size=3)\n\nggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaArTotalesLog.jpg\",width=6,height=6,units=\"in\",dpi=600)\n\n# Growth Factor para casos totales\n#\ncor <- cor %>% mutate(delta=casos-lag(casos),deltaPrev=lag(delta),growthFactor= delta/deltaPrev)\n\nggplot(cor %>% filter(dias>3),aes(x=dias,y=growthFactor)) + geom_point() + theme_bw() + stat_smooth(method=lm,se=FALSE) + labs(title = bquote(\"Growth Factor=\" ~ Delta* N[t] / Delta* N[t-1] )) + theme_bw() + annotate(geom=\"text\", x=5, y=8, label=\"Fuente @msalnacion\\n by @larysar\",color=\"red\",size=2)\n\n# Nuevos casos vs casos totales en log\n#\n\npredexp <- predexp %>% mutate( preddia = pred - lag(pred))\n\nggplot(cor, aes(x = casos, y = casosdia) ) +\n geom_point() + geom_line() + scale_x_log10() + scale_y_log10() + theme_bw() + ylab(\"Nuevos casos\") + xlab(\"Casos totales\")+\n geom_line(data=predexp, aes(x=pred, y = preddia), size = .5, color= \"blue\") + coord_cartesian(xlim=c(9,max(predexp$pred)))+ \n annotate(geom=\"text\", x=1000, y=1, label=\"Fuente @msalnacion\\n by @larysar\",color=\"red\",size=2)\n\nggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaArNuevosVsTotales.jpg\",width=6,height=6,units=\"in\",dpi=600)\n\n# geom_line(data=predexp, aes(x=fecha,y = pred), size = .5, color= \"blue\") \n \n\n\n#\n# Contactos e Importados Comunitarios by group usando tidyverse\n#\nrequire(tidyr)\ncor1 <- cor %>% gather(tipo,N,casos:comunitarios,importados) %>% filter(tipo %in% c(\"contactos\",\"importados\",\"comunitarios\")) %>% mutate(N = ifelse(N==0,NA,N))\n\nggplot(cor1 ,aes(x=dias,y=N,color=tipo)) + geom_point() + theme_bw() + stat_smooth(method=lm, se=F) + scale_y_log10() + scale_color_viridis_d() + ylab(\"Casos\")\n\nggplot(cor1,aes(x=dias,y=N,color=tipo)) + geom_point() + theme_bw() + scale_color_viridis_d() + scale_color_viridis_d() + scale_y_log10() + ylab(\"Casos\") + geom_line()\n\nmod <- cor1 %>% filter(N>0) %>% group_by(tipo) %>% do(mod=drm(N ~ dias, fct=L.3() , data = .) )\nmod %>% do(data.frame(max= coef(.$mod)[2],.$tipo))\n\nnewdat <- data.frame(dias = 0:ldia)\nlibrary(tidyverse) \npredexp <- cor1 %>%\n group_by(tipo) %>%\n nest %>%\n mutate(mod = purrr::map(.x = data, .f = ~ drm(N ~ dias, fct=L.3() , data = .))) %>% \n# mutate(mod = purrr::map(.x = data, .f = ~ nls(N~ alpha*exp(dias*beta),start=c(alpha=1.4,beta=0.2),data=.))) %>%\n mutate(pred = purrr::map(.x = mod, ~ predict(., newdat))) %>% \n dplyr::select(tipo,pred) %>% unnest(cols=pred) %>% bind_cols(dias = rep(newdat$dias,3)) %>% mutate(fecha = min(cor1$fecha)+dias)\n\n\nggplot(cor1,aes(x=fecha,y=N,color=tipo)) + geom_point() + theme_bw() + scale_color_viridis_d() + scale_color_viridis_d() + ylab(\"Casos\") + geom_line(data=predexp, aes(x=fecha,y = pred,color=tipo), size = .5) \n#ggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaArComparacion.jpg\",width=6,height=6,units=\"in\",dpi=600)\n\nggplot(cor1,aes(x=fecha,y=N,color=tipo)) + geom_point() + theme_bw() + scale_color_viridis_d() + scale_color_viridis_d() + scale_y_log10() + ylab(\"Casos\") + geom_line(data=predexp, aes(x=fecha,y = pred,color=tipo), size = .5) \nggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaArComparacionComunitarios.jpg\",width=6,height=6,units=\"in\",dpi=600)\n\n#ggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaArComparacionLog.jpg\",width=6,height=6,units=\"in\",dpi=600)\n\n\n\n# \n# Comparacion Casos GLobales Tasa de crecimiento vs Casos Totales \n#\n# Fuente: Johns Hopkins University Center for Systems Science and Engineering.\n# https://systems.jhu.edu/research/public-health/ncov/\n#\n#\n\ncorg <- read_csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\") \n\ncorg <- corg %>% rename(country=\"Country/Region\",province=\"Province/State\") %>% filter( country %in% c(\"US\",\"Italy\",\"Brazil\", \"Korea, South\"))\nrequire(tidyr)\n\n# Umbral de casos a partir de los cuales se calcula la curva\n#\numbral <- 100\n\ncor1 <- corg %>% gather(date,N,5:ncol(corg) ) %>% arrange(country) %>% mutate(casosdia = N - lag(N)) %>% filter(N>umbral, casosdia>0 ) %>% group_by(country) %>% mutate(fecha=mdy(date), dias =as.numeric( fecha - min(fecha))) \n\n# Para argentina usa los datos de @minsal \n#\ncor1 <- bind_rows( cor1, cor %>% filter(casos>umbral) %>%dplyr::select(casos,casosdia,fecha) %>% mutate(country=\"Argentina\",dias =as.numeric( fecha - min(fecha))) %>% rename(N=casos))\n\nrequire(ggplot2)\n\nggplot(cor1, aes(x = N, y = casosdia, colour=country) ) + scale_y_log10() + scale_x_log10() + \n geom_point() + theme_bw() + guides(fill=FALSE) + scale_color_viridis_d() + geom_line() + xlab(\"Casos Totales\") + ylab( \"Casos por Día\") + \n annotate(\"text\",x=1850, y=10, label=\"Fuente https://systems.jhu.edu/research/public-health/ncov/\\n by @larysar\",color=\"red\",size=2) + theme(legend.position=\"bottom\")\nggsave(\"/home/leonardo/Academicos/GitProjects/covid19/coronaGlobalNuevosVsTotales.jpg\",width=6,height=6,units=\"in\",dpi=600)\n", "meta": {"hexsha": "83199d75435aeb806d2023ee94d13075642e55bb", "size": 8020, "ext": "r", "lang": "R", "max_stars_repo_path": "coronavirus.r", "max_stars_repo_name": "lsaravia/covid19ar", "max_stars_repo_head_hexsha": "8787dc99fec07521d04c19b576cd14e5decb0fda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coronavirus.r", "max_issues_repo_name": "lsaravia/covid19ar", "max_issues_repo_head_hexsha": "8787dc99fec07521d04c19b576cd14e5decb0fda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coronavirus.r", "max_forks_repo_name": "lsaravia/covid19ar", "max_forks_repo_head_hexsha": "8787dc99fec07521d04c19b576cd14e5decb0fda", "max_forks_repo_licenses": ["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.8044692737, "max_line_length": 302, "alphanum_fraction": 0.6891521197, "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6108470906092693}} {"text": "\"\nВвести с клавиатуры число N. Подсчитать сумму 1 + 2 + ... + N.\nВывести на экран введенное число и результат расчета.\n\"\n{\n N <- readline(\"Введите число N -> \")\n \n sum <- 0\n for(i in 1:N){\n print(i)\n sum <- sum + i\n }\n \n print(paste(\"Сумма:\",sum))\n}", "meta": {"hexsha": "f8f31931598ad2e51d5b39155967e026f959c06a", "size": 263, "ext": "r", "lang": "R", "max_stars_repo_path": "Course II/R/pract/pract5/task4.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course II/R/pract/pract5/task4.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course II/R/pract/pract5/task4.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 17.5333333333, "max_line_length": 62, "alphanum_fraction": 0.5741444867, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.61078452613628}} {"text": "IsPrime <- function(n) {\n for (i in 2:(n/2)) {\n if ( n %% i == 0) {\n return(FALSE)\n }\n }\n return(TRUE)\n}\n\nfor (i in 2:100)\n if (IsPrime(i))\n print(i)\n", "meta": {"hexsha": "ae779561976b470e6f9e57dcda484078947f2cd1", "size": 194, "ext": "r", "lang": "R", "max_stars_repo_path": "examples/primes.r", "max_stars_repo_name": "josephmckenna/2021_June_IOP_CAPS_2021", "max_stars_repo_head_hexsha": "d3c2e1d661d5fffa7233bf831b76ceccd2a69d63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/primes.r", "max_issues_repo_name": "josephmckenna/2021_June_IOP_CAPS_2021", "max_issues_repo_head_hexsha": "d3c2e1d661d5fffa7233bf831b76ceccd2a69d63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/primes.r", "max_forks_repo_name": "josephmckenna/2021_June_IOP_CAPS_2021", "max_forks_repo_head_hexsha": "d3c2e1d661d5fffa7233bf831b76ceccd2a69d63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.9230769231, "max_line_length": 27, "alphanum_fraction": 0.3969072165, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6106872763453042}} {"text": "# Install and load required packages --------------------------------------------------------------------------------------------------\r\n\r\ninstall.packages(\"tidyverse\")\r\ninstall.packages(\"dagitty\")\r\ninstall.packages(\"ggdag\")\r\ninstall.packages(\"bnlearn\")\r\ninstall.packages(\"Rgraphviz\")\r\ninstall.packages(\"causaleffect\")\r\ninstall.packages(\"igraph\")\r\ninstall.packages(\"latex2exp\")\r\n\r\nlibrary(tidyverse)\r\nlibrary(dagitty)\r\nlibrary(ggdag)\r\nlibrary(bnlearn)\r\nlibrary(Rgraphviz)\r\nlibrary(causaleffect)\r\nlibrary(igraph)\r\nlibrary(latex2exp)\r\n\r\n\r\n\r\n# Slide 12. Common Effect example -----------------------------------------------------------------------------------------------------\r\n\r\ntalent <- rnorm(10000, 0, 1)\r\nhardwork <- rnorm(10000, 0, 1)\r\ndf <- data.frame(talent, hardwork)\r\n\r\n# Compute the correlation between the variables\r\n\r\ndf %>% summarize(correlation = cor(talent, hardwork))\r\n\r\n# Success is equal to one if the sum of talent and hardwork is above the 80th percentile in the population -----------\r\n\r\nx <- talent + hardwork\r\nsuccess <- 1*(x > quantile(x, c(.8)))\r\ndf <- cbind(df, success)\r\n\r\ndf %>% filter(success == 1) %>% summarize(correlation = cor(talent, hardwork))\r\n\r\n# Slide 17. Correlation doesn't imply causation ---------------------------------------------------------------------\r\n\r\n# Error terms\r\n\r\ne_x <- rnorm(10000)\r\ne_y <- rnorm(10000)\r\ne_z <- rnorm(10000)\r\n\r\n# Create nodes for the DAG: y <- x, y <- z, x <- z \r\n\r\nz <- 1*(e_z > 0)\r\nx <- 1*(z + e_x > 0.5)\r\ny <- 1*(x + z + e_y > 2)\r\ny_dox <- 1*(1 + z + e_y > 2)\r\n\r\n# We see that P(y|do(x=1)) is not equal to P(y|x=1)\r\n\r\nmean(y_dox)\r\nmean(y[x==1])\r\n\r\n# Slide 17. Visualizing DAGs with ggdag -----------------------------------------------------------------------------\r\n\r\ncoords <- data.frame(matrix(c(\"x\",0,0,\r\n \"y\",2,0,\r\n \"z\",1,1,\r\n \"w\",1,0), nrow=4, ncol=3, byrow=T))\r\n\r\ncolnames(coords) <- c(\"name\",\"x\",\"y\")\r\n\r\n# \"y ~ w\" means that w is a parent of y\r\n\r\ndag <- ggdag:: dagify(y ~ w, \r\n y ~ z,\r\n w ~ x,\r\n x ~ z,\r\n exposure = \"x\",\r\n outcome = \"y\",\r\n coords=coords)\r\n\r\n# Plot the DAG\r\n\r\nggdag::ggdag(dag)\r\n\r\n# Find all parents of outcome\r\n\r\nggdag:: ggdag_parents(dag, \"y\")\r\n\r\n\r\n# Slide 20.Testable implications of graphs --------------------------------------------------------------------------\r\n\r\ncoords <- data.frame(matrix(c(\"A\",0,0,\r\n \"B\",0,1,\r\n \"C\",1,2,\r\n \"D\",2,1,\r\n \"E\",2,0), nrow=5, ncol=3, byrow=T))\r\n\r\ncolnames(coords) <- c(\"name\",\"x\",\"y\")\r\n\r\n# \"A ~ B\" means that B is a parent of A\r\n\r\ndag <- ggdag:: dagify(A ~ B, \r\n C ~ A,\r\n C ~ B,\r\n E ~ A,\r\n C ~ D,\r\n E ~ C,\r\n E ~ D,\r\n exposure = \"A\",\r\n outcome = \"E\",\r\n coords=coords)\r\n\r\n# Plot the DAG\r\n\r\nggdag::ggdag(dag)\r\n\r\n\r\n# Find all d-separation relationships in a DAG\r\n\r\nimpliedConditionalIndependencies(dag)\r\n\r\n# Slide 24. PC Algorithm --------------------------------------------------------------------------------------------\r\n\r\n# Simulate data : z <- x, w <- x, w <- y, w <- z \r\n\r\nx <- rnorm(10000, 0, 1)\r\ny <- rnorm(10000, 0, 1)\r\nz <- x + rnorm(10000, 0, 1)\r\nw <- x + y + z + rnorm(1000, 0, 1)\r\n\r\ndf <- data.frame(x,y,z,w)\r\n\r\n# PC Algorithm\r\n\r\nstr <- pc.stable(df, test = \"cor\", alpha = 0.05, undirected = FALSE)\r\n\r\ngraphviz.plot(str)\r\n\r\n# Slide 29. Backdoor Criterion --------------------------------------------------------------------------------------\r\n\r\ncoords <- data.frame(matrix(c(\"x\",0,0,\r\n \"w\",1,0,\r\n \"y\",2,0,\r\n \"z\",1,1), nrow=4, ncol=3, byrow=T))\r\n\r\ncolnames(coords) <- c(\"name\",\"x\",\"y\")\r\n\r\n# \"x ~ z\" means that z is a parent of x\r\n\r\ndag <- ggdag:: dagify(x ~ z, \r\n w ~ x,\r\n y ~ w,\r\n y ~ z,\r\n exposure = \"x\",\r\n outcome = \"y\",\r\n coords=coords)\r\n\r\n# Plot the DAG\r\n\r\nggdag::ggdag(dag)\r\n\r\n\r\n# List all direct causal effects that are identifiable via backdoor adjustment\r\n\r\nfor(n in names(dag)){\r\n for(m in dagitty::children(dag,n)){\r\n a <- adjustmentSets(dag, n, m, effect=\"direct\")\r\n if(length(a) > 0){\r\n cat(\"The causal effect of \",n,\" on \",m,\r\n \" is identifiable controlling for:\\n\",sep=\"\")\r\n print(a, prefix=\" * \")\r\n }\r\n }\r\n}\r\n\r\n# Example \r\n\r\n# Error terms\r\n\r\ne_x <- rnorm(10000)\r\ne_y <- rnorm(10000)\r\ne_z <- rnorm(10000)\r\n\r\n# Create nodes for the DAG: y <- x, y <- z, x <- z \r\n\r\nz <- 1*(e_z > 0)\r\nx <- 1*(z + e_x > 0.5)\r\ny <- 1*(x + z + e_y > 2)\r\n\r\ny_dox <- 1*(1 + z + e_y > 2)\r\n\r\n\r\nmean(y_dox)\r\n\r\n# Adjustment formula: P(y|do(x=1)) = P(y|x=1, z=1)*P(z=1) + P(y|x=1, z=0)*P(z=0)\r\n\r\nmean(y[x==1 & z==1]) * mean(z==1) + mean(y[x==1 & z==0]) * mean(z==0)\r\n\r\n# Do-Calculus ------------------------------------------------------------------------------------------------------\r\n\r\n# The causaleffect package uses different syntax than \"dagitty\", note the +- instead of ~\r\n\r\ndag <- graph.formula(y +- z5, y +- z6, y +- z1,\r\n z6 +- x,\r\n z5 +- z4,\r\n z2 +- z3,\r\n z1 +- z4, z1 +- z3,\r\n x +- z2, x +- z1, \r\n simplify = FALSE)\r\n\r\n# Shpitser and Pearl (2006) algorithm for the rules of do-calculus. If the effect is identifiable, the function\r\n# returns an expression for the causal effect.\r\n\r\nce_backdoor <- causal.effect(y = \"y\", x = \"x\", z = NULL, G = dag, expr = TRUE)\r\nplot(TeX(ce_backdoor), cex=2)\r\n", "meta": {"hexsha": "edc7c449312fc1d21ec18b7f1d58fe6cc7b0ab63", "size": 5897, "ext": "r", "lang": "R", "max_stars_repo_path": "Session 2/ALS.r", "max_stars_repo_name": "AZharinova/Evaluating-Complex-Interventions-Action-Learning-Set", "max_stars_repo_head_hexsha": "da9997e55ddb140aa6c96c425b79c1d9ddd5e655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session 2/ALS.r", "max_issues_repo_name": "AZharinova/Evaluating-Complex-Interventions-Action-Learning-Set", "max_issues_repo_head_hexsha": "da9997e55ddb140aa6c96c425b79c1d9ddd5e655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session 2/ALS.r", "max_forks_repo_name": "AZharinova/Evaluating-Complex-Interventions-Action-Learning-Set", "max_forks_repo_head_hexsha": "da9997e55ddb140aa6c96c425b79c1d9ddd5e655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4279069767, "max_line_length": 136, "alphanum_fraction": 0.4285229778, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6106802358969181}} {"text": "\nf_logLikelihood <- function(M,x_train,uniform_dist,u,sigma)\n{\n logLike <- sum(log(M[[1]]*uniform_dist + M[[2]]*dnorm(x_train, u, sqrt(sigma))))\n return (logLike)\n}\n \nf_updateResposibilities <- function(M,x_train,uniform_dist,u,sigma)\n{\n uniformP <- uniform_dist\n gaussP <- dnorm(x_train, u, sqrt(sigma)) #stats.norm.pdf(x_train,u,sqrt(sigma))\n resposibilities <- cbind( (M[[1]]*uniformP / (M[[1]]*uniformP + M[[2]]*gaussP)), #.reshape(-1,1),\n (M[[2]]*gaussP / (M[[1]]*uniformP + M[[2]]*gaussP)) ) # .reshape(-1,1) ))\n return (resposibilities)\n}\n \nf_updateMixtureParams <- function(resposibilities,M,x_train)\n{\n M[[1]] <- sum(resposibilities[,1])/sum(resposibilities)\n M[[2]] <- sum(resposibilities[,2])/sum(resposibilities)\n u <- (sum(resposibilities[,2]*x_train))/sum(resposibilities[,2])\n sigma <- sum((x_train-u)**2*resposibilities[,2])/sum(resposibilities[,2])\n return (list(\"M\" = M,\n #\"uniform_dist\" = uniform_dist,\n \"u\" = u,\n \"sigma\" = sigma))\n} \n\nf_calcCutoffs <- function(M,x_train,u,sigma)\n{\n tmp <- sqrt(-2*sqrt(sigma)**2 * (log(M[[1]]/M[[2]]) - log(max(x_train)-min(x_train)) + log(sqrt(sigma)) + 0.5*log(2*pi)))\n cutoffs <- c(\"low\" = u-tmp,\n \"high\" = u+tmp)\n return (cutoffs)\n}\n \nf_call_changes <- function(all_t_tests)\n{\n # ignore DEAD and GHOST columns\n localization_cols <- colnames(all_t_tests)[ !colnames(all_t_tests) %in% c(\"GHOST\", \"DEAD\")]\n tscores <- all_t_tests[ ,localization_cols ]\n\n localization_hits = list()\n Outlier_M <- 0.001\n for (loc in localization_cols)\n {\n x_train = tscores[,loc]\n ### remove BLANK\n x_train <- x_train[ grep(\"BLANK\", names(x_train), invert=T)]\n ### end remove BLANK\n M <- c(Outlier_M, 1-Outlier_M)\n #randInd = np.random.rand(len(x_train))\n resposibilities <- cbind(0.5 * rep(1, length(x_train)), \n 0.5 * rep(1, length(x_train)))\n uniform_dist <- rep(1, length(x_train))/(max(x_train) - min(x_train))\n u <- 0\n sigma <- 0.1**2\n loglike_prev <- 1\n loglike <- 10\n i <- 0\n while (abs(loglike_prev-loglike) > 0.1)\n {\n loglike_prev <- loglike\n resposibilities <- f_updateResposibilities(M, x_train, uniform_dist, u, sigma)\n res_f_upd <- f_updateMixtureParams(resposibilities, M, x_train)\n u <- res_f_upd$u\n sigma <- res_f_upd$sigma\n #M = [Outlier_M, 1.-Outlier_M] # I do not update this parameter, therefore we do not need to reset it\n loglike <- f_logLikelihood(M, x_train, uniform_dist, u, sigma)\n i <- i+1\n }\n cutoffs <- f_calcCutoffs(M,x_train,u,sigma)\n localization_hits[[loc]] <- all_t_tests[ (all_t_tests[,loc] < cutoffs[[\"low\"]]) |\n (all_t_tests[,loc] > cutoffs[[\"high\"]]), ]\n }\n sapply(localization_hits, nrow)\n sum(sapply(localization_hits, nrow))\n sum(sapply(localization_hits, function(x) { length(grep(\"BLANK\", row.names(x), invert=T)) }))\n df <- do.call(\"rbind\", localization_hits)\n nrow(df)\n nrow(unique(df))\n nrow(unique(df[ grep(\"BLANK\", row.names(df), invert = T),]))\n return (localication_hits)\n}\n\nf_get_significant_changes <- function(t_tests, Outlier_M = 0.001, VERBOSE=F)\n{\n compartments <- colnames(t_tests)\n localization_hits = list()\n significant_changes <- list()\n significant_mut_higher <- list()\n significant_WT_higher <- list()\n cutoffs <- list()\n for (loc in compartments)\n {\n x_train = t_tests[,loc]\n M <- c(Outlier_M, 1-Outlier_M)\n resposibilities <- cbind(0.5 * rep(1, length(x_train)), \n 0.5 * rep(1, length(x_train)))\n uniform_dist <- rep(1, length(x_train))/(max(x_train) - min(x_train))\n u <- 0\n sigma <- 0.1**2\n loglike_prev <- 1\n loglike <- 10\n i <- 0\n while (abs(loglike_prev-loglike) > 0.1)\n {\n loglike_prev <- loglike\n resposibilities <- f_updateResposibilities(M, x_train, uniform_dist, u, sigma)\n res_f_upd <- f_updateMixtureParams(resposibilities, M, x_train)\n u <- res_f_upd$u\n sigma <- res_f_upd$sigma\n #M = [Outlier_M, 1.-Outlier_M] # I do not update this parameter, therefore we do not need to reset it\n loglike <- f_logLikelihood(M, x_train, uniform_dist, u, sigma)\n i <- i+1\n }\n cutoffs[[loc]] <- f_calcCutoffs(M,x_train,u,sigma)\n cutoffs[[loc]][[\"u\"]] <- u\n cutoffs[[loc]][[\"sigma\"]] <- sigma\n localization_hits[[loc]] <- t_tests[ (t_tests[,loc] < cutoffs[[loc]][[\"low\"]]) |\n (t_tests[,loc] > cutoffs[[loc]][[\"high\"]]), ,\n drop=FALSE]\n cutoffs[[loc]][[\"counts_changes\"]] <- nrow(localization_hits[[loc]])\n cutoffs[[loc]][[\"counts_mut_higher\"]] <- sum(t_tests[,loc] < cutoffs[[loc]][[\"low\"]])\n cutoffs[[loc]][[\"counts_WT_higher\"]] <- sum(t_tests[,loc] > cutoffs[[loc]][[\"high\"]])\n significant_changes[[loc]] <- sort(row.names(localization_hits[[loc]]))\n significant_mut_higher[[loc]] <- sort(row.names(t_tests)[ t_tests[,loc] < cutoffs[[loc]][[\"low\"]] ])\n significant_WT_higher[[loc]] <- sort(row.names(t_tests)[ t_tests[,loc] > cutoffs[[loc]][[\"high\"]] ])\n if (VERBOSE) { cat(sprintf(\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\", loc, u, sigma, cutoffs[[loc]][[\"low\"]], cutoffs[[loc]][[\"high\"]], sum((t_tests[,loc] < cutoffs[[\"low\"]]) | (t_tests[,loc] > cutoffs[[\"high\"]]) ) ) ) }\n }\n # table to return w/ all t-tests, and adding the significant change in each row (we only show rows w/ at least a significant change)\n df <- unique(as.data.frame(do.call(\"rbind\", localization_hits),stringsAsFactors = F))\n tmp <- do.call(\"rbind\", sapply(names(significant_changes), function(x) { cbind(x, significant_changes[[x]] ) }) )\n locs_per_ORF <- sapply(split(tmp[,1], tmp[,2]), function(x) { paste(x, collapse=\",\") })\n df$enriched_loc <- locs_per_ORF[ row.names(df) ]\n # summary\n df_summary <- as.data.frame(do.call(\"rbind\", cutoffs), stringsAsFactors = F)\n df_summary$genes_changing <- sapply(significant_changes[ row.names(df_summary) ], function(x) { paste(x, collapse=\",\") })\n df_summary$genes_mut_higher <- sapply(significant_mut_higher[ row.names(df_summary) ], function(x) { paste(x, collapse=\",\") })\n df_summary$genes_WT_higher <- sapply(significant_WT_higher[ row.names(df_summary) ], function(x) { paste(x, collapse=\",\") })\n return (list(\"df\" = df,\n \"df_summary\" = df_summary))\n}\n", "meta": {"hexsha": "093bd4be56dffff8eb2b6531bda1cb9413dcd7bd", "size": 6395, "ext": "r", "lang": "R", "max_stars_repo_path": "lib_mixture_model.r", "max_stars_repo_name": "BooneAndrewsLab/DUB_Biology", "max_stars_repo_head_hexsha": "0da43e84d58987bdf8ed0a6d4cb7be2d3e336701", "max_stars_repo_licenses": ["MIT"], "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_mixture_model.r", "max_issues_repo_name": "BooneAndrewsLab/DUB_Biology", "max_issues_repo_head_hexsha": "0da43e84d58987bdf8ed0a6d4cb7be2d3e336701", "max_issues_repo_licenses": ["MIT"], "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_mixture_model.r", "max_forks_repo_name": "BooneAndrewsLab/DUB_Biology", "max_forks_repo_head_hexsha": "0da43e84d58987bdf8ed0a6d4cb7be2d3e336701", "max_forks_repo_licenses": ["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.4097222222, "max_line_length": 209, "alphanum_fraction": 0.6195465207, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.6106640830812442}} {"text": "library(ggplot2)\n\n\n#' @param k The shape parameter of the Erlang distribution.\n#' @param gamma The rate parameter of the Erlang distribution.\n#' @return A vector containing all p_i values, for i = 1 : n.\ncompute_erlang_discrete_prob <- function(k, gamma) {\n n_bin <- 0\n factorials <- 1 ## 0! = 1\n for (i in 1 : k) {\n factorials[i + 1] <- factorials[i] * i ## factorial[i + 1] = i!\n }\n\n one_sub_cummulative_probs <- NULL\n cummulative_prob <- 0\n while (cummulative_prob <= 0.99) {\n n_bin <- n_bin + 1\n\n one_sub_cummulative_probs[n_bin] <- 0\n for ( j in 0 : (k - 1) ) {\n one_sub_cummulative_probs[n_bin] <-\n one_sub_cummulative_probs[n_bin] +\n (\n exp( -n_bin * gamma )\n * ( (n_bin * gamma) ^ j )\n / factorials[j + 1] ## factorials[j + 1] = j!\n )\n }\n cummulative_prob <- 1 - one_sub_cummulative_probs[n_bin]\n }\n one_sub_cummulative_probs <- c(1, one_sub_cummulative_probs)\n\n density_prob <-\n head(one_sub_cummulative_probs, -1) - tail(one_sub_cummulative_probs, -1)\n density_prob <- density_prob / cummulative_prob\n\n return(density_prob)\n}\n\n#' @param initial_state A vector that contains 4 numbers corresponding to the\n#' initial values of the 4 classes: S, E, I, and R.\n#' @param parameters A vector that contains 5 numbers corresponding to the\n#' following parameters: the shape and the rate parameters\n#' of the Erlang distribution that will be used to\n#' calculate the transition rates between the E components\n#' (i.e. k[E] and gamma[E]), the shape and the rate parameters\n#' of the Erlang distribution that will be used to\n#' calculate the transition rates between the I components\n#' (i.e. k[I] and gamma[I]), and the base transmission rate\n#' (i.e. beta).\n#' @param max_time The length of the simulation.\n#' @return A data frame containing the values of S, E, I, and R over time\n#' (from 1 to max_time).\nseir_simulation <- function(initial_state, parameters, max_time) {\n names(initial_state) <- c(\"S\", \"E\", \"I\", \"R\")\n names(parameters) <- c( \"erlang_shape_for_E\", \"erlang_rate_for_E\",\n \"erlang_shape_for_I\", \"erlang_rate_for_I\",\n \"base_transmission_rate\" )\n\n population_size <- sum(initial_state)\n sim_data <- data.frame( time = c(1 : max_time),\n S = NA, E = NA, I = NA, R = NA )\n sim_data[1, 2:5] <- initial_state\n\n ## Initialise a matrix to store the states of the exposed sub-blocks over time.\n exposed_block_adm_rates <- compute_erlang_discrete_prob(\n k = parameters[\"erlang_shape_for_E\"],\n gamma = parameters[\"erlang_rate_for_E\"]\n )\n n_exposed_blocks <- length(exposed_block_adm_rates)\n exposed_blocks <- matrix( data = 0, nrow = max_time,\n ncol = n_exposed_blocks )\n exposed_blocks[1, n_exposed_blocks] <- sim_data$E[1]\n\n ## Initialise a matrix to store the states of the infectious sub-blocks over time.\n infectious_block_adm_rates <- compute_erlang_discrete_prob(\n k = parameters[\"erlang_shape_for_I\"],\n gamma = parameters[\"erlang_rate_for_I\"]\n )\n n_infectious_blocks <- length(infectious_block_adm_rates)\n infectious_blocks <- matrix( data = 0, nrow = max_time,\n ncol = n_infectious_blocks )\n infectious_blocks[1, n_infectious_blocks] <- sim_data$I[1]\n\n ## Run the simulation from time t = 2 to t = max_time\n for (time in 2 : max_time) {\n transmission_rate <-\n parameters[\"base_transmission_rate\"] * sim_data$I[time - 1] /\n population_size\n exposure_prob <- 1 - exp(-transmission_rate)\n\n new_exposed <- rbinom(1, sim_data$S[time - 1], exposure_prob)\n new_infectious <- exposed_blocks[time - 1, 1]\n new_recovered <- infectious_blocks[time - 1, 1]\n \n if (new_exposed > 0) {\n exposed_blocks[time, ] <- t(\n rmultinom(1, size = new_exposed,\n prob = exposed_block_adm_rates)\n )\n }\n exposed_blocks[time, ] <-\n exposed_blocks[time, ] +\n c( exposed_blocks[time - 1, 2 : n_exposed_blocks], 0 )\n\n if (new_infectious > 0) {\n infectious_blocks[time, ] <- t(\n rmultinom(1, size = new_infectious,\n prob = infectious_block_adm_rates)\n )\n }\n infectious_blocks[time, ] <-\n infectious_blocks[time, ] +\n c( infectious_blocks[time - 1, 2 : n_infectious_blocks], 0 )\n\n sim_data$S[time] <- sim_data$S[time - 1] - new_exposed\n sim_data$E[time] <- sum(exposed_blocks[time, ])\n sim_data$I[time] <- sum(infectious_blocks[time, ])\n sim_data$R[time] <- sim_data$R[time - 1] + new_recovered\n }\n\n return(sim_data)\n}\n\nsim <- seir_simulation( initial_state = c(S = 9999, E = 1, I = 0, R = 0),\n parameters = c(5, 1, 10, 1, 0.25),\n max_time = 300 )\n\n# Plot\nggplot(sim, aes(time)) + \n geom_line(aes(y = S, colour = \"Susceptible\"), lwd = 1) + \n geom_line(aes(y = E, colour = \"Exposed\"), lwd = 1) +\n geom_line(aes(y = I, colour = \"Infectious\"), lwd = 1) +\n geom_line(aes(y = R, colour = \"Recovered\"), lwd = 1) +\n xlab(\"Time\") + ylab(\"Number of Individuals\")\n\nset.seed(12345)\ntest_sim <- seir_simulation( initial_state = c(S = 9999, E = 1, I = 0, R = 0),\n parameters = c(5, 1, 10, 1, 0.25),\n max_time = 100 )\ntest_result <- as.matrix( tail(test_sim, 3) )\n\ncorrect_result <- matrix( c( 98, 7384, 794, 1015, 807,\n 99, 7184, 864, 1068, 884,\n 100, 6986, 920, 1144, 950), nrow = 3, byrow = T )\n\nn_correct_cells <- sum(correct_result == test_result)\n\ncat(\"\\n--------------------\\n\")\nif (n_correct_cells == 15) {\n cat(\" Test PASSED\\n\")\n} else {\n cat(\" Test FAILED\\n\")\n}\ncat(\"--------------------\\n\\n\")\n", "meta": {"hexsha": "76bcd8155ecf7574e8c139ee1097e876d38cfae8", "size": 6302, "ext": "r", "lang": "R", "max_stars_repo_path": "models/nonexponential_passage_times/discrete_erlang_sir.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/nonexponential_passage_times/discrete_erlang_sir.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/nonexponential_passage_times/discrete_erlang_sir.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": 40.3974358974, "max_line_length": 86, "alphanum_fraction": 0.5669628689, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6106621983012761}} {"text": "inputs <- c(1.2, 5.1, 2.1)\nweights <- c(3.1, 2.1, 8.7)\nbias <- 3\n\noutput <- inputs[1] * weights[1] + inputs[2] * weights[2] + inputs[3] * weights[3] + bias\noutput\n", "meta": {"hexsha": "10e1e7094e30d914123946d70f9dca3131053ec3", "size": 163, "ext": "r", "lang": "R", "max_stars_repo_path": "R/p001.r", "max_stars_repo_name": "yarikbratashchuk/NNfSiX", "max_stars_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1045, "max_stars_repo_stars_event_min_datetime": "2020-04-16T20:11:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:33:49.000Z", "max_issues_repo_path": "R/p001.r", "max_issues_repo_name": "yarikbratashchuk/NNfSiX", "max_issues_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87, "max_issues_repo_issues_event_min_datetime": "2020-04-17T02:36:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-15T01:04:27.000Z", "max_forks_repo_path": "R/p001.r", "max_forks_repo_name": "yarikbratashchuk/NNfSiX", "max_forks_repo_head_hexsha": "6ea56e3187d3742752c8cbef1bf30d8cf91bfe09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 359, "max_forks_repo_forks_event_min_datetime": "2020-04-16T21:41:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:23:47.000Z", "avg_line_length": 23.2857142857, "max_line_length": 89, "alphanum_fraction": 0.5705521472, "num_tokens": 77, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.6098538035651112}} {"text": "# purpose: calculate the heterosis\n# Jinliang Yang\n# 2.1.2012\n\nsetwd(\"/Users/yangjl/Documents/Heterosis_GWAS/pheno2011\");\nptrait <- read.csv(\"diallel_ptrait.csv\")\n\np <- subset(ptrait, Note==\"Founder\")\nf1 <- subset(ptrait, Note==\"F1\")\n\nf1$KRN_HPH <- NA\nf1$KRN_MPH <- NA\nf1$CL_HPH <- NA\nf1$CL_MPH <- NA\nf1$CW_HPH <- NA\nf1$CW_MPH <- NA\nf1$CD_HPH <- NA\nf1$CD_MPH <- NA\nf1$AKW_HPH <- NA\nf1$AKW_MPH <- NA\nf1$TKW_HPH <- NA\nf1$TKW_MPH <- NA\nf1$KC_HPH <- NA\nf1$KC_MPH <- NA\n\nfor (i in 1:nrow(f1)){\n p1 <- as.character(f1$p1[i]);\n p2 <- as.character(f1$p2[i]);\n f1$KRN_HPH[i] <- f1$KRN[i] - max(p[p$ped==p1, ]$KRN, p[p$ped==p2, ]$KRN);\n f1$KRN_MPH[i] <- f1$KRN[i] - mean(c(p[p$ped==p1, ]$KRN, p[p$ped==p2, ]$KRN), na.rm=T);\n f1$CL_HPH[i] <- f1$CL[i] - max(p[p$ped==p1, ]$CL, p[p$ped==p2, ]$CL);\n f1$CL_MPH[i] <- f1$CL[i] - mean(c(p[p$ped==p1, ]$CL, p[p$ped==p2, ]$CL), na.rm=T);\n f1$CW_HPH[i] <- f1$CW[i] - max(p[p$ped==p1, ]$CW, p[p$ped==p2, ]$CW);\n f1$CW_MPH[i] <- f1$CW[i] - mean(c(p[p$ped==p1, ]$CW, p[p$ped==p2, ]$CW), na.rm=T);\n f1$CD_HPH[i] <- f1$CD[i] - max(p[p$ped==p1, ]$CD, p[p$ped==p2, ]$CD);\n f1$CD_MPH[i] <- f1$CD[i] - mean(c(p[p$ped==p1, ]$CD, p[p$ped==p2, ]$CD), na.rm=T);\n f1$AKW_HPH[i] <- f1$AKW[i] - max(p[p$ped==p1, ]$AKW, p[p$ped==p2, ]$AKW);\n f1$AKW_MPH[i] <- f1$AKW[i] - mean(c(p[p$ped==p1, ]$AKW, p[p$ped==p2, ]$AKW), na.rm=T);\n f1$TKW_HPH[i] <- f1$TKW[i] - max(p[p$ped==p1, ]$TKW, p[p$ped==p2, ]$TKW);\n f1$TKW_MPH[i] <- f1$TKW[i] - mean(c(p[p$ped==p1, ]$TKW, p[p$ped==p2, ]$TKW), na.rm=T);\n f1$KC_HPH[i] <- f1$KC[i] - max(p[p$ped==p1, ]$KC, p[p$ped==p2, ]$KC);\n f1$KC_MPH[i] <- f1$KC[i] - mean(c(p[p$ped==p1, ]$KC, p[p$ped==p2, ]$KC), na.rm=T);\n}\n#########################################################################################\npar(mfrow=c(2,4))\nhist(f1$KRN_HPH, main=\"KRN HPH\", xlab=\"row\", cex.lab=1.5);\nhist(f1$KC_HPH, main=\"KC HPH\", xlab=\"count\", cex.lab=1.5);\nhist(f1$TKW_HPH, main=\"TKW HPH\", xlab=\"weight (g)\", cex.lab=1.5);\nhist(f1$AKW_HPH, main=\"AKW HPH\", xlab=\"weight (g)\", cex.lab=1.5);\nhist(f1$CL_HPH, main=\"CL HPH\", xlab=\"length (mm)\", cex.lab=1.5);\nhist(f1$CW_HPH, main=\"CW HPH\", xlab=\"weight (g)\", cex.lab=1.5);\nhist(f1$CD_HPH, main=\"CD HPH\", xlab=\"diameter (mm)\", cex.lab=1.5);\n\npar(mfrow=c(2,4))\nhist(f1$KRN_MPH, main=\"KRN HPH\", xlab=\"row\", cex.lab=2);\nhist(f1$KC_MPH, main=\"KC HPH\", xlab=\"count\", cex.lab=2);\nhist(f1$TKW_MPH, main=\"TKW HPH\", xlab=\"weight (g)\", cex.lab=2);\nhist(f1$AKW_MPH, main=\"AKW HPH\", xlab=\"weight (g)\", cex.lab=2);\nhist(f1$CL_MPH, main=\"CL HPH\", xlab=\"length (mm)\", cex.lab=2);\nhist(f1$CW_MPH, main=\"CW HPH\", xlab=\"weight (g)\", cex.lab=2);\nhist(f1$CD_MPH, main=\"CD HPH\", xlab=\"diameter (mm)\", cex.lab=2);\n\n#################################################################################\ndiallel <- f1\n\ndiallel$p1 <- toupper(diallel$p1)\ndiallel$p2 <- toupper(diallel$p2)\n\nparents <- read.table(\"nam_parents\", header=TRUE)\nparents$parent <- toupper(parents$parent)\nB73 <- data.frame(pop=\"B73\", pedigree=\"B73\", parent=\"B73\")\nparents <- rbind(B73, parents)\n\ndiallel <- merge(diallel, parents[, c(1,3)], by.x=\"p1\", by.y=\"parent\")\ndiallel <- merge(diallel, parents[, c(1,3)], by.x=\"p2\", by.y=\"parent\")\n\ndiallel$FID <- paste(diallel$pop.x, diallel$pop.y, sep=\"x\")\ndiallel$IID <- 1\ndiallel <- diallel[,c(\"FID\", \"IID\", \"KRN\", \"CL\", \"CW\", \"CD\", \"AKW\", \"TKW\", \"KC\",\n \"KRN_HPH\", \"CL_HPH\", \"CW_HPH\", \"CD_HPH\", \"AKW_HPH\", \"TKW_HPH\", \"KC_HPH\",\n \"KRN_MPH\", \"CL_MPH\", \"CW_MPH\", \"CD_MPH\", \"AKW_MPH\", \"TKW_MPH\", \"KC_MPH\")];\n\n\n####default --missing-phenotype -9\ndiallel[is.na(diallel)] <- -9\n\nwrite.table(diallel, \"diallel_PLINK_040412.txt\", row.names=FALSE, col.names=FALSE, quote=FALSE)\n\n########################### Specific Combining Ability##########################################\n\n\n\n\n\n\n", "meta": {"hexsha": "ac7ef5c07f6d316acfff67816ce4bbbb57e804f7", "size": 3794, "ext": "r", "lang": "R", "max_stars_repo_path": "profiling/pheno2011/9.diallel_heterosis.r", "max_stars_repo_name": "yangjl/Heterosis-GWAS", "max_stars_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-16T08:27:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T13:00:43.000Z", "max_issues_repo_path": "profiling/pheno2011/9.diallel_heterosis.r", "max_issues_repo_name": "yangjl/Heterosis-GWAS", "max_issues_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "profiling/pheno2011/9.diallel_heterosis.r", "max_forks_repo_name": "yangjl/Heterosis-GWAS", "max_forks_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T14:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T01:34:08.000Z", "avg_line_length": 39.5208333333, "max_line_length": 96, "alphanum_fraction": 0.5553505535, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6097667806235416}} {"text": "# Maddison and Kremer long-run evidence\n\n#########################################################################\n# Pull Maddison data into dataframe\nmad <- read.csv(\"maddison2010.csv\", header=TRUE)\n\nmad <- mad[which(mad$year>1819),] # only 1820 and later\n\nmad$lndenmark <- round(log(mad$denmark),digits=2)\nmad$lnfrance <- round(log(mad$france),digits=2)\nmad$lnusa <- round(log(mad$usa),digits=2)\nmad$lnenglandgbuk <- round(log(mad$englandgbuk),digits=2)\nmad$lnhollandnetherlands <- round(log(mad$hollandnetherlands),digits=2)\n\n#########################################################################\n# Figure for long-run GDP per capita\n#########################################################################\nfig <- plot_ly(mad, x = ~year)\nfig <- fig %>% add_trace(y = ~lnfrance, name = 'France', type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~lnusa, name = 'USA', type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~lnhollandnetherlands, name = 'Holland/Netherlands', type = 'scatter', mode = 'lines+markers')\nfig <- fig %>% add_trace(y = ~lnenglandgbuk, name = 'England/UK', type = 'scatter', mode = 'lines+markers')\nfig <- layout(fig, title = list(text = 'Log GDP per capita in the long run', x=0),\n xaxis = list(title = 'Year', tick0=1820, dtick=20),\n yaxis = list (title = 'Log GDP per capita', range=c(6,11)),\n hovermode=\"x unified\")\napi_create(fig, filename = \"mad-stable-lngdppc\")\n\n##########################################################################\n# Pull Maddison world data in and figure for global GDP per capita and pop\n#########################################################################\nmad <- read.csv(\"maddison_world.csv\", header=TRUE)\n\nfig <- plot_ly(mad, x = ~ln_pop, y = ~ln_gdppc, text=~year,\n type = 'scatter', mode = 'markers',\n marker = list(size = 10),\n hovertemplate = paste(\"Year: %{text}
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Relationship of GDP p.c. and population', x=0),\n xaxis = list(title = 'Log global population'),\n yaxis = list(title = 'Log global GDP per capita')\n )\napi_create(fig, filename = \"mad-global-lngdppc-pop\")\n\n# Calculate average growth rates between Maddison observations\nmad <- # lag the population\n mad %>%\n mutate(lag.ln_pop = dplyr::lag(ln_pop, n = 1, default = NA))\nmad <- # lag the year\n mad %>%\n mutate(lag.year = dplyr::lag(year, n = 1, default = NA))\nmad <- # lag the GDP per capita\n mad %>%\n mutate(lag.ln_gdppc = dplyr::lag(ln_gdppc, n = 1, default = NA))\nmad$gy <- (mad$ln_gdppc - mad$lag.ln_gdppc)/(mad$year-mad$lag.year)\nmad$gl <- (mad$ln_pop - mad$lag.ln_pop)/(mad$year-mad$lag.year)\n\n#########################################################################\n# Figure of growth rate of population and growth rate of GDP per capita\n#########################################################################\nfig <- plot_ly(mad, x = ~gl, y = ~gy, text=~year,\n type = 'scatter', mode = 'markers',\n marker = list(size = 10),\n hovertemplate = paste(\"Year: %{text}
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Population and GDP p.c. growth', x=0),\n xaxis = list(title = 'Global population growth'),\n yaxis = list(title = 'GDP p.c.')\n)\napi_create(fig, filename = \"mad-global-gy-gl\")\n\n#########################################################################\n# Figure of pop growth rate and GDP per capita\n#########################################################################\nfig <- plot_ly(mad, x = ~gl, y = ~ln_gdppc, text=~year,\n type = 'scatter', mode = 'markers',\n marker = list(size = 10),\n hovertemplate = paste(\"Year: %{text}
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Population growth and GDP p.c.', x=0),\n xaxis = list(title = 'Global population growth'),\n yaxis = list(title = 'Global GDP p.c.')\n)\napi_create(fig, filename = \"mad-global-y-gl\")\n\n\n#########################################################################\n# Pull in Kremer data and create figure\n#########################################################################\nkr <- read.csv(\"kremer.csv\", header=TRUE)\nfig <- plot_ly(kr, x = ~pop, y = ~n, text=~year,\n type = 'scatter', mode = 'markers',\n marker = list(size = 10),\n hovertemplate = paste(\"Year: %{text}
\",\"%{yaxis.title.text}: %{y:.2f}
\",\n \"%{xaxis.title.text}: %{x:.2f}
\")\n)\nfig <- layout(fig, title = list(text = 'Population level and growth', x=0),\n xaxis = list(title = 'Population (millions)'),\n yaxis = list(title = 'Population growth rate')\n)\napi_create(fig, filename = \"kremer-pop-gl\")\n", "meta": {"hexsha": "1bbd00d5b2ab7b8d880a7cf311f30ef809497dcd", "size": 5202, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Guide_MAD_Facts.r", "max_stars_repo_name": "dvollrath/StudyGuide", "max_stars_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2020-07-13T21:10:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T07:45:31.000Z", "max_issues_repo_path": "code/Guide_MAD_Facts.r", "max_issues_repo_name": "dvollrath/StudyGuide", "max_issues_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Guide_MAD_Facts.r", "max_forks_repo_name": "dvollrath/StudyGuide", "max_forks_repo_head_hexsha": "b4bb0b794ecf3953cd93b2614ab850253e48d7e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-20T12:36:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:20:40.000Z", "avg_line_length": 49.5428571429, "max_line_length": 123, "alphanum_fraction": 0.4915417147, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6096955188904307}} {"text": "# James Rekow\r\n\r\nmeanOverCurve = function(M, lambda){\r\n \r\n # ARGS:\r\n #\r\n # RETURNS: the expected value of the mean overlap of a DOC with M samples and exponentially distributed\r\n # wait times between interactions with rate parameter lambda\r\n \r\n return(1 - exp(-100 * lambda / M))\r\n \r\n} # end meanOverCurve function\r\n", "meta": {"hexsha": "9e8d5507e41a21ba89a6e3a85e1eaf2bf7248642", "size": 338, "ext": "r", "lang": "R", "max_stars_repo_path": "meanOverCurve.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": "meanOverCurve.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": "meanOverCurve.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": 26.0, "max_line_length": 107, "alphanum_fraction": 0.6538461538, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6095180424473027}} {"text": "#' Evaluate the probability density function of a density approximation\n#'\n#' description\n#' @param fit An mvd.density object obtained from one of the density fitting functions.\n#' @param x Matrix or vector of positions at which to evaluate the density function.\n#' @param log Boolean which specifies whether to return the probability density in log space.\n#' @export\nmvd.pdf <- function(fit, x, log = FALSE) {\n stopifnot(class(fit) == \"mvd.density\")\n\n if (fit$type == \"kde\") {\n return(.evaluate.kde(fit, x, log))\n } else if (fit$type == \"kde.transformed\") {\n transformed <- mvd.transform_to_unbounded(x, fit$transform.bounds)\n p <- .evaluate.kde(fit$kde, transformed, log = log)\n return(mvd.correct_p_for_transformation(x, fit$transform.bounds, p, log = log))\n } else if (fit$type == \"gmm\") {\n if (is.matrix(x)) {\n stopifnot(ncol(x) == ncol(fit$centers))\n\n p <- matrix(NA, nrow(x), fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[, ki] <- mvtnorm::dmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[, ki] <- mvtnorm::dmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = FALSE) * fit$proportions[ki]\n }\n }\n\n if (log) {\n return(apply(p, 1, .logsum))\n } else {\n return(apply(p, 1, sum))\n }\n } else {\n stopifnot(length(x) == ncol(fit$centers))\n\n p <- rep(NA, fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[ki] <- mvtnorm::dmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[ki] <- mvtnorm::dmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], log = FALSE) * fit$proportions[ki]\n }\n }\n\n if (log) {\n return(.logsum(p))\n } else {\n return(sum(p))\n }\n }\n } else if (fit$type == \"gmm.transformed\") {\n transformed <- mvd.transform_to_unbounded(x, fit$transform.bounds)\n p <- mvd.pdf(fit$gmm, transformed, log = log)\n return(mvd.correct_p_for_transformation(x, fit$transform.bounds, p, log = log))\n } else if (fit$type == \"gmm.truncated\") {\n if (is.matrix(x)) {\n stopifnot(ncol(x) == ncol(fit$centers))\n\n p <- matrix(NA, nrow(x), fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[, ki] <- tmvtnorm::dtmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[, ki] <- tmvtnorm::dtmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = FALSE) * fit$proportions[ki]\n }\n }\n\n if (log) {\n return(apply(p, 1, .logsum))\n } else {\n return(apply(p, 1, sum))\n }\n } else {\n stopifnot(length(x) == ncol(fit$centers))\n\n p <- rep(NA, fit$K)\n for (ki in 1:fit$K) {\n if (log) {\n p[ki] <- tmvtnorm::dtmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = TRUE) + log(fit$proportions[ki])\n } else {\n p[ki] <- tmvtnorm::dtmvnorm(x, fit$centers[ki,], fit$covariances[[ki]], lower = fit$bounds[, 1], upper = fit$bounds[, 2], log = FALSE) * fit$proportions[ki]\n }\n }\n\n if (log) {\n return(.logsum(p))\n } else {\n return(sum(p))\n }\n }\n } else if (fit$type == \"gp\") {\n return(evaluate.gp(fit, x, log))\n } else if (fit$type == \"vine.copula\") {\n return(evaluate.vine.copula(fit, x, log))\n } else if (fit$type == \"mfa\") {\n return(evaluate.factor.mixture(fit, x, log))\n } else if (fit$type == \"mfa.transformed\") {\n transformed <- mvd.transform_to_unbounded(x, fit$transform.bounds)\n p <- mvd.pdf(fit$mfa, transformed, log = log)\n return(mvd.correct_p_for_transformation(x, fit$transform.bounds, p, log = log))\n } else {\n stop(\"Unknown type\")\n }\n}\n", "meta": {"hexsha": "3b9827f80562c09e2336c737532238a6822c0d12", "size": 4433, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pdf.r", "max_stars_repo_name": "bramthijssen/mvdens", "max_stars_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/pdf.r", "max_issues_repo_name": "bramthijssen/mvdens", "max_issues_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-04-21T12:45:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-21T12:45:03.000Z", "max_forks_repo_path": "R/pdf.r", "max_forks_repo_name": "NKI-CCB/mvdens", "max_forks_repo_head_hexsha": "27a31caef525dcdd97eaa89e6664f60036b1320c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4299065421, "max_line_length": 182, "alphanum_fraction": 0.5057523122, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.609511246783141}} {"text": "G02BRJ Example Program Results\n\nNumber of variables (columns) = 3\nNumber of case (rows) = 9\n\nData matrix is:-\n\n\n 1 2 3\n 1 1.7000 1.0000 0.5000\n 2 2.8000 4.0000 3.0000\n 3 0.6000 6.0000 2.5000\n 4 1.8000 9.0000 6.0000\n 5 0.9900 4.0000 2.5000\n 6 1.4000 2.0000 5.5000\n 7 1.8000 9.0000 7.5000\n 8 2.5000 7.0000 0.0000\n 9 0.9900 5.0000 3.0000\n\nMatrix of rank correlation coefficients:\nUpper triangle -- Spearman's\nLower triangle -- Kendall's tau\n\n 1 2 3\n 1 1.0000 0.2941 0.4058\n 2 0.1429 1.0000 0.7537\n 3 0.2760 0.5521 1.0000\n\nNumber of cases actually used: 6\n", "meta": {"hexsha": "7621bb43509647dbf58420f54b21e35dfe5c7a3c", "size": 686, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/g02brje.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/g02brje.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/g02brje.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": 22.8666666667, "max_line_length": 40, "alphanum_fraction": 0.5626822157, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.6094173519143471}} {"text": "#' Print a Simplex Table\n#' \n#' Using the notation of Bazaraa et. al., given a table \\code{x} and a\n#' basis vector \\code{Bs}, this will produce the LaTeX for a simplex\n#' tableau.\n#' \n#' @param x\n#' A matrix of values for the simplex table.\n#' @param Bs\n#' The indices of the current basis.\n#' @param digits\n#' The number of decimal digits to use in the table.\n#' \n#' @importFrom xtable xtable align\n#' \n#' @export\ntableau <- function(x, Bs, digits=0)\n{\n namedBs <- sapply(Bs, function(i) ifelse(is.na(i), NA, paste0(\"$a_\", i, \"$\")))\n df <- data.frame(cbind(x, namedBs))\n colnames(df) <- c(\"$z$\", paste0(\"$x_\", 1:(ncol(x)-2), \"$\"), \"RHS\", \"$B_s$\")\n \n tabl <- xtable::xtable(df, digits=digits)\n \n align <- paste0(\"r|r|\", paste0(rep(\"r\", ncol(x)-2), collapse=\"\"), \"|r|r|\")\n xtable::align(tabl) <- align\n \n cat(\"\\\\begin{center}\")\n print(tabl, floating=FALSE, include.rownames=FALSE, \n hline.after=c(-1:1, nrow(x)), sanitize.text.function=function(x){x})\n cat(\"\\\\end{center}\")\n \n invisible()\n}\n", "meta": {"hexsha": "dbb3cd3872dc68432810577d3cca9dd579272326", "size": 1012, "ext": "r", "lang": "R", "max_stars_repo_path": "R/simplex.r", "max_stars_repo_name": "wrathematics/lptools", "max_stars_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-09-14T00:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-14T00:58:45.000Z", "max_issues_repo_path": "R/simplex.r", "max_issues_repo_name": "wrathematics/lptools", "max_issues_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/simplex.r", "max_forks_repo_name": "wrathematics/lptools", "max_forks_repo_head_hexsha": "8922464add3261a670e092321027e83f741c96a9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9142857143, "max_line_length": 80, "alphanum_fraction": 0.6156126482, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6093688586937898}} {"text": "library(pomp)\nlibrary(magrittr)\nlibrary(plyr)\nlibrary(reshape2)\nlibrary(ggplot2)\nlibrary(scales)\nlibrary(dplyr)\n\n\n# measurement model \ndmeas <- Csnippet(\"lik = dnbinom_mu(cases, 1/od, H, 1); \")\nrmeas <- Csnippet(\"cases = rnbinom_mu(1/od,H);\")\n\n# transmission model is Markovian SIRS with 3 age classes, seasonal forcing and overdispersion\nsir.step <- Csnippet(\"double rate[7];\n double dN[7];\n double Beta1;\n double dW;\n \n // compute the environmental stochasticity\n dW = rgammawn(sigma,dt);\n \n Beta1 = beta1*(1 + beta11 * cos(M_2PI/52*t + phi)) * dW/dt;\n rate[0] = mu*N;\n rate[1] = Beta1*I/N;\n rate[2] = mu;\n rate[3] = gamma;\n rate[4] = mu;\n rate[5] = omega;\n rate[6] = mu;\n \n dN[0] = rpois(rate[0]*dt); // births are Poisson\n reulermultinom(2, S, &rate[1], dt, &dN[1]);\n reulermultinom(2, I, &rate[3], dt, &dN[3]);\n reulermultinom(2, R, &rate[5], dt, &dN[5]);\n S += dN[0] - dN[1] - dN[2] + dN[5];\n I += dN[1] - dN[3] - dN[4];\n R += dN[3] - dN[6] - dN[5];\n H += dN[1];\n \")\n\n# initializer\ninit <- function(params, t0, ...) {\n x0 <- c(S=0,I=0,R=0,H=0)\n x0[\"S\"] <- 79807318\n x0[\"I\"] <- 3683\n x0[\"R\"] <- params[\"N\"] - x0[\"I\"] - x0[\"S\"]\n round(x0) \n}\n\n# paramter vector with betas and inital data, unit is weeks\nparams <- c(beta1=1, beta11=0.17, phi=0.1, gamma=1, mu=1/(75*52), N=80000000, \n omega=1/(1*52), od=0.1, sigma=0.05)\n\n# create an empty data frame\ndat <- data.frame(times=seq(1:400), cases = rep(0, 400))\n\n#pomp object; initalize at t0 before t=0 so system can equilibrate\npomp(data = dat,\n times=\"times\",\n t0=-100,\n dmeasure = dmeas,\n rmeasure = rmeas,\n rprocess = euler.sim(step.fun = sir.step, delta.t = 1/10),\n statenames = c(\"S\", \"I\", \"R\", \"H\"),\n paramnames = names(params),\n zeronames=c(\"H\"),\n initializer=init,\n params = params\n) -> sir\n\n#simulate one trajectory from the pomp object\ndf <- simulate(sir, as.data.frame=TRUE, seed=123)\n# delete first row of the df because this is the accumulation of cases from t0 until t=0\ndf <-df[-1,] \n# delete the last column of the df because this is the number of simulation\ndf <- df[,-7]\n\n# plotting the simulated trajectory\ndf <-df%>% melt(id=\"time\")\ndf$variable <- factor(df$variable)\n\ndf %>% mutate(variable = recode(variable, cases = \"Cases\")) %>%\n mutate(variable = recode(variable, S = \"Susceptible\")) %>%\n mutate(variable = recode(variable, I = \"Infectious\")) %>%\n mutate(variable = recode(variable, R = \"Recovered\")) %>%\n mutate(variable = recode(variable, H = \"True incidence\")) %>%\n # Plot\n ggplot() +\n geom_line(aes(x = time, y = value)) +\n facet_wrap( ~variable, ncol=1, scales = \"free_y\")+ \n xlab(\"Time (years)\") + ylab(\" Number of individuals\")\n", "meta": {"hexsha": "9611e2860e6a3fb4926ad5122ff5799074e1c1d3", "size": 3202, "ext": "r", "lang": "R", "max_stars_repo_path": "models/applications/stochastic_seasonal_discrete_t_rotavirus.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/applications/stochastic_seasonal_discrete_t_rotavirus.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/applications/stochastic_seasonal_discrete_t_rotavirus.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": 34.4301075269, "max_line_length": 94, "alphanum_fraction": 0.5206121174, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6091256677226451}} {"text": "##### calculate the TSLS esitmators and covariance matrix estimator\r\n\r\npara=function(ivmodel){\r\n output=list()\r\n fit1=lm(ivmodel$Dadj~ivmodel$Zadj-1)\r\n output$gamma=coef(fit1)\r\n names(output$gamma)=NULL\r\n output$beta=c(KClass(ivmodel, k=1)$point.est)\r\n hat_eps=ivmodel$Yadj-c(output$beta)*ivmodel$Dadj\r\n hat_eta=resid(fit1)\r\n output$sigmau=sqrt(sum(hat_eps^2)/(ivmodel$n-ivmodel$p))\r\n output$sigmav=sqrt(sum(hat_eta^2)/(ivmodel$n-ivmodel$p))\r\n output$rho=sum(hat_eta*hat_eps)/(ivmodel$n-ivmodel$p)/output$sigmau/output$sigmav\r\n return(output)\r\n}\r\n", "meta": {"hexsha": "21a9904560341e8a84f1bf725b5e7a1f37b7f1d0", "size": 558, "ext": "r", "lang": "R", "max_stars_repo_path": "R/para.r", "max_stars_repo_name": "qingyuanzhao/ivmodel", "max_stars_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_stars_repo_licenses": ["MIT"], "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/para.r", "max_issues_repo_name": "qingyuanzhao/ivmodel", "max_issues_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_issues_repo_licenses": ["MIT"], "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/para.r", "max_forks_repo_name": "qingyuanzhao/ivmodel", "max_forks_repo_head_hexsha": "ad59c7cbd32734b25b12c9aef3deb8ba1559cacb", "max_forks_repo_licenses": ["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.875, "max_line_length": 84, "alphanum_fraction": 0.7258064516, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6091256660160443}} {"text": "#main function and helper functions for pTFCE R package\n\n\n#main function\n\n#' pTFCE main function.\n#'\n#' The threshold-free cluster enhancement (TFCE) approach integrates cluster information into voxel-wise statistical inference to enhance detectability of neuroimaging signal. Despite the significantly increased sensitivity, the application of TFCE is limited by several factors: (i) generalization to data structures, like brain network connectivity data is not trivial, (ii) TFCE values are in an arbitrary unit, therefore, P-values can only be obtained by a computationally demanding permutation-test.\n#' Here, we introduce a probabilistic approach for TFCE (pTFCE), that gives a simple general framework for topology-based belief boosting.\n#' The core of pTFCE is a conditional probability, calculated based on Bayes' rule, from the probability of voxel intensity and the threshold-wise likelihood function of the measured cluster size. We provide an estimation of these distributions based on Gaussian Random Field (GRF) theory. The conditional probabilities are then aggregated across cluster-forming thresholds by a novel incremental aggregation method. Our approach is validated on simulated and real fMRI data.\n#' pTFCE is shown to be more robust to various ground truth shapes and provides a stricter control over cluster \"leaking\" than TFCE and, in the most realistic cases, further improves its sensitivity. Correction for multiple comparison can be trivially performed on the enhanced P-values, without the need for permutation testing, thus pTFCE is well-suitable for the improvement of statistical inference in any neuroimaging workflow.\n#'\n#' @references\n#' T. Spisák, Z. Spisák, M. Zunhammer, U. Bingel, S. Smith, T. Nichols, T. Kincses, Probabilistic TFCE: a generalized combination of cluster size and voxel intensity to increase statistical power, Neuroimage.\n#'\n#' https://github.com/spisakt/pTFCE\n#'\n#' @param img Nifti Z-score image to enhance (\"nifti\" class from \"oro.nifti\" package)\n#' @param mask Mask\n#' @param Rd Resel count (FSL smoothest: VOLUME*DHL)\n#' @param V Number of voxels in mask (FSL smoothest: VOLUME)\n#' @param resels Resel size (FSL smoothest: RESELS)\n#' @param residual 4D residual data for a better estimate of image smoothness (optional)\n#' @param dof Degrees of freedom (optional, but obligatory if residual is specified)\n#' @param Nh Number of thresholds (not safe to change the default)\n#' @param logpmin min threshold (not safe to change the default)\n#' @param logpmax max threshold (not safe to change the default)\n#' @param ZestThr Cluster-forming Z threshold below which P(h|c) is estimated as P(h), due to limitation of GRF theory. (default: 1.3, not safe to change)\n#' @param verbose boolean: print progress bar and diagnostic messages if true (default)\n#'\n#' @details The function takes a Z-score image and a mask image (both \"nifti\" object of the oro.nifti package) as obligatory inputs.\n#' Mask can be either binary or continous, in the latter case it will be thresholded at 0.5.\n#' Parameters V (number of voxels) and Rd (voxels per RESEL, computed as V*RESELS from the smoothest outpout) are optional and are to be interpreted as in FSL \"smoothest\".\n#' If you want pTFCE to compute FWER-based Z-threshold for correction of multiple comparisons, specify the parameter resels (resels field of smoothest), together with Rd and V.\n#' If not specified, these values are estimated from the data, internally via the smoothest() function of this package, which is a direct port of the corresponding FSL function.\n#' If Rd and/or V is not specified, and residual and dof is specified, image smoothness will be determined basedd on teh 4D residual data (more accurate, see ?smoothest()).\n#' For more details on smoothness estimation, see https://github.com/spisakt/pTFCE/wiki/Some-important-notes-on-smoothness-estimation.\n#' The default value of the parameter Nh should work with images having usual ranges of Z-scores. At low values, although the processing becomes faster, the estimation of the enhanced values might become inaccurate and the enhanced p-value distribution becomes increasingly non-uniform. It is not recommended to set it lower than 30.\n#' The parameters logpmin and logpmax define the range of values the incremental thresholding procedure covers. By default, these are based on the input data and it is not recommended to cahnge them.\n#'\n#' @return An object of class \"ptfce\" is a list containing at least the following components:\n#' \\itemize{\n#' \\item{\\strong{p} (uncorrected) pTFCE enhanced p-values}\n#' \\item{\\strong{logp} negative logarithm of pTFCE enhanced p-values}\n#' \\item{\\strong{Z} pTFCE enhanced p-values converted to Z-scores}\n#' \\item{\\strong{number_of_resels} number of resels (input for e.g. ptoz) }\n#' \\item{\\strong{fwer0.05.Z} Z-score threshold corresponding to the corrected p<0.05 threshold, controlled for FWER}\n#' }\n#'\n#' @export\n#'\n#' @examples \\dontrun{Z=readNIfTI(\"Zmap.nii.gz\");\n#'\n#' MASK=readNIfTI(\"mask.nii.gz\");\n#'\n#' # OPTION 1: use standalone with Z-map-based smoothness estimation\n#' pTFCE=ptfce(Z, MASK); # estimate smoothness based on the Z-score map\n#' # (might be inaccurate, but still guarantees FWER)\n#'\n#' #OPTION 2: use smoothness estimation based oj residual data (more accurate)\n#' RES4D=readNIfTI(\"res4D.nii.gz\");\n#' pTFCE=ptfce(Z, MASK, residual=RES4D) # a bit slow, currently...\n#'\n#' #OPTION 2: equivalent to option2, but faster (uses FSL)\n#' # run FSL smoothest in the command line:\n#' # smoothest -r res4d.nii.gz -d DOF -m mask.nii.gz > smoothness.txt\n#'\n#' smooth=read.table(\"smoothness.txt\"); # output by FSL smoothest\n#' pTFCE=ptfce(Z, V=smooth[2,2], Rd = smooth[1,2]*smooth[2,2], mask = MASK);\n#'\n#' # plot if you want\n#' orthographic(pTFCE$Z)\n#'\n#' # save NIfTI image\n#' writeNIfTI(pTFCE$Z, \"pTFCE_Z\")\n#'\n#' #See https://github.com/spisakt/pTFCE fro more examples\n#' }\nptfce=function(img, mask, Rd=NA, V=NA, resels=NA, residual=NA, dof=NA, logpmin=0, logpmax=-log(stats::pnorm(max(img), lower.tail = F)), ZestThr=1.3, Nh=100, verbose=T )\n{\n if (length(img[is.na(img)])>0)\n {\n warning(\"NAs detected and replaced with zero!\")\n img[is.na(img)] = 0\n }\n if (length(img[!is.finite(img)])>0)\n {\n warning(\"Infinite values detected and replaced with zero!\")\n img[!is.finite(img)] = 0\n }\n autosmooth=F\n if (is.na(Rd) || is.na(V))\n {\n autosmooth=T\n if (!is.na(residual))\n {\n if (!is.na(dof))\n {\n warning(\"Smoothness estimatmion based on 4D residual data is suboptimal and might be slow! Consider using FSL smoothest instead!\")\n smooth=smoothest(residual, mask, dof = dof, verbose = verbose)\n }\n else\n {\n warning(\"Residual but no dof specified: defaulting back to Z-score map-based smoothnes estimation\")\n smooth=smoothest(img, mask, verbose = verbose)\n }\n }\n else\n {\n smooth=smoothest(img, mask, verbose = verbose)\n }\n V=smooth$volume\n Rd=smooth$dLh*V\n }\n\n logp.thres=seq(logpmin, logpmax, length.out=Nh)\n dh=logp.thres[2]-logp.thres[1]\n p.thres=exp(-logp.thres)\n threshs=stats::qnorm(p.thres, lower.tail = F)\n threshs[1]=-9999999999 # exp(-Inf):=0 #TODO: machine minimum\n ndh = length(threshs)\n CLUST=array(NA, dim=c(dim(img), length(threshs)))\n PVC=array(1, dim=c(dim(img), length(threshs)))\n\n if (verbose) cat(\"* Performing pTFCE...\\n\")\n if (verbose) pb <- utils::txtProgressBar(style = 3)\n for (hi in 1:length(threshs))\n {\n if (verbose) utils::setTxtProgressBar(pb, hi/length(threshs))\n h=threshs[hi]\n thr=img\n thr[img>h]=1\n thr[img<=h]=0\n ccc=mmand::components(thr, kernel = mmand::shapeKernel(3, dim = 3, type = \"diamond\"))\n t=table(ccc)\n sizes=t[ccc]\n sizes=sizes*as.numeric(mask)\n\n CLUST[,,,hi]=sizes\n\n for (size in sort(unique(sizes)) )\n {\n if (size==0)\n next;\n PVC[,,,hi][sizes==size]=pvox.clust(V, Rd, size, h, ZestThr=ZestThr)\n }\n # plot if you want\n # orthographic(nifti(CLUST[,,, hi], datatype=16) )\n }\n # calculate pTFCE\n pTFCE=array(apply(PVC, c(1,2,3), function(x){exp( -aggregate_logpvals(-log(x), dh) )}), dim=dim(img))\n\n # copy nifit header information\n snames = methods::slotNames(img)\n snames = snames[ !snames %in% c(\".Data\", \"dim_\") ]\n pTFCE = oro.nifti::nifti(img = pTFCE, dim = dim(pTFCE))\n #BUG: this does not work if input is an array instead of nifti image\n class(pTFCE) = class(img)\n oro.nifti::datatype(pTFCE) = 16 # FLOAT32\n oro.nifti::bitpix(pTFCE) = 32 # FLOAT32\n pTFCE=oro.nifti::zero_trans(pTFCE)\n for (islot in snames) {\n methods::slot(pTFCE, islot) = methods::slot(img, islot)\n }\n # done copying header\n\n pTFCE[pTFCE==0]=.Machine$double.xmin #underflow\n pTFCE[pTFCE==1]=1-.Machine$double.neg.eps #underflow\n if (verbose) close(pb)\n if (autosmooth)\n {\n number_of_resels=smooth$volume / smooth$resels\n fwer0.05.Z=fwe.p2z(number_of_resels, 0.05)\n }\n else\n {\n if (is.na(resels))\n {\n warning(\"For GRF-based FWER correction, please specify resels, or use smoothness estimation based on the data, by not specifying Rd and V!\")\n number_of_resels=NA\n fwer0.05.Z=NA\n }\n else\n {\n number_of_resels=V / resels\n fwer0.05.Z=fwe.p2z(number_of_resels, 0.05)\n }\n\n }\n Z=stats::qnorm(pTFCE, lower.tail = F)\n oro.nifti::datatype(Z) = 16 # FLOAT32\n oro.nifti::bitpix(Z) = 32 # FLOAT32\n Z=oro.nifti::zero_trans(Z)\n return(list(p=pTFCE,\n logp=-log(pTFCE),\n Z=Z,\n number_of_resels=number_of_resels,\n fwer0.05.Z=fwer0.05.Z\n )\n )\n}\n\n# helper functions\n\n#' Aggregate logpvals by the \"equidistant incremental logarithmic probability aggregation\".\n#'\n#' @param logpvals vector of enhnaced -logP values correspoinding tho various thresholds\n#' @param d delta -logP (giving the equidistant distribution in the log-space)\n#'\n#' @return aggregated -logP probability\n#' @export\naggregate_logpvals=function(logpvals, d) #\n{\n logpvals[is.infinite(logpvals)]=745\n s=sum(logpvals)\n return( 0.5*(sqrt(d*(8*s+d))-d) )\n}\n\n#' expected value of cluster size at threshold h in img of size V with RESEL count Rd\n#' mainly ported from the source code of FSL (https://fsl.fmrib.ox.ac.uk/fsl/fslwiki)\n#'\n#' @param h image height, that is, Z score threshold\n#' @param V Number of voxels\n#' @param Rd Rd (dLh*V)\n#'\n#' @return Expected value of cluster size\nEs=function(h, V, Rd)\n{\n h2=h*h\n ret= ( log(V)+stats::pnorm(h, log.p = T, lower.tail = F) )\n h2=h2[h>=1.1]\n ret[h>=1.1] = ret[h>=1.1] - ( log(Rd)+log(h2-1)-h2/2+-2*log(2*pi) ) # from FSL\n\n return( exp(ret) )\n\n}\n\ndvox=function(h) # PDF of Z threshold/voxel value\n{\n stats::dnorm(h )\n}\n\npvox=function(h) # p-value for voxel value\n{\n stats::pnorm(h, lower.tail = F)\n}\n\ndclust=function(h, V, Rd, c, ZestThr=1.3, CONST=10^40) # PDF of cluster extent, given h thershold\n{\n if (is.na(c))\n return(dvox(h))\n dcl=function(h, V, Rd, c)\n {\n lambda=(Es(h, V, Rd)/gamma(2.5) )^(-2/3)\n dclust=lambda*exp(-lambda*c^(2/3))\n #dclust[dclust==0]=.Machine$double.xmin # underflow happened\n dclust[h0.5) &&\n (mask[x-1, y, z]>0.5) &&\n (mask[x, y-1, z]>0.5) &&\n ( (!usez) || (mask[x, y, z-1]>0.5) ) )\n {\n N=N+1\n\n if (!is.na(dim(img)[4])) # using res4D\n {\n for ( t in 1:dim(img)[4])\n {\n # Sum over M\n SSminus[X] = SSminus[X] + img[x, y, z, t] * img[x-1, y, z, t]\n SSminus[Y] = SSminus[Y] + img[x, y, z, t] * img[x, y-1, z, t]\n if (usez) SSminus[Z] = SSminus[Z] + img[x, y, z, t] * img[x, y, z-1, t]\n\n S2[X] = S2[X] + 0.5 * (img[x, y, z, t]*img[x, y, z, t] + img[x-1, y, z, t]*img[x-1, y, z, t])\n S2[Y] = S2[Y] + 0.5 * (img[x, y, z, t]*img[x, y, z, t] + img[x, y-1, z, t]*img[x, y-1, z, t])\n if (usez) S2[Z] = S2[Z] + 0.5 * (img[x, y, z, t]*img[x, y, z, t] + img[x, y, z-1, t]*img[x, y, z-1, t])\n }\n }\n else # using Z-score map\n {\n SSminus[X] = SSminus[X] + img[x, y, z] * img[x-1, y, z]\n SSminus[Y] = SSminus[Y] + img[x, y, z] * img[x, y-1, z]\n if (usez) SSminus[Z] = SSminus[Z] + img[x, y, z] * img[x, y, z-1]\n\n S2[X] = S2[X] + 0.5 * (img[x, y, z]*img[x, y, z] + img[x-1, y, z]*img[x-1, y, z])\n S2[Y] = S2[Y] + 0.5 * (img[x, y, z]*img[x, y, z] + img[x, y-1, z]*img[x, y-1, z])\n if (usez) S2[Z] = S2[Z] + 0.5 * (img[x, y, z]*img[x, y, z] + img[x, y, z-1]*img[x, y, z-1])\n\n }\n } # endif mask\n } #endz\n } #endy\n } #endx\n norm = 1.0/N\n v = dof # v - degrees of freedom (nu)\n if (!is.na(dim(img)[4])) # using res4D\n {\n print(paste(\"Non-edge voxels = \", N))\n print(paste(\"(v - 2)/(v - 1) = \", (v - 2)/(v - 1)))\n\n norm = (v - 2) / ((v - 1) * N * dim(img)[4]);\n }\n #print(paste(\"SSminus[X]\", SSminus[X], \"SSminus[Y]\", SSminus[Y],\"SSminus[Z]\", SSminus[Z],\"S2[X]\", S2[X],\"S2[Y]\", S2[Y],\"S2[Z]\", S2[Z]))\n\n # for extreme smoothness\n if (SSminus[X]>=0.99999999*S2[X])\n {\n SSminus[X]=0.99999*S2[X]\n warning(\"Extreme smoothness detected in X - possibly biased global estimate.\")\n }\n if (SSminus[Y]>=0.99999999*S2[Y])\n {\n SSminus[Y]=0.99999*S2[Y]\n warning(\"Extreme smoothness detected in Y - possibly biased global estimate.\")\n }\n if (usez)\n {\n if (SSminus[Z]>=0.99999999*S2[Z])\n {\n SSminus[Z]=0.99999*S2[Z]\n warning(\"Extreme smoothness detected in Z - possibly biased global estimate.\")\n }\n }\n\n # Convert to sigma squared\n sigmasq=rep(NA,3);\n\n sigmasq[X] = -1.0 / (4 * log(abs(SSminus[X]/S2[X])))\n sigmasq[Y] = -1.0 / (4 * log(abs(SSminus[Y]/S2[Y])))\n if (usez)\n {\n sigmasq[Z] = -1.0 / (4 * log(abs(SSminus[Z]/S2[Z])))\n }\n else\n {\n sigmasq[Z]=0\n }\n names(sigmasq)=c(\"x\", \"y\", \"z\")\n\n # the following is determininant of Lambda to the half\n # i.e. dLh = | Lambda |^(1/2)\n # Furthermore, W_i = 1/(2.lambda_i) = sigma_i^2 =>\n # det(Lambda) = det( lambda_i ) = det ( (2 W_i)^-1 ) = (2^D det(W))^-1\n # where D = number of dimensions (2 or 3)\n if (usez)\n {\n dLh=((sigmasq[X]*sigmasq[Y]*sigmasq[Z])^-0.5)*(8^-0.5)\n }\n else\n {\n dLh=((sigmasq[X]*sigmasq[Y])^-0.5)*(4^-0.5)\n }\n #correcting for temporal DOF!!!!!\n if(!is.na(dim(img)[4]))\n dLh = dLh * interpolate(v);\n\n # Convert to full width half maximum\n FWHM=rep(NA,3)\n FWHM[X] = sqrt(8 * log(2) * sigmasq[X])\n FWHM[Y] = sqrt(8 * log(2) * sigmasq[Y])\n if (usez)\n {\n FWHM[Z] = sqrt(8 * log(2) * sigmasq[Z])\n }\n else\n {\n FWHM[Z]=0\n }\n names(FWHM)=c(\"x\", \"y\", \"z\")\n\n resels = FWHM[X] * FWHM[Y]\n if (usez)\n resels = resels * FWHM[Z]\n\n if (verbose) close(pb)\n\n return(list(volume=mask_volume,\n sigmasq=sigmasq,\n FWHM=FWHM,\n dLh=dLh,\n resels=resels))\n}\n\nstandardise=function(mask, R)\n{\n M=dim(R)[4]\n if( !is.na(M) )\n {\n # For each voxel\n # standardise data in 4th direction\n R=aperm(apply(R, c(1,2,3), scale), c(2,3,4,1))\n R[is.na(R)]=0\n std=apply(R, c(1,2,3), stats::sd)\n mask[std<=0]=0 #TODO_ready: updtae mask if it differs from the actual data\n\n }#endif 4d\n mask[is.na(mask)]=0\n\n count=sum(mask[mask>0.5])\n\n return(list(count=count, mask=mask, R=R))\n}\n\ninterpolate=function(v)\n{\n lut=rep(NA,500)\n lut[5] = 1.5423138; lut[6] = 1.3757105; lut[7] = 1.2842680;\n lut[8] = 1.2272151; lut[9] = 1.1885232; lut[10] = 1.1606988;\n lut[11] = 1.1398000; lut[12] = 1.1235677; lut[13] = 1.1106196;\n lut[14] = 1.1000651; lut[15] = 1.0913060; lut[16] = 1.0839261;\n lut[17] = 1.0776276; lut[18] = 1.0721920; lut[19] = 1.0674553;\n lut[20] = 1.0632924; lut[25] = 1.0483053; lut[30] = 1.0390117;\n lut[40] = 1.0281339; lut[50] = 1.0219834; lut[60] = 1.0180339;\n lut[70] = 1.0152850; lut[80] = 1.0132621; lut[90] = 1.0117115;\n lut[100] = 1.0104851; lut[150] = 1.0068808; lut[200] = 1.0051200;\n lut[300] = 1.0033865; lut[500] = 1.0020191;\n\n if (v<6) return(1.1) # ?? no idea - steve ??\n\n if (v>500)\n {\n retval=1.0321/v + 1\n }\n else\n {\n lut.low=lut[1:floor(v)]\n lut.high=lut[ceiling(v):length(lut)]\n\n j.first=which(lut==min(lut.low, na.rm = T))\n j.second=lut[j.first]\n\n i.first=which(lut==max(lut.high, na.rm = T))\n i.second=lut[i.first]\n\n retval = (j.second - i.second)/(j.first - i.first)*(v - i.first) + j.second\n }\n return(retval^0.5)\n\n}\n\n#' Convert Z-score value to FWER corrected p-value\n#'\n#' https://github.com/spisakt/pTFCE\n#'\n#' @param resel_count resel count\n#' @param Z z-score value\n#'\n#' @details The Z-score value is converted to to p-value, corrected for multiple comparisons by controlling for famili-wise error rate\n#' The parameter resel_count is the number of resels (resolution elements) in the image, and can be obtained e.g by smoothest() (see examples).\n#'\n#' @return FWER-corrected p-value\n#'\n#' @export\n#'\n#' @examples\n#' \\dontrun{\n#' s=smoothest(zmap, mask)\n#' fwe.z2p(resel_count=s$volume/s$resels, Z=2.3)\n#'\n#' pTFCE=ptfe(zmap, mask)\n#' fwe.z2p(pTFCE$number_of_resels, Z=3.1)\n#' }\nfwe.z2p=function(resel_count, Z)\n{\n # based on FSL\n #the probability of a family wise error is approximately equiv- alent to the expected Euler Characteristic\n if (Z<2)\n p=1 # Below z of 2 E(EC) becomes non-monotonic\n else\n p = resel_count * 0.11694 * exp(-0.5*Z*Z)*(Z*Z-1) #/* 0.11694 = (4ln2)^1.5 / (2pi)^2 */\n return(min(p,1.0))\n}\n\n#' Get Z-score threshold for an FWER corrected p-value\n#'\n#' https://github.com/spisakt/pTFCE\n#'\n#' @param resel_count resel count\n#' @param FWEP FWER corrected p-value\n#'\n#' @details The p-value, corrected for multiple comparisons by controlling for family-wise error rate, is converted to a Z-score threshold.\n#' The parameter resel_count is the number of resels (resolution elements) in the image, and can be obtained e.g by smoothest() (see examples).\n#'\n#' @return Z-score threshold\n#'\n#' @export\n#'\n#' @examples\n#' \\dontrun{\n#' s=smoothest(zmap, mask)\n#' fwe.p2z(resel_count=s$volume/s$resels, FWEP=0.05)\n#'\n#' pTFCE=ptfe(zmap, mask)\n#' fwe.p2z(pTFCE$number_of_resels, FWEP=0.05)\n#' }\nfwe.p2z=function(resel_count, FWEP=0.05)\n{\n # based on FSL ptoz implementation\n p=FWEP/(resel_count*0.11694) #/* (4ln2)^1.5 / (2pi)^2 */\n\n #if (p0.5)\n return(0)\n else\n {\n l=2\n u=100\n z=0\n while (u-l>0.001)\n {\n z=(u+l)/2\n pp=exp(-0.5*z*z)*(z*z-1)\n if (pp k_min}. Here \\eqn{k_min} is the degree threshold above which the parametric distribution holds, \\eqn{\\pi_k} are probabilities of the low-tail, \\eqn{f(.,\\theta)} is the parametric distribution with parameter vector \\eqn{\\theta}. \n\nFor fixed \\eqn{k_min} and \\eqn{f}, \\eqn{\\pi_k} and \\eqn{\\theta} can be estimated by Maximum Likelihood Estimation. We can choose the best \\eqn{k_min} for each \\eqn{f} by comparing the AIC (or BIC). More details can be founded in Handcock and Jones (2004).\n}\n\\usage{\n test_linear_PA(degree_vector)\n}\n%- maybe also 'usage' for other objects documented here.\n\\arguments{\n \\item{degree_vector}{\n a degree vector\n }\n}\n\\value{\n Outputs a \\code{Linear_PA_test_result} object which contains the fitting of five distributions to the degree vector: Yule (\\code{yule}), Waring (\\code{waring}), Poisson (\\code{pois}), geometric (\\code{geom}) and negative binomial (\\code{nb}). In particular, for each distribution, the AIC and BIC are calcualted for each \\eqn{k_min}. \n}\n\\author{\n Thong Pham \\email{thongpham@thongpham.net}\n}\n\\references{\n 1. Handcock MS, Jones JH (2004). “Likelihood-based inference for stochastic models of sexual network formation.” Theoretical Population Biology, 65(4), 413 – 422. ISSN 0040-5809. \\url{https://doi.org/10.1016/j.tpb.2003.09.006}. Demography in the 21st Century, \\url{http://www.sciencedirect.com/science/article/pii/S0040580904000310}.\n}\n\\examples{\n\\dontrun{\n library(\"PAFit\")\n set.seed(1)\n net <- generate_BA(n = 1000)\n stats <- get_statistics(net, only_PA = TRUE)\n u <- test_linear_PA(stats$final_deg)\n print(u)\n}\n}\n\n\\concept{linear preferential attachment}\n\\concept{fitting degree distributions}\n", "meta": {"hexsha": "0383b48402f5a1d262ae01a5ae773e186f255ee2", "size": 2829, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/test_linear_PA.rd", "max_stars_repo_name": "eddelbuettel/PAFit", "max_stars_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "man/test_linear_PA.rd", "max_issues_repo_name": "eddelbuettel/PAFit", "max_issues_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "man/test_linear_PA.rd", "max_forks_repo_name": "eddelbuettel/PAFit", "max_forks_repo_head_hexsha": "4e362700bccb0de76778f31312b113cce85f6b4b", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.5, "max_line_length": 528, "alphanum_fraction": 0.7426652527, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6086981980526607}} {"text": "#==========================================================================================================================\n#==========================================================================================================================\n\n# 4. faza: Analiza podatkov\n\n#==========================================================================================================================\n#==========================================================================================================================\n\nstar_skup_60_64 <- starostne_skupine %>% filter(starostne_skupine == \"60-64 let\")\n\ng63 <- ggplot(star_skup_60_64) + \n aes(x = leto, y = stevilo) + \n geom_point() + \n geom_smooth(method = \"gam\", se = FALSE)\n\nmgam1 <- gam(stevilo ~ leto , \n data = star_skup_60_64)\nleta1 <- data.frame(leto = seq(2021,2026))\nnapoved <- leta1 %>% mutate(stevilo = predict(mgam1, .))\n\ntabela.napoved <- bind_rows(star_skup_60_64, napoved) %>% select(-starost)\ntabela.napoved1 <- tabela.napoved[c(17:22),]\n\ngraf_napoved_60_64 <- ggplot(tabela.napoved, \n aes(x = leto, y = stevilo)) + \n geom_point() + \n scale_x_continuous(name = \"leto\", breaks = seq(2005,2026,1)) + \n ylab(\"število delovno aktivnih\") +\n ggtitle(\"Napoved števila delovno aktivnih v starostni skupini od 60 do 64 do leta 2026\") +\n geom_smooth(method = 'gam', formula = y ~ x, se = FALSE, color=\"darkgoldenrod1\") + \n theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1))\n\nnovi_podatki <- data.frame(leto = seq(2021, 2026))\nnapoved <- novi_podatki %>% mutate(stevilo=predict(mgam1, .))\n\ngraf_napoved_60_64 <- graf_napoved_60_64 +\n geom_point(data=tabela.napoved1,\n aes(x=leto, y=stevilo),\n color=\"red\")\n\n#==========================================================================================================================\n\nstar_skup_25_29 <- starostne_skupine %>% filter(starostne_skupine == \"25-29 let\")\n\ng638 <- ggplot(star_skup_25_29) + \n aes(x = leto, y = stevilo) + \n geom_point() + \n geom_smooth(method = \"gam\", se = FALSE)\n\nmgam2 <- gam(stevilo ~ leto , \n data = star_skup_25_29)\nnapoved <- leta1 %>% mutate(stevilo = predict(mgam2, .))\n\ntabela.napoved2 <- bind_rows(star_skup_25_29, napoved) %>% select(-starost)\ntabela.napoved3 <- tabela.napoved2[c(17:22),]\n\ngraf_napoved_25_29 <- ggplot(tabela.napoved2) + \n aes(x = leto, y = stevilo) + \n geom_point() + \n scale_x_continuous(name = \"leto\", breaks = seq(2005,2026,1)) + \n ylab(\"število delovno aktivnih\") +\n ggtitle(\"Napoved števila delovno aktivnih v starostni skupini od 25 do 29 let do leta 2026\") +\n geom_smooth(method = 'gam', formula = y ~ x, se = FALSE, color=\"aquamarine2\") + \n theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1)) + \n expand_limits(y=0)\n\nnovi_podatki2 <- data.frame(leto = seq(2021, 2026))\nnapoved2 <- novi_podatki2 %>% mutate(stevilo=predict(mgam2, .))\n\ngraf_napoved_25_29 <- graf_napoved_25_29 +\n geom_point(data=tabela.napoved3,\n aes(x=leto, y=stevilo),\n color=\"red\")\n\n", "meta": {"hexsha": "05154f7208c72be445e1260bf3fc1366416fabb2", "size": 3068, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "NikaFurlan/APPR-2020-21", "max_stars_repo_head_hexsha": "1e7a5a8fa540ea03cb544bd057b6fb6f5263d6b4", "max_stars_repo_licenses": ["MIT"], "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": "NikaFurlan/APPR-2020-21", "max_issues_repo_head_hexsha": "1e7a5a8fa540ea03cb544bd057b6fb6f5263d6b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-23T09:32:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T11:00:04.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "NikaFurlan/APPR-2020-21", "max_forks_repo_head_hexsha": "1e7a5a8fa540ea03cb544bd057b6fb6f5263d6b4", "max_forks_repo_licenses": ["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.9066666667, "max_line_length": 123, "alphanum_fraction": 0.5290091265, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.608618850392262}} {"text": "designBasedCont = function(gamma, outcome_vec, pcf_cat_vec, instid_vec){\r\n\t#' Compute Design Based Draper-Gittoes Z-Scores\r\n\t#'\r\n\t#'\t\\code{designBased} implements design based approach and\r\n\t#' computes O, E, and z vectors following Draper-Gittoes (2004)\r\n\t#'\r\n\t#' @param gamma Parameter in [0,1] controling pooling.\r\n\t#' Gamma = 1 is complete global pooling, gamma = 0 is complete local pooling.\r\n\t#' @param outcome_vec Vector with elements in {0,1} denoting the binary outcome.\r\n\t#' @param pcf_cat_vec Vector with unique values for each PCF category.\r\n\t#' @param instid_vec Vector with unique values for each institution.\r\n\t\t\t\r\n\t#Some of the inputs need to be factors\r\n\tpcf_cat_vec = as.factor(pcf_cat_vec)\r\n\tinstid_vec = as.factor(instid_vec)\r\n\tinstid_vec_i = as.integer(instid_vec)\r\n\tpcf_cat_vec_i = as.integer(pcf_cat_vec)\r\n\t\r\n\t#Summarize\r\n\tinstid_unique = levels(instid_vec)\r\n\tinstid_unique_i = as.integer(instid_unique)\r\n\tn = length(outcome_vec)\r\n\tn_u = length(levels(instid_vec))\r\n\tunique_cat = levels(pcf_cat_vec)\r\n\tn_cat = length(unique_cat)\r\n\tp_global = mean(outcome_vec)\r\n\t\r\n\t\r\n\t#Compute Table 2 in Draper-Gittoes\r\n\ty_mat = n_mat = s_mat = matrix(0, nrow =n_u, ncol = n_cat)\r\n\r\n\tfor (i in 1:n){\r\n inst = as.integer(instid_vec[i])\r\n categ = as.integer(pcf_cat_vec[i])\r\n n_mat[inst,categ] = n_mat[inst,categ] + 1\r\n y_mat[inst, categ] = y_mat[inst, categ] + outcome_vec[i]\r\n\t} \r\n\tybar_mat = y_mat / n_mat \r\n\tybar_mat[n_mat == 0] = 0 \r\n\t\r\n\t#Create variance mat.\r\n\tmean_mat2 = matrix(0, nrow = n_u, ncol = n_cat)\r\n\tfor (i in 1:n_cat){\r\n\t\tfor (j in 1:n_u){\r\n\t\t\toutcomes = outcome_vec[pcf_cat_vec_i == i & instid_vec_i == j]\r\n\t\t\tif (length(outcomes) > 0){\r\n\t\t\t\tmean_mat2[j,i] = mean(outcomes)\r\n\t\t\t}\r\n\t\t\tif (length(outcomes) > 1){\r\n\t\t\t\ts_mat[j,i] = var(outcomes)\r\n\t\t\t\t}\t\r\n\t\t}\r\n\t}\r\n\t\r\n\ts_global = var(outcome_vec)\r\n\ts_mat[n_mat == 1] = s_global\r\n\t\r\n\t#Compute marginals\r\n\tpcf_ybar_vec = apply(y_mat, 2, sum) / apply(n_mat, 2, sum)\r\n\tn_u_vec = apply(n_mat, 1, sum)\r\n\tn_cat_vec = apply(n_mat, 2, sum)\r\n\r\n\t#Equation (2) in Draper-Gittoes (2004)\r\n\tO = apply(y_mat, 1, sum) / apply(n_mat, 1, sum)\r\n\t#Equation (3) in D-G\r\n\tE = apply(t(t(n_mat) * pcf_ybar_vec), 1, sum) / n_u_vec\r\n\t#Equation (4) in D-G\r\n\tD = O - E\r\n\r\n\t#Variance\r\n\tlambdaFun = function(i,k,j){\r\n\t\t#Equation (7) in D-G. #Unchanged for continious\r\n\t\tif (i == k){\r\n\t\t\treturn(n_mat[i,j]/n_u_vec[i] * (1 - (n_mat[i,j]/n_cat_vec[j])))\r\n\t\t} else{\r\n\t\t\treturn( -1 * (n_mat[i,j] * n_mat[k,j]) / (n_u_vec[i] * n_cat_vec[j]) )\r\n\t\t}\r\n\t}\r\n\t\r\n\tvFun = function(k,j, gamma = 0.5){\r\n\t\t#Equation (11) in D-G #Changed for continous\r\n\t\tn = n_mat[k,j]\r\n\t\tif (n > 0){\r\n\t\t\ts_local = s_mat[k,j]\r\n\t\t\ts_use = gamma * s_global + (1-gamma) * s_local\r\n\t\t\treturn(s_use/n)\r\n\t\t} else {\r\n\t\t\treturn(0)\r\n\t\t}\r\n\t}\r\n\tcomputeVi = function(i, gamma){\r\n\t\t#Equation (8) in D-G #Unchanged for cnontnious\r\n\t\tv = 0\r\n\t\tfor (k in 1:n_u){\r\n\t\t\tfor (j in 1:n_cat){\r\n\t\t\t\tv = v + lambdaFun(i,k,j)^2 * vFun(k, j, gamma)\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn(v)\r\n\t}\r\n\t# #Now compute w/ lapply\r\n\tV = sapply(1:n_u, computeVi, gamma)\r\n\tSE = sqrt(V)\r\n\t\r\n\tout_df = data.frame(\r\n\t\t\tinst = as.numeric(as.character(instid_unique)),\r\n\t\t\teffect = O-E,\r\n\t\t\tO = O,\r\n\t\t\tE = E,\r\n\t\t\tD = D,\r\n\t\t\tSE = SE,\r\n\t\t\tZ = (O - E) / SE,\r\n\t\t\tn = n_u_vec\t\r\n\t)\r\n\treturn( out_df[order(out_df$inst), ])\r\n}\r\n", "meta": {"hexsha": "378a2e58ce8eaddafb2b5b1251bee0e2973b7bd3", "size": 3278, "ext": "r", "lang": "R", "max_stars_repo_path": "R/designBasedCont.r", "max_stars_repo_name": "dhelkey/babymonitor", "max_stars_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/designBasedCont.r", "max_issues_repo_name": "dhelkey/babymonitor", "max_issues_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/designBasedCont.r", "max_forks_repo_name": "dhelkey/babymonitor", "max_forks_repo_head_hexsha": "591dbfa43678ee25be1ea0d9601da78735be0639", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0170940171, "max_line_length": 82, "alphanum_fraction": 0.6226357535, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6085633116846662}} {"text": "# 4. faza: Napredna analiza podatkov\n\n#NAPOVED RASTI BRUTO MINIMALNE PLAČE V SLOVENIJI\n\nslo_napoved <- min_place %>% filter(Drzava == 'Slovenia')\nprileganje <- lm(data = slo_napoved, Placa ~ Leto)\ng <- data.frame(Leto=seq(2016, 2020, 1))\nnapoved <- mutate(g, Placa=predict(prileganje, g))\n\ngraf_regresija <- ggplot(slo_napoved, aes(x=Leto, y=Placa)) + \n geom_point() + geom_smooth(method=lm, fullrange = TRUE, color = 'blue') + \n geom_point(data=napoved, aes(x=Leto, y=Placa), color='red', size=2) +\n ggtitle('Napoved nadaljne rasti minimalne bruto plače v Sloveniji') + \n ylab('Plača')\n \n\nplaca_v_2018 <- filter(napoved, Leto == 2018)\nplaca_v_2019 <- filter(napoved, Leto == 2019)\n#Realna min. plača v 2018: 842,79€\n#Realna min. plača v 2019: 886,63€\n\n", "meta": {"hexsha": "677e00aad2f1b1a9191af31772c7948f15147ba3", "size": 759, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "lanazajc/APPR-2018-19", "max_stars_repo_head_hexsha": "8792b30f9ea5fa72c8752efc096dc87fd1af5e6b", "max_stars_repo_licenses": ["MIT"], "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": "lanazajc/APPR-2018-19", "max_issues_repo_head_hexsha": "8792b30f9ea5fa72c8752efc096dc87fd1af5e6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2018-12-12T18:38:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-19T11:28:16.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "lanazajc/APPR-2018-19", "max_forks_repo_head_hexsha": "8792b30f9ea5fa72c8752efc096dc87fd1af5e6b", "max_forks_repo_licenses": ["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.5, "max_line_length": 76, "alphanum_fraction": 0.6996047431, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.608225239095674}} {"text": "# Algorithms\n# Source this file to load simulation algorithms for Ising model.\n# Includes:\n# - Sumit's algorithm (AG algorithm for Ising model)\n# - Metropolis-Hastings\n# - Swendsen-Wang\n# - Wolff's algorithm\n# - Exact force\n#\n# Remark: this file uses functions in tools.r\n# Source this file before running tests.\n\nsource(\"tools.r\")\n\n#####################################################################\n## Sumit's algorithm (more formally, Auxiliary Gaussian algorithm\n# for Ising model.\n# Note: this algorithm is also proposed in Martens & Sutskever (2010))\n\nsumit_sampler <- function (A, beta, B = 0, init, n_iter = 1000,\n alpha_modif = 1e-7,\n retain_alpha = FALSE,\n perturb = TRUE) {\n # Simulate states from the Ising model, using an auxiliary\n # gaussian variable, q, for the Ising model.\n #\n # There are two options for setting alpha:\n # (i) alpha is the smallest absolute eigenvalue, plus\n # an 'infitinesimal' modifier. This modifier needs to\n # be large enough to be significant within floating point\n # precision. A default that seems to work is 1E-15.\n # The user can specify the modifier with alpha_modif.\n # (ii) the user specifies alpha directly with alpha_modif\n # argument, after setting retain_alpha = TRUE.\n #\n # Note: this algorithm requires x in {-1, 1}\n\n if (retain_alpha) { alpha = alpha_modif } else {\n # alpha = min(abs(eigen(A, symmetric = TRUE, \n # only.values = TRUE)$values))\n # CHECK ME!!!\n # alpha = min(abs(eigen(A, symmetric = TRUE,\n # only.values = TRUE)$values))\n alpha = abs(min(eigen(A, symmetric = TRUE,\n only.values = TRUE)$values))\n alpha = alpha + alpha_modif \n }\n\n n_particles = nrow(A)\n C = beta * (A + alpha * diag(n_particles))\n # lower triangular Cholesky decomposition of Sigma\n L = t(chol(solve(C)))\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n for (i in (1:n_iter - 1)) {\n # update q\n q = mvrnorm_cholesky(n = 1, mu = x, L = L)\n\n # update x\n q_C = q %*% C\n u = runif(n_particles, 0, 1)\n for (j in 1:n_particles) {\n p = 1 / (1 + exp(-2 * (q_C[j] + B)))\n if (p > u[j]) { x[j] = 1 } else { x[j] = -1 }\n }\n\n # Random perturbator.\n if (perturb) {\n prob_flip = exp(- 2 * B * sum(x))\n u = runif(1, 0, 1)\n perturbator = - 2 * (u <= prob_flip) + 1\n x = perturbator * x\n X[i + 1, ] = x\n } else {\n X[i + 1, ] = x\n }\n }\n X\n}\n\n##########################################################################\n## Specialization of the lowrank AG Potts sampler for the Ising\n# model case.\n\nag_ising_lowrank <- function (A, beta, init, n_iter, epsilon = 1e-12) {\n n_particles = nrow(A)\n alpha = abs(min(eigen(A, symmetric = TRUE,\n only.values = TRUE)$values))\n C = beta * (A + alpha * diag(n_particles))\n spectral_decomposition = eigen(C, symmetric = TRUE)\n \n n_rank = length(\n spectral_decomposition$values[spectral_decomposition$values > epsilon])\n eigen_values_sqrt = sqrt(spectral_decomposition$values[1:n_rank])\n \n scaled_eigenvectors <- matrix(NA, nrow = n_particles, ncol = n_rank)\n for (i in 1:n_rank) {\n scaled_eigenvectors[, i] = spectral_decomposition$values[i] *\n spectral_decomposition$vectors[, i]\n }\n\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n \n q = rep(NA, n_rank)\n\n for (i in 2:n_iter) {\n mu_q = t(spectral_decomposition$vectors[, 1:n_rank]) %*% x\n q = rnorm(n_rank) / eigen_values_sqrt + mu_q\n\n P = scaled_eigenvectors %*% q\n\n u = runif(n_particles, 0, 1)\n for (j in 1:n_particles) {\n # p = 1 / (1 + exp(-2 * scaled_eigenvectors[j, ] %*% q))\n p = 1 / (1 + exp(-2 * P[j]))\n if (p > u[j]) { x[j] = 1 } else { x[j] = -1 }\n }\n X[i, ] = x\n }\n\n X\n}\n\n#####################################################################\n## Metropolis-Hastings\n\nmh_sampler <- function (A, beta, B = 0, \n init, n_iter, perturb = FALSE) {\n # CHECK ME - the Markov chain samples the same point when the\n # Metropolis proposal gets rejected??\n n_particles = nrow(A)\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n kernel_x = ising_kernel(beta, A, x, B)\n\n for (i in 1:n_iter) {\n # randomly generate a new state.\n # x_new = sample(c(-1, 1), n_particles, replace = TRUE)\n\n # randomly flip one of the spins\n x_new = x\n index <- sample(length(x), 1)\n x_new[index] = - x[index]\n\n kernel_new = ising_kernel(beta, A, x_new, B)\n a = kernel_new / kernel_x\n\n # a = ising_kernel(beta, A, x_new, B) / ising_kernel(beta, A, x, B)\n u = runif(1, 0, 1)\n if (u < a) {\n x = x_new\n kernel_x = kernel_new\n }\n\n if (perturb) {\n prob_flip = exp(- 2 * B * sum(x))\n u = runif(1, 0, 1)\n perturbator = - 2 * (u < prob_flip) + 1\n x = perturbator * x\n kernel_x = exp(log(kernel_x) - 2 * B * sum(x))\n } else {\n x = x\n }\n\n X[i, ] = x\n }\n X\n}\n\n#####################################################################\n## Heat bath -- for each iteration, attempt to update each node.\n\nhb_sampler <- function(A, beta, B = 0, init, n_iter,\n sub_sample = nrow(A),\n is_potts = FALSE, n_states = 2) {\n n_particles = nrow(A)\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n if (!is_potts) {\n kernel_x = ising_kernel(beta, A, x, B, log = T)\n } else {\n kernel_x = potts_log_kernel(beta = beta, A = A, x = x, B = B)\n }\n \n for (i in 1:n_iter) {\n # randomly sample which particles get updated\n update_particles = sample(1:n_particles, sub_sample, replace = FALSE)\n \n if (!is_potts) { # Ising model with x in {-1, 1}\n for (j in update_particles) {\n x_new = x\n x_new[j] = - x_new[j]\n kernel_new = ising_kernel(beta, A, x_new, B, log = T)\n a = 1 / (1 + exp(kernel_x - kernel_new))\n u = runif(1, 0, 1)\n if (u < a) {\n x = x_new\n kernel_x = kernel_new\n }\n }\n } else { # Potts model with x in {1, 2, ..., n_states}\n for (j in update_particles) {\n x_new = x\n other_states <- (1:n_states)[-x[j]]\n x_new[j] = other_states[sample(n_states - 1, 1)]\n kernel_new = potts_log_kernel(beta = beta, A = A, x = x_new,\n n_states = n_states)\n a = 1 / (1 + exp(kernel_x - kernel_new))\n u = runif(1, 0, 1)\n if (u < a) {\n x = x_new\n kernel_x = kernel_new\n }\n }\n }\n X[i, ] = x\n }\n X\n}\n\n#####################################################################\n## Swendsen-Wang\n\nsw_sampler <- function (A, beta, B = 0, init, n_iter, wolff = FALSE,\n is_potts = FALSE, n_states = 2) {\n # Simulates samples from an ising model, using the\n # Swendsen-Wang algorithm. This algorithm introduces\n # an auxiliary random cluster.\n # The algorithm is written for a complete graph, meaning\n # every particle can be connected to any other particle,\n # when constructing the random cluster (i.e. the algorithm is\n # agnostic to whether we're sampling on a grid or not).\n # \n # If Wolff = TRUE, use Wolff's algorithm instead of SW.\n # That is, for each iteration, construct only one cluster,\n # started at a random point.\n #\n # The space of x is {-1, 1}, unless is_potts is TRUE,\n # in which case the space is {1, 2, ..., n_states}. Note\n # the Adjacency matrix needs to be adjusted to reduce to the \n # Ising model case.\n #\n # FIX ME - use a lower triangular matrix instead of a full\n # matrix for the edges. Could be done in C++ (with Eigen).\n n_particles = nrow(A)\n n_edges = n_particles * (n_particles - 1) / 2\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n edges = matrix(NA, nrow = n_particles, ncol = n_particles)\n\n # Remark: p[i, j] = 0 if A[i, j] = 0.\n p = 1 - exp(-2 * beta * A)\n \n if (is_potts) p_states = 1 / n_states # Assuming B = 0\n\n for (i in 1:(n_iter - 1)) {\n # Compute auxiliary random clusters.\n # j and k respectively index rows and columns in the\n # edge matrix.\n for (j in 2:n_particles) {\n for (k in 1:(j - 1)) {\n if (x[j] != x[k] | A[j, k] == 0) { edges[j, k] = 0\n } else {\n u = runif(1, 0, 1)\n if (u < p[j, k]) { edges[j, k] = 1 } else { edges[j, k] = 0 }\n }\n }\n }\n\n # Identify clusters and assign a spin.\n free_nodes = 1:n_particles\n j = 1\n if (wolff == T) wolff_node = sample(1:n_particles, 1)\n while (length(free_nodes) != 0) {\n if (wolff == T) j = wolff_node\n\n # Can only start a new cluster with a free node.\n cluster = c(j)\n cluster_grows = TRUE\n free_nodes = free_nodes[-match(j, free_nodes)]\n\n while (cluster_grows) {\n cluster_grows = FALSE\n potential_connection = free_nodes\n\n # Only expand the cluster if there are potential connections.\n if (length(potential_connection) != 0) {\n for (k in potential_connection) {\n if (edges[max(k, j), min(k, j)] == 1) {\n cluster = c(cluster, k)\n free_nodes = free_nodes[-match(k, free_nodes)]\n }\n }\n }\n if (length(cluster) > match(j, cluster)) {\n cluster_grows = T\n j = cluster[match(j, cluster) + 1]\n }\n }\n\n u = runif(1, 0, 1)\n \n if (!is_potts) { # Ising model with x in {-1, 1}\n p_flip = 1 / (1 + exp(- 2 * length(cluster) * B))\n if (u < p_flip) { x[cluster] = 1 } else { x[cluster] = -1 }\n # print(paste0(\"cluster: \", cluster)) # use for tests\n } else { # Potts models with x in {1, 2, ..., n_states}\n p_current = p_states\n state = 1\n while (u > p_current) {\n state = state + 1\n p_current = p_current + p_states\n }\n x[cluster] = state\n }\n\n if (length(free_nodes) != 0) j = min(free_nodes)\n if (wolff == T) break\n }\n\n X[i + 1, ] = x\n }\n X\n}\n\nwolff_sampler <- function (A, beta, B = 0, init, n_iter,\n is_potts = FALSE, n_states = 2) {\n # Wolff algorithm. This is a variation of S-W that only\n # pertubs one cluster per iteration (and as a consequence,\n # it is easier to code).\n\n n_particles = nrow(A)\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n x = init\n X[1, ] = x\n\n # Remark: p[i, j] = 0 if A[i, j] = 0.\n p = 1 - exp(-2 * beta * A)\n \n if (is_potts) p_states = 1 / n_states # Assuming B = 0\n\n for (i in 1:(n_iter - 1)) {\n source_node = sample(1:n_particles, 1)\n free_nodes = (1:n_particles)[-source_node]\n cluster = c(source_node)\n j = source_node\n cluster_grows = T\n\n while (cluster_grows) {\n cluster_grows = F\n for (k in free_nodes) {\n # compute whether there is an edge or not\n u = runif(1, 0, 1)\n edge = (x[j] == x[k]) & (u < p[j, k])\n if (edge) {\n # cluster_grows = T\n cluster = c(cluster, k)\n free_nodes = free_nodes[-match(k, free_nodes)]\n }\n }\n if (length(cluster) > match(j, cluster)) {\n cluster_grows = T\n j = cluster[match(j, cluster) + 1]\n }\n # if (cluster_grows) j = cluster[match(j, cluster) + 1]\n }\n u = runif(1, 0, 1)\n # p_flip = 1 / (1 + exp(- 2 * length(cluster) * B))\n if (!is_potts) { # Ising model with x in {-1, 1}\n p_flip = exp(- 2 * B * sum(x[cluster]))\n if (u < p_flip) { x[cluster] = -x[cluster]}\n } else { # Potts models with x in {1, 2, ..., n_states}\n p_current = p_states\n state = 1\n while (u > p_current) {\n state = state + 1\n p_current = p_current + p_states\n }\n x[cluster] = state\n }\n\n X[i + 1, ] = x\n }\n X\n}\n\n###############################################################################\n## Potts sampler\npotts_sampler <- function(A, theta, init, n_sample) {\n # Uses the R package Potts sampler by (Okabayashi, Johnson and Geyer, 2011)\n # Assume we have a squared grid.\n # Convert from {-1, 1} to {2, 1} to respect Potts convention.\n # NOTE -- we may be waisting time doing a lot of copying back\n # and forth, so don't use this measure algorithm run time.\n #\n # theta is canonical parameter, equals 2 * beta.\n ncolor <- as.integer(2)\n n_particles <- nrow(A)\n init_color <- init\n init_color[init_color == -1] <- 2\n x_init <- packPotts(matrix(init_color,\n nrow = sqrt(n_particles),\n ncol = sqrt(n_particles)),\n ncolor = 2)\n\n samples <- matrix(NA, n_sample, n_particles)\n\n # set canonical parameter. No B-field, so \"color parameters\"\n # need to be equal.\n parameter <- c(rep(0, 2), theta)\n\n for (i in 1:n_sample) {\n if (i %% 100 == 0) print(paste0(\"iteration: \", i, \" / \", n_sample))\n if (i == 1) out <- x_init\n out <- potts(out, parameter, nbatch = 1,\n boundary = \"free\")\n\n samples[i, ] <- as.vector(t(unpackPotts(out$final)))\n samples[i, samples[i, ] == 2] <- -1\n }\n samples\n}\n\n###############################################################################\n## Exact sampler\n\nexact_sampler <- function (p, n_particles, n_iter) {\n # Takes in the exact probability for each state, ordered using\n # binary basis.\n\n X = matrix(NA, nrow = n_iter, ncol = n_particles)\n for (i in 2:length(p)) p[i] = p[i - 1] + p[i]\n\n for (i in 1:n_iter) {\n u = runif(1, 0, 1)\n state = which(abs(p - u) == min(abs(p - u)))\n if (p[state] - u < 0) state = state + 1\n\n # remember we count states, starting at 0!\n X[i, ] = to_binary(state - 1, n_particles, ising_state = TRUE)\n }\n\n X\n}\n", "meta": {"hexsha": "19c3ba1f298299b73900e521ffd883a27af0c566", "size": 13807, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/algorithms.r", "max_stars_repo_name": "charlesm93/potts_simulation", "max_stars_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-21T16:25:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-21T16:25:09.000Z", "max_issues_repo_path": "scripts/algorithms.r", "max_issues_repo_name": "charlesm93/potts_simulation", "max_issues_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/algorithms.r", "max_forks_repo_name": "charlesm93/potts_simulation", "max_forks_repo_head_hexsha": "5f0247d58b5d83b777679b10d2d6e424fee3606b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4118942731, "max_line_length": 79, "alphanum_fraction": 0.5403056421, "num_tokens": 4193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6082115079071766}} {"text": "# Defines several coefficents for the drift and diffusion.\n# Also defines functions for conversions between processes related through a lamperti transform.\n\n#################################\n## General Coefficients\n#################################\n\nmake_constant_coefficient <- function(const_val)\n # Creates a function that returns a constant.\n #\n # Args:\n # const_val (numeric): The value that the produced function should return\n # Returns:\n # (function(anything, anything)): A function that will always return const_val\n function(t,x) const_val\n\nmake_affine_coefficient <- function(a, b)\n # Creates a affine function a*x+b.\n #\n # Args:\n # a (numeric): The constant term of the affine function\n # b (numeric): The first order term of the affine function\n # Returns:\n # (function(anything, numeric)): A function that returns a*x+b\n function(t,x) a*x + b\n\n#################################\n## Drift Coefficients\n#################################\n\nmake_mean_reverting_coefficient <- function(reversion_rate, long_term_mean)\n # Creates a mean reverting function of the form -reversion_rate(x-long_term_mean)\n #\n # Args:\n # reversion_rate (numeric): The mean reverting rate\n # long_term_mean (numeric): The value that the process reverts to.\n # Returns:\n # (function(anything, numeric)): A function that returns -reversion_rate(x-long_term_mean)\n function(t,x) -reversion_rate*(x - long_term_mean)\n\nmu_1d_from_paper <- function(t, y){\n # The drift coefficient. Implementing equation 5.2 from the paper.\n #\n # Args:\n # t (numeric): The current time\n # y (numeric): The Lamperti-transformed process\n sigma <- 0.4\n x <- convert_y_to_x_1d(y)\n denom <- 1 + x*x\n return(2*sigma*x/(denom*denom))\n}\n\nconvert_y_to_x_1d <- function(y){\n # Converts Y_t to X_t in equation 5.2\n #\n # Args:\n # y (numeric): The Lamperti-transformed process\n X0 <- 1\n sigma <- 0.4\n temp <- (27*X0*X0 + 81)*X0 + 162*sigma*y\n temp <- (.5*(sqrt(temp*temp + 2916) + temp))^(1.0/3) / 3\n return(temp - 1/temp)\n}\n\nconvert_x_to_y_1d <- function(x){\n # Converts X_t to Y_t in equation 5.2\n #\n # Args:\n # x (numeric): The original process\n X0 <- 1\n sigma <- .4\n return((x-X0 + (x*x*x - X0*X0*X0)/3) / (2*sigma))\n}\n\nmake_mu_section_52_euler <- function(d)\n # Returns the drift coefficient function described in section 5.2 from the paper.\n #\n # Args:\n # d (int): The current dimension\n function(t, x){\n # Args:\n # t (numeric): The current time\n # x (matrix): The current value of the process across all paths for this dimension\n x <- matrix(x)\n x[d,]*0.1*(sqrt(x[d,]) - 1)\n }\n\nmake_mu_from_paper_multi_dimension_lamperti <- function(d)\n # Returns the drift coefficient function of the lamperti transform\n # of the process described in section 5.2 from the paper.\n #\n # Args:\n # d (int): The current dimension\n function(t, y){\n # Args:\n # t (numeric): The current time\n # y (matrix): The ending value of the process for each dimension and path\n X0 <- 1\n x <- convert_y_to_x_multi_d(y)\n return(0.2*(sqrt(x[d])-1) - 0.25)\n }\n\nconvert_y_to_x_multi_d <- function(y){\n # Converts Y_t (lamperti) to X_t from section 5.2\n #\n # Args:\n # y (matrix or vector or numeric): Values of Y_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of X_t corresponding to each Y_t\n X0 <- 1\n return(X0*exp(0.5*y))\n}\n\nconvert_x_to_y_multi_d <- function(x){\n # Converts X_t to Y_t (lamperti) from section 5.2\n #\n # Args:\n # x (matrix or vector or numeric): Values of X_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of Y_t corresponding to each X_t\n X0 <- 1\n return(2*log(x/X0))\n}\n\nmake_mu_heston_variance <- function(lambda, vbar)\n # Returns the drift coefficient function of the lamperti transform\n # of the Heston variance process\n #\n # Args:\n # lambda (numeric): The mean reversion rate\n # vbar (numeric): The long term mean\n function(t, v){\n # Args:\n # t (numeric): The current time\n # v (vector or numeric): The current variance\n if (any(v<=0)) print('(mu) v went <=0 !!!') # FIXME\n return(-lambda*((v>0)*v - vbar)) # full truncation\n }\n\nmake_mu_heston_variance_lamperti <- function(lambda, vbar, eta, v0){\n # Returns the drift coefficient function of the lamperti transform\n # of the Heston variance process\n #\n # Args:\n # lambda (numeric): The mean reversion rate\n # vbar (numeric): The long term mean\n # eta (numeric): The volatility of volatility\n # v0 (numeric): The initial variance\n convert_y_to_x_heston_variance <- make_convert_y_to_x_heston_variance(eta, v0)\n function(t, y){\n # Args:\n # t (numeric): The current time\n # v (vector or numeric): The current variance\n v <- convert_y_to_x_heston_variance(y)\n if (any(v<=0)) print('(mu L) v went <=0 !!!') # FIXME\n v <- (v>0)*v # full truncation\n return((-lambda*(v-vbar)/eta - 0.25*eta) / sqrt(v))\n }\n}\n\nmake_convert_y_to_x_heston_variance <- function(eta, v0)\n function(y){\n # Converts Y_t (lamperti) to v_t from the Heston variance process\n #\n # Args:\n # y (matrix or vector or numeric): Values of Y_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of X_t corresponding to each Y_t\n rootv <- 0.5*eta*y + sqrt(v0)\n return(rootv*rootv)\n }\n\nmake_convert_x_to_y_heston_variance <- function(eta, v0)\n function(v)\n # Converts X_t to Y_t (lamperti) from the Heston variance process\n #\n # Args:\n # x (matrix or vector or numeric): Values of X_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of Y_t corresponding to each X_t\n return(2*(sqrt(v)-sqrt(v0))/eta)\n\nmake_mu_black_scholes_lamperti <- function(mu, sigma)\n # Returns the drift coefficient function of the lamperti transform\n # of the Black Scholes process\n #\n # Args:\n # TODO\n function(t, y)\n # Args:\n # t (numeric): The current time\n # y (matrix): The location of the Lamperti transformed process\n return(mu/sigma - 0.5*sigma)\n\nmake_convert_y_to_x_black_scholes <- function(sigma, X0)\n function(y)\n # Converts Y_t (lamperti) to v_t from the Black Scholes process\n #\n # Args:\n # y (matrix or vector or numeric): Values of Y_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of X_t corresponding to each Y_t\n return(X0*exp(sigma*y))\n\nmake_convert_x_to_y_black_scholes <- function(sigma, X0)\n function(x)\n # Converts X_t to Y_t (lamperti) from the Black Scholes process\n #\n # Args:\n # x (matrix or vector or numeric): Values of X_t potentially across dimensions and timesteps\n # Returns:\n # (matrix or vector or numeric): Values of Y_t corresponding to each X_t\n return(log(x/X0)/sigma)\n \nmake_mu_sin <- function(a, k, phi, b)\n # Returns the drift coefficient function of the sin process\n # dX_t = (b + a*sin(n*pi*x))*dt + sigma*dW_t\n #\n # Args:\n # a (numeric): The amplitude of the oscillatory process\n # n (numeric): The frequency of the oscillatory process\n # b (numeric): The drift of the sine process\n function(t, x)\n # Args:\n # t (numeric): The current time\n # x (matrix): The location of the process\n return(a*(sin(k*t + phi) + b))\n\n\n#################################\n## Diffusion Coefficients\n#################################\n\nsigma_from_paper <- function(t, x){\n # The diffusion coefficient. Implementing equation 5.1 from the paper.\n #\n # Args:\n # t (numeric): The current time\n # x (array_like): The previous value of the process for each path\n sigma <- 0.4\n return(2*sigma/(1+x*x))\n}\n\nsigma_deriv_from_paper <- function(t, x){\n # The derivative of the diffusion coefficient. Implementing equation 5.1 from the paper.\n #\n # Args:\n # t (numeric): The current time\n # x (array_like): The previous value of the process for each path\n sigma <- 0.4\n denom <- 1 + x*x\n return(-4*x*sigma / (denom*denom))\n}\n\nmake_sigma_section_52_euler <- function(d)\n # Returns the diffusion coefficient function described in section 5.2 from the paper.\n #\n # Args:\n # d (int): The current dimension\n function(t, x){\n # Args:\n # t (numeric): The current time\n # x (matrix): The current value of the process across all paths for this dimension\n x <- matrix(x)\n return(0.5*x[d,])\n }\n\nmake_sigma_cir <- function(eta)\n # Returns the CIR diffusion coefficient function eta*sqrt(X_t)\n #\n # Args:\n # eta (numeric): The diffusion scaling parameter.\n function(t, x){\n # Args:\n # t (numeric): The current time\n # x (matrix): The ending value of the process for each dimension and path\n if (any(x<=0)) print('(CIR) x went <=0 !!!') # FIXME\n return(eta*sqrt((x>0)*x)) # full truncation\n }\n", "meta": {"hexsha": "f2abfab5aedbbf8f5331f1cec02a9e1828fb210e", "size": 9612, "ext": "r", "lang": "R", "max_stars_repo_path": "coefficients.r", "max_stars_repo_name": "scotthounsell/exact-simulation", "max_stars_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-21T18:46:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T18:46:57.000Z", "max_issues_repo_path": "coefficients.r", "max_issues_repo_name": "scotthounsell/exact-simulation", "max_issues_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coefficients.r", "max_forks_repo_name": "scotthounsell/exact-simulation", "max_forks_repo_head_hexsha": "71ea16268e07e23ef99ad5586844a843bb1cf48a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3285714286, "max_line_length": 104, "alphanum_fraction": 0.6078859759, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.60818380187674}} {"text": "Temporal_Jaccard<-function(pre,post){\r\n if(class(pre)!=\"matrix\"){beta<-vegdist(rbind(pre,post),method = \"jaccard\")} else \r\n {beta<-rep(NA,nrow(pre))\r\n for(i in 1:nrow(pre)){\r\n beta[i]<-vegdist(rbind(pre[i,],post[i,]),method = \"jaccard\")}}\r\n return(beta)\r\n}\r\n\r\nTemporal_Bray<-function(pre,post){\r\n if(class(pre)!=\"matrix\"){beta<-vegdist(rbind(pre,post),method = \"bray\")} else \r\n {beta<-rep(NA,nrow(pre))\r\n for(i in 1:nrow(pre)){\r\n beta[i]<-vegdist(rbind(pre[i,],post[i,]),method = \"bray\")}}\r\n return(beta)\r\n}\r\n\r\n\r\nchange_metrics<-function(x,means=T){\r\n SR_ts<-apply(x>0,3,rowSums)\r\n Com_abund_ts<-apply(x,3,rowSums)\r\n Shan_ts<-apply(x,3,renyi,hill=T,scales=c(1))\r\n Simp_ts<-apply(x,3,renyi,hill=T,scales=c(2))\r\n \r\n log_SR<-log(SR_ts[,-1]/SR_ts[,1])\r\n log_abund<-log(Com_abund_ts[,-1]/Com_abund_ts[,1])\r\n log_shan<-log(Shan_ts[,-1]/Shan_ts[,1])\r\n log_simp<-log(Simp_ts[,-1]/Simp_ts[,1])\r\n \r\n Jaccard<-log_simp\r\n for(i in 2:dim(x)[3]){\r\n Jaccard[,i-1]<-Temporal_Jaccard(pre = x[,,1],post = x[,,i])\r\n }\r\n \r\n Bray_Curtis<-log_simp\r\n for(i in 2:dim(x)[3]){\r\n Bray_Curtis[,i-1]<-Temporal_Bray(pre = x[,,1],post = x[,,i])\r\n }\r\n \r\n if(means==T){Change.df<-data.frame(log_SR=colMeans(log_SR),log_Abund=colMeans(log_abund),log_Shannon=colMeans(log_shan),log_Simpson=colMeans(log_simp),Jaccard=colMeans(Jaccard),Bray_Curtis=colMeans(Bray_Curtis),Stress=Stressor_sub[-1])\r\n } else{Change.df<-data.frame(log_SR=c(log_SR),log_Abund=c(log_abund),log_Shannon=c(log_shan),log_Simpson=c(log_simp),Jaccard=c(Jaccard),Bray_Curtis=c(Bray_Curtis),Stress=rep(Stressor_sub[-1],each=dim(x)[1]))}\r\n return(Change.df)\r\n}\r\n\r\n", "meta": {"hexsha": "7aab25f9f4bffe2860ed4c201ca4fdcfc3cd3690", "size": 1641, "ext": "r", "lang": "R", "max_stars_repo_path": "metacomm-model/change_metrics.r", "max_stars_repo_name": "elahi/CIEE_models", "max_stars_repo_head_hexsha": "2a75bacc11c692e887bd353d7fd81d4c5a3da8c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "metacomm-model/change_metrics.r", "max_issues_repo_name": "elahi/CIEE_models", "max_issues_repo_head_hexsha": "2a75bacc11c692e887bd353d7fd81d4c5a3da8c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metacomm-model/change_metrics.r", "max_forks_repo_name": "elahi/CIEE_models", "max_forks_repo_head_hexsha": "2a75bacc11c692e887bd353d7fd81d4c5a3da8c7", "max_forks_repo_licenses": ["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.2954545455, "max_line_length": 238, "alphanum_fraction": 0.6569165143, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6081740196484299}} {"text": "Viterbi <- function(nQ, nS, A, E, Ini, Obs){\n # Viterbi's Algorithm: given HMM model & observed sequence, infer state path\n #\n # Args: \n # mQ: number of states\n # nS: number of different observed values\n # A: transition matrix\n # E: Emission matrix\n # Ini: initial state prob\n # Obs: observed sequence, an integer vector\n #\n # Output: A list of path(integer vector) and maximum likelihood(numerical)\n \n # Initialize vq\n vq <- Ini * E[, Obs[1]]\n nl <- length(Obs)\n # Update vq and save path\n i <- 2\n pathlist <- matrix(0, nQ, nl)\n pathlist[, 1] <- 1:nQ\n while (i <= nl){\n mat <- vq * A * (rep(1, nQ) %*% t(E[, Obs[i]]))\n vq <- apply(mat, 2, max)\n nextState <- apply(mat, 2, which.max)\n pathlist[, i] <- nextState\n i <- i + 1\n }\n ml <- max(vq)\n endState <- which.max(vq)\n path <- rep(0, nl)\n path[nl] <- endState\n for (i in (nl - 1):1){\n path[i] <- pathlist[path[i + 1], i + 1]\n }\n output <- list(Path = path, Likelihood = ml)\n return(output)\n}\n\n\n\nE <- matrix(c(.7, .9, .6, .2, .05, .3, .1, .05, .1), 3, 3)\nA <- matrix(c(.1, .9, .7, .5, .05, .2, .4, .05, .1), 3, 3)\nObs <- c(3, 1, 2, 3, 1)\nIni <- c(.2, .4, .4)\nViterbi(3, 3, A, E, Ini, Obs)\n#\"3\" \"1\" \"3\" \"1\" \"2\"\n\n#Comparison between \"HMM\" and this function. Viterbi is 30% faster.\nlibrary(HMM)\nhmm <- initHMM(c(\"1\", \"2\", \"3\"), c(\"a\", \"b\", \"c\"), Ini, A, E)\nObsletter <- c(\"c\", \"a\", \"b\", \"c\", \"a\")\n\nlibrary(microbenchmark)\nmicrobenchmark(viterbi(hmm, Obsletter), Viterbi(3, 3, A, E, Ini, Obs))\n", "meta": {"hexsha": "3a2a17aa598ad8f0bd500990be4b98525316a560", "size": 1499, "ext": "r", "lang": "R", "max_stars_repo_path": "viterbi.r", "max_stars_repo_name": "DeltaMethod721/HMM", "max_stars_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "viterbi.r", "max_issues_repo_name": "DeltaMethod721/HMM", "max_issues_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viterbi.r", "max_forks_repo_name": "DeltaMethod721/HMM", "max_forks_repo_head_hexsha": "62710307159a2a9c860f52208a7b13da4b8a2e32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2545454545, "max_line_length": 78, "alphanum_fraction": 0.5530353569, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6080607797892378}} {"text": "\nphredToProb <- function(phred) {\n\tif (phred == \"#\") return(1)\n\tphredNum <- as.integer(charToRaw(phred))-33\n\t10^(-phredNum/10)\n}\n\n#calculster posteriors for variant calls, taking into account the size of the cluster\n# in which the calls were found\nbayesBase <- function(calls, quals, templ, mutRate=0.0025, clusterSize=1) {\n\t#convert phred quals to error probabilities\n\tprobs <- sapply(quals, function(phred) {\n\t\t#multiple qualities for the same base can occur for inserations or deletions\n\t\t#they are treated as multiplicative (i.e. the probability of all being errors)\n\t\tprod(sapply(toChars(phred), phredToProb))\n\t})\n\t#all possible hypothetical bases (=q) to test\n\tqs <- unique(c(templ,calls))\n\t#calculate priors for each base given the template and mutation rate\n\t#note: this could be sped up by keeping a hash/lookup table of all possible values around\n\tr <- mutRate\n\tm <- clusterSize\n\tlogPriorOdds <- sapply(qs,\n\t\tfunction(q) if (q==templ) {#WT case\n\t\t\tlog((1-r)^m)-log(1-(1-r)^m)\n\t\t} else {#Mutant case\n\t\t\tlog(1-(1-r)^m)-log(3)-log(1-(1-(1-r)^m)/3)\n\t\t}\n\t)\n\t#log posterior odds = sum of log likelihood ratios plus prior\n\tk <- colSums(do.call(rbind,lapply(1:length(calls), function(i) {\n\t\t#error probablity\n\t\tp <- probs[[i]]\n\t\t#for each possible base: calculate the log likelihood ratio (LLR).\n\t\t#Given that illumina discretizes the qualities, a lookup table could speed this up too\n\t\tsetNames(sapply(qs, function(q) {\n\t\t\t#if the basecall supports the hypothetical base\n\t\t\tif (calls[[i]] == q) {\n\t\t\t\tlog(1-p)-log(p)+log(3)\n\t\t\t#otherwise, if the basecall contradicts the hypothetical base\n\t\t\t} else {\n\t\t\t\tlog(p) - log(3) - log(1/3-p/9)\n\t\t\t}\n\t\t}),qs)\n\t}))) + logPriorOdds\n\t#convert to posterior probabilities\n\treturn(exp(k)/(1+exp(k)))\n}\n\n#input \"callClusters\" is list of lists of dataframes. Each top layer element correponds to a\n# read pair, containing a list clusters. The clusters themselves are datafraames that list proximal\n# proposed variant calls with columns refbase, refpos, readbase1, qual1, readbase2, qual2\n# in case of insertions, refbase is \"-\" and readbase and qual can contain more than one value,\n# in case of deletions, readbase1/readbase2 is \"-\" and qual1/qual2 would contain the qualities of the neighbouring two base calls.\nprocessClusters <- function(callClusters, mutrate=0.0025) {\n\t#calculate posterior probabilites for each call in each cluster\n\tout <- lapply(callClusters, function(clusters) {\n\t\t#iterate over each cluster for the current read pair\n\t\tlapply(clusters, function(cluster) {\n\t\t\tif (!is.data.frame(cluster)){\n\t\t\t\treturn(cluster)\n\t\t\t}\n\t\t\t#cluster size\n\t\t\tcsize <- nrow(cluster)\n\t\t\t#iterate over the proposed nucleotide change in the current cluster\n\t\t\t# and calculate posteriors\n\t\t\tposteriors <- lapply(1:csize,function(i) with(cluster[i,],{\n\t\t\t\t#check if any calls are missing or \"N\"\n\t\t\t\tna1 <- is.na(readbase1) || readbase1==\"N\"\n\t\t\t\tna2 <- is.na(readbase2) || readbase2==\"N\"\n\t\t\t\tif (na1 && na2) {\n\t\t\t\t\t#if there's no usable data, it's WT\n\t\t\t\t\t# return(cbind(cluster,varcall=refbase,post=1))\n\t\t\t\t\tsetNames(1,refbase)\n\t\t\t\t} else if (na1) {\n\t\t\t\t\tbayesBase(readbase2,qual2,refbase,mutrate,csize)\n\t\t\t\t} else if (na2) {\n\t\t\t\t\tbayesBase(readbase1,qual1,refbase,mutrate,csize)\n\t\t\t\t} else {\n\t\t\t\t\tbayesBase(\n\t\t\t\t\t\tc(readbase1,readbase2),\n\t\t\t\t\t\tc(qual1,qual2),\n\t\t\t\t\t\trefbase,mutrate,csize\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}))\n\t\t\tvarcall <- sapply(posteriors,function(x)names(which.max(x)))\n\t\t\tcallPosteriors <- mapply(function(posteriors,varcall)posteriors[[varcall]],posteriors,varcall)\n\t\t\treturn(cbind(cluster,varcall=varcall,post=callPosteriors))\n\t\t})\n\t})\n\treturn(out)\n}\n", "meta": {"hexsha": "6b3c1eb840524ac4e9fe07237833e1f9940347a9", "size": 3590, "ext": "r", "lang": "R", "max_stars_repo_path": "other/varCallerSnippet.r", "max_stars_repo_name": "RyogaLi/tilseq_mutcount", "max_stars_repo_head_hexsha": "ba6d82851981d0849673e8858b208a5aecab4064", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "other/varCallerSnippet.r", "max_issues_repo_name": "RyogaLi/tilseq_mutcount", "max_issues_repo_head_hexsha": "ba6d82851981d0849673e8858b208a5aecab4064", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2020-08-19T22:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-17T14:22:35.000Z", "max_forks_repo_path": "other/varCallerSnippet.r", "max_forks_repo_name": "RyogaLi/tilseq_mutcount", "max_forks_repo_head_hexsha": "ba6d82851981d0849673e8858b208a5aecab4064", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-09T14:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T14:15:45.000Z", "avg_line_length": 38.1914893617, "max_line_length": 130, "alphanum_fraction": 0.7011142061, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.6076914391785943}} {"text": "subroutine stoke(x1,y1,x2,y2,rw,area,s1,eps,nerror)\n\n# Apply Stokes' theorem to find the area of a polygon;\n# we are looking at the boundary segment from (x1,y1)\n# to (x2,y2), travelling anti-clockwise. We find the\n# area between this segment and the horizontal base-line\n# y = ymin, and attach a sign s1. (Positive if the\n# segment is right-to-left, negative if left to right.)\n# The area of the polygon is found by summing the result\n# over all boundary segments.\n\n# Just in case you thought this wasn't complicated enough,\n# what we really want is the area of the intersection of\n# the polygon with the rectangular window that we're using.\n\n# Called by dirout.\n\nimplicit double precision(a-h,o-z)\ndimension rw(4)\nlogical value\n\nzero = 0.d0\nnerror = -1\n\n# If the segment is vertical, the area is zero.\ncall testeq(x1,x2,eps,value)\nif(value) {\n area = 0.\n s1 = 0.\n return\n}\n\n# Find which is the right-hand end, and which is the left.\nif(x1=xmax) {\n area = 0.\n return\n}\n\n# We're now looking at a trapezoidal region which may or may\n# not protrude above or below the horizontal strip bounded by\n# y = ymax and y = ymin.\nybot = min(yl,yr)\nytop = max(yl,yr)\n\n# Case 1; ymax <= ybot:\n# The `roof' of the trapezoid is entirely above the\n# horizontal strip.\nif(ymax<=ybot) {\n area = (xr-xl)*(ymax-ymin)\n return\n}\n\n# Case 2; ymin <= ybot <= ymax <= ytop:\n# The `roof' of the trapezoid intersects the top of the\n# horizontal strip (y = ymax) but not the bottom (y = ymin).\nif(ymin<=ybot&ymax<=ytop) {\n call testeq(slope,zero,eps,value)\n if(value) {\n w1 = 0.\n w2 = xr-xl\n }\n else {\n xit = xl+(ymax-yl)/slope\n w1 = xit-xl\n w2 = xr-xit\n if(slope<0.) {\n tmp = w1\n w1 = w2\n w2 = tmp\n }\n }\n area = 0.5*w1*((ybot-ymin)+(ymax-ymin))+w2*(ymax-ymin)\n return\n}\n\n# Case 3; ybot <= ymin <= ymax <= ytop:\n# The `roof' intersects both the top (y = ymax) and\n# the bottom (y = ymin) of the horizontal strip.\nif(ybot<=ymin&ymax<=ytop) {\n xit = xl+(ymax-yl)/slope\n xib = xl+(ymin-yl)/slope\n if(slope>0.) {\n w1 = xit-xib\n w2 = xr-xit\n }\n else {\n w1 = xib-xit\n w2 = xit-xl\n }\n area = 0.5*w1*(ymax-ymin)+w2*(ymax-ymin)\n return\n}\n\n# Case 4; ymin <= ybot <= ytop <= ymax:\n# The `roof' is ***between*** the bottom (y = ymin) and\n# the top (y = ymax) of the horizontal strip.\nif(ymin<=ybot&ytop<=ymax) {\n area = 0.5*(xr-xl)*((ytop-ymin)+(ybot-ymin))\n return\n}\n\n# Case 5; ybot <= ymin <= ytop <= ymax:\n# The `roof' intersects the bottom (y = ymin) but not\n# the top (y = ymax) of the horizontal strip.\nif(ybot<=ymin&ymin<=ytop) {\n call testeq(slope,zero,eps,value)\n if(value) {\n area = 0.\n return\n }\n xib = xl+(ymin-yl)/slope\n if(slope>0.) w = xr-xib\n else w = xib-xl\n area = 0.5*w*(ytop-ymin)\n return\n}\n\n# Case 6; ytop <= ymin:\n# The `roof' is entirely below the bottom (y = ymin), so\n# there is no area contribution at all.\nif(ytop<=ymin) {\n area = 0.\n return\n}\n\n# Default; all stuffed up:\nnerror = 8\nreturn\n\nend\n", "meta": {"hexsha": "fe1d0589d0ced95c2033990fb32d9056a4799feb", "size": 3958, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/stoke.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/stoke.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/stoke.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 23.843373494, "max_line_length": 62, "alphanum_fraction": 0.5533097524, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.6075943833828248}} {"text": "library(\"MASS\")\nlibrary(\"lattice\")\nload(\"./simul-2017.Rdata\")\n\n#Valeur pour mettre plus en valeur les screens pour le rapport\nlwd_default <- 1\n\n##########################################\n# Q1.1\n##########################################\n#Affichage de l'ensemble d'apprentissage\ncouleur_app<-rep('red',n_app)\ncouleur_app[classe_app==1]='red'\ncouleur_app[classe_app==2]='blue'\ncouleur_app[classe_app==3]='green'\n\nplot(x_app, col = couleur_app, lwd = lwd_default)\n\n#Affichage de l'ensemble de test\ncouleur_test<-rep('red',n_test)\ncouleur_test[classe_test==1]='red'\ncouleur_test[classe_test==2]='blue'\ncouleur_test[classe_test==3]='green'\nplot(x_test, col = couleur_test, lwd = lwd_default)\n\n##########################################\n# Q1.2\n##########################################\n#Affichage de l'ensemble d'apprentissage\nplot(x_app, col = couleur_app, lwd = lwd_default)\n\n# Déclaration des vecteurs moyennes\nM1 = seq(1,2)\nM2 = seq(1,2)\nM3 = seq(1,2)\n\n# Vecteur moyenne de la classe 1\nM1[1] = mean(x_app[classe_app==1,1])\nM1[2] = mean(x_app[classe_app==1,2])\n\n# Vecteur moyenne de la classe 2\nM2[1] = mean(x_app[classe_app==2,1])\nM2[2] = mean(x_app[classe_app==2,2])\n\n# Vecteur moyenne de la classe 3\nM3[1] = mean(x_app[classe_app==3,1])\nM3[2] = mean(x_app[classe_app==3,2])\n\npoints(M1[1], y = M1[2], pch = 20, col = \"red\", lwd=15)\npoints(M2[1], y = M2[2], pch = 20, col = \"blue\", lwd=15)\npoints(M3[1], y = M3[2], pch = 20, col = \"green\", lwd=15)\n\n#Affichage de l'ensemble d'apprentissage\nplot(x_app, col = couleur_app, lwd = lwd_default)\n\n# Matrices de co variance\nSigma1 <- matrix(1,2,2)\nSigma2 <- matrix(1,2,2)\nSigma3 <- matrix(1,2,2)\n\nfor (i in 1:2) {\n for (j in 1:2) {\n Sigma1[i,j]=cov(as.vector(x_app[classe_app==1,i]), as.vector(x_app[classe_app==1,j]))\n Sigma2[i,j]=cov(as.vector(x_app[classe_app==2,i]), as.vector(x_app[classe_app==2,j]))\n Sigma3[i,j]=cov(as.vector(x_app[classe_app==3,i]), as.vector(x_app[classe_app==3,j]))\n }\n}\n\ns1 = s1^2\ns2 = s2^2\ns3 = s3^2\n\n##########################################\n# Q1.3\n##########################################\n\n# Grille d'estimation de la densit´e de probabilit´e en 50 intervalles selon 1er attribut\nxp1 <- seq(min(x_app[,1]),max(x_app[,1]),length=50)\n# Grille d'estimation de la densit´e de probabilit´e en 50 intervalles selon 2eme attribut\nxp2 <- seq(min(x_app[,2]),max(x_app[,2]),length=50)\n\ngrille <- expand.grid(x1=xp1,x2=xp2)\nx_app_lda<-lda(x_app,classe_app)\n\n# Estimation des densit´es de probabilit´es a posteriori dans Zp\ngrille = cbind(grille[,1],grille[,2])\nZp <- predict(x_app_lda,grille)\n\n#Affichage des lignes de décision\nzp_3<-Zp[[\"posterior\"]][,3]-pmax(Zp[[\"posterior\"]][,1],Zp[[\"posterior\"]][,2])\nzp_2<-Zp[[\"posterior\"]][,2]-pmax(Zp[[\"posterior\"]][,1],Zp[[\"posterior\"]][,3])\n\ncontour(xp1,xp2,matrix(zp_3,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"green\", lwd = lwd_default)\ncontour(xp1,xp2,matrix(zp_2,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"blue\", lwd = lwd_default)\n\n##########################################\n# Q1.4\n##########################################\n\nassigne_test <- predict(x_app_lda, newdata=x_test)\n# Estimation des taux de bonnes classifications\ntable_classification_test_lda <-table(classe_test, assigne_test[[\"class\"]])\n# table of correct class vs. classification\ndiag(prop.table(table_classification_test_lda, 1))\n# total percent correct\ntaux_bonne_classif_test_lda <-sum(diag(prop.table(table_classification_test_lda)))\n\n# Création du vecteur contenant le code de la forme des données test assignées aux\nshape<-rep(1,n_test) ;\n# Forme des données assignées \nshape[assigne_test[[\"class\"]]==1]=1 ;\nshape[assigne_test[[\"class\"]]==2]=2 ;\nshape[assigne_test[[\"class\"]]==3]=3 ;\nplot(x_test,col=couleur_test,pch=shape,xlab = \"X1\", ylab = \"X2\", lwd = lwd_default)\n\n#Affichage des lignes de décision\ncontour(xp1,xp2,matrix(zp_3,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"green\", lwd = lwd_default)\ncontour(xp1,xp2,matrix(zp_2,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"blue\", lwd = lwd_default)\n\n##########################################\n# Q1.5\n##########################################\n#Affichage de l'ensemble d'apprentissage\nplot(x_app, col = couleur_app, lwd = lwd_default)\n\nx_app_qda<-qda(x_app,classe_app)\n\n# Estimation des densit´es de probabilit´es a posteriori dans Zp\nZp <- predict(x_app_qda,grille)\n\n#Affichage des lignes de décision\nzp_3<-Zp[[\"posterior\"]][,3]-pmax(Zp[[\"posterior\"]][,1],Zp[[\"posterior\"]][,2])\nzp_2<-Zp[[\"posterior\"]][,2]-pmax(Zp[[\"posterior\"]][,1],Zp[[\"posterior\"]][,3])\ncontour(xp1,xp2,matrix(zp_3,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"green\", lwd = lwd_default)\ncontour(xp1,xp2,matrix(zp_2,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"blue\", lwd = lwd_default)\n\nassigne_test <- predict(x_app_qda, newdata=x_test)\n# Estimation des taux de bonnes classifications\ntable_classification_test_qda <-table(classe_test, assigne_test[[\"class\"]])\n# table of correct class vs. classification\ndiag(prop.table(table_classification_test_qda, 1))\n# total percent correct\ntaux_bonne_classif_test_qda <-sum(diag(prop.table(table_classification_test_qda)))\n\n# Création du vecteur contenant le code de la forme des données test assignées aux\nshape<-rep(1,n_test) ;\n# Forme des données assignées \nshape[assigne_test[[\"class\"]]==1]=1 ;\nshape[assigne_test[[\"class\"]]==2]=2 ;\nshape[assigne_test[[\"class\"]]==3]=3 ;\n# Affichage avec code couleur et forme adapt´ees\nplot(x_test,col=couleur_test,pch=shape,xlab = \"X1\", ylab = \"X2\", lwd = lwd_default)\n\n#Affichage des lignes de décision\ncontour(xp1,xp2,matrix(zp_3,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"green\", lwd = lwd_default)\ncontour(xp1,xp2,matrix(zp_2,50),add=TRUE,levels=0,drawlabels=FALSE, col=\"blue\", lwd = lwd_default)\n\n", "meta": {"hexsha": "172600e02f38a01ba114afceb099fdbf209edcdc", "size": 5707, "ext": "r", "lang": "R", "max_stars_repo_path": "TP06/RDF_TP6_BARCHID_SLIMANI.r", "max_stars_repo_name": "Barchid/RDF", "max_stars_repo_head_hexsha": "1e0600de0a2e70f7edf598711d717a84e89231c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-02-08T19:23:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-25T15:22:24.000Z", "max_issues_repo_path": "TP06/RDF_TP6_BARCHID_SLIMANI.r", "max_issues_repo_name": "Barchid/RDF", "max_issues_repo_head_hexsha": "1e0600de0a2e70f7edf598711d717a84e89231c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TP06/RDF_TP6_BARCHID_SLIMANI.r", "max_forks_repo_name": "Barchid/RDF", "max_forks_repo_head_hexsha": "1e0600de0a2e70f7edf598711d717a84e89231c7", "max_forks_repo_licenses": ["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.1202531646, "max_line_length": 99, "alphanum_fraction": 0.6679516383, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6074984366307836}} {"text": "### Model Complexity Toy Example\r\n## Use: Generate data for the toy example in the paper\r\n## Author: Mark Verhagen\r\n\r\n## Load libraries\r\nlibrary(tidyverse)\r\nlibrary(texreg)\r\nlibrary(lmtest)\r\n\r\n## Set n and seed\r\nn <- 40000\r\nset.seed(1704)\r\n\r\n\r\nn <- 40000\r\nset.seed(1704)\r\n\r\n## Simulate data for toy example\r\n\r\nage <- rnorm(n, 0, 7.5) + 70\r\nage[age <= 50] <- runif(length(age[age <= 50]), 50, 51)\r\nage[age >= 90] <- runif(length(age[age >= 90]), 89, 90)\r\nmedication_use <- ifelse((age - 20) / 100 + runif(n, 0, 0.2) >\r\n runif(n, 0, 1), 1, 0)\r\ngender <- ifelse((runif(n, 0, 1) + (age / 1000)) > 0.5, 1, 0)\r\nassistance <- ifelse(runif(n, 0, 0.08) + (age / 180) > 0.5, 1, 0)\r\nerror <- rnorm(n, 0, 0.3)\r\n\r\nfixed_part <- (10 * (ifelse(age >= 50, (age - 50) * 0.025, -0.8) +\r\n ifelse(age > 65, (age - 65) * 0.05, 0) -\r\n ifelse(age > 75, (age - 75) * 0.04, 0) -\r\n ifelse(age > 85, (age - 85) * 0.025, 0) + 0.05 * assistance +\r\n 0.05 * medication_use -\r\n 0.1 * gender + error)) + 10\r\n\r\ny <- ifelse(fixed_part < 0, 0, fixed_part)\r\n\r\ndf <- data.frame(\r\n fall = y, age = age, age2 = age^2, med_use = medication_use,\r\n sex = gender, assist = assistance\r\n) %>%\r\n mutate(\r\n age_50p = ifelse(age >= 50, age - 50, 0),\r\n age_65p = ifelse(age > 65, age - 65, 0),\r\n age_75p = ifelse(age > 75, age - 75, 0),\r\n age_85p = ifelse(age > 85, age - 85, 0)\r\n )\r\n\r\n## Save datasets for other scripts\r\nsave(df, file = \"toy_example/data/edit/toy_data.rda\")\r\nwrite.csv(df, \"toy_example/data/edit/toy_df.csv\")\r\n\r\n\r\n## Estimate three functional forms\r\nlm1 <- lm(fall ~ 1 + age + assist + sex + med_use, data = df)\r\n\r\nlm2 <- lm(fall ~ 1 + age + age2 + assist + sex + med_use, data = df)\r\n\r\nlm3 <- lm(fall ~ 1 + age_50p + age_65p + age_75p + age_85p + assist + sex +\r\n med_use, data = df)\r\n\r\n## Evaluate LR-likelihood test\r\nlrtest(lm1, lm2)\r\nlrtest(lm2, lm3)\r\n\r\n## Output regression results\r\ntexreg(list(summary(lm1), summary(lm2), summary(lm3)),\r\n file = \"tex/tables/results_toy.tex\"\r\n)\r\nscreenreg(list(summary(lm1), summary(lm2), summary(lm3)))\r\n\r\n## Generate dataset including the implied age effect from the linear models\r\nlm1_df <- summary(lm1)$coefficients %>% as.data.frame()\r\nlm2_df <- summary(lm2)$coefficients %>% as.data.frame()\r\nlm3_df <- summary(lm3)$coefficients %>% as.data.frame()\r\n\r\ndf <- df %>%\r\n mutate(\r\n true_effect = 10 * (age_50p * 0.025 + age_65p * 0.05 -\r\n age_75p * 0.04 - age_85p * 0.025),\r\n lm1_implied = lm1_df$Estimate[1] + lm1_df$Estimate[2] * age - 10,\r\n lm2_implied = lm2_df$Estimate[1] + lm2_df$Estimate[2] * age + lm2_df$Estimate[3] * age2 - 10,\r\n lm3_implied = lm3_df$Estimate[1] + lm3_df$Estimate[2] * age_50p + lm3_df$Estimate[3] * age_65p +\r\n lm3_df$Estimate[4] * age_75p + lm3_df$Estimate[5] * age_85p - 10\r\n )\r\n\r\ndf_effects <- df %>%\r\n sample_frac(0.1) %>%\r\n dplyr::select(age, true_effect, lm1_implied, lm2_implied, lm3_implied) %>%\r\n reshape2::melt(id.vars = c(\"age\")) %>%\r\n mutate(` ` = ifelse(grepl(\"true\", variable), \"True effect\", NA))\r\n\r\nsaveRDS(df_effects, \"toy_example/data/edit/df_effects.rds\")", "meta": {"hexsha": "f190c69b651a9af182413f55a72d9aa87054dec5", "size": 3141, "ext": "r", "lang": "R", "max_stars_repo_path": "toy_example/00_gen_data.r", "max_stars_repo_name": "MarkDVerhagen/functional_form_complexity", "max_stars_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toy_example/00_gen_data.r", "max_issues_repo_name": "MarkDVerhagen/functional_form_complexity", "max_issues_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toy_example/00_gen_data.r", "max_forks_repo_name": "MarkDVerhagen/functional_form_complexity", "max_forks_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_forks_repo_licenses": ["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.7741935484, "max_line_length": 105, "alphanum_fraction": 0.5966252786, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.607119368727759}} {"text": "# James Rekow\r\n\r\neulerIntegrate = function(smpl, threshold = 10 ^ (-6), maxSteps = 10 ^ 4, tStep = 10 ^ (-2)){\r\n \r\n # ARGS: smpl - a sample of the form list(abd, gr, imat)\r\n # maxSteps - maximum number of time steps allowed before termination\r\n # tStep - length of time covered in each iteration (e.g. delta t)\r\n # threshold - cutoff below which a change in the abd vector is considered\r\n # a small step\r\n #\r\n # RETURNS: abd - numeric vector containing the integrated abd vector corresponding to smpl\r\n \r\n # extract list elements\r\n abd = smpl[[1]]\r\n gr = smpl[[2]]\r\n imat = smpl[[3]]\r\n \r\n # stores the number of consecutive small steps\r\n smallSteps = 0\r\n \r\n # integrate the system of ODEs from the GLV model with parameters from smpl using Euler's method\r\n for(j in 1:maxSteps){\r\n \r\n # compute delta x\r\n abdChange = abd * {gr + c(imat %*% abd)}\r\n deltaabd = tStep * abdChange\r\n abd = abd + deltaabd\r\n \r\n # ensure nonnegativity of abundances\r\n abd = 0.5 * {abs(abd) + abd}\r\n \r\n # check if delta x is less than the threshold value (euclidean distance with threshold pre-squared)\r\n smallStep = sum(abdChange * abdChange) < threshold\r\n \r\n # if delta x is less than the threshold value five times in a row, we assume x has \r\n # reached a steady state and terminate the loop\r\n if(smallStep){\r\n smallSteps = smallSteps + 1\r\n \r\n if(smallSteps == 5){\r\n break\r\n } # end if\r\n } # end if\r\n \r\n # reset small step counter if delta x is greater than the threshold value\r\n else{\r\n smallSteps = 0\r\n } # end else\r\n \r\n } # end integration loop\r\n \r\n # round (in part to set very small abundances to zero)\r\n abd = round(abd, 4)\r\n \r\n return(abd)\r\n \r\n} # end eulerIntegrate function\r\n", "meta": {"hexsha": "295719beb2d5a3bbe8412cfd93c7173bff378048", "size": 1840, "ext": "r", "lang": "R", "max_stars_repo_path": "eulerIntegrate.r", "max_stars_repo_name": "JamesRekow/GLV_Model", "max_stars_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eulerIntegrate.r", "max_issues_repo_name": "JamesRekow/GLV_Model", "max_issues_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-05-08T20:21:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T20:21:25.000Z", "max_forks_repo_path": "eulerIntegrate.r", "max_forks_repo_name": "JamesRekow/GLV_Model", "max_forks_repo_head_hexsha": "0c77c1e94906ee783d6a1698f4fa92d36ab08d70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.724137931, "max_line_length": 105, "alphanum_fraction": 0.6059782609, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6066398403299206}} {"text": "# Jinliang Yang\n# purpose: calculate the GCA and SCA\n# updated: 3.7.2012\n\n#Row Barcode KRN Note.x Pedigree Genotype Note.y\n#3133 8757 11-8757-23 OP 16 10g-1028-21/2048 Tzi8 x P39 Diallel\n# input data=d should contain trait and Genotype (Tzi x P39)\n\ngetca2 <- function(data=d, trait=\"KRN\", square=FALSE){\n ### check the required cols\n if (!(\"Genotype\" %in% names(data) & trait %in% names(data) )) \n stop(paste(\"Make sure your data frame contains columns Genotype and \", trait, sep=\"\"));\n data$Genotype <- as.character(data$Genotype)\n ### remove the self genotype\n idx <- grep(\"@\", data$Genotype);\n if(sum(idx)>0) data <- data[-idx,];\n \n ### get the p1, p2 and reciprocal col\n if(!(\"p1\" %in% names(data) & \"p2\" %in% names(data) & \"reciprocal\" %in% names(data) )){\n data$p1 <- NA;\n data$p2 <- NA;\n data$reciprocal <- NA;\n data$Genotype <- as.character(data$Genotype);\n for(i in 1:nrow(data)){\n tem <- unlist(strsplit(data$Genotype[i], split=\"x\"));\n tem <- sort(tem)\n data$p1[i] <- tem[1];\n data$p2[i] <- tem[2];\n data$reciprocal[i] <- paste(tem[1], tem[2], sep=\"_\")\n }\n }\n \n ### start the calculation according to Method 4, Model I\n uhat <- mean(data[,trait], na.rm=T);\n inbred <- sort(unique(c(data$p1, data$p2)));\n \n ### General Combining Ability\n gca <- data.frame(Genotype=inbred, GCA=NA);\n for(j in 1:length(inbred)){\n inbredj = inbred[j];\n ghat <- mean(subset(data, p1==inbredj | p2==inbredj)[, trait], na.rm=T)-uhat;\n gca[gca$Genotype==inbredj,]$GCA <- ghat;\n }\n \n ### Specific Combining Ability\n sca <- matrix(NA, nrow=length(inbred), ncol=length(inbred)+1);\n sca <- as.data.frame(sca)\n names(sca) <- c(trait, inbred)\n sca[,1] <- inbred\n \n specific <- unique(data$reciprocal);\n \n scatable <- data.frame()\n for(k in 1:length(specific)){\n tem2 <- unlist(strsplit(specific[k], split=\"_\"));\n myp1 <- tem2[1];\n myp2 <- tem2[2];\n \n pheno <- subset(data, (p1==myp1 & p2==myp2) | (p1==myp2 & p2==myp1));\n shat <- mean(pheno[, trait], na.rm=T) - subset(gca, Genotype==myp1)$GCA - subset(gca, Genotype==myp2)$GCA - uhat;\n if(square){\n sca[sca[,1]==myp1, myp2] <- shat;\n } else {\n temid <- paste(myp1, myp2, sep=\"x\");\n temsca <- data.frame(Genotype=temid, SCA=shat)\n scatable <- rbind(scatable, temsca)\n }\n \n }\n \n outputlist <- list();\n names(gca)[2] <- trait;\n outputlist[[1]] <- gca;\n names(scatable)[2] <- trait;\n if(square){\n outputlist[[2]] <- sca;\n } else{\n outputlist[[2]] <- scatable;\n }\n \n return(outputlist)\n}\n###############################################\nmydata <- read.csv(\"pheno_diallel_master_BLUE.csv\")\n\nkrnca <- getca2(data=mydata, trait=\"KRN\", square=FALSE)\nakwca <- getca2(data=mydata, trait=\"AKW\", square=FALSE)\ntkwca <- getca2(data=mydata, trait=\"TKW\", square=FALSE)\nkcca <- getca2(data=mydata, trait=\"KC\", square=FALSE)\n\ncdca <- getca2(data=mydata, trait=\"CD\", square=FALSE)\ncwca <- getca2(data=mydata, trait=\"CW\", square=FALSE)\nclca <- getca2(data=mydata, trait=\"CL\", square=FALSE)\n\n########## GCA #################\ngca_master <- merge(krnca[[1]], akwca[[1]], by=\"Genotype\")\ngca_master <- merge(gca_master, tkwca[[1]], by=\"Genotype\")\ngca_master <- merge(gca_master, kcca[[1]], by=\"Genotype\")\ngca_master <- merge(gca_master, cdca[[1]], by=\"Genotype\")\ngca_master <- merge(gca_master, cwca[[1]], by=\"Genotype\")\ngca_master <- merge(gca_master, clca[[1]], by=\"Genotype\")\n\nwrite.table(gca_master, \"pheno_diallel_master_BLUE_GCA.csv\", sep=\",\", row.names=FALSE, quote=FALSE)\n\n########## SCA #################\nsca_master <- merge(krnca[[2]], akwca[[2]], by=\"Genotype\")\nsca_master <- merge(sca_master, tkwca[[2]], by=\"Genotype\")\nsca_master <- merge(sca_master, kcca[[2]], by=\"Genotype\")\nsca_master <- merge(sca_master, cdca[[2]], by=\"Genotype\")\nsca_master <- merge(sca_master, cwca[[2]], by=\"Genotype\")\nsca_master <- merge(sca_master, clca[[2]], by=\"Genotype\")\n\nwrite.table(sca_master, \"pheno_diallel_master_BLUE_SCA.csv\", sep=\",\", row.names=FALSE, quote=FALSE)\n\n\n\n\n\npairs(d[, c(4,7,9, 11:13)], text.panel = diag, upper.panel=panel.smooth, \nlower.panel=panel.cor, gap=0, main=\"KRN Correlation Plots of three obs\")\n \n\n\n\n\n\n#################################################################################\n# make the design matrix\n#####################################################################################################################################################\ndesign <- read.table(\"/Users/yangjl/Documents/Heterosis_GWAS/SNP/diallel_4impute.txt\", header=TRUE)\n\ndm <- matrix(0, nrow=378, ncol=28+378)\ndm <- as.data.frame(dm)\np <- as.character(unique(design$p1));\nnames(dm) <- c(\"Geno\", p, as.character(design$geno))\ndm$Geno <- as.character(design$geno);\n\nfor(i in 1:nrow(dm)){\n tem <- unlist(strsplit(dm$Geno[i], split=\"x\"));\n p1 <- tem[1];\n p2 <- tem[2];\n dm[i, p1] <- 1;\n dm[i, p2] <- 1;\n dm[i, dm$Geno[i]] <- 1;\n}\n\n#################\ntrait <- read.csv(\"pheno_diallel_master_raw_040612.csv\")\ntrait$Curtiss <- 0; # Only B73\ntrait$Dairy <- 0;\ntrait$Johnson <- 0;\ntrait$zumwalt <- 0;\n\nfor (i in 1:nrow(trait)){\n farm <- as.character(trait$Farm[i]);\n trait[i, farm] <- 1;\n}\n\n#############################\n#FUNCTION to GCA and SCA\ngetca1 <- function(traitnm=\"TKW\"){\n tem <- merge(trait[, c(\"Genotype2\", traitnm, \"Dairy\", \"Johnson\", \"zumwalt\")], dm, by.x=\"Genotype2\", by.y=\"Geno\")\n tem <- tem[!is.na(tem[,2]),]\n yield <- tem[,2]\n \n idx1 <- numeric(ncol(tem))\n for(i in 3:ncol(tem)){\n idx1[i] <- sum(tem[,i])\n }\n idx <- which(idx1==0)\n \n dmatrix1 <- as.matrix(tem[, -idx]);\n fit1 <- lm(yield ~ dmatrix1)\n ped.hat1 <- fit1$coef\n ped.hat1 <- ped.hat1[!is.na(ped.hat1)]\n \n names(ped.hat1) <- gsub(\"dmatrix1\", \"\", names(ped.hat1));\n names(ped.hat1)[1] <- \"yhat\"\n \n gcaout <- data.frame(Genotype=names(ped.hat1[1:29]), GCA=ped.hat1[1:29]);\n names(gcaout)[2] <- traitnm;\n \n scaout <- data.frame(Genotype=names(ped.hat1[30:227]), GCA=ped.hat1[30:227]);\n names(gcaout)[2] <- traitnm;\n \n \n output <- list(gca=gcaout, sca=scaout)\n return(output)\n}\n\n#############\nkrn1 <- getca1(\"KRN\")\n\nkrntem <- merge(krnca[[2]], krn1[[2]], by=\"Genotype\", all.x=TRUE)\nkrntem[is.na(krntem)] <- 0\n\n\n\nkc <- getca(\"KC\")\nakw <- getca(\"AKW\")\ntkw <- getca(\"TKW\")\ncd <- getca(\"CD\")\ncw <- getca(\"CW\")\ncl <- getca(\"CL\")\n\n################################\n\ngetca(data=sample, trait=\"Yield\")\n#########################################################################################################################\nx1 <- c(\"P1\", \"P1\", \"P1\", \"P1\", \"P2\", \"P2\");\nx2 <- c(\"P2\", \"P2\", \"P3\", \"P3\", \"P3\", \"P3\")\nyield <- c(10, 12, 20, 22, 14, 16)\n\nsample <- data.frame(Parent1=x1, Parent2=x2, Yield=yield)\n\n#####################################################################################################################################################\nX <- matrix(c(1, 1, 0, 1, 0, 0,\n 1, 1, 0, 1, 0, 0,\n 1, 0, 1, 0, 1, 0,\n 1, 0, 1, 0, 1, 0,\n 0, 1, 1, 0, 0, 1,\n 0, 1, 1, 0, 0, 1), ncol=6, byrow=TRUE)\n\ny <- sample$Yield\nXX=t(X)%*%X \nlibrary(MASS) \nXXgi=ginv(XX) \nPx=X%*%XXgi%*%t(X)\nyhat=Px%*%y\n\nfit <- lm(y~X)\n\n\ny=c(4,1,3,5,3,3,1) \nX=matrix(c( \n 1,1,0,0,0,1,0,0, \n 1,1,0,0,0,0,1,0, \n 1,0,1,0,0,0,1,0, \n 1,0,1,0,0,0,0,1, \n 1,0,0,1,0,0,0,1, \n 1,0,0,0,1,1,0,0, \n 1,0,0,0,1,0,1,0 \n ),byrow=T,nrow=7) \nfit <- lm(y ~X)\nXX=t(X)%*%X \nlibrary(MASS) \nXXgi=ginv(XX) \nPx=X%*%XXgi%*%t(X)\nyhat=Px%*%y\n\n#################\ndata1 <- read.csv(\"~/Documents/Heterosis_GWAS/pheno2011/LL_KN_AKW_test.csv\");\n\n###########################################################\n### Delete duplicated input and missing data\nfile1 <- read.csv(\"LL_KRN_test.csv\")\ndim(file1)\n#8678 8\n\ndiallel <- subset(file1, Note.y==\"Diallel\" | Note.y==\"NAM Filler\");\ndim(diallel)\n#[1] 2850 8\n#summary(diallel)\n\n###########################################################\n### Delete duplicated input and missing data\n# Get ride of 4 duplicated records\ndup <- which(duplicated(diallel$Barcode))\ndiallel <- diallel[!duplicated(diallel$Barcode),]\n\n# Get ride of the missing records\n### checking for outlyers\ndiallel$KRN <- as.numeric(as.character(diallel$KRN));\ndiallel[is.na(diallel$KRN),]\ndiallel <- diallel[!is.na(diallel$KRN),]\nhist(diallel$KRN, breaks=10)\ndim(diallel)\n#[1] 2837 8\n\n\ndata2 <- read.csv(\"~/Documents/Heterosis_GWAS/pheno2011/LL_KRN_test.csv\");\ndata3 <- read.csv(\"~/Documents/Heterosis_GWAS/pheno2011/LL_cob.test.csv\");\n\ndata1 <- subset(data1, )\n\ndm2 <- merge(sample, dm, by.x=\"Genotype\", by.y=\"Geno\")\n\nyield <- dm2$Yield\ndmatrix <- as.matrix(dm2[, 7:52]);\n\nfit <- lm(yield ~ dmatrix)\n\n\n\n\n", "meta": {"hexsha": "9af1d6779ba49d3125ca56ad5c7e120b6eea2096", "size": 8668, "ext": "r", "lang": "R", "max_stars_repo_path": "profiling/pheno2011/5.pheno_diallel_combining_ability.r", "max_stars_repo_name": "yangjl/Heterosis-GWAS", "max_stars_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-04-16T08:27:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T13:00:43.000Z", "max_issues_repo_path": "profiling/pheno2011/5.pheno_diallel_combining_ability.r", "max_issues_repo_name": "yangjl/Heterosis-GWAS", "max_issues_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "profiling/pheno2011/5.pheno_diallel_combining_ability.r", "max_forks_repo_name": "yangjl/Heterosis-GWAS", "max_forks_repo_head_hexsha": "454208509c22b1269f17ba63452ef19a9c3d13f8", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-03T14:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T01:34:08.000Z", "avg_line_length": 29.2837837838, "max_line_length": 149, "alphanum_fraction": 0.5523765575, "num_tokens": 3011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6065120111762465}} {"text": "n_experiments <- 100\nresult <- 0\nexper <- 0\n\nwhile (exper <= n_experiments) \n{\n\tn_samples <- 100\n\tsamples <- runif(n_samples)\n\tcounter <- 1\n\tfor (sample in samples) \n\t{\n\t\tif (sample <= 1/6) \n\t\t{\n\t\t\tresult = result + counter\n\t\t\tbreak\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcounter = counter + 1\n\t\t}\n\t}\n\texper = exper + 1\n}\n\nresult = result / n_experiments\nprint(result)\n\n", "meta": {"hexsha": "ade9e90904efd5930193008e37189f592455c701", "size": 349, "ext": "r", "lang": "R", "max_stars_repo_path": "cub.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cub.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cub.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.4642857143, "max_line_length": 31, "alphanum_fraction": 0.6045845272, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6058994221903262}} {"text": "=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Algebra::Polynomial\n((*(1変数多項式環クラス)*))\n\n1変数の多項式環を表現します。実際のクラスを生成するには環を指定して、クラスメソッド ((<::create>)) あるいは関数 (())() を用います。\n\n== ファイル名:\n* ((|polynomial.rb|))\n\n== スーパークラス:\n\n* ((|Object|))\n\n== インクルードしているモジュール:\n\n* ((|Enumerable|))\n* ((|Comparable|))\n* (())\n* (())\n* (())\n* (())\n\n== 関連するメソッド:\n\n--- Algebra.Polynomial(ring [, obj0 , obj1 [, ...]])\n ((<::create>))(ring, obj0[, obj1 [, ...]])> に同じ。\n\n== クラスメソッド:\n\n--- ::create(ring, obj0[, obj1[, ...]])\n ((|ring|)) で表現されるクラスを係数環とする多項式環クラスを\n 生成します。\n \n (({obj0, obj1, ...})) で指定されたオブジェクトが変数を\n 表現し、これが複数ならば、再帰的に多項式環上の多項\n 式環を生成します。\n\n このメソッドの戻り値は Polynomial クラスのサブクラス\n です。このサブクラスにはクラスメソッドとして ((|ground|)) と\n ((|var|))、((|vars|)) が定義され、それぞれ、係数環 ((|ring|))、\n 主変数オブジェクト(最後に指定された変数)、全ての変数オ\n ブジェクトを返します。\n\n オブジェクト(({obj0, obj1, ...}))は変数の名(((|to_s|))の値)\n に利用されるだけです。\n \n 例: 整数を係数とする多項式環の生成\n require \"polynomial\"\n P = Algebra::Polynomial.create(Integer, \"x\")\n x = P.var\n p((x + 1)**100) #=> x^100 + 100x^99 + ... + 100x + 1\n p P.ground #=> integer\n\n\n 例: 整数を係数とする複数変数多項式環の生成\n require \"polynomial\"\n P = Algebra::Polynomial.create(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -z^3 + (y + x)z^2 + (y^2 - 2xy + x^2)z - y^3 + xy^2 + x^2y - x^3\n p P.var #=> z\n \n この例の (({P})) は\n\n Algebra::Polynomial.create(\n Algebra::Polynomial.create(\n Algebra::Polynomial.create(\n Integer,\n \"x\"),\n \"y\"),\n \"z\")\n\n と同値で、最後の変数 ((|z|)) が主変数となります。\n\n--- ::var\n 多項式環の変数(主変数)を返します。\n\n--- ::vars\n 再帰的に各多項式環の変数を集めた配列を返します。\n\n--- ::mvar\n ((<::vars>)) と同じです。\n\n--- ::to_ary\n (({[self, *vars]})) を返します。\n\n 例: 多項式環と変数を同時に定義する。\n P, x, y, z = Algebra::Polynomial.create(Integer, \"x\", \"y\", \"z\")\n\n--- ::variable\n 変数(主変数)を表現するオブジェクトを返します。\n\n--- ::variables\n 再帰的に各多項式環の変数を表現するオブジェクトを\n 集めた配列を返します。\n\n--- ::indeterminate(obj)\n ((|obj|)) で表現される変数を再帰的に探して返します。\n\n--- ::monomial([n])\n ((|n|)) 次の単項式を返します。\n \n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n P.monomial(3) #=> x^3\n\n--- ::const(c)\n 値 ((|c|)) の定数項を返します。\n\n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n P.const(3) #=> 3\n P.const(3).type #=> P\n\n--- ::zero\n 零元を返します。\n \n--- ::unity\n 単位元を返します。\n\n#--- ::euclidian?\n\n== メソッド:\n\n--- var\n ((<::var>)) と同じです。\n\n--- variable\n ((<::variable>)) と同じです。\n\n--- each(&b)\n 各次の係数を昇冪順に繰り返します。\n \n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n (x**3 + 2*x**2 + 4).each do |c|\n p c #=> 4, 0, 2, 1\n end\n\n--- reverse_each(&b)\n 各次の係数を降冪順に繰り返します。\n\n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n (x**3 + 2*x**2 + 4).reverse_each do |c|\n p c #=> 1, 2, 0, 4\n end\n\n--- [](n)\n ((|n|)) 次の係数を返します。\n\n--- []=(n, v)\n ((|n|)) 次の係数を((|v|))に設定します。\n\n--- monomial\n ((<::monomial>)) と同じです。\n\n--- monomial?\n 単項式であるとき真を返します。\n\n--- zero?\n 零元であるとき真を返します。\n\n--- zero\n 零元を返します。\n \n--- unity\n 単位元を返します。\n\n#--- variable=(bf)\n#--- size\n#--- compact!\n#--- ground_div(n, d)\n\n--- ==(other)\n 等しいとき真を返します。\n\n--- <=>(other)\n 大小関係を求めます。\n\n--- +(other)\n 和を計算します。\n\n--- -(other)\n 差を計算します。\n\n--- *(other)\n 積を計算します。\n\n--- **(n)\n ((|n|)) 乗を計算します。\n\n--- /(other)\n 商を計算します。((
))と同じです。\n\n--- divmod(other)\n ((|other|)) で割った商と余りの配列を返します。\n\n--- div(other)\n ((|other|)) で割った商を返します。(({divmod(other).first}))\n と一致します。\n\n--- %(other)\n ((|other|)) で割った余りを返します。(({divmod(other).last}))\n と一致します。\n\n--- divide?(other)\n ((|other|)) で割り切れるとき真を返します。\n (({divmod(other).last == zero?}))と一致します。\n\n--- deg\n 次数を返します。\n\n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n (5*x**3 + 2*x + 1).deg #=> 3\n\n--- lc\n 先頭係数(leading coeffcient)を返します。\n\n 例:\n (5*x**3 + 2*x + 1).lc #=> 5\n\n--- lm\n 先頭単項式(leading monomial)を返します。\n\n 例:\n (5*x**3 + 2*x + 1).lm #=> x**3\n\n--- lt\n 先頭項(leading term)を返します。(({lc * lm}))と等しい値を持ちます。\n\n 例:\n (5*x**3 + 2*x + 1).lt #=> 5*x**3\n\n--- rt\n 残余項(rest term)を返します。(({self - lt}))と等しい値を持ちます。\n\n 例:\n (5*x**3 + 2*x + 1).rt #=> 2*x + 1\n\n--- monic\n 最高次係数を1に直した式を返します。(({self / lc})) と同じ値を持\n ちます。\n\n--- cont\n 係因数(content(全ての係数の最大公約数))を返します。\n\n--- pp\n 原始的部分(primitive part)を返します。(({self / cont}))と\n 同じ値を持ちます。\n\n--- to_s\n 文字列表現を得ます。表示形式を変えるには ((|display_type|)) を用います。\n ((|display_type|)) に与えられる値は ((|:norm|))(デフォルト), ((|:code|))\n です。\n \n 例:\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n p 5*x**3 + 2*x + 1 #=>5x^3 + 2x + 1\n P.display_type = :code\n p 5*x**3 + 2*x + 1 #=> 5*x**3 + 2*x + 1\n\n--- derivate\n 微分した値を返します。\n \n 例:\n (5*x**3 + 2*x + 1).derivate #=> 15*x**2 + 2\n\n--- sylvester_matrix(other)\n ((|other|)) とのシルベスター行列を返します。\n\n--- resultant(other)\n ((|other|)) との集結式返します。予め\n\n--- project(ring[, obj]){|c, n| ... }\n 各単項式について、\n 次数を ((|n|)) に、係数 ((|c|)) に代入し ... を評価したものを\n その単項式の値に置き換え、((|ring|)) 上で和を取った値を\n 返します。((|obj|)) が省略されると (({ring.var})) が用いら\n れます。\n \n 例:\n require \"polynomial\"\n require \"rational\"\n P = Algebra::Polynomial(Integer, \"x\")\n PQ = Algebra::Polynomial(Rational, \"y\")\n x = P.var\n f = 5*x**3 + 2*x + 1\n p f.convert_to(PQ) #=> 5y^3 + 2y + 1\n p f.project(PQ) {|c, n| Rational(c) / (n + 1)} #=> 5/4y^3 + y + 1\n\n--- evaluate(obj)\n 主変数に ((|obj|)) を代入した値を返します。\n (({ project(ground, obj){|c, n| c} })) の値と一致します。\n\n 例:\n require \"polynomial\"\n P = Algebra::Polynomial(Integer, \"x\")\n x = P.var\n f = x**3 - 3*x**2 + 1\n p f.evaluate(-1) #=> -3 (in Integer)\n p f.evaluate(x + 1) #=> x^3 - 3x - 1 (in P)\n\n--- call(obj)\n (())と同じです。\n\n--- sub(var, value)\n 変数 ((|var|)) に ((|value|)) を代入した値を返します。\n\n 例:\n require \"polynomial\"\n P = Algebra::Polynomial(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n f = (x - y)*(y - z - 1)\n p f.sub(y, z+1) #=> 0\n\n--- convert_to(ring)\n 各項を((|ring|))上で評価します。(({ project(ring){|c, n| c} }))の\n 値と一致します。\n\n= Algebra::PolynomialFactorization\n((*(因数分解モジュール)*))\n\n因数分解をするためのモジュールです。\n\n== ファイル名:\n((|polynomial-factor.rb|))\n\n== メソッド:\n\n--- sqfree\n 無平方化します。\n\n--- sqfree?\n 無平方なら真を返します。\n\n--- irreducible?\n 既約なら真を返します。\n\n--- factorize\n 因数分解します。\n \n 因数分解可能な係数環は\n * Integer\n * Rational\n * 素体\n * 代数体(Rational 上の有限次拡大)\n です。\n\n\n= Algebra::SplittingField\n((*(分解体モジュール)*))\n\n多項式の最小分解体を求めるためのモジュール\n\n\n== ファイル名:\n* ((|splitting-field.rb|))\n\n\n== メソッド:\n\n\n--- decompose([fac0])\n 自身の最小分解体を ((|field|))、拡大に要した既約多項式\n の配列を ((|def_polys|))、最小分解体上で1次式の積に因数分解し\n たものを ((|facts|))、多項式の根の配列を ((|roots|))、\n ((|roots|)) を基礎体に添加した元が前に来るように並べ替えた\n の配列を ((|proots|)) として、\n\n [field, def_polys, facts, roots, proots]\n\n を返します。基礎体上の因数分解 ((|fac0|)) を添えると高速化に役立ちます。\n (((|facts|)) の要素と ((|fact0|)) は ((|Algebra::Factors|)) オブジェクト\n 、((|field|)) は\n (())\n オブジェクトです。ただし、自身が一次因子に分解されるときは\n (()) そのものを返します。\n\n 例:\n require \"algebra\"\n PQ = Polynomial(Rational, \"x\")\n x = PQ.var\n f = x**5 - x**4 + 2*x - 2\n field, def_polys, facts, roots, proots = f.decompose\n p def_polys #=> [a^4 + 2, b^2 + a^2]\n p facts #=> (x - 1)(x - a)(x + a)(x - b)(x + b)\n p roots #=> [1, a, -a, b, -b]\n p proots #=> [a, b, 1, -a, -b]\n fp = Polynomial(field, \"x\")\n x = fp.var\n facts1 = Factors.new(facts.collect{|g, n| [g.call(x), n]})\n p facts1.pi == f.convert_to(fp) #=> true\n\n--- splitting_field([fac0]))\n 自身の最小分解体の情報を返します。返り値の各フィールドの値は以下\n の通りです。poly_exps 以外は (()) の以下のものに相当します。\n\n poly, field, roots, proots, def_polys\n\n ただし、((|roots|))、((|proots|)) の各要素は ((|field|)) の\n 要素として変換されています。\n \n 例:\n require \"algebra\"\n PQ = Polynomial(Rational, \"x\")\n x = PQ.var\n f = x**5 - x**4 + 2*x - 2\n sf = f.splitting_field\n p sf.roots #=> [1, a, -a, b, -b]\n p sf.proots #=> [a, b, 1, -a, -b]\n p sf.def_polys #=> [a^4 + 2, b^2 + a^2]\n\n= Algebra::Galois\n((*(ガロア群)*))\n\n多項式のガロア群を求めるためのモジュール\n\n== ファイル名:\n* ((|galois-group.rb|))\n\n== インクルードしているモジュール:\n* なし\n\n== 関連するメソッド:\n\n--- GaloisGroup.galois_group(poly)\n (()) と同じ\n\n== モジュールメソッド:\n* なし\n\n== メソッド:\n\n--- galois_group\n 多項式のガロア群を返します。群は各元が \n (()) である \n (()) オブジェクトとして表現されます。\n\n 例:\n require \"rational\"\n require \"polynomial\"\n\n P = Algebra.Polynomial(Rational, \"x\")\n x = P.var\n p( (x**3 - 3*x + 1).galois_group.to_a )\n #=>[[0, 1, 2], [1, 2, 0], [2, 0, 1]]\n\n (x**3 - x + 1).galois_group.each do |g|\n p g\n end\n #=> [0, 1, 2]\n # [1, 0, 2]\n # [2, 0, 1]\n # [0, 2, 1]\n # [1, 2, 0]\n # [2, 1, 0]\n\n=end\n", "meta": {"hexsha": "96b819a98cf58ec0c08c58d8d594e84b2b3029b5", "size": 9164, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/polynomial-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/polynomial-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/polynomial-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3333333333, "max_line_length": 98, "alphanum_fraction": 0.5123308599, "num_tokens": 4596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6058455474359522}} {"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 for 8 formants. Each\n# parameter has a name such as f[1-8][fba] to specify\n# formant number (1-8) and parameter (f(requency), \n# b(andwidth), or a(mplitude)). All frequencies and \n# bandwidths specified in Hertz, and amplitudes in dB.\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\nvtfn <- function(pars, np=512, fs=16000) {\n maxf <- fs/2\n a1s <- 10^(pars['f1a']/20)\n a2s <- 10^(pars['f2a']/20)\n a3s <- 10^(pars['f3a']/20)\n a4s <- 10^(pars['f4a']/20)\n a5s <- 10^(pars['f5a']/20)\n a6s <- 10^(pars['f6a']/20)\n a7s <- 10^(pars['f7a']/20)\n a8s <- 10^(pars['f8a']/20)\n\n f1 <- formant(pars['f1f'], pars['f1b'], np, maxf, scale=F)\n f2 <- formant(pars['f2f'], pars['f2b'], np, maxf, scale=F)\n f3 <- formant(pars['f3f'], pars['f3b'], np, maxf, scale=F)\n f4 <- formant(pars['f4f'], pars['f4b'], np, maxf, scale=F)\n f5 <- formant(pars['f5f'], pars['f5b'], np, maxf, scale=F)\n f6 <- formant(pars['f6f'], pars['f6b'], np, maxf, scale=F)\n f7 <- formant(pars['f7f'], pars['f7b'], np, maxf, scale=F)\n f8 <- formant(pars['f8f'], pars['f8b'], np, maxf, scale=F)\n \n s <- a1s*f1 + a2s*f2 + a3s*f3 + a4s*f4 + a5s*f5 +\n a6s*f6 + a7s*f7 + a8s*f8\n s\n}", "meta": {"hexsha": "62b564b5a74403195b108d7deed1d7144fedcacc", "size": 2302, "ext": "r", "lang": "R", "max_stars_repo_path": "R/vtfn.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/vtfn.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/vtfn.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": 42.6296296296, "max_line_length": 69, "alphanum_fraction": 0.5842745439, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6056549515784144}} {"text": "# take radius from user\n\na <- readline(prompt=\"Enter the radius:\")\nr <- as.double(a)\n\n# compute area and store in a variable\narea <- pi * r ^ 2\n\n# print area\nprint(area)", "meta": {"hexsha": "2ccbed0b63f17afe973998c21763c352838110a7", "size": 169, "ext": "r", "lang": "R", "max_stars_repo_path": "Session-1/r2_area.r", "max_stars_repo_name": "pankajchejara23/Stats-in-R", "max_stars_repo_head_hexsha": "e256464b0548b9e0c4a46aeb46c06416cf744780", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Session-1/r2_area.r", "max_issues_repo_name": "pankajchejara23/Stats-in-R", "max_issues_repo_head_hexsha": "e256464b0548b9e0c4a46aeb46c06416cf744780", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Session-1/r2_area.r", "max_forks_repo_name": "pankajchejara23/Stats-in-R", "max_forks_repo_head_hexsha": "e256464b0548b9e0c4a46aeb46c06416cf744780", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-02T21:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T16:14:27.000Z", "avg_line_length": 16.9, "max_line_length": 41, "alphanum_fraction": 0.6686390533, "num_tokens": 46, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.6055938712468593}} {"text": "QSAR_ridge_regression <- function (X, Y, K) {\n \n # Ridge regression with parcor package\n # Date: 8-4-2014\n # Author: Sheikh M. Rahman\n # require parcor, ggplot2 packages\n # X variables, Y response, k - fold validation\n ridgeFit <- ridge.cv(X, Y, k = K, scale = FALSE); # it will find the optimum lambda by 10-fold validation\n \n coeff_ridge <- matrix(ridgeFit$coefficients,nrow = 1)\n \n \n # fitted data\n yFit <- X %*% t(coeff_ridge) # matrix multiplication\n yFit <- yFit + ridgeFit$intercept # add intercept\n \n residualY <- yFit - Y # residual\n sumResidual <- sum(residualY);\n \n SquaredError <- (yFit - Y)^2\n SumSquareError <- sum(SquaredError);\n #############################################\n # R- square calculation\n # DOF: Model- p (p, no. of explanatory variables, not includes the intercept)\n # \tError- n-p-1 (n, no. of samples)\n #############################################\n SumSquareModel <- sum((yFit - mean(Y))^2)\n SumSquareTotal <- sum((Y - mean(Y))^2)\n \n Rsquared <- SumSquareModel/SumSquareTotal;\n \n return (list(ridgeFit = ridgeFit, yFit = yFit, residualY = residualY,\n sumResidual = sumResidual, SquaredError = SquaredError, \n SumSquareError = SumSquareError, Rsquared = Rsquared, X = X, Yobs = Y))\n \n}\n\n\nQSAR_lasso_regression <- function (X, Y, K) {\n lassoFit <- adalasso(X,Y, k = K, both = FALSE); # it will find the optimum lambda by k-fold validation\n \n coeff_lasso <- matrix(lassoFit$coefficients.lasso,nrow = 1)\n \n # fitted data\n yFit <- X %*% t(coeff_lasso) # matrix multiplication\n yFit <- yFit + lassoFit$intercept.lasso # add intercept\n yFit[yFit<0] <- 0 # to change the negative value to 0\n residualY <- yFit - Y # residual\n sumResidual <- sum(residualY);\n \n SquaredError <- (yFit - Y)^2\n SumSquareError <- sum(SquaredError);\n \n #############################################\n # R- square calculation\n # DOF: Model- p (p, no. of explanatory variables, not includes the intercept)\n # Error- n-p-1 (n, no. of samples)\n #############################################\n SumSquareModel <- sum((yFit - mean(Y))^2)\n SumSquareTotal <- sum((Y - mean(Y))^2)\n \n Rsquared <- SumSquareModel/SumSquareTotal;\n \n return (list(lassoFit = lassoFit, yFit = yFit, residualY = residualY,\n sumResidual = sumResidual, SquaredError = SquaredError, \n SumSquareError = SumSquareError, Rsquared = Rsquared, X = X, Yobs = Y))\n \n}\n\nplotPanelFigures <- function (Y, regMdl, axsLabel,subHdr) {\nyTest_obs <- Y\n#coeff <- matrix(regMdl$lassoFit$coefficients.lasso, nrow = 1)\n#intercept <- regMdl$lassoFit$intercept.lasso\n#yTest <- regMdl$X %*% t( coeff ) # matrix multiplication\nyTest <- regMdl$yFit\n#yTest[yTest<0] <- 1\n#dat <- data.frame(xvar = log(yTest_obs), yvar = log(yTest))\ndat <- data.frame(xvar = (yTest_obs), yvar = (yTest))\np <- ggplot(dat, aes(x=xvar, y=yvar)) + labs(title=axsLabel,subtitle=subHdr)+\n geom_point(colour=\"blue\", size = 2.0, shape = 21, fill='orange') +\n theme_bw() + coord_cartesian(xlim = c(0, 8000), ylim = c(0, 8000)) + #coord_cartesian(xlim = c(0, 10), ylim = c(0, 10)) +\n geom_abline(intercept = 0, slope = 1,'linetype' = 'dashed',color = 'black','size' = 0.5) +\n theme (axis.title = element_text(size=21), axis.text=element_text(colour=\"black\",size=10)) +\n labs(x=\"\", y=\"\") + theme(plot.title = element_text(size=12, hjust=0.5, face=\"bold\", vjust=-1)) +\n theme(plot.subtitle = element_text(size=9, hjust=0.5, vjust=1)) +\n #annotate(\"text\", x=1.25, y=9.5, label= paste(\"R^2 == \", round(regMdl$Rsquared,2)), parse=TRUE, size = 4,family=\"Arial\", fontface = 2) \n annotate(\"text\", x=1000, y=7500, label= paste(\"R^2 == \", round(regMdl$Rsquared,2)), parse=TRUE, size = 4,family=\"Arial\", fontface = \"bold\") \n \n# labs(x=paste(\"Observed\", axsLabel), y=paste(\"Predicted\", axsLabel)) \n \nreturn(p)\n}", "meta": {"hexsha": "af8e557ea7e4173ff37223708a6cac15d95b1d67", "size": 4030, "ext": "r", "lang": "R", "max_stars_repo_path": "cytotoxicity_prediction/lib/QSAR_functions.r", "max_stars_repo_name": "mokhles002/qsar_project", "max_stars_repo_head_hexsha": "30907c611a1e3e10e85ca61db506ad36846771ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cytotoxicity_prediction/lib/QSAR_functions.r", "max_issues_repo_name": "mokhles002/qsar_project", "max_issues_repo_head_hexsha": "30907c611a1e3e10e85ca61db506ad36846771ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cytotoxicity_prediction/lib/QSAR_functions.r", "max_forks_repo_name": "mokhles002/qsar_project", "max_forks_repo_head_hexsha": "30907c611a1e3e10e85ca61db506ad36846771ab", "max_forks_repo_licenses": ["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.8043478261, "max_line_length": 143, "alphanum_fraction": 0.5930521092, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6053998908145937}} {"text": "# Likelihood and optimization of an AR(1) model with trend\n# Rest is taken over from analysis v23\n\n# Model ------------------------------------------------------------------------\n\nset.seed(2020)\n\n#' LogLikelihood of AR(1) model with drift and seasonality\n#'\n#' Box & Jenkins suggest using unconditional likelihood, but here I have taken\n#' the approach of excluding p + q variables for ease.\n#'\n#' @param mu,sigma,phi scalars\n#' @param betas vector of betas for xreg\n#' @param xreg matrix of regressors similar to mu\n#'\n#' @keywords internal\nlogL <- function(x, mu, sigma, phi1, betas = NULL, xreg = NULL) {\n n <- length(x)\n M <- phi1*x[-n] + mu * (1 - phi1)\n if (!is.null(betas) || !is.null(xreg)) {\n reg <- xreg[-1,,drop=FALSE] - phi1*xreg[-n,,drop=FALSE]\n M <- M + reg %*% betas\n }\n squared <- (x[-1] - M)^2\n sum(-squared/(2*sigma^2)) - (n - 1)*log(sigma * sqrt(2*pi))\n}\n\nlogL(rnorm(100), mu = 0, sigma = 1, phi1 = 5, betas = 2, xreg = matrix(c(rep(0, 4), 1:(100-4))))\nlogL(rnorm(100), mu = 0, sigma = 1, phi1 = 5)\n\nlogL.compile <- function(mu = NULL, sigma = NULL, phi1 = NULL, betas = list()) {\n\n stopifnot(length(betas) == 0 || !is.null(names(betas)))\n\n i <- 0\n\n fn.str <- sprintf(\n 'function(par, x, xreg = NULL) {\n logL(x = x, mu = %s, sigma = %s, phi1 = %s, betas = %s, xreg = xreg)\n }'\n , if (is.null(mu)) sprintf('par[%i]', (i <- i + 1)) else mu\n , if (is.null(sigma)) sprintf('par[%i]', (i <- i + 1)) else sigma\n , if (is.null(phi1)) sprintf('par[%i]', (i <- i + 1)) else phi1\n , if (length(betas) > 0L)\n sprintf('c(%s)', paste(names(betas), '=', vapply(betas, function(v)\n if (is.null(v)) sprintf('par[%i]', (i <<- i + 1)) else as.character(v), ''), collapse = ', '))\n else 'NULL'\n )\n\n fn <- eval(parse(text = fn.str))\n environment(fn) <- globalenv()\n\n fn\n}\n\n(logL.fn <- logL.compile(phi1 = 0, betas = list('b1' = 1, 'b2' = NULL, 'b3' = 3)))\nlogL.fn(par = c(1,2,3), x = rnorm(100), xreg = matrix(rnorm(300), ncol = 3))\n(logL.fn <- logL.compile(phi1 = 0))\nlogL.fn(par = c(1,2), x = rnorm(100))\n\n\nsim <- function(n, mu, sigma, phi1, betas = NULL, xreg = NULL,\n init = mu, xt = NULL, a = rnorm(n, 0, sd = sigma)) {\n\n R <- rep(0, n)\n if (!is.null(betas) || !is.null(xreg)) {\n reg <- xreg[-1,,drop=FALSE] - phi1*xreg[-n,,drop=FALSE]\n R <- c(0, reg %*% betas)\n }\n\n if (is.null(xt)) {\n # xp is the previous x: x_{t-1}\n Reduce(f = function(xp, t) phi1*xp + mu*(1-phi1) + R[t] + a[t], x = 2:n, init = init, accumulate = TRUE)\n } else {\n c(xt[1],\n phi1*xt[-n] + mu*(1-phi1) + R[-1] + a[-1])\n }\n}\n\nset.seed(2020)\n\nx.sim <- sim(10000, mu = 1032, sigma = sqrt(23), phi1 = 0.9, betas = 0, xreg = matrix(1:10000, ncol = 1))\nplot(x.sim, type = 'l')\nacf(x.sim)\npacf(x.sim)\n\n\nx.sim.trend <- sim(10000, mu = 1032, sigma = sqrt(23), phi1 = 0.9, betas = 0.005, xreg = matrix(1:10000, ncol = 1))\nplot(x.sim.trend, type = 'l')\n\n\n#' Fit the custom drift detection model\n#'\n#' If specific parameters are supplied, then they will be fixed.\n#'\n#' @keywords internal\nfit <- function(x, mu = NULL, sigma = NULL, phi1 = NULL,\n betas = if (is.null(xreg)) list() else setNames(vector('list', ncol(xreg)), colnames(xreg)),\n xreg = NULL) {\n\n stopifnot(is.null(xreg) || is.matrix(xreg))\n stopifnot(!is.matrix(xreg) || length(betas) == ncol(xreg))\n stopifnot(!is.matrix(xreg) || all(names(betas) == colnames(xreg)))\n\n all.param.names <- c('mu', 'sigma', 'phi1', names(betas))\n stopifnot(length(unique(all.param.names)) == length(all.param.names))\n\n stopifnot(!any(ls() %in% names(betas)))\n list2env(betas, envir = environment())\n\n inits <- c(\n 'mu'= median(x),\n 'sigma' = var(x),\n 'phi1' = pacf(x, plot = FALSE, lag.max = 1)$acf[1,1,1],\n if (length(betas) == 0L) NULL else setNames(coef(lm(x ~ xreg))[-1], names(betas))\n )\n\n scale <- c(\n 'mu' = if (length(betas) == 0L) 1 else summary(lm(x ~ xreg))$coefficients[1L, 2L],\n 'sigma' = 1,\n 'phi1' = 1/100,\n if (length(betas) == 0L) NULL else setNames(summary(lm(x ~ xreg))$coefficients[-1L, 2L], names(betas))\n )\n\n lower.bound <- c(\n 'mu' = -Inf,\n 'sigma' = 1e-7,\n 'phi1' = -Inf,\n setNames(rep(-Inf, length(betas)), names(betas))\n )\n\n upper.bound <- c(\n 'mu' = Inf,\n 'sigma' = Inf,\n 'phi1' = 1 - 1e-7,\n setNames(rep(Inf, length(betas)), names(betas))\n )\n\n fixed <- unlist(mget(all.param.names)[!sapply(mget(all.param.names), is.null)])\n param.names <- setdiff(all.param.names, names(fixed))\n\n opt <- optim(\n par = inits[param.names],\n fn = logL.compile(mu = mu, sigma = sigma, phi1 = phi1, betas = betas),\n method = 'L-BFGS-B',\n x = x,\n lower = lower.bound[param.names],\n upper = upper.bound[param.names],\n xreg = xreg,\n control = list('fnscale' = -1,\n 'parscale' = scale[param.names],\n 'trace' = 0)\n )\n\n # Add fixed parameters\n opt <- append(x = opt, values = list('par.fixed' = fixed), after = 1)\n\n opt\n}\n\nxreg.trend.1 <- matrix(data = 1:length(x.sim), dimnames = list(NULL, 'trend'))\n\n# Here specification of likelihood is tested with general arima model.\n## x.sim\nfit(x = x.sim) # -29832.06\nfit(x = x.sim, xreg = xreg.trend.1)\nfit(x = x.sim, betas = list('trend' = 0), xreg = xreg.trend.1) # -29832.06\n\n#forecast::auto.arima(y = x.sim, trace = TRUE)\nfit.arima <- arima(x = x.sim, order = c(1, 0, 0))\nfit.arima # -29835.35\n\n## x.sim.trend\nfit(x = x.sim.trend, xreg = xreg.trend.1) # -29997.49\nfit.arima <- arima(x = x.sim.trend, order = c(1, 0, 0), xreg = xreg.trend.1)\nfit.arima # -30000.82\n\n# Data -------------------------------------------------------------------------\n\nsource('./../../gwloggeR/R/fourier.R')\n\nlogger.names <- grep('barometer/', gwloggeR.data::enumerate(), value = TRUE)\n\nlogger.names <- setdiff(logger.names, 'barometer/BAOL016X_W1666.csv')\nlogger.names <- setdiff(logger.names, 'barometer/BAOL050X_56819.csv') # high freq manu in range of 80 cmH2O\n\nround_timestamp <- function(ts, scalefactor.sec = 3600*12) {\n as.POSIXct(round(as.numeric(ts)/scalefactor.sec) * scalefactor.sec, origin = '1970-01-01', tz = 'UTC')\n}\n\nread.baro <- function(logger.name) {\n df <- gwloggeR.data::read(logger.name)$df\n if (nrow(df) == 0L) return(df)\n df <- df[!is.na(TIMESTAMP_UTC), ]\n df <- df[!is.na(PRESSURE_VALUE), ]\n df <- df[!duplicated(TIMESTAMP_UTC), ]\n df <- df[, .('PRESSURE_VALUE' = mean(PRESSURE_VALUE)),\n by = .('TIMESTAMP_UTC' = round_timestamp(TIMESTAMP_UTC))]\n\n # Meta data\n df[, 'FILE' := basename(logger.name)]\n df[, 'N' := .N]\n\n data.table::setkey(df, TIMESTAMP_UTC)\n data.table::setattr(df, 'logger.name', logger.name)\n\n df\n}\n\n# from analysis 04\ncompare <- function(df1, df2) {\n if (nrow(df1) == 0L || nrow(df2) == 0L) return(data.table::data.table())\n\n diff.df <- df1[J(df2), .('PRESSURE_DIFF' = x.PRESSURE_VALUE - i.PRESSURE_VALUE, TIMESTAMP_UTC)][!is.na(PRESSURE_DIFF), ]\n\n data.table::setkey(diff.df, TIMESTAMP_UTC)\n\n diff.df\n}\n\nref.compare <- function(logger.name) {\n compare(read.baro(logger.name), read.baro('KNMI_20200312_hourly'))\n}\n\ncoef.pvals <- function(M) {\n (1-pnorm(abs(M$coef)/sqrt(diag(M$var.coef))))*2\n}\n\nplt.comp <- function(TIMESTAMP_UTC, Y, M = NULL, significant = NULL, front_layer = NULL,\n xlim = range(TIMESTAMP_UTC), ylim = quantile(Y, c(0.005, 0.995))) {\n\n force(TIMESTAMP_UTC); force(Y); force(M)\n force(ylim); force(xlim)\n\n p <- ggplot2::ggplot(mapping = ggplot2::aes(x = TIMESTAMP_UTC, y = Y)) +\n front_layer +\n ggplot2::geom_line(col = 'red', alpha = 0.9)\n\n if (!is.null(M))\n p <- p + ggplot2::geom_line(mapping = ggplot2::aes(y = fitted(M)), col = 'black', size = 1.5)\n\n if (!is.null(significant)) {\n p <- p + ggplot2::annotate(\n \"label\", x = as.POSIXct(-Inf, origin = '1970-01-01'), y = Inf,\n size = 4, col = if (significant) 'green' else 'red',\n hjust = 0, vjust = 1, fill = 'grey', label.size = NA,\n label = if (significant) 'SIGNIFINCANT' else 'NOT SIGNIFICANT'\n )\n }\n\n if (!is.null(M[['btrend']]) && coef.pvals(M)['btrend'] < 0.001)\n p <- p + ggplot2::geom_vline(xintercept = TIMESTAMP_UTC[which.max(M$btrend > 0)],\n col = 'blue', linetype = 'dotted', size = 1.2)\n\n p <- p +\n ggplot2::coord_cartesian(ylim = ylim, xlim = xlim) +\n ggplot2::ylab('PRESSURE_DIFF') +\n ggplot2::theme_light() +\n ggplot2::theme(axis.text.y = ggplot2::element_text(angle = 90, hjust = 0.5))\n\n p\n}\n\nreport <- function(logger.name) {\n\n environment(plt.comp) <- environment() # fitted(Arima) then can find the source data.\n\n print(logger.name)\n\n df.diff <- ref.compare(logger.name)\n\n if (nrow(df.diff) < 10L) return(invisible(FALSE))\n\n # M <- fit(x = df.diff$PRESSURE_DIFF, phi1 = 0, d = 0, dsi = 1)\n M <- arima(x = df.diff$PRESSURE_DIFF, order = c(0, 0, 0))\n df.diff[, M_pred := fitted(M)]\n\n # M.AR <- fit(x = df.diff$PRESSURE_DIFF, d = 0, dsi = 1)\n M.AR <- arima(x = df.diff$PRESSURE_DIFF, order = c(1, 0, 0))\n df.diff[, M.AR.pred := fitted(M.AR)]\n\n trend <- c(0, cumsum(diff(as.numeric(df.diff$TIMESTAMP_UTC))/3600/24))\n breakpoints <- seq(from = 1, to = nrow(df.diff), by = 10)\n # M.ARD <- M.AR\n # for (bp in breakpoints) {\n # .M <- fit(x = df.diff$PRESSURE_DIFF, dsi = bp)\n # if (.M$value > M.ARD$value) M.ARD <- .M\n # }\n M.ARD <- M.AR\n for (bp in breakpoints) {\n btrend <- c(rep(0, bp - 1), trend[bp:length(trend)] - trend[bp])\n .M <- arima(x = df.diff$PRESSURE_DIFF, order = c(1, 0, 0), xreg = btrend)\n .M[['btrend']] <- btrend\n if (logLik(.M) > logLik(M.ARD)) M.ARD <- .M\n }\n df.diff[, M.ARD.pred := fitted(M.ARD)]\n\n\n sbasis <- fbasis(timestamps = df.diff$TIMESTAMP_UTC, frequencies = 1/(365.25*3600*24))\n\n M.ARS <- arima(x = df.diff$PRESSURE_DIFF, order = c(1, 0, 0), xreg = sbasis)\n\n M.ARDS <- M.ARS\n for (bp in breakpoints) {\n btrend <- c(rep(0, bp - 1), trend[bp:length(trend)] - trend[bp])\n .M <- arima(x = df.diff$PRESSURE_DIFF, order = c(1, 0, 0), xreg = cbind(sbasis, btrend))\n .M[['btrend']] <- btrend\n if (logLik(.M) > logLik(M.ARDS)) M.ARDS <- .M\n }\n\n p.comp <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF)\n\n p.M <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF, M)\n\n p.M.AR <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF, M.AR)\n\n p.M.ARS <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF, M.ARS)\n\n p.M.ARD <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF, M.ARD)\n\n p.M.ARDS <- plt.comp(df.diff$TIMESTAMP_UTC, df.diff$PRESSURE_DIFF, M.ARDS)\n\n # File export ----------------------------------------------------------------\n\n filename <- sprintf('./drifts/analysis_25/%s.png', tools::file_path_sans_ext(basename(logger.name)))\n dir.create(dirname(filename), showWarnings = FALSE, recursive = TRUE)\n\n layout_matrix <- rbind(c(1, 2),\n c(3, 4),\n c(5, 6))\n\n grob.title <- grid::textGrob(sprintf('%s (#%s differences with KNMI data from %s to %s)',\n basename(logger.name), nrow(df.diff),\n min(df.diff$TIMESTAMP_UTC), max(df.diff$TIMESTAMP_UTC)),\n x = 0.05, hjust = 0)\n\n p.empty <- ggplot2::ggplot() + ggplot2::theme_void()\n\n local({\n png(filename, width = 1280, height = 720)\n on.exit(dev.off())\n gridExtra::grid.arrange(p.comp, p.empty,\n p.M, p.M.ARS,\n p.M.ARD, p.M.ARDS,\n layout_matrix = layout_matrix,\n top = grob.title)\n })\n\n invisible(TRUE)\n\n}\n\n# report('BAOL009X_78680')\ninvisible(lapply(logger.names, report))\n", "meta": {"hexsha": "7c533a9083cff686392d7c21bbf76ebc3c0ddb09", "size": 11670, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/drifts/analysis_25.r", "max_stars_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_stars_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-16T10:47:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T10:47:56.000Z", "max_issues_repo_path": "src/r/drifts/analysis_25.r", "max_issues_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_issues_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61, "max_issues_repo_issues_event_min_datetime": "2019-05-17T21:14:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T13:47:40.000Z", "max_forks_repo_path": "src/r/drifts/analysis_25.r", "max_forks_repo_name": "DOV-Vlaanderen/groundwater-logger-validation", "max_forks_repo_head_hexsha": "db9bd59c1644bb298206e717a528b4974e3939d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-07-30T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T10:48:04.000Z", "avg_line_length": 32.7808988764, "max_line_length": 122, "alphanum_fraction": 0.5759211654, "num_tokens": 3935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6052565030758471}} {"text": "# 07. Beta Diversity\n# Figure 3c, Figure 5c, Figure S6, Figure S10\n# Ref for CLR PCA: Gloor, G. B.; Macklaim, J. M.; Pawlowsky-Glahn, V.; Egozcue, J. J. Microbiome Datasets Are Compositional: And This Is Not Optional. Front. Microbiol. 2017, 8. https://doi.org/10.3389/fmicb.2017.02224.\n# Ref for PhILR PCA: Silverman, J. D.; Washburne, A. D.; Mukherjee, S.; David, L. A. A Phylogenetic Transform Enhances Analysis of Compositional Microbiota Data. eLife 2017, 6, e21887. https://doi.org/10.7554/eLife.21887.\n# Water and sediment sequences were analyzed separately\n\n#### Phyloseq Object ####\nps.noncontam.tree\n\n#### Set Directory ####\nbeta <- file.path(paste(path_phy, \"/beta_diversity/Ordination\", sep=\"\"))\ndir.create(beta, showWarnings=FALSE, recursive=TRUE)\nsetwd(beta)\n\n#### CLR transformation ####\nset.seed(2021)\n\n# Obtain the OTU table\nps_filt_otu <- as.data.frame(otu_table(ps.noncontam.tree))\nmetadata <- as.data.frame(as.matrix(sample_data(ps.noncontam.tree)))\n\n# Transform the OTU table and replace 0 values with an estimate\nf.n0 <- cmultRepl(t(ps_filt_otu), method=\"CZM\", label=0, output=\"p-counts\")\n\n# CLR Transformation\nf.clr <- codaSeq.clr(f.n0, IQLR=FALSE)\nhead(f.clr)\n\n# Check distribution\nqplot(rowSums(f.clr),bins=50) + xlab(\"clr transformed counts-per-sample\")\nqplot(colSums(f.clr),bins=50) + xlab(\"clr transformed counts-per-taxa\")\n\n# Add CLR to phyloseq object\nps_clr <- phyloseq(\n otu_table(t(f.clr), taxa_are_rows = TRUE),\n sample_data(sample_data(ps.noncontam.tree)),\n phy_tree(filt_tree),\n tax_table(tax_table(ps.noncontam.tree))\n)\nps_clr\n\n# get PCA\nf.pcx <- prcomp(f.clr)\n\n# extract results from PCA\nvar <- get_pca_var(f.pcx)\n\n# get eigenvalue\neig.val <- get_eigenvalue(f.pcx)\nhead(eig.val)\n\n#### PhILR transformation ####\nlibrary(\"philr\")\n\n# Add clr to phyloseq object\nps_philr <- phyloseq(\n otu_table(t(f.n0), taxa_are_rows = TRUE),\n sample_data(sample_data(ps.noncontam.tree)),\n phy_tree(filt_tree),\n tax_table(tax_table(ps.noncontam.tree))\n)\nps_philr\n\n# check the object\nis.rooted(phy_tree(ps_philr))\nis.binary.tree(phy_tree(ps_philr))\n\n# labels and name balance\nphy_tree(ps_philr) <- makeNodeLabel(phy_tree(ps_philr), method=\"number\", prefix='n')\n\nname.balance(phy_tree(ps_philr), tax_table(ps_philr), 'n1')\n\n# calculate philr\notu.table <- as.data.frame(otu_table(ps_philr))\notu.table <- as.matrix(t(otu.table))\ntree <- phy_tree(ps_philr)\nmetadata <- sample_data(ps_philr)\ntax <- tax_table(ps_philr)\n\ngp.philr <- philr(otu.table, tree, part.weights='enorm.x.gm.counts', ilr.weights='blw.sqrt', return.all=TRUE)\n\n# get philr info\ngp.dist <- dist(gp.philr$df.ilrp, method=\"euclidean\")\ngp.pcoa <- ordinate(ps_philr, 'PCoA', distance=gp.dist)\n\n#### Prepare for combining CLR and PhILR data to plot (Water Samples) ####\nordi_clr <- as.data.frame(f.pcx$x[,1:2])\nordi_clr$ID_keep <- rownames(ordi_clr)\nhead(ordi_clr)\n\nDATA_PHYLOSEQ_FIXED$ID_keep <- rownames(DATA_PHYLOSEQ_FIXED)\nordi_data <- merge(DATA_PHYLOSEQ_FIXED, ordi_clr, by = c('ID_keep'))\nordi_data$strat_time <- ifelse(ordi_data$Season == \"Fall\", \"Stratified (~7 months)\",\n ifelse(ordi_data$Season == \"Spring\", \"Incipient Stratification\",\n ifelse(ordi_data$Season == \"Summer\", \"Stratified (~3 months)\", \"\")))\nordi_data$strat_time <- factor(ordi_data$strat_time, ordered = TRUE, levels = c(\"Incipient Stratification\", \"Stratified (~3 months)\", \"Stratified (~7 months)\"))\n\nordi.scores_philr <- as.data.frame(gp.pcoa$vectors)\ncolnames(ordi.scores_philr) <- c(\"Axis.1philr\", \"Axis.2philr\")\nordi.scores_philr <- ordi.scores_philr[c(\"Axis.1philr\",\"Axis.2philr\")]\nordi.scores_philr$ID_keep <- rownames(ordi.scores_philr)\n\n# Merge data with ordi_data\nordi_data <- merge(ordi_data, ordi.scores_philr, by = c('ID_keep'))\nhead(ordi_data)\ncolnames(ordi_data)\n\n# remove bad samples\nordi_data_sub <- subset(ordi_data, SampleID != \"W64\")\nordi_data_sub <- subset(ordi_data_sub, SampleID != \"W66\")\nordi_data_sub <- subset(ordi_data_sub, SampleID != \"W67\")\n\n# remove batch 4 (same as batch 1 and 3)\nordi_data_sub_NoBatch4 <- subset(ordi_data_sub, Sequence_batch != \"Batch4\")\n\n# data for plotting batches\nordi_data_sub_batch <- subset(ordi_data_sub, Plot_batch == \"Y\")\n\n#### Prepare for combining CLR and PhILR data to plot (Sediment Samples) ####\n# CLR\nordi_clr = ordinate(ps_clr, \"PCoA\", \"euclidean\")\nhead(ordi_clr$values)\nhead(ordi_clr$vectors)\n\nordi.scores_clr <- as.data.frame(ordi_clr$vectors)\nordi.scores_clr[,3:20] <- NULL\ncolnames(ordi.scores_clr) <- c(\"Axis.1clr\", \"Axis2.clr\")\nordi.scores_clr$ID_keep <- rownames(ordi.scores_clr)\n\n# PhILR\nordi.scores_philr <- as.data.frame(gp.pcoa$vectors)\nordi.scores_philr[,3:20] <- NULL\ncolnames(ordi.scores_philr) <- c(\"Axis.1philr\", \"Axis.2philr\")\nordi.scores_philr$ID_keep <- rownames(ordi.scores_philr)\n\n# Merge data with ordi_data\nDATA_PHYLOSEQ_FIXED$ID_keep <- rownames(DATA_PHYLOSEQ_FIXED)\nordi_data <- merge(DATA_PHYLOSEQ_FIXED, ordi.scores_clr, by = c('ID_keep'))\nordi_data <- merge(ordi_data, ordi.scores_philr, by = c('ID_keep'))\nhead(ordi_data)\n\n#### Plot CLR and PhILR PCA ####\n# Set up theme\nplot_theme <- theme(panel.background = element_rect(fill = \"white\", colour = \"black\", size = 1, linetype = \"solid\"),\n panel.border = element_rect(colour=\"black\", size=1, fill=NA),\n strip.background=element_rect(fill='white', colour='white', size = 0),\n strip.text = element_text(face=\"bold\", size=20),\n panel.spacing.x=unit(0.5, \"lines\"),\n panel.grid.major = element_line(size = 0),\n panel.grid.minor = element_line(size = 0),\n axis.text = element_text(size=15, colour=\"black\"),\n axis.title = element_text(face=\"bold\", size=20),\n legend.position=\"right\",\n legend.key = element_rect(fill = \"transparent\"),\n legend.title = element_text(face=\"bold\", size=20),\n legend.text = element_text(size=20),\n legend.background = element_rect(fill = \"transparent\"),\n legend.box.background = element_rect(fill = \"transparent\", colour = NA))\nplot_guide <- guides(fill = guide_colourbar(frame.linewidth = 1, frame.colour = \"black\", ticks = TRUE, ticks.colour = \"black\", ticks.linewidth = 1, reverse=T),\n shape = guide_legend(order=1, override.aes = list(size = 5, color=\"black\", alpha=1)),\n color = \"none\")\n\n### CLR PCA\n## Water Samples\nclr_plot_final <- ggplot(ordi_data_sub_NoBatch4, aes(x=PC1, y = PC2)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, aes(fill=Depth_meters, shape=strat_time)) +\n xlab(paste(\"PC1: 29.2%\")) +\n ylab(paste(\"PC2: 15.3%\")) +\n scale_shape_manual(name = \"Stratification?\", values=c(21, 23, 24)) +\n scale_fill_gradient2(name = \"Depth (m)\", breaks = c(0, 2, 6, 10), limits = c(0, 10), low=\"#fffab1\", mid=\"#ed105f\", high=\"#023e73\", midpoint=5) +\n plot_theme + plot_guide\nclr_plot_final\n\nsave_file <- paste(\"clr.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# label CLR PCA\nclr_plot_label <- clr_plot_final +\n geom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\n\nsave_file <- paste(\"clr_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# Plot batches CLR PCA\nplot_guide <- guides(shape = guide_legend(order=1, override.aes = list(size = 5, color=\"black\", alpha=1)),\n color = \"none\")\nordi_data_sub_batch$Sequence_batch <- gsub(\"Batch1\", \"Batch 1\", ordi_data_sub_batch$Sequence_batch)\nordi_data_sub_batch$Sequence_batch <- gsub(\"Batch2\", \"Batch 2\", ordi_data_sub_batch$Sequence_batch)\nordi_data_sub_batch$Sequence_batch <- gsub(\"Batch3\", \"Batch 3\", ordi_data_sub_batch$Sequence_batch)\nordi_data_sub_batch$Sequence_batch <- gsub(\"Batch4\", \"Batch 4\", ordi_data_sub_batch$Sequence_batch)\n\nclr_plot_batch <- ggplot(ordi_data_sub_batch, aes(x=PC1, y = PC2)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, shape=21, aes(fill=Sequence_batch)) +\n xlab(paste(\"PC1: 29.2%\")) +\n ylab(paste(\"PC2: 15.3%\")) +\n scale_fill_manual(name=\"Sequence Batch\", values = c(\"#003566\", \"#ffc300\", \"#ed105f\")) +\n plot_theme + plot_guide\n\nsave_file <- paste(\"clr_plot_batch.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# label CLR PCA batch\nclr_plot_batch_label <- clr_plot_batch +\n geom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\nclr_plot_batch_label\n\nsave_file <- paste(\"clr_plot_batch_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n## Sediment Samples\nclr_plot_final <- ggplot(ordi_data, aes(x=Axis.1clr, y = Axis2.clr)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, aes(fill=Location_description, shape=Depth_desc)) +\n xlab(paste(\"PC1: 23.6%\")) +\n ylab(paste(\"PC2: 10.8%\")) +\n scale_shape_manual(name = \"Depth layer\", values=c(25, 21, 22)) +\n scale_fill_manual(name = \"Location\", values=c(\"#dcab6b\", \"#9be564\")) +\n plot_theme + plot_guide\nclr_plot_final\n\n# save file\nsave_file <- paste(\"PCA_clr.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 9, height = 5, units = c(\"in\"), dpi = 300)\n\n# label plot\nclr_plot_label <- clr_plot_final +\ngeom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\npca_clr_label\n\n# save file\nsave_file <- paste(\"PCA_clr_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 9, height = 5, units = c(\"in\"), dpi = 300)\n\n### Plot PhILR PCA\n## Water Samples\nplot_guide <- guides(fill = guide_colourbar(frame.linewidth = 1, frame.colour = \"black\", ticks = TRUE, ticks.colour = \"black\", ticks.linewidth = 1, reverse=T),\n shape = guide_legend(order=1, override.aes = list(size = 5, color=\"black\", alpha=1)),\n color = \"none\")\n\nphilr_plot_final <- ggplot(ordi_data_sub_NoBatch4, aes(x=Axis.1philr, y = Axis.2philr)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, aes(fill=Depth_meters, shape=strat_time)) +\n xlab(paste(\"PC1: 53.8%\")) +\n ylab(paste(\"PC2: 14.5%\")) +\n scale_shape_manual(name = \"Stratification?\", values=c(21, 23, 24)) +\n scale_fill_gradient2(name = \"Depth (m)\", breaks = c(0, 2, 6, 10), limits = c(0, 10), low=\"#fffab1\", mid=\"#ed105f\", high=\"#023e73\", midpoint=5) +\n plot_theme + plot_guide\nphilr_plot_final\n\nsave_file <- paste(\"philr.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# label PhILR PCA plot\nphilr_plot_label <- philr_plot_final +\n geom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\n\nsave_file <- paste(\"philr_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# plot batches PhILR PCA\nplot_guide <- guides(shape = guide_legend(order=1, override.aes = list(size = 5, color=\"black\", alpha=1)),\n color = \"none\")\n\nphilr_plot_batch <- ggplot(ordi_data_sub_batch, aes(x=Axis.1philr, y = Axis.2philr)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, shape=21, aes(fill=Sequence_batch)) +\n xlab(paste(\"PC1: 53.8%\")) +\n ylab(paste(\"PC2: 14.5%\")) +\n scale_fill_manual(name=\"Sequence Batch\", values = c(\"#003566\", \"#ffc300\", \"#ed105f\")) +\n plot_theme + plot_guide\n\nsave_file <- paste(\"philr_plot_batch.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n# label PhILR PCA batch\nphilr_plot_batch_label <- philr_plot_batch +\n geom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\nphilr_plot_batch_label\n\nsave_file <- paste(\"philr_plot_batch_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 8, height = 5, units = c(\"in\"), dpi = 300)\n\n## Sediment Samples\nphilr_plot_final <- ggplot(ordi_data, aes(x=Axis.1philr, y = Axis.2philr)) +\n geom_hline(yintercept=0, size=.2, linetype = \"dashed\", color=\"black\") + geom_vline(xintercept=0, size=.2, linetype = \"dashed\", color=\"black\") +\n geom_point(color=\"black\", size=4, aes(fill=Location_description, shape=Depth_desc)) +\n xlab(paste(\"PC1: 52.7%\")) +\n ylab(paste(\"PC2: 8.7%\")) +\n scale_shape_manual(name = \"Depth layer\", values=c(25, 21, 22)) +\n scale_fill_manual(name = \"Location\", values=c(\"#dcab6b\", \"#9be564\")) +\n plot_theme + plot_guide\nphilr_plot_final\n\n# save file\nsave_file <- paste(\"PCA_philr.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 9, height = 5, units = c(\"in\"), dpi = 300)\n\n# label plot\nphilr_plot_label <- philr_plot_final +\ngeom_label_repel(aes(label = SampleID), box.padding = 0.35, point.padding = 0.5, segment.color = 'grey50', max.overlaps=Inf)\npca_philr_label\n\n# save file\nsave_file <- paste(\"PCA_philr_labelled.pdf\", sep=\"\")\nggsave(save_file, path = beta, scale = 1, width = 9, height = 5, units = c(\"in\"), dpi = 300)\n\n### combine CLR and PhILR PCA plots (Figure 3c, Figure 5c, Figure S6, Figure S10)\nboth <- plot_grid(clr_plot_final + theme(legend.position=\"none\"),\n philr_plot_final + theme(legend.position=\"none\"),\n ncol=2, align = \"v\", axis=\"b\")\n\nsave_file <- paste(\"Combo_ordination.pdf\", sep=\"\")\nggsave(save_file, path = beta, plot = both, scale = 1, width = 10, height = 5, units = c(\"in\"), dpi = 300)\n\n# Water Samples Labelled\nboth <- plot_grid(clr_plot_batch_label + theme(legend.position=\"none\"),\n philr_plot_batch_label + theme(legend.position=\"none\"),\n ncol=3, align = \"v\", axis=\"b\")\n\n# Sediment Samples Labelled\nboth <- plot_grid(clr_plot_label + theme(legend.position=\"none\"),\n philr_plot_label + theme(legend.position=\"none\"),\n ncol=3, align = \"v\", axis=\"b\")\n\nsave_file <- paste(\"Combo_ordination_batch_labelled.svg\", sep=\"\")\nggsave(save_file, path = beta, plot = both, scale = 1, width = 15, height = 5, units = c(\"in\"), dpi = 300)\n\n#### Stats on beta diversity ####\n\n# obtain distance matrix CLR\nordi_clr_dist <- as.matrix(phyloseq::distance(ps_clr, method=\"euclidean\"))\nhead(ordi_clr_dist)\n\n# obtain distance matrix PhILR\nordi_philr_dist <- as.matrix(gp.dist)\nhead(ordi_philr_dist)\n\n# Water ADONIS\nadonis2(ordi_clr_dist~DATA_PHYLOSEQ_FIXED$Depth_cat + DATA_PHYLOSEQ_FIXED$Location_description + DATA_PHYLOSEQ_FIXED$Season, permutations=999, by=\"margin\", method=\"euclidean\")\nadonis2(ordi_philr_dist~DATA_PHYLOSEQ_FIXED$Depth_cat + DATA_PHYLOSEQ_FIXED$Location_description + DATA_PHYLOSEQ_FIXED$Season, permutations=999, by=\"margin\", method=\"euclidean\")\n\n# Sediment ADONIS\nadonis2(ordi_clr_dist~DATA_PHYLOSEQ_FIXED$Location + DATA_PHYLOSEQ_FIXED$Depth_cat, permutations=999, by=\"margin\", method=\"euclidean\")\nadonis2(ordi_philr_dist~DATA_PHYLOSEQ_FIXED$Location + DATA_PHYLOSEQ_FIXED$Depth_cat, permutations=999, by=\"margin\", method=\"euclidean\")\n\n# Water Geochem ADONIS\nadonis2(ordi_clr_dist~\n DATA_PHYLOSEQ_FIXED$Fe_mg_L+\n DATA_PHYLOSEQ_FIXED$ChlA_RFU+\n DATA_PHYLOSEQ_FIXED$DO_percSat+\n DATA_PHYLOSEQ_FIXED$TDS_ppt+\n DATA_PHYLOSEQ_FIXED$pH+\n DATA_PHYLOSEQ_FIXED$Temp_C+\n DATA_PHYLOSEQ_FIXED$Fe_mg_L, permutations=999, by=\"margin\", method=\"euclidean\")\n\nadonis2(ordi_philr_dist~\n DATA_PHYLOSEQ_FIXED$Fe_mg_L+\n DATA_PHYLOSEQ_FIXED$ChlA_RFU+\n DATA_PHYLOSEQ_FIXED$DO_percSat+\n DATA_PHYLOSEQ_FIXED$TDS_ppt+\n DATA_PHYLOSEQ_FIXED$pH+\n DATA_PHYLOSEQ_FIXED$Temp_C+\n DATA_PHYLOSEQ_FIXED$Fe_mg_L, permutations=999, by=\"margin\", method=\"euclidean\")\n", "meta": {"hexsha": "5b7e278cc2814bbd0c1d2b82f99bb6d3cafe961a", "size": 16274, "ext": "r", "lang": "R", "max_stars_repo_path": "07.BetaDiversity.r", "max_stars_repo_name": "LLNL/2022_PondB_microbiome", "max_stars_repo_head_hexsha": "d9aaade01033eea9f220e96521099fd881971c82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "07.BetaDiversity.r", "max_issues_repo_name": "LLNL/2022_PondB_microbiome", "max_issues_repo_head_hexsha": "d9aaade01033eea9f220e96521099fd881971c82", "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": "07.BetaDiversity.r", "max_forks_repo_name": "LLNL/2022_PondB_microbiome", "max_forks_repo_head_hexsha": "d9aaade01033eea9f220e96521099fd881971c82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-23T17:39:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:39:35.000Z", "avg_line_length": 44.4644808743, "max_line_length": 221, "alphanum_fraction": 0.6985989923, "num_tokens": 5091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6052564855927832}} {"text": "# Prediction efficiency in two ways, plus identity of taxa for which we obtain a, b, c or d\nprediction_accuracy_id <- function(predicted, empirical) {\n # Parameters:\n # predicted matrix of predicted interactions\n # empirical matrix of empirical interactions\n\n # Output vector of a, b, c, d, and TSS\n # a number of links predicted (1) and observed (1)\n # b number predicted (1) but not observed (0)\n # c number predicted absent (0) but observed (1)\n # d number of predicted absent (0) and observed absent (0)\n # TSS TSS = (ad-\u0002bc)/[(a+c)(b+d)]\n # \"[...] quantifies the proportion of prediction success relative to false predictions\n # and returns values ranging between 1 (perfect predictions) and \u00021 (inverted forecast)\n # (Allouche, Tsoar & Kadmon 2006).\" Gravel et al. 2013\n # ScoreY1 Fraction of 1 correctly predicted a / (a + c)\n # ScoreY0 Fraction of 0 correctly predicted d / (b + d)\n # FSS FSS = ScoreY1 + ScoreY0 / sum(a, b, c, d)^2\n\n if(identical(colnames(predicted), colnames(empirical)) == FALSE ||\n identical(rownames(predicted), rownames(empirical)) == FALSE ||\n identical(dim(predicted), dim(empirical)) == FALSE) {\n print('matrices need to have same dimensions and row and column names')\n break\n }\n\n efficiency <- numeric(8)\n aa <- bb <- cc <- dd <- numeric(2)\n names(efficiency) <- c('a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')\n\n for(i in 1:ncol(predicted)){\n for(j in 1:nrow(predicted)) {\n if(predicted[i,j] == 1 && empirical[i,j] == 1) {\n efficiency[1] <- efficiency[1] + 1\n aa <- rbind(aa,c(j,i))\n } else if(predicted[i,j] == 1 && empirical[i,j] == 0) {\n efficiency[2] <- efficiency[2] + 1\n bb <- rbind(bb,c(j,i))\n } else if(predicted[i,j] == 0 && empirical[i,j] == 1) {\n efficiency[3] <- efficiency[3] + 1\n cc <- rbind(cc,c(j,i))\n } else if(predicted[i,j] == 0 && empirical[i,j] == 0) {\n efficiency[4] <- efficiency[4] + 1\n dd <- rbind(dd,c(j,i))\n }\n }\n }\n\n a <- efficiency[1]\n b <- efficiency[2]\n c <- efficiency[3]\n d <- efficiency[4]\n\n efficiency[5] <- ((a * d) - (b * c)) / ((a + c) * (b + d)) # TSS\n efficiency[6] <- a / (a + c) # ScoreY1\n efficiency[7] <- d / (b + d) # ScoreY0\n efficiency[8] <- (a + d) / sum(a, b, c, d) # FSS\n\n efficiency.id <- vector('list',5)\n efficiency.id[[1]] <- efficiency\n efficiency.id[[2]] <- aa\n efficiency.id[[3]] <- bb\n efficiency.id[[4]] <- cc\n efficiency.id[[5]] <- dd\n\n return(efficiency.id)\n}\n", "meta": {"hexsha": "25f7cc63214582ff382aad76b41e0cb30d6b5f85", "size": 2911, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/prediction_accuracy_id.r", "max_stars_repo_name": "david-beauchesne/predicting_interactions", "max_stars_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-08-12T11:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-09T18:16:12.000Z", "max_issues_repo_path": "Script/prediction_accuracy_id.r", "max_issues_repo_name": "david-beauchesne/predicting_interactions", "max_issues_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-12T14:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T15:25:21.000Z", "max_forks_repo_path": "Script/prediction_accuracy_id.r", "max_forks_repo_name": "david-beauchesne/predicting_interactions", "max_forks_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-12T10:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-12T10:46:53.000Z", "avg_line_length": 42.8088235294, "max_line_length": 109, "alphanum_fraction": 0.5132256956, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7025300449389327, "lm_q1q2_score": 0.6052564719930319}} {"text": "khat.new=function(h,p){ \nnum=(1-((h^2+2)/h^2)^(-p/2))^2\ndin = ((h^2 + 4)/h^2)^(-p/2) - 2 * ((h^2 + 1)/h^2)^(-p/2) * \n ((h^2 + 3)/h^2)^(-p/2) + ((h^2 + 2)/h^2)^(-p)\ndof=num/din\nreturn(p * (dof^(1/p) - 1)/2)\n}\n\nkhat.direct=function(h,p,k) khat.new(h,p)-k\n\nhvec=function(p,len=10){\nkvec=seq(2,15,length.out=len)\nh=rep(0,length=len)\nfor (i in 1:len){\nh[i]=uniroot(khat.direct, c(0.1,7), p=p,k=kvec[i])$root\n}\nreturn(h)\n}\n", "meta": {"hexsha": "60d6a6af8f30d400f66d91e008ca871b27ca9aa2", "size": 424, "ext": "r", "lang": "R", "max_stars_repo_path": "code/khat.new.r", "max_stars_repo_name": "id175196/PhenocamProject", "max_stars_repo_head_hexsha": "3291deb8b1b8899b78df4ae0ffff64d0bcd300d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-02-08T22:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-08T22:12:02.000Z", "max_issues_repo_path": "code/khat.new.r", "max_issues_repo_name": "id175196/PhenocamProject", "max_issues_repo_head_hexsha": "3291deb8b1b8899b78df4ae0ffff64d0bcd300d6", "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": "code/khat.new.r", "max_forks_repo_name": "id175196/PhenocamProject", "max_forks_repo_head_hexsha": "3291deb8b1b8899b78df4ae0ffff64d0bcd300d6", "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": 22.3157894737, "max_line_length": 60, "alphanum_fraction": 0.5188679245, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.6052156192406969}} {"text": "#\r\n# ooc_montecarlo.r\r\n#\r\nrm(list=ls(all=TRUE))\r\n#\r\nlibrary(MASS)\r\nlibrary(MCMCpack)\r\nlibrary(hitandrun)\r\nlibrary(ooc)\r\nlibrary(statar)\r\nlibrary(Matrix)\r\nlibrary(reshape)\r\nlibrary(ggplot2)\r\nlibrary(viridis)\r\nlibrary(foreach)\r\nlibrary(doParallel)\r\n#\r\ncl <- makeCluster(detectCores() - 1)\r\nregisterDoParallel(cl)\r\n#\r\nset.seed(1985)\r\n#\r\nsetwd(\"c:/\")\r\n#\r\n#\r\n# Utility functions plot\r\n#\r\nx <- seq(0, 2.0, by=0.01)\r\nlinearutility <- 1 - abs(x-0)\r\nnormalutility <- exp(-2 * ((x-0)^2))\r\nquadraticutility <- 1 - 2*(x-0)^2\r\n#\r\n#\r\n#pdf(\"Dropbox/OC_publicopinion/images/montecarlo_utilityfunctions.pdf\", height=6, width=6)\r\n#\r\nplot(c(0,2), c(-1,1), type=\"n\", bty=\"n\", cex.lab=1.1, xlab=\"Distance from Ideal Point\", ylab=\"Utility\", main=\"Linear, Normal, and Quadratic Utility Functions\")\r\nlines(x,linearutility, lwd=2, lty=1)\r\nlines(x,normalutility, lwd=2, lty=2)\r\nlines(x,quadraticutility, lwd=2, lty=3)\r\n#\r\ndev.off()\r\n#\r\n#\r\n# DEFINE MONTE CARLO FUNCTION\r\n#\r\nmontecarlo.oc <- function(n=1200, q=20, ndim=2, utility.probs=c(0.33,0.33,0.33),\r\n\tmissing=0.1, error.respondents=c(0.1,1), error.issues=c(2,1)){\r\n#\r\n# %%%%%%%%%%%%%%%%%%%%%%%%%\r\n# %%%%% BEGIN %%%%%%%\r\n# %%%%% Monte Carlo %%%%%%%\r\n# %%%%%%%%%%%%%%%%%%%%%%%%%\r\n#\r\nheteroskedastic.respondents <- runif(n, error.respondents[1], error.respondents[2])\r\nheteroskedastic.issues <- rgamma(q, error.issues[1], error.issues[2])\r\n#\r\ncorrelations <- runif(n, -0.1, 0.7)\r\nknowledge <- xtile(correlations, 3)\r\n#\r\n# 1.) Generate respondent ideal points\r\n#\r\nmu <- rep(0,ndim)\r\nSigma <- list()\r\nidealpoints <- matrix(NA, nrow=n, ncol=ndim)\r\nfor (i in 1:n){\r\n\tSigma[[i]] <- matrix(1, nrow=ndim, ncol=ndim)\r\n\tSigma[[i]][lower.tri(Sigma[[i]])] <- runif(sum(lower.tri(Sigma[[i]])), correlations[i]-0.2, correlations[i]+0.2)\r\n\tSigma[[i]][upper.tri(Sigma[[i]])] <- t(Sigma[[i]])[upper.tri(t(Sigma[[i]]))]\r\n\tSigma[[i]] <- as.matrix(nearPD(Sigma[[i]])$mat)\r\n\tidealpoints[i,] <- mvrnorm(1, mu=mu, Sigma=Sigma[[i]])\r\n}\r\n#\r\nidealpoints[idealpoints > 2] <- 2\r\nidealpoints[idealpoints < -2] <- -2\r\n#\r\n# 2.) Generate normal vectors\r\n#\r\nnormalvectors <- hypersphere.sample(ndim, q)\r\n#\r\nfor (j in 1:q){\r\nif (normalvectors[j,1] < 0) normalvectors[j,] <- -1 * normalvectors[j,]\r\n}\r\n#\r\n# 3.) Project respondents on normal vectors\r\n#\r\nrespondent.projections <- idealpoints %*% t(normalvectors)\r\n#\r\n# 4.) Generate outcome locations\r\n#\r\noutcome.locations <- apply(respondent.projections, 2, function(x){sort(runif(5,min(x),max(x)))})\r\n#\r\n# 5.) Define utility functions\r\n#\r\nlinear.utility <- function(idealpoint, choices){\r\n tmp <- 1 - (3*abs(idealpoint - choices))\r\n return(tmp)}\r\n#\r\nnormal.utility <- function(idealpoint, choices){\r\n tmp <- 5 * exp(-1 * ((idealpoint - choices)^2))\r\n return(tmp)}\r\n#\r\nquad.utility <- function(idealpoint, choices){\r\n tmp <- 1 - 2 * (idealpoint - choices)^2\r\n return(tmp)}\r\n#\r\n# 6.) Calculate utility and response probabilities\r\n#\r\nutility.fun <- sample(c(\"linear\",\"normal\",\"quadratic\"), n, replace=TRUE, prob=utility.probs)\r\n#\r\nsystematic.utility <- total.utility <- probmat <- list()\r\nfor (j in 1:q){\r\nsystematic.utility[[j]] <- matrix(NA, nrow=n, ncol=5)\r\ntotal.utility[[j]] <- matrix(NA, nrow=n, ncol=5)\r\nprobmat[[j]] <- matrix(NA, nrow=n, ncol=5)\r\n}\r\n#\r\nfor (i in 1:n){\r\nfor (j in 1:q){\r\n#\r\n\tif(utility.fun[i]==\"linear\"){\r\n\tsystematic.utility[[j]][i,] <- linear.utility(respondent.projections[i,j], outcome.locations[,j])\r\n\t}\r\n#\r\n\tif(utility.fun[i]==\"normal\"){\r\n\tsystematic.utility[[j]][i,] <- normal.utility(respondent.projections[i,j], outcome.locations[,j])\r\n\t}\r\n#\r\n\tif(utility.fun[i]==\"quadratic\"){\r\n\tsystematic.utility[[j]][i,] <- quad.utility(respondent.projections[i,j], outcome.locations[,j])\r\n\t}\r\n#\r\ntotal.utility[[j]][i,] <- systematic.utility[[j]][i,] / exp(heteroskedastic.respondents[i] * heteroskedastic.issues[j])\r\nprobmat[[j]][i,] <- pnorm(total.utility[[j]][i,]) / sum(pnorm(total.utility[[j]][i,]))\r\n}}\r\n#\r\nfor (j in 1:q){\r\nprobmat[[j]][is.na(probmat[[j]])] <- 1\r\n}\r\n#\r\n# 7.) Generate perfect and error (probabilistic) responses\r\n#\r\nsimulated.responses <- perfect.responses <- matrix(NA, nrow=n, ncol=q)\r\n#\r\nfor (i in 1:n){\r\nfor (j in 1:q){\r\nsimulated.responses[i,j] <- sample(1:5, 1, prob=probmat[[j]][i,])\r\n# Note: perfect voting could of course also be simulated using the maximum of total.utility\r\nperfect.responses[i,j] <- which.max(systematic.utility[[j]][i,])\r\n}}\r\n#\r\n# 8.) Insert missing data at random\r\n#\r\nif(missing > 0){\r\nmiss <- expand.grid(n=1:n, q=1:q)\r\nmissing.selected <- as.matrix(miss)[sample(1:nrow(miss), (n*q*missing), replace=FALSE),]\r\nfor (i in 1:nrow(missing.selected)){\r\nsimulated.responses[missing.selected[i,1], missing.selected[i,2]] <- NA\r\nperfect.responses[missing.selected[i,1], missing.selected[i,2]] <- NA\r\n}\r\n}\r\n#\r\n# 9.) Organize output\r\n#\r\ncorrectvotes <- sum(diag(table(simulated.responses,perfect.responses)))\r\ntotalvotes <- sum(table(simulated.responses,perfect.responses))\r\n#\r\nreturn(list(simulated.responses = simulated.responses,\r\n\t perfect.responses = perfect.responses,\r\n\t idealpoints = idealpoints,\r\n\t normalvectors = normalvectors,\r\n\t heteroskedastic.respondents = heteroskedastic.respondents,\r\n\t heteroskedastic.issues = heteroskedastic.issues,\r\n\t correlations = correlations,\r\n\t knowledge = knowledge,\r\n\t error = (1 - (correctvotes / totalvotes))\r\n\t))\r\n#\r\n}\r\n#\r\n# %%%%%%%%%%%%%%%%%%%%%%%%%\r\n# %%%%%% END %%%%%%%\r\n# %%%%% Monte Carlo %%%%%%%\r\n# %%%%%%%%%%%%%%%%%%%%%%%%%\r\n#\r\n#\r\n#\r\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n# @@@@@@@@@@@@@ RUN ORDERED @@@@@@@@@@@@@\r\n# @@@@@@@@ OPTIMAL CLASSIFICATION @@@@@@@\r\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n#\r\n#\r\n# utility.probs = c(linear, normal, quadratic)\r\n# error.respondents = normal(mu, sigma)\r\n# error.issues = gamma(shape, rate)\r\n#\r\n# Simulations randomize:\r\n#\r\n#\t\t1.) Respondent utility functions\r\n#\t\t2.) Missingness\r\n#\t\t3.) Error rate\r\n#\r\n#\r\nntrials <- 400\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# Basic setup:\r\n#sim <- montecarlo.oc(n=1500, q=40, ndim=2, utility.probs=runif(3,0,1), missing=0.1, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\n#res <- ooc(sim$perfect.responses, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\n#\r\n#\r\n#\r\n# I. VARY AMOUNT OF MISSING DATA\r\n#\r\nfit.2dim.missing10 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=2, utility.probs=runif(3,0,1), missing=0.1, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.missing10, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing10.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nfit.2dim.missing25 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=2, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.missing25, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing25.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nfit.2dim.missing40 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=2, utility.probs=runif(3,0,1), missing=0.4, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.missing40, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing40.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nfit.3dim.missing10 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=3, utility.probs=runif(3,0,1), missing=0.1, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,3), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- 1\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.missing10, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing10.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nfit.3dim.missing25 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=3, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,3), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- 1\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.missing25, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing25.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nfit.3dim.missing40 <- foreach(i=101:(100+ntrials), .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=3, utility.probs=runif(3,0,1), missing=0.4, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,3), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- 1\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.missing40, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing40.rda\")\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\n#\r\n#\r\n#\r\n# II. INFORMAL TEST OF CONSISTENCY:\r\n# VARY NUMBER OF ISSUES (25, 50, 100)\r\n#\r\nfit.2dim.issues25 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=25, ndim=2, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.issues25, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues25.rda\")\r\n#\r\n#\r\nfit.2dim.issues50 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=50, ndim=2, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.issues50, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues50.rda\")\r\n#\r\n#\r\nfit.2dim.issues100 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=100, ndim=2, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.2dim.issues100, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues100.rda\")\r\n#\r\n#\r\nfit.3dim.issues25 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=25, ndim=3, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.issues25, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues25.rda\")\r\n#\r\n#\r\nfit.3dim.issues50 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=50, ndim=3, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.issues50, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues50.rda\")\r\n#\r\n#\r\nfit.3dim.issues100 <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=100, ndim=3, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=3, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nnormvecs <- res$issues.unique[,grepl(\"normVector\", colnames(res$issues.unique)) & colnames(res$issues.unique)!=\"normVectorAngle2D\"]\r\n#\r\n# Perform Procrustes rotation\r\nrotation <- procrustes(x, sim$idealpoints)$R\r\nrotated.idealpoints <- x %*% rotation\r\nrotated.normalvectors <- normvecs %*% rotation\r\nrotated.normalvectors[(rotated.normalvectors[,1] < 0),] <- -1 * rotated.normalvectors[(rotated.normalvectors[,1] < 0),]\r\n#\r\ntruetheta <- apply(sim$normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntruetheta[sim$normalvectors[,2] < 0] <- -1 * truetheta[sim$normalvectors[,2] < 0]\r\n#\r\ntheta <- apply(rotated.normalvectors, 1, function(x){ acos_d(sum(x * c(1,0))/(sqrt(sum(x * x)) * sqrt(sum(c(1,0) * c(1,0)))))})\r\ntheta[rotated.normalvectors[,2] < 0] <- -1 * theta[rotated.normalvectors[,2] < 0]\r\n#\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\nissues.PRE <- res$issues.unique[,\"PREScale\"]\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncornormvec <- cor(as.vector(dist(rotated.normalvectors)), as.vector(dist(sim$normalvectors)))\r\ncortheta <- cor(truetheta, theta)\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorhetissues <- cor(sim$heteroskedastic.issues, issues.PRE)\r\n#\r\nerror <- sim$error\r\nc(corx, cornormvec, cortheta, corhetresp, corconstraintresp, corhetissues, error)\r\n}\r\n#\r\nsave(fit.3dim.issues100, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues100.rda\")\r\n#\r\n#\r\n#\r\n#\r\n# III. COMPARE FITS OF MODERATES AND EXTREMISTS\r\n#\r\nfit.2dim.moderatesextremists <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=2, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\n#\r\nmoderate.1dim <- rotated.idealpoints[,1] > quantile(sim$idealpoints[,1])[\"25%\"] &\r\nrotated.idealpoints[,1] < quantile(sim$idealpoints[,1])[\"75%\"]\r\nmoderate.2dim <- rotated.idealpoints[,2] > quantile(sim$idealpoints[,2])[\"25%\"] &\r\nrotated.idealpoints[,2] < quantile(rotated.idealpoints[,2])[\"75%\"]\r\nmoderate <- moderate.1dim & moderate.2dim\r\n#\r\nextreme.1dim <- rotated.idealpoints[,1] < quantile(sim$idealpoints[,1])[\"25%\"] |\r\nrotated.idealpoints[,1] > quantile(sim$idealpoints[,1])[\"75%\"]\r\nextreme.2dim <- rotated.idealpoints[,2] < quantile(sim$idealpoints[,2])[\"25%\"] |\r\nrotated.idealpoints[,2] > quantile(sim$idealpoints[,2])[\"75%\"]\r\nextreme <- extreme.1dim & extreme.2dim\r\n#\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncorx.moderate <- cor(as.vector(dist(x[moderate,])), as.vector(dist(sim$idealpoints[moderate,])))\r\ncorx.extreme <- cor(as.vector(dist(x[extreme,])), as.vector(dist(sim$idealpoints[extreme,])))\r\n#\r\n#\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorhetresp.moderate <- cor(sim$heteroskedastic.respondents[moderate], respondents.correct[moderate])\r\ncorhetresp.extreme <- cor(sim$heteroskedastic.respondents[extreme], respondents.correct[extreme])\r\n#\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorconstraintresp.moderate <- cor(sim$correlations[moderate], respondents.correct[moderate])\r\ncorconstraintresp.extreme <- cor(sim$correlations[extreme], respondents.correct[extreme])\r\n#\r\nerror <- sim$error\r\nc(corx, corx.moderate, corx.extreme, corhetresp, corhetresp.moderate, corhetresp.extreme, corconstraintresp, corconstraintresp.moderate, corconstraintresp.extreme)\r\n}\r\n#\r\nsave(fit.2dim.moderatesextremists, file=\"Dropbox/OC_publicopinion/analysis/fit.2dim.moderatesextremists.rda\")\r\n#\r\n#\r\nfit.3dim.moderatesextremists <- foreach(i=1:ntrials, .combine='rbind', .packages=c(\"ooc\", \"statar\", \"Matrix\")) %dopar% {\r\nset.seed(i)\r\nsim <- montecarlo.oc(n=1500, q=40, ndim=3, utility.probs=runif(3,0,1), missing=0.25, error.respondents=sort(runif(2,0,0.5)), error.issues=c(runif(1,0,3), 0.5))\r\nissuescales <- sim$simulated.responses\r\nres <- ooc(issuescales, dims=2, min=10, lop=0.0001, polarity=rep(1,2), iter=25, nv.method=\"svm.reg\", cost=1)\r\nx <- res$respondents[,grepl(\"coord\", colnames(res$respondents))]\r\nrespondents.correct <- res$respondents[,\"percent.correctScale\"]\r\n#\r\nmoderate.1dim <- rotated.idealpoints[,1] > quantile(sim$idealpoints[,1])[\"25%\"] &\r\nrotated.idealpoints[,1] < quantile(sim$idealpoints[,1])[\"75%\"]\r\nmoderate.2dim <- rotated.idealpoints[,2] > quantile(sim$idealpoints[,2])[\"25%\"] &\r\nrotated.idealpoints[,2] < quantile(rotated.idealpoints[,2])[\"75%\"]\r\nmoderate.3dim <- rotated.idealpoints[,3] > quantile(sim$idealpoints[,3])[\"25%\"] &\r\nrotated.idealpoints[,3] < quantile(rotated.idealpoints[,3])[\"75%\"]\r\nmoderate <- moderate.1dim & moderate.2dim & moderate.3dim\r\n#\r\nextreme.1dim <- rotated.idealpoints[,1] < quantile(sim$idealpoints[,1])[\"25%\"] |\r\nrotated.idealpoints[,1] > quantile(sim$idealpoints[,1])[\"75%\"]\r\nextreme.2dim <- rotated.idealpoints[,2] < quantile(sim$idealpoints[,2])[\"25%\"] |\r\nrotated.idealpoints[,2] > quantile(sim$idealpoints[,2])[\"75%\"]\r\nextreme.3dim <- rotated.idealpoints[,3] < quantile(sim$idealpoints[,3])[\"25%\"] |\r\nrotated.idealpoints[,3] > quantile(sim$idealpoints[,3])[\"75%\"]\r\nextreme <- extreme.1dim & extreme.2dim & extreme.3dim\r\n#\r\n#\r\ncorx <- cor(as.vector(dist(x)), as.vector(dist(sim$idealpoints)))\r\ncorx.moderate <- cor(as.vector(dist(x[moderate,])), as.vector(dist(sim$idealpoints[moderate,])))\r\ncorx.extreme <- cor(as.vector(dist(x[extreme,])), as.vector(dist(sim$idealpoints[extreme,])))\r\n#\r\n#\r\ncorhetresp <- cor(sim$heteroskedastic.respondents, respondents.correct)\r\ncorhetresp.moderate <- cor(sim$heteroskedastic.respondents[moderate], respondents.correct[moderate])\r\ncorhetresp.extreme <- cor(sim$heteroskedastic.respondents[extreme], respondents.correct[extreme])\r\n#\r\ncorconstraintresp <- cor(sim$correlations, respondents.correct)\r\ncorconstraintresp.moderate <- cor(sim$correlations[moderate], respondents.correct[moderate])\r\ncorconstraintresp.extreme <- cor(sim$correlations[extreme], respondents.correct[extreme])\r\n#\r\nerror <- sim$error\r\nc(corx, corx.moderate, corx.extreme, corhetresp, corhetresp.moderate, corhetresp.extreme, corconstraintresp, corconstraintresp.moderate, corconstraintresp.extreme)\r\n}\r\n#\r\nsave(fit.3dim.moderatesextremists, file=\"Dropbox/OC_publicopinion/analysis/fit.3dim.moderatesextremists.rda\")\r\n#\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\nstopCluster(cl)\r\n#\r\n# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n#\r\n#\r\n# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\r\n# $$$$$$$$$$ PLOTS $$$$$$$$$$$$$$$$\r\n# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\r\n#\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing10.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing25.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.missing40.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing10.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing25.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.missing40.rda\")\r\n#\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues25.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues50.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.issues100.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues25.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues50.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.3dim.issues100.rda\")\r\n#\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.moderatesextremists.rda\")\r\nload(\"Dropbox/OC_publicopinion/analysis/fit.2dim.moderatesextremists.rda\")\r\n#\r\n#\r\n#\r\n# 10%\r\nfit <- fit.2dim.missing10\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"10% Missing\"\r\ntwodim.df10 <- twodim.df\r\n#\r\n# 25%\r\nfit <- fit.2dim.missing25\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"25% Missing\"\r\ntwodim.df25 <- twodim.df\r\n#\r\n# 40%\r\nfit <- fit.2dim.missing40\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"40% Missing\"\r\ntwodim.df40 <- twodim.df\r\n#\r\n#\r\n#\r\ntwodim.df <- rbind(twodim.df10, twodim.df25, twodim.df40)\r\n#\r\n# Create line breaks\r\nswr = function(string, nwrap=20) {\r\n paste(strwrap(string, width=nwrap), collapse=\"\\n\")\r\n}\r\nswr <- Vectorize(swr)\r\ntwodim.df$variable <- swr(twodim.df$variable)\r\n#\r\ntwodim.df$variable <- factor(twodim.df$variable, levels=c(\"True and recovered\\nideal points\", \"True and recovered\\nissue normal\\nvectors\", \"Reversed issue\\nerror variance and\\nrecovered issue PRE\"))\r\n#\r\npdf(\"Dropbox/OC_publicopinion/images/ooc_montecarlo_twodim.pdf\", height=9, width=8)\r\n#\r\nggplot(twodim.df, aes(errorlevel, value, fill=errorlevel)) +\r\n\tfacet_wrap(~Missing+variable) +\r\n\tgeom_boxplot() +\r\n\txlab(\"\") +\r\n\tylab(\"Correlation\\n\") +\r\n\tscale_fill_viridis(discrete=TRUE, begin=0.8, end=0.2) +\r\n\tylim(0,1) +\r\n\tguides(fill=FALSE) +\r\n\tggtitle(\"Two Dimensions\\n\") +\r\n\ttheme(plot.title = element_text(hjust = 0.5))\r\n#\r\ndev.off()\r\n#\r\n# 3-dimensional graph\r\n#\r\n# 10%\r\nfit <- fit.3dim.missing10\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"10% Missing\"\r\nthreedim.df10 <- threedim.df\r\n#\r\n# 25%\r\nfit <- fit.3dim.missing25\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"25% Missing\"\r\nthreedim.df25 <- threedim.df\r\n#\r\n# 40%\r\nfit <- fit.3dim.missing40\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"40% Missing\"\r\nthreedim.df40 <- threedim.df\r\n#\r\n#\r\n#\r\nthreedim.df <- rbind(threedim.df10, threedim.df25, threedim.df40)\r\n#\r\n# Create line breaks\r\nswr = function(string, nwrap=20) {\r\n paste(strwrap(string, width=nwrap), collapse=\"\\n\")\r\n}\r\nswr <- Vectorize(swr)\r\nthreedim.df$variable <- swr(threedim.df$variable)\r\n#\r\nthreedim.df$variable <- factor(threedim.df$variable, levels=c(\"True and recovered\\nideal points\", \"True and recovered\\nissue normal\\nvectors\", \"Reversed issue\\nerror variance and\\nrecovered issue PRE\"))\r\n#\r\npdf(\"Dropbox/OC_publicopinion/images/ooc_montecarlo_threedim.pdf\", height=9, width=8)\r\n#\r\nggplot(threedim.df, aes(errorlevel, value, fill=errorlevel)) +\r\n\tfacet_wrap(~Missing+variable) +\r\n\tgeom_boxplot() +\r\n\txlab(\"\") +\r\n\tylab(\"Correlation\\n\") +\r\n\tscale_fill_viridis(discrete=TRUE, begin=0.8, end=0.2) +\r\n\tylim(0,1) +\r\n\ttheme(plot.title = element_text(hjust = 0.5)) +\r\n\tguides(fill=FALSE) +\r\n\tggtitle(\"Three Dimensions\\n\") +\r\n\ttheme(plot.title = element_text(hjust = 0.5))\r\n#\r\ndev.off()\r\n#\r\n#table(fit[,\"errorlevel\"], fit.twodim$errorlevel)\r\n#\r\n#\r\n#\r\n#\r\n# 25 issues\r\nfit <- fit.2dim.issues25\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"25 Issues\"\r\ntwodim.df25 <- twodim.df\r\n#\r\n# 50 issues\r\nfit <- fit.2dim.issues50\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"50 Issues\"\r\ntwodim.df50 <- twodim.df\r\n#\r\n# 100 issues\r\nfit <- fit.2dim.issues100\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.twodim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.twodim$errorlevel <- factor(xtile(fit.twodim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.twodim$cor.errorissues <- abs(fit.twodim$cor.errorissues)\r\n#\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.twodim)[names(fit.twodim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\ntwodim.df <- melt(fit.twodim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(twodim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\ntwodim.df$Missing <- \"100 Issues\"\r\ntwodim.df100 <- twodim.df\r\n#\r\n#\r\n#\r\ntwodim.df <- rbind(twodim.df25, twodim.df50, twodim.df100)\r\n#\r\n# Create line breaks\r\nswr = function(string, nwrap=20) {\r\n paste(strwrap(string, width=nwrap), collapse=\"\\n\")\r\n}\r\nswr <- Vectorize(swr)\r\ntwodim.df$variable <- swr(twodim.df$variable)\r\n#\r\ntwodim.df$variable <- factor(twodim.df$variable, levels=c(\"True and recovered\\nideal points\", \"True and recovered\\nissue normal\\nvectors\", \"Reversed issue\\nerror variance and\\nrecovered issue PRE\"))\r\n#\r\npdf(\"Dropbox/OC_publicopinion/images/ooc_montecarlo_twodim_numberissues.pdf\", height=9, width=8)\r\n#\r\nggplot(twodim.df, aes(errorlevel, value, fill=errorlevel)) +\r\n\tfacet_wrap(~Missing+variable) +\r\n\tgeom_boxplot() +\r\n\txlab(\"\") +\r\n\tylab(\"Correlation\\n\") +\r\n\tscale_fill_viridis(discrete=TRUE, begin=0.8, end=0.2) +\r\n\tylim(0,1) +\r\n\tguides(fill=FALSE) +\r\n\tggtitle(\"Two Dimensions\\n\") +\r\n\ttheme(plot.title = element_text(hjust = 0.5))\r\n#\r\ndev.off()\r\n#\r\n# 3-dimensional graph\r\n#\r\n# 25 issues\r\nfit <- fit.3dim.issues25\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"25 Issues\"\r\nthreedim.df25 <- threedim.df\r\n#\r\n# 50 issues\r\nfit <- fit.3dim.issues50\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"50 Issues\"\r\nthreedim.df50 <- threedim.df\r\n#\r\n# 100 issues\r\nfit <- fit.3dim.issues100\r\ncolnames(fit) <- c(\"cor.idealpoints\", \"cor.normvecs\", \"cor.theta\", \"cor.errorrespondents\", \"cor.constraintrespondents\", \"cor.errorissues\", \"errorlevel\")\r\nfit.threedim <- data.frame(fit[,c(\"cor.idealpoints\",\"cor.normvecs\",\"cor.errorissues\",\"errorlevel\")])\r\n#\r\nfit.threedim$errorlevel <- factor(xtile(fit.threedim$errorlevel, 3), labels=c(\"Low error\", \"Medium error\", \"High error\"))\r\nfit.threedim$cor.errorissues <- abs(fit.threedim$cor.errorissues)\r\n#\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.idealpoints\"] <- \"True and recovered ideal points\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.normvecs\"] <- \"True and recovered issue normal vectors\"\r\nnames(fit.threedim)[names(fit.threedim)==\"cor.errorissues\"] <- \"Reversed issue error variance and recovered issue PRE\"\r\n#\r\nthreedim.df <- melt(fit.threedim, id=c(\"errorlevel\"))\r\n#\r\n#ggplot(threedim.df, aes(errorlevel, value)) + facet_wrap(~variable) + geom_boxplot()\r\n#\r\nthreedim.df$Missing <- \"100 Issues\"\r\nthreedim.df100 <- threedim.df\r\n#\r\n#\r\n#\r\nthreedim.df <- rbind(threedim.df25, threedim.df50, threedim.df100)\r\n#\r\n# Create line breaks\r\nswr = function(string, nwrap=20) {\r\n paste(strwrap(string, width=nwrap), collapse=\"\\n\")\r\n}\r\nswr <- Vectorize(swr)\r\nthreedim.df$variable <- swr(threedim.df$variable)\r\n#\r\nthreedim.df$variable <- factor(threedim.df$variable, levels=c(\"True and recovered\\nideal points\", \"True and recovered\\nissue normal\\nvectors\", \"Reversed issue\\nerror variance and\\nrecovered issue PRE\"))\r\n#\r\npdf(\"Dropbox/OC_publicopinion/images/ooc_montecarlo_threedim_numberissues.pdf\", height=9, width=8)\r\n#\r\nggplot(threedim.df, aes(errorlevel, value, fill=errorlevel)) +\r\n\tfacet_wrap(~Missing+variable) +\r\n\tgeom_boxplot() +\r\n\txlab(\"\") +\r\n\tylab(\"Correlation\\n\") +\r\n\tscale_fill_viridis(discrete=TRUE, begin=0.8, end=0.2) +\r\n\tylim(0,1) +\r\n\ttheme(plot.title = element_text(hjust = 0.5)) +\r\n\tguides(fill=FALSE) +\r\n\tggtitle(\"Three Dimensions\\n\") +\r\n\ttheme(plot.title = element_text(hjust = 0.5))\r\n#\r\ndev.off()\r\n#\r\n#table(fit[,\"errorlevel\"], fit.twodim$errorlevel)\r\n#\r\n#\r\n", "meta": {"hexsha": "c3c87d9623e72cc62109571b8d294b1a81cc58a7", "size": 52752, "ext": "r", "lang": "R", "max_stars_repo_path": "Replication R Codes/ooc_montecarlo.r", "max_stars_repo_name": "tzuliu/What-Ordered-Optimal-Classification-Reveals-about-Ideological-Structure-Cleavages-and-Polarization", "max_stars_repo_head_hexsha": "6f26c03ace723f7d4686216b50d6be32e71b1ea2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-07-23T02:51:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T21:01:25.000Z", "max_issues_repo_path": "Replication R Codes/ooc_montecarlo.r", "max_issues_repo_name": "tzuliu/What-Ordered-Optimal-Classification-Reveals-about-Ideological-Structure-Cleavages-and-Polarization", "max_issues_repo_head_hexsha": "6f26c03ace723f7d4686216b50d6be32e71b1ea2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Replication R Codes/ooc_montecarlo.r", "max_forks_repo_name": "tzuliu/What-Ordered-Optimal-Classification-Reveals-about-Ideological-Structure-Cleavages-and-Polarization", "max_forks_repo_head_hexsha": "6f26c03ace723f7d4686216b50d6be32e71b1ea2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5185185185, "max_line_length": 203, "alphanum_fraction": 0.6907605399, "num_tokens": 16633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6052075238348484}} {"text": "### Draws a figure illustrating change detection in the distribution of synthetic data.\n### Each dot represents a single time period with 1000 samples. Before the change,\n### the data is sampled from a unit normal distribution. After the change, 20 samples\n### in each time period are taken from N(3,1). Comparing counts with a chi^2 test that\n### is robust to small expected counts robustly detects this shift.\n\n### log-likelihood ratio test for multinomial data\nllr = function(k) {\n 2 * sum(k) * (H(k) - H(rowSums(k)) - H(colSums(k)))\n}\nH = function(k) {\n N = sum(k) ;\n return (sum(k/N * log(k/N + (k==0))))\n}\n\n### compare recent samples to historical by comparing counts in a range of interest\nanalyze = function(historical, recent, cuts) {\n counts = data.frame(\n a=hist(recent, breaks=cuts, plot=F)$counts, \n b=hist(historical, breaks=cuts, plot=F)$counts)\n llr(counts)\n}\n\n### use fixed seed for stability of the pictures\nset.seed(3)\n### lots of reference data\nhistorical = rnorm(100000)\n\n### set cuts based on historical data\n### in practical systems, this step would be implemented with a t-digest \ncuts = c(-10, quantile(historical, probs=c(0.99, 0.999)), 20)\n\n### 1000 samples per time period, 2% perturbation after change\nn = 1000\nepsilon = 0.02\n\n### sample 60 scores without perturbation\nscores = rep(0,100)\nfor (i in 1:60) {\n scores[i] = analyze(historical, c(rnorm(n)), cuts)\n}\n\n### sample 40 scores with perturbation\nfor (i in 1:40) {\n scores[i + 60] = analyze(historical, c(rnorm(n * (1-epsilon)), rnorm(n * epsilon, 3)), cuts)\n}\n\n### plot the data\npdf(\"change-point.pdf\", width=5, height=4, pointsize=10)\nold = par('mgp')\npar(mgp=c(3,0.6,0))\ncolors = c(rep(rgb(0,0,0,alpha=0.8),60), rep(rgb(1,0,0,alpha=0.8),40))\nplot(scores, xaxt='n', xlab=NA, ylab=NA, ylim=c(0,60), cex=1.3, pch=21, bg=colors, col=NA)\nabline(v=60.5, lwd=3, col=rgb(0,0,0, alpha=0.1))\n\npolygon(c(-1,55,55,-1,-1), c(60, 60,36,36,60), col='white')\npoints(c(1.5, 1.5), c(55, 45), pch=21, bg=c('black', 'red'), col=NA)\ntext(5, c(55,45), adj=0, labels=c(\n expression(x %~% symbol(N)(mu == 0)), \n expression(x %~% bgroup(\"[\", atop(symbol(N)(mu==0) , symbol(N)(mu==3)),\"\"))))\ntext(30, c(55,48,41.5), c(\"1000 samples\", \"980 samples\", \"20 samples\"), adj=0)\n\n\nmtext(expression(llr(counts)), side=2, padj=-1.3, cex=1.4)\nmtext(\"Before change\", at=25, side=1, padj=1, cex=1.5)\nmtext(\"After change\", at=75, side=1, padj=1, cex=1.5)\npar(mgp=old)\ndev.off()\n\n\n", "meta": {"hexsha": "0a8f752bcb531b04a7456d2b5f7eaa57d50f1d7e", "size": 2467, "ext": "r", "lang": "R", "max_stars_repo_path": "docs/simpa/figures/detection.r", "max_stars_repo_name": "slandelle/t-digest", "max_stars_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1479, "max_stars_repo_stars_event_min_datetime": "2015-01-05T09:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T04:20:21.000Z", "max_issues_repo_path": "docs/simpa/figures/detection.r", "max_issues_repo_name": "slandelle/t-digest", "max_issues_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 141, "max_issues_repo_issues_event_min_datetime": "2015-01-02T14:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T22:54:11.000Z", "max_forks_repo_path": "docs/simpa/figures/detection.r", "max_forks_repo_name": "slandelle/t-digest", "max_forks_repo_head_hexsha": "8630c2b678ae5d2c055ee26bea6cf0af79c55fa6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 222, "max_forks_repo_forks_event_min_datetime": "2015-01-08T23:52:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T04:50:59.000Z", "avg_line_length": 34.7464788732, "max_line_length": 96, "alphanum_fraction": 0.6538305634, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6049311947105885}} {"text": "#Exercise for Lecture 1 FISH554: exploring data from the FAO database\r\n#the trophic level, species, maximum length, habitat, mean catch\r\n#for each of the species, based on data used in \r\n#Branch TA et al. (2010) The trophic fingerprint of marine fisheries. \r\n#Nature 468:431-435\r\n\r\n#reading in data\r\nlibrary(tidyverse)\r\nFAOdata1 <- read_csv(file=\"FAO catch.csv\")\r\nFAOdata1\r\n\r\n#using ggplot to make explorations of the data\r\n#relation between Lmax and Trophic level\r\nggplot(data=FAOdata1) +\r\n aes(x=Lmax, y=TrophicLevel) + \r\n geom_point()\r\n\r\nggplot(data=FAOdata1) +\r\n aes(x=Lmax, y=TrophicLevel) + \r\n geom_point() +\r\n scale_x_log10()\r\n\r\nggplot(data=FAOdata1) +\r\n aes(x=Lmax, y=TrophicLevel) + \r\n geom_point() +\r\n scale_x_log10() +\r\n aes(size=MeanCatch) +\r\n scale_size_area()\r\n\r\nroundedFAO <- FAOdata1\r\nroundedFAO$TrophicLevel <- round(roundedFAO$TrophicLevel,1)\r\nggplot(data=roundedFAO) +\r\n aes(x=Lmax, y=TrophicLevel) + \r\n geom_point() +\r\n scale_x_log10() +\r\n aes(size=MeanCatch) +\r\n scale_size_area()\r\n\r\n#boxplots\r\nggplot(data=roundedFAO) +\r\n aes(x=TrophicLevel, y=Lmax) + \r\n geom_boxplot() + aes(group=TrophicLevel)\r\n\r\n#trophic level vs maximum length\r\nggplot(data=roundedFAO) +\r\n aes(x=TrophicLevel, y=Lmax) + \r\n geom_boxplot() + aes(group=TrophicLevel) + \r\n scale_y_log10()\r\n\r\n#trophic level vs average catch\r\nggplot(data=roundedFAO) +\r\n aes(x=TrophicLevel, y=MeanCatch) + \r\n geom_boxplot() + aes(group=TrophicLevel) + \r\n scale_y_log10()\r\n", "meta": {"hexsha": "bc1748026c2af3f8cb0e51bafb92a460913cc5c8", "size": 1466, "ext": "r", "lang": "R", "max_stars_repo_path": "Lecture 1 exercise.r", "max_stars_repo_name": "maria-kuruvilla/beautiful_graphics", "max_stars_repo_head_hexsha": "b26eba58ef667f3d9836788d35a869871b44994e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture 1 exercise.r", "max_issues_repo_name": "maria-kuruvilla/beautiful_graphics", "max_issues_repo_head_hexsha": "b26eba58ef667f3d9836788d35a869871b44994e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture 1 exercise.r", "max_forks_repo_name": "maria-kuruvilla/beautiful_graphics", "max_forks_repo_head_hexsha": "b26eba58ef667f3d9836788d35a869871b44994e", "max_forks_repo_licenses": ["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.6545454545, "max_line_length": 71, "alphanum_fraction": 0.7032742156, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6049311851939948}} {"text": "# R script to calculate P values using binomial test\r\n\r\n\r\n##########################################################\r\n## Functions\r\n\r\n#This function calculates the p value for each window.\r\n#The probability is the % of RE sites in the chromosome covered with reads and for each window a p value is assigned using the binom.test function.\r\npValCal<-function (windows_data,windows_data_full)\r\n{\r\n\tpVal<-c()\r\n\tchromosomes <- unique(windows_data[,1])\r\n\tfor (i in 1:length(chromosomes)) \r\n\t{\r\n\t\ttmp.data<-windows_data[windows_data[,1]==i,]\r\n\t\ttmp.data_full<-windows_data_full[windows_data_full[,1]==i,]\r\n\t\tprob<-sum(tmp.data[,4])/sum(tmp.data_full[,4])\r\n\t\ttmp<-mapply(binom.test, x=as.vector(tmp.data[,4]), n=as.vector(tmp.data_full[,4]), p=prob, alternative=\"greater\")\r\n\t\tpVal<-c(pVal,as.numeric(tmp[3,]))\r\n\t}\r\n\t#We save both the p-values and the p-scores which are -log10 of the p-values.\r\n\tpVal2<- -log10(pVal);pVal2[pVal2 == Inf]<-max(pVal2[pVal2!=Inf])\r\n\tlist(pVal,pVal2)\r\n}\r\n\r\n#################################################################\r\n\r\n## Constants\r\nWIND<- N/2 # Half of the size of the window (N) used for the analysis.\r\ndata_full<-read.delim(\"RE_sites_genome_N_windows_with_RE\", header=FALSE) #RE windows with the number of total RE per window.\r\n\r\n## Calcualte per sample\r\ndata_bait<-read.delim(\"RE_sites_genome_N_windows_with_Sample_RE\", header=FALSE) #RE windows with the number of valid RE from the sample per window.\r\n\r\n#Calcualte p-values\r\npValues<-pValCal(data_bait,data_full)\r\n#Save the windows with their p scores for genome browser and other analyses.\r\nSample_N_pScore<-cbind(data_bait[,1:3],pValues[[2]])\r\n#Each window is represented by the RE site it is spanning\r\nSample_N_pScore[,3]<-Sample_N_pScore[,3]-WIND\r\nSample_N_pScore[,2]<-Sample_N_pScore[,3]-4\r\n#save the file\r\nwrite.table(Sample_N_pScore,\"Sample_N_pScore.bedgraph\",quote=F,row.names=F,col.names=F,append=F, sep=\"\\t\")\r\n\r\n\r\n", "meta": {"hexsha": "77a16ce302a0c4c552502215aa905b4645945f36", "size": 1907, "ext": "r", "lang": "R", "max_stars_repo_path": "Pval_analysis_4C.r", "max_stars_repo_name": "HakimLab/4SEE", "max_stars_repo_head_hexsha": "a551a660affa766a0427c747b4a92be9be89bc1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pval_analysis_4C.r", "max_issues_repo_name": "HakimLab/4SEE", "max_issues_repo_head_hexsha": "a551a660affa766a0427c747b4a92be9be89bc1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pval_analysis_4C.r", "max_forks_repo_name": "HakimLab/4SEE", "max_forks_repo_head_hexsha": "a551a660affa766a0427c747b4a92be9be89bc1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4565217391, "max_line_length": 148, "alphanum_fraction": 0.6822233875, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.6047833919746406}} {"text": "twenty.four <- function(operators=c(\"+\", \"-\", \"*\", \"/\", \"(\"),\n selector=function() sample(1:9, 4, replace=TRUE),\n arguments=selector(),\n goal=24) {\n newdigits <- function() {\n arguments <<- selector()\n cat(\"New digits:\", paste(arguments, collapse=\", \"), \"\\n\")\n }\n help <- function() cat(\"Make\", goal,\n \"out of the numbers\",paste(arguments, collapse=\", \"),\n \"and the operators\",paste(operators, collapse=\", \"), \".\",\n \"\\nEnter 'q' to quit, '!' to select new digits,\",\n \"or '?' to repeat this message.\\n\")\n help()\n repeat {\n switch(input <- readline(prompt=\"> \"),\n q={ cat(\"Goodbye!\\n\"); break },\n `?`=help(),\n `!`=newdigits(),\n tryCatch({\n expr <- parse(text=input, n=1)[[1]]\n check.call(expr, operators, arguments)\n result <- eval(expr)\n if (isTRUE(all.equal(result, goal))) {\n cat(\"Correct!\\n\")\n newdigits()\n } else {\n cat(\"Evaluated to\", result, \"( goal\", goal, \")\\n\")\n }\n },error=function(e) cat(e$message, \"\\n\")))\n }\n}\n\ncheck.call <- function(expr, operators, arguments) {\n unexpr <- function(x) {\n if (is.call(x))\n unexpr(as.list(x))\n else if (is.list(x))\n lapply(x,unexpr)\n else x\n }\n leaves <- unlist(unexpr(expr))\n if (any(disallowed <-\n !leaves %in% c(lapply(operators, as.name),\n as.list(arguments)))) {\n stop(\"'\", paste(sapply(leaves[disallowed], as.character),\n collapse=\", \"),\n \"' not allowed. \")\n }\n numbers.used <- unlist(leaves[sapply(leaves, mode) == 'numeric'])\n\n if (! isTRUE(all.equal(sort(numbers.used), sort(arguments))))\n stop(\"Must use each number once.\")\n}\n", "meta": {"hexsha": "e977928bffc23879bc5ee462a9f02900848d8632", "size": 1840, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/24-game/R/24-game-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/24-game/R/24-game-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/24-game/R/24-game-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 33.4545454545, "max_line_length": 73, "alphanum_fraction": 0.4961956522, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6046672286863092}} {"text": "#本文需要用到的 R 包\nlibrary(vegan)\t#用于计算 Shannon 熵指数、Simpson 指数、Chao1 指数、ACE 指数等,同时用于抽样\nlibrary(picante)\t#用于计算 PD_whole_tree,若不计算它就无需加载。事实上,picante 包加载时默认同时加载 vegan\nlibrary(ggplot2)\t#用于 ggplot2 作图\nlibrary(doBy)\t#用于分组统计(第 97 行使用到)\nlibrary(ggalt)\t#用于绘制拟合曲线(第 138 行使用到)\nlibrary(BiodiversityR)\t#用于绘制 Rank-abundance 曲线(第 160 行使用到)\n\n##定义函数\n#计算多种 Alpha 多样性指数,结果返回至向量\n#各子函数的用法详见 http://blog.sciencenet.cn/blog-3406804-1179983.html\nalpha_index <- function(x, method = 'richness', tree = NULL, base = exp(1)) {\n if (method == 'richness') result <- rowSums(x > 0)\t#丰富度指数\n else if (method == 'chao1') result <- estimateR(x)[3, ]\t#Chao1 指数\n else if (method == 'ace') result <- estimateR(x)[5, ]\t#ACE 指数\n else if (method == 'shannon') result <- diversity(x, index = 'shannon', base = base)\t#Shannon 指数\n else if (method == 'simpson') result <- diversity(x, index = 'simpson')\t#Gini-Simpson 指数\n else if (method == 'pielou') result <- diversity(x, index = 'shannon', base = base) / log(estimateR(x)[1, ], base)\t#Pielou 均匀度\n else if (method == 'gc') result <- 1 - rowSums(x == 1) / rowSums(x)\t#goods_coverage\n else if (method == 'pd' & !is.null(tree)) {\t#PD_whole_tree\n pd <- pd(x, tree, include.root = FALSE)\n result <- pd[ ,1]\n names(result) <- rownames(pd)\n }\n result\n}\n\n#根据抽样步长(step),统计每个稀释梯度下的 Alpha 多样性指数,结果返回至列表\nalpha_curves <- function(x, step, method = 'richness', rare = NULL, tree = NULL, base = exp(1)) {\n x_nrow <- nrow(x)\n if (is.null(rare)) rare <- rowSums(x) else rare <- rep(rare, x_nrow)\n alpha_rare <- list()\n \n for (i in 1:x_nrow) {\n step_num <- seq(0, rare[i], step)\n if (max(step_num) < rare[i]) step_num <- c(step_num, rare[i])\n \n alpha_rare_i <- NULL\n for (step_num_n in step_num) alpha_rare_i <- c(alpha_rare_i, alpha_index(x = rrarefy(x[i, ], step_num_n), method = method, tree = tree, base = base))\n names(alpha_rare_i) <- step_num\n alpha_rare <- c(alpha_rare, list(alpha_rare_i))\n }\n \n names(alpha_rare) <- rownames(x)\n alpha_rare\n}\n\n##测试\n#统计 OTU 丰度表中各样本的 Shannon 指数,对数底数使用 e\n# shannon_index <- alpha_index(otu, method = 'shannon', base = exp(1))\n#以 1000 条序列为抽样步长,依次对 OTU 表稀释抽样,直到最大序列深度;并统计各抽样梯度下的 OTU 丰度表中各样本的 Shannon 指数,对数底数使用 e\n# shannon_curves <- alpha_curves(otu, step = 1000, method = 'shannon', base = exp(1))\n\n##以下以物种丰富度指数为例绘制 Alpha 多样性曲线(当为丰富度指数时,另一个名称即为常说的稀释曲线,或物种累计曲线)\n#读取 OTU 丰度表\nif(1) {\n setwd('~/Documents/R/Numerical_Ecology/Hong/')\n otu <- read.delim('Tomato.txt', row.names = 1, sep = '\\t', stringsAsFactors = FALSE, check.names = FALSE)\n otu <- t(otu)\n}\n\n\n#以 2000 步长(step=2000)为例统计\nrichness_curves <- alpha_curves(otu, step = 2000, method = 'richness')\n\n#获得 ggplot2 作图文件\nplot_richness <- data.frame()\nfor (i in names(richness_curves)) {\n richness_curves_i <- (richness_curves[[i]])\n richness_curves_i <- data.frame(rare = names(richness_curves_i), alpha = richness_curves_i, sample = i, stringsAsFactors = FALSE)\n plot_richness <- rbind(plot_richness, richness_curves_i)\n}\n\nrownames(plot_richness) <- NULL\nplot_richness$rare <- as.numeric(plot_richness$rare)\nplot_richness$alpha <- as.numeric(plot_richness$alpha)\n\n#ggplot2 作图\nggplot(plot_richness, aes(rare, alpha, color = sample)) +\n geom_line() +\n labs(x = 'Number of sequences', y = 'Richness', color = NULL) +\n theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent', color = 'black'), legend.key = element_rect(fill = 'transparent')) +\n geom_vline(xintercept = min(rowSums(otu)), linetype = 2) +\n scale_x_continuous(breaks = seq(0, 30000, 5000), labels = as.character(seq(0, 30000, 5000)))\n\n##多计算几次以获取均值 ± 标准差,然后再展示出也是一个不错的选择\n#重复抽样 5 次\nplot_richness <- data.frame()\n\nfor (n in 1:5) {\n richness_curves <- alpha_curves(otu, step = 2000, method = 'richness')\n \n for (i in names(richness_curves)) {\n richness_curves_i <- (richness_curves[[i]])\n richness_curves_i <- data.frame(rare = names(richness_curves_i), alpha = richness_curves_i, sample = i, stringsAsFactors = FALSE)\n plot_richness <- rbind(plot_richness, richness_curves_i)\n }\n}\n\n#计算均值 ± 标准差(doBy 包中的 summaryBy() 函数)\nplot_richness_stat <- summaryBy(alpha~sample+rare, plot_richness, FUN = c(mean, sd))\nplot_richness_stat$rare <- as.numeric(plot_richness_stat$rare)\nplot_richness_stat[which(plot_richness_stat$rare == 0),'alpha.sd'] <- NA\n\n#ggplot2 作图\nggplot(plot_richness_stat, aes(rare, alpha.mean, color = sample)) +\n geom_line() +\n geom_point() +\n geom_errorbar(aes(ymin = alpha.mean - alpha.sd, ymax = alpha.mean + alpha.sd), width = 500) +\n labs(x = 'Number of sequences', y = 'Richness', color = NULL) +\n theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent', color = 'black'), legend.key = element_rect(fill = 'transparent')) +\n geom_vline(xintercept = min(rowSums(otu)), linetype = 2) +\n scale_x_continuous(breaks = seq(0, 30000, 5000), labels = as.character(seq(0, 30000, 5000)))\n\n##对于 Shannon 指数等,方法类似\n#以 2000 步长(step=2000)为例统计每个稀释梯度下的 Shannon 指数,Shannon 公式的对数底数默认为 e,若有需要可更改(例如 2)\nshannon_curves <- alpha_curves(otu, step = 2000, method = 'shannon', base = 2)\n\n#获得 ggplot2 作图文件(略,参见上述)\n#ggplot2 作图(略,参见上述)\n\n##若简单的“geom_line()”样式波动幅度过大,不平滑等,可以尝试拟合曲线的样式\n#获得作图数据。前面多生成一个点,使得 Shannon 拟合曲线更加平滑(你把 shannon_curves1 注释掉就知道我说的啥了)\nshannon_curves1 <- alpha_curves(otu, step = 200, rare = 200, method = 'shannon')\nshannon_curves2 <- alpha_curves(otu, step = 2000, method = 'shannon')\nshannon_curves <- c(shannon_curves1, shannon_curves2)\n\nplot_shannon <- data.frame()\nfor (i in 1:length(shannon_curves)) {\n shannon_curves_i <- shannon_curves[[i]]\n shannon_curves_i <- data.frame(rare = names(shannon_curves_i), alpha = shannon_curves_i, sample = names(shannon_curves)[i], stringsAsFactors = FALSE)\n plot_shannon <- rbind(plot_shannon, shannon_curves_i)\n}\n\nrownames(plot_shannon) <- NULL\nplot_shannon$rare <- as.numeric(plot_shannon$rare)\nplot_shannon$alpha <- as.numeric(plot_shannon$alpha)\nplot_shannon <- plot_shannon[order(plot_shannon$sample, plot_shannon$rare), ]\n\n#ggplot2 作图(使用到 ggalt 包的 geom_xspline() 绘制平滑拟合线)\nggplot(plot_shannon, aes(rare, alpha, color = sample)) +\n geom_xspline() +\n labs(x = 'Number of sequences', y = 'Shannon', color = NULL) +\n theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent', color = 'black'), legend.key = element_rect(fill = 'transparent')) +\n geom_vline(xintercept = min(rowSums(otu)), linetype = 2) +\n scale_x_continuous(breaks = seq(0, 30000, 5000), labels = as.character(seq(0, 30000, 5000)))\n\n\n# Above -------------------------------------------------------------------\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n# \n# ##对于 PD_whole_tree,除了 OTU 丰度表,还使用到进化树文件\n# #加载 OTU 丰度表和进化树文件\n# otu <- read.delim('otu_table.txt', row.names = 1, sep = '\\t', stringsAsFactors = FALSE, check.names = FALSE)\n# otu <- t(otu)\n# # tree <- read.tree('otu_tree.tre')\n# \n# #以 2000 步长(step=2000)为例统计\n# pd_curves <- alpha_curves(otu, tree = tree, step = 2000, method = 'pd')\n# \n# #统计及做图方法同上述\n# \n# ##Rank-abundance 曲线\n# #统计(BiodiversityR 包 rankabundance() 实现 OTU 排序)\n# otu_relative <- otu / rowSums(otu)\n# rank_dat <- data.frame()\n# for (i in rownames(otu_relative)) {\n# rank_dat_i <- data.frame(rankabundance(subset(otu_relative, rownames(otu_relative) == i), digits = 6))[1:2]\n# rank_dat_i$sample <- i\n# rank_dat <- rbind(rank_dat, rank_dat_i)\n# }\n# rank_dat <- subset(rank_dat, rank_dat$abundance != 0)\n# \n# #ggplot2 作图\n# ggplot(rank_dat, aes(rank, log(abundance, 10), color = sample)) +\n# geom_line() +\n# labs(x = 'OTUs rank', y = 'Relative adundance (%)', color = NULL) +\n# theme(panel.grid = element_blank(), panel.background = element_rect(fill = 'transparent', color = 'black'), legend.key = element_rect(fill = 'transparent')) +\n# scale_y_continuous(breaks = 0:-5, labels = c('100', '10', '1', '0.1', '0.01', '0.001'), limits = c(-5, 0))\n", "meta": {"hexsha": "6377f749e233781a481a44f8ed97f60ea32533ed", "size": 7998, "ext": "r", "lang": "R", "max_stars_repo_path": "Hong/plot_revised.r", "max_stars_repo_name": "TY-Cheng/Numerical_Ecology", "max_stars_repo_head_hexsha": "44727b3f7185bd5f1744707c3da70d7dc1bc7eb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hong/plot_revised.r", "max_issues_repo_name": "TY-Cheng/Numerical_Ecology", "max_issues_repo_head_hexsha": "44727b3f7185bd5f1744707c3da70d7dc1bc7eb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hong/plot_revised.r", "max_forks_repo_name": "TY-Cheng/Numerical_Ecology", "max_forks_repo_head_hexsha": "44727b3f7185bd5f1744707c3da70d7dc1bc7eb1", "max_forks_repo_licenses": ["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.4333333333, "max_line_length": 164, "alphanum_fraction": 0.6691672918, "num_tokens": 3047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6045465121438778}} {"text": "#' cq.reg\n#'\n#' Estimate conditional quantile in two steps:\n#' 1. estimate the conditional probability for each observation: tau=p(y|x)\n#' Default to use local method over knn method,\n#' if both arguement supply or unspecify,\n#' only the local method will use.\n#' 2. apply scam package to fix x to y with one more predictor tau,\n#' constrain tau to be monotonely nondecreasing.\n#'\n#' @param x vector or matrix whose rows contains predictors\n#' of each observations.\n#' @param y vector of the variable we want to estimate its condtional cdf\n#' @param span fraction of total distance to be the bandwidth, between 0 and 1,\n#' default to be 0.5 if bandwidth not supply.\n#' @param bandwidth the bandwidth of x to evaluate the cdf,\n#' overwrite the span input.\n#' @param rnn fraction of total number of observations to be knn,\n#' between 0 and 1. Set span to be NULL to use knn,\n#' default to be 0.5, if not supply\n#' @param knn the number of nearest neighbor to estimate the cdf,\n#' should be less than the number of observation and greater than 0\n#' (\\code{knn < length(y)}.\n#' setting this value overwrite the rnn\n#' @param ... additional arguement pass into scam (eg. sp, gamma, weights)\n#'\n#' @import scam\n#'\n#' @return a scam object\n#'\n#' @examples\n#' devtools::load_all()\n#' x <- soy$V5\n#' y <- soy$V6\n#' fit <- cq.reg(x, y)\n#' cq_plot(fit)\n\ncq.reg <- function(x, y, arg_bs = c(\"tesmi1\", \"ps\"),\n opt = \"efs\", dims = c(5, 15), ords = NA,\n span = 0.05, bandwidth=NULL, rnn=NULL, knn=NULL,\n analysis=F, sp = NULL, ...) {\n #1. Estimate the conditional probability\n tau <- cond_pr(x, y, span, bandwidth, rnn, knn)\n\n if (is.vector(x)) {\n s_k <- 1\n } else if (is.matrix(x)) {\n s_k <- ncol(x)\n } else {\n stop(\"input x type not support\")\n }\n\n xnam <- c(\"tau\", paste0(\"x\", seq_len(s_k)))\n newx <- cbind(tau, x)\n\n dat <- data.frame(y, newx)\n colnames(dat) <- c(\"y\", xnam)\n\n #2. apply scam package\n fit <- scam(y ~ s(tau, x1, k = dims, m = ords, bs = arg_bs),\n data = dat, optimizer = opt, sp = sp, ...)\n\n if (analysis) {\n par(mfrow = c(2, 2), mar = c(4, 4, 2, 2))\n plot(fit, se = TRUE)\n plot(fit, pers = TRUE, theta = 30, phi = 40)\n plot(y, fit$fitted.values,\n xlab = \"Real Data\",\n ylab = \"Fitted data\", pch = \".\", cex = 3)\n\n plot(x, y)\n sort_x <- sort(x)\n for (i in 1:10) {\n newx <- data.frame(i / 10, sort_x)\n colnames(newx) <- xnam\n lines(sort_x, predict(fit, newx), col = i + 1)\n }\n }\n\n fit$x <- x\n fit$xnam <- xnam\n return(fit)\n}\n\n\n#' @rdname cq.reg\n#' @export\ncq_regplot <- function(fit, v_taus = seq(0.05, 0.95, 0.15), ...) {\n x <- fit$x\n y <- fit$y\n xnam <- fit$xnam\n sort_x <- sort(x)\n\n xlim <- grDevices::extendrange(x, f = .01)\n ylim <- grDevices::extendrange(y, f = .01)\n xlab <- \"x\"\n ylab <- \"y\"\n\n plot(x, y, ...,\n type = \"p\", pch = 16, cex = 0.8, col = \"grey\",\n xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab)\n\n for (i in seq_along(v_taus)) {\n newx <- data.frame(v_taus[i], sort_x)\n colnames(newx) <- xnam\n lines(sort_x, predict(fit, newx), col = i + 1)\n}\n\n# lgd <- c(\n # expression(paste(mu, \"=0.1\")),\n# expression(paste(mu, \"=0.2\")),\n# expression(paste(mu, \"=0.3\")),\n# expression(paste(mu, \"=0.4\")),\n# expression(paste(mu, \"=0.5\")),\n# expression(paste(mu, \"=0.6\")),\n# expression(paste(mu, \"=0.7\")),\n# expression(paste(mu, \"=0.8\")),\n# expression(paste(mu, \"=0.9\")),\n# expression(paste(mu, \"=1\")))\n\n# legend(\"topleft\",\n# lty = 1, legend = rev(lgd), col = 11:2,\n# lwd = 1, cex = 1, bty = \"n\"\n# )\n}", "meta": {"hexsha": "7e756eb6ac63eb4226ec600ff1232a1a932253dd", "size": 3991, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cq_reg.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/cq_reg.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/cq_reg.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": 31.928, "max_line_length": 80, "alphanum_fraction": 0.5301929341, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6043747567507659}} {"text": "# demo: lsystem.r\n# author: Daniel Adler\n\n#\n# geometry \n#\n\ndeg2rad <- function( degree ) {\n return( degree*pi/180 )\n}\n\nrotZ.m3x3 <- function( degree ) {\n kc <- cos(deg2rad(degree))\n ks <- sin(deg2rad(degree))\n return( \n matrix(\n c(\n kc, -ks, 0, \n ks, kc, 0,\n 0, 0, 1\n ),ncol=3,byrow=TRUE\n ) \n )\n}\n\nrotX.m3x3 <- function( degree ) {\n kc <- cos(deg2rad(degree))\n ks <- sin(deg2rad(degree))\n return(\n matrix(\n c(\n 1, 0, 0,\n 0, kc, -ks,\n 0, ks, kc\n ),ncol=3,byrow=TRUE\n )\n )\n}\n\nrotY.m3x3 <- function( degree ) {\n kc <- cos(deg2rad(degree))\n ks <- sin(deg2rad(degree))\n return(\n matrix(\n c(\n kc, 0, ks,\n 0, 1, 0,\n -ks, 0, kc\n ),ncol=3,byrow=TRUE\n )\n )\n}\n\nrotZ <- function( v, degree ) {\n return( rotZ.m3x3(degree) %*% v)\n}\n\nrotX <- function( v, degree ) {\n return( rotX.m3x3(degree) %*% v)\n}\n\nrotY <- function( v, degree ) {\n return( rotY.m3x3(degree) %*% v)\n}\n\n\n#\n# turtle graphics, rgl implementation:\n#\n\nturtle.init <- function(pos=c(0,0,0),head=0,pitch=90,roll=0,level=0) {\n rgl.clear(\"all\")\n rgl.bg(color=\"black\")\n rgl.light()\n return( list(pos=pos,head=head,pitch=pitch,roll=roll,level=level) )\n}\n\n\nturtle.move <- function(turtle, steps, color) {\n \n rm <- rotX.m3x3(turtle$pitch) %*% rotY.m3x3(turtle$head) %*% rotZ.m3x3(turtle$roll)\n \n from <- as.vector( turtle$pos ) \n dir <- rm %*% c(0,0,-1)\n to <- from + dir * steps\n \n x <- c( from[1], to[1] )\n y <- c( from[2], to[2] )\n z <- c( from[3], to[3] )\n rgl.lines(x,y,z,col=color,size=1.5,alpha=0.5)\n turtle$pos <- to\n return(turtle)\n}\n\nturtle.pitch <- function(turtle, degree) {\n turtle$pitch <- turtle$pitch + degree\n return(turtle)\n}\n\nturtle.head <- function(turtle, degree) {\n turtle$head <- turtle$head + degree\n return(turtle)\n}\n\nturtle.roll <- function(turtle, degree) {\n turtle$roll <- turtle$roll + degree\n return(turtle)\n}\n\n#\n# l-system general\n#\n\n\nlsystem.code <- function( x )\n substitute( x )\n\nlsystem.gen <- function( x, grammar, levels=0 ) {\n code <- eval( substitute( substitute( REPLACE , grammar ), list(REPLACE=x) ) )\n if (levels)\n return( lsystem.gen( code , grammar , levels-1 ) )\n else\n return( code )\n}\n\n#\n# l-system plot\n#\n\nlsystem.plot <- function( expr, level ) {\n turtle <- turtle.init(level=level)\n lsystem.eval( expr, turtle )\n}\n\nlsystem.eval <- function( expr, turtle ) {\n if ( length(expr) == 3 ) {\n turtle <- lsystem.eval( expr[[2]], turtle )\n turtle <- lsystem.eval( expr[[3]], turtle )\n turtle <- lsystem.eval( expr[[1]], turtle )\n } else if ( length(expr) == 2 ) {\n saved <- turtle\n turtle <- lsystem.eval( expr[[1]], turtle )\n turtle <- lsystem.eval( expr[[2]], turtle )\n turtle <- saved\n } else if ( length(expr) == 1 ) {\n if ( as.name(expr) == \"stem\" ) turtle <- turtle.move(turtle, 5, \"brown\")\n else if ( as.name(expr) == \"short\") turtle <- turtle.move(turtle, 5, \"brown\")\n else if ( as.name(expr) == \"leaf\" ) {\n rgl.spheres(turtle$pos[1],turtle$pos[2],turtle$pos[3],radius=0.1+turtle$level*0.3,color=\"green\")\n rgl.sprites(turtle$pos[1],turtle$pos[2],turtle$pos[3],radius=0.5+turtle$level*0.3 ,color=\"green\",texture=system.file(\"textures/particle.png\",package=\"rgl\"),textype=\"alpha\",alpha=0.5) \n }\n else if ( as.name(expr) == \"roll\" ) turtle <- turtle.head(turtle, 60)\n else if ( as.name(expr) == \"down\" ) turtle <- turtle.pitch(turtle,10)\n else if ( as.name(expr) == \"up\" ) turtle <- turtle.pitch(turtle,-10)\n else if ( as.name(expr) == \"left\" ) turtle <- turtle.head(turtle, 1)\n else if ( as.name(expr) == \"right\") turtle <- turtle.head(turtle,-1.5)\n else if ( as.name(expr) == \"turnleft\") turtle <- turtle.head(turtle,20)\n else if ( as.name(expr) == \"turnright\") turtle <- turtle.head(turtle,-20)\n else if ( as.name(expr) == \"turn\") turtle <- turtle.roll(turtle,180)\n }\n return(turtle)\n}\n\n\n#\n# example\n#\n\nsimple <- function(level=0) {\n grammar <- list(\n stem=lsystem.code(\n stem-(up-stem-leaf)-stem-(down-stem-leaf)-stem-leaf\n )\n )\n plant <- lsystem.gen(lsystem.code(stem), grammar, level )\n lsystem.plot(plant,level)\n}\n\nrgl.demo.lsystem <- function(level=0) {\n gen <- list(\n stem=lsystem.code( \n stem-left-stem-branch( turnleft-down-short-turnleft-down-stem-leaf)-right-right-stem--branch( turnright-up-short-turnright-up-short-turnright-short-stem-leaf)-left-left-left-stem-branch( turnleft-down-short-turnright-down-stem-leaf )-branch( up-turnright-short-up-turnleft-up-stem-leaf ) \n )\n ) \n plant <- lsystem.gen(lsystem.code(stem), gen, level )\n lsystem.plot(plant,level) \n}\n\nrgl.open()\nrgl.demo.lsystem(level=1)\n", "meta": {"hexsha": "9c11a321593456ca472153d32579efd6e575425e", "size": 4727, "ext": "r", "lang": "R", "max_stars_repo_path": "renv/library/R-4.0/x86_64-w64-mingw32/rgl/demo/lsystem.r", "max_stars_repo_name": "rebeccagb/gtsummary", "max_stars_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "renv/library/R-4.0/x86_64-w64-mingw32/rgl/demo/lsystem.r", "max_issues_repo_name": "rebeccagb/gtsummary", "max_issues_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "renv/library/R-4.0/x86_64-w64-mingw32/rgl/demo/lsystem.r", "max_forks_repo_name": "rebeccagb/gtsummary", "max_forks_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_forks_repo_licenses": ["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.7486910995, "max_line_length": 294, "alphanum_fraction": 0.5940342712, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6042244192395219}} {"text": "[[[[[\n KRAFT INEQUALITY CRITERION FOR CONSTRUCTING COMPUTERS\n Take as input requirement pairs (output, size of program)\n and produce as output assignment pairs (program, output).\n \n We assume that the requirements are consistent. \n I.e. the sum of 1/2 raised to each size is <= unity. \n Then we can produce a set of assignments that meets\n the requirements and is prefex free, i.e. no extension\n of a valid program is a valid program.\n \n The basic data structure in this program is the free space pool.\n That's a list of prefixes all of whose extensions (by zero \n or more bits) are unassigned programs. Initially this is the \n list consisting of the empty string because everything is free.\n\n The algorithm consists of assigning that program that meets\n each requirement that is available and that comes first in\n lexicographic order (0 before 1).\n\n The free space pool is kept in lexicographic order, to facilitate\n searching. So the algorithm is to look for the first prefix in\n the pool that is <= the requested size in each requirement.\n\n If it has exactly the requested size, then that prefix is the\n program assigned to the output in the requirement. If not,\n the prefix must be smaller than the requirement, and represents\n a piece of free storage that is a power of two larger than needed.\n So as program we assign the prefix extended by sufficiently many\n 0's to reach the requested size, and then the prefix is replaced\n in the free space pool by prefix00001, prefix0001, prefix001,\n prefix01, prefix1, for all sizes up to the assigned size.\n This will always work if the Kraft inequality is satisfied.\n \n If this algorithm is given the requirements \n (0 1) (1 2) (2 3) (3 4)...\n (i.e., a 1-bit p for 0, a 2-bit p for 1, a 3-bit p for 2, etc.)\n it will produce the assignments \n (0 0) (10 1) (110 2) (1110 3)... \n (i.e., p = 0 yields 0, p = 10 yields 1, p = 110 yields 2, etc.)\n In this case the free storage pool will always consist of a \n single piece.\n\n Key fact: if you follow this first-fit algorithm, the free space\n will appear in blocks in the unit interval whose sizes are all\n distinct powers of two, and in order of increasing size. So\n if an allocation cannot be made, the piece requested must be\n larger (at least twice as large) as the last & largest piece.\n But the total free storage is less than twice the size of the\n last & largest free piece, so allocating this would have violated\n the Kraft inequality.\n\n To actually run these programs, we have to feed the output of\n this program kraft.l into the previous one, exec.l.\n So there will in fact be an additional prefix in front of the\n assigned programs to tell U how to do kraft.l and how to do exec.l.\n \n Kraft is written as a function that is applied to a finite list\n of requirements and produces the corresponding finite list of\n assignments. Exec.l will use try to run the requirement generator\n for more and more time to produce longer and longer lists of\n assignments. It will then use the Kraft function to transform \n these into longer and longer lists of assignments, which it will \n use to actually run individual programs by reading them bit by \n bit as required. The Kraft function has the property that applying \n it to a longer list of requirements just produces a longer list \n of assignments. I.e., it's monotone, it never changes its mind. \n]]]]]\n\n[used to assign a program to an output]\n\ndefine (extend-with-0s bit-string [to] given-length) \n if = length bit-string given-length [then]\n bit-string [else]\n append (extend-with-0s bit-string [to] - given-length 1) \n cons 0 nil\n\ndefine extend-with-0s\nvalue (lambda (bit-string given-length) (if (= (length b\n it-string) given-length) bit-string (append (exten\n d-with-0s bit-string (- given-length 1)) (cons 0 n\n il))))\n\n[test it]\n \n(extend-with-0s '(1 1 1) [to] 6)\n\nexpression (extend-with-0s (' (1 1 1)) 6)\nvalue (1 1 1 0 0 0)\n\n(extend-with-0s '(1 1 1) [to] 5)\n\nexpression (extend-with-0s (' (1 1 1)) 5)\nvalue (1 1 1 0 0)\n\n(extend-with-0s '(1 1 1) [to] 4)\n\nexpression (extend-with-0s (' (1 1 1)) 4)\nvalue (1 1 1 0)\n\n(extend-with-0s '(1 1 1) [to] 3)\n\nexpression (extend-with-0s (' (1 1 1)) 3)\nvalue (1 1 1)\n\n[used to subtract storage from a piece of free storage]\n\ndefine (remove-piece free-prefix size-of-program)\n if = size-of-program length free-prefix\n nil [then no storage left, else] \n cons append (extend-with-0s free-prefix [to] - size-of-program 1) \n cons 1 nil\n (remove-piece free-prefix - size-of-program 1)\n\ndefine remove-piece\nvalue (lambda (free-prefix size-of-program) (if (= size-\n of-program (length free-prefix)) nil (cons (append\n (extend-with-0s free-prefix (- size-of-program 1)\n ) (cons 1 nil)) (remove-piece free-prefix (- size-\n of-program 1)))))\n\n[test it]\n\n(remove-piece '(1 1 1) 6)\n\nexpression (remove-piece (' (1 1 1)) 6)\nvalue ((1 1 1 0 0 1) (1 1 1 0 1) (1 1 1 1))\n\n(remove-piece '(1 1 1) 5)\n\nexpression (remove-piece (' (1 1 1)) 5)\nvalue ((1 1 1 0 1) (1 1 1 1))\n\n(remove-piece '(1 1 1) 4)\n\nexpression (remove-piece (' (1 1 1)) 4)\nvalue ((1 1 1 1))\n\n(remove-piece '(1 1 1) 3)\n\nexpression (remove-piece (' (1 1 1)) 3)\nvalue ()\n\n[ \n Make-assignments uses debug to show us the \n free-space-pool after making each assignment.\n If an assignment cannot be made because \n there is not enough storage, we just skip it.\n]\ndefine (make-assignments free-space-pool requirements)\n\n let free-space-pool debug free-space-pool \n [Done just to show pool!]\n\n if atom requirements nil [no requirements => no assignments]\n [If so, we're finished!]\n\n let requirement car requirements\n let requirements cdr requirements\n let output-of-program car requirement\n let size-of-program cadr requirement\n let already-scanned nil\n let not-yet-scanned free-space-pool\n\n let (loop-thru-free-space-pool) [DEFINE IT!]\n\n if atom not-yet-scanned [cannot make this assignment!]\n [indicate problem and go to next requirement]\n cons not-enough-storage! \n (make-assignments free-space-pool requirements) \n\n let free-prefix car not-yet-scanned\n let not-yet-scanned cdr not-yet-scanned\n if < size-of-program length free-prefix\n\n [doesn't fit --- continue scanning]\n let already-scanned \n append already-scanned \n cons free-prefix nil\n (loop-thru-free-space-pool)\n\n [fits! --- make assignment]\n [add to list of rest of assignments]\n let free-space-pool \n append already-scanned \n append (remove-piece free-prefix size-of-program)\n not-yet-scanned\n\n let assignment \n [make assignment - add to list of rest of assignments]\n [found free piece where it fits!] \n [extend with zeros to correct size]\n cons (extend-with-0s free-prefix [to] size-of-program) \n cons output-of-program \n nil\n\n [return full list of assignments]\n cons assignment\n (make-assignments free-space-pool requirements) \n\n [NOW DO IT!]\n (loop-thru-free-space-pool)\n\ndefine make-assignments\nvalue (lambda (free-space-pool requirements) ((' (lambda\n (free-space-pool) (if (atom requirements) nil (('\n (lambda (requirement) ((' (lambda (requirements) \n ((' (lambda (output-of-program) ((' (lambda (size-\n of-program) ((' (lambda (already-scanned) ((' (lam\n bda (not-yet-scanned) ((' (lambda (loop-thru-free-\n space-pool) (loop-thru-free-space-pool))) (' (lamb\n da () (if (atom not-yet-scanned) (cons not-enough-\n storage! (make-assignments free-space-pool require\n ments)) ((' (lambda (free-prefix) ((' (lambda (not\n -yet-scanned) (if (< size-of-program (length free-\n prefix)) ((' (lambda (already-scanned) (loop-thru-\n free-space-pool))) (append already-scanned (cons f\n ree-prefix nil))) ((' (lambda (free-space-pool) ((\n ' (lambda (assignment) (cons assignment (make-assi\n gnments free-space-pool requirements)))) (cons (ex\n tend-with-0s free-prefix size-of-program) (cons ou\n tput-of-program nil))))) (append already-scanned (\n append (remove-piece free-prefix size-of-program) \n not-yet-scanned)))))) (cdr not-yet-scanned)))) (ca\n r not-yet-scanned)))))))) free-space-pool))) nil))\n ) (car (cdr requirement))))) (car requirement)))) \n (cdr requirements)))) (car requirements))))) (debu\n g free-space-pool)))\n\n[put it all together]\n\ndefine (kraft requirements)\n\n let free-space-pool '(()) [everything free]\n \n (make-assignments free-space-pool requirements)\n\ndefine kraft\nvalue (lambda (requirements) ((' (lambda (free-space-poo\n l) (make-assignments free-space-pool requirements)\n )) (' (()))))\n\n[TEST KRAFT!]\n\n(kraft '((x 0) (y 1)))\n\nexpression (kraft (' ((x 0) (y 1))))\ndebug (())\ndebug ()\ndebug ()\nvalue ((() x) not-enough-storage!)\n\n \n(kraft '((a 1) (b 0) (c 1)))\n\nexpression (kraft (' ((a 1) (b 0) (c 1))))\ndebug (())\ndebug ((1))\ndebug ((1))\ndebug ()\nvalue (((0) a) not-enough-storage! ((1) c))\n\n \n(kraft '((x 1) (y 2)))\n\nexpression (kraft (' ((x 1) (y 2))))\ndebug (())\ndebug ((1))\ndebug ((1 1))\nvalue (((0) x) ((1 0) y))\n\n \n(kraft '((a 1) (b 2) (c 3) (d 4) (e 5)))\n\nexpression (kraft (' ((a 1) (b 2) (c 3) (d 4) (e 5))))\ndebug (())\ndebug ((1))\ndebug ((1 1))\ndebug ((1 1 1))\ndebug ((1 1 1 1))\ndebug ((1 1 1 1 1))\nvalue (((0) a) ((1 0) b) ((1 1 0) c) ((1 1 1 0) d) ((1 1\n 1 1 0) e))\n\n \n(kraft '((e 5) (d 4) (c 3) (b 2) (a 1)))\n\nexpression (kraft (' ((e 5) (d 4) (c 3) (b 2) (a 1))))\ndebug (())\ndebug ((0 0 0 0 1) (0 0 0 1) (0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (1))\ndebug ((0 0 0 0 1))\nvalue (((0 0 0 0 0) e) ((0 0 0 1) d) ((0 0 1) c) ((0 1) \n b) ((1) a))\n\n \n(kraft '((e 5) (c 3) (d 4) (a 1) (b 2)))\n\nexpression (kraft (' ((e 5) (c 3) (d 4) (a 1) (b 2))))\ndebug (())\ndebug ((0 0 0 0 1) (0 0 0 1) (0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (0 0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (0 1) (1))\ndebug ((0 0 0 0 1) (0 1))\ndebug ((0 0 0 0 1))\nvalue (((0 0 0 0 0) e) ((0 0 1) c) ((0 0 0 1) d) ((1) a)\n ((0 1) b))\n", "meta": {"hexsha": "76f0b36ddcdb378a1d49ff1b6ddb4d7d0147bd3c", "size": 10956, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/kraft.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/kraft.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/kraft.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 35.3419354839, "max_line_length": 70, "alphanum_fraction": 0.5996714129, "num_tokens": 3232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6040969791254341}} {"text": "=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Algebra::MatrixAlgebra\n((*(行列クラス)*))\n\n行列を表現します。実際のクラスを生成するには基底環とサイズを指定して、\nクラスメソッド ((<::create>)) あるいは関数 (())()\nを用います。\n\nサブクラスとして (())(縦ベクトル), \n(())(横ベクトル), \n(())(正方行列) を持ちます。\n\n== ファイル名:\n* ((|matrix-algebra.rb|))\n\n== スーパークラス:\n\n* ((|Object|))\n\n== インクルードしているモジュール:\n\n* (())\n* Enumerable\n\n== 関連する関数:\n\n--- Algebra.MatrixAlgebra(ring, m, n)\n ((<::create>))(ring, m, n)と同じです。\n\n== クラスメソッド:\n\n--- ::create(ring, m, n)\n 環 ((|ring|)) を要素とする, (({ (m, n) })) 型の行列を\n 表現するクラスを生成します。\n\n このメソッドの戻り値は (()) クラスのサブクラス\n です。このサブクラスにはクラスメソッドとして ((|ground|)) と\n ((|rsize|)), ((|csize|)), ((|sizes|)) が定義され、それぞれ、\n 基底となる環 ((|ring|))、行のサイズ ((|m|))、列のサイズ ((|n|))、\n それらの配列 (({ [m, n] })) を返します。\n\n 実際に行列を作るには ((<::new>)), ((<::matrix>)), \n ((<::[]>)) を使います。\n\n--- ::new(array)\n ((|array|)) を配列の配列とするとき、それを要素とする行列を返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M.new([[1, 2, 3], [4, 5, 6]])\n a.display\n #=> [1, 2, 3]\n #=> [4, 5, 6]\n\n--- ::matrix{|i, j| ... }\n ((|i|)) と ((|j|)) に行と列のインデックスを与え ... を評価した値を\n (({ (i, j) })) 成分にした行列を返します。\n \n 例:\n M = Alebra.MatrixAlgebra(Integer, 2, 3)\n a = M.matrix{|i, j| 10*(i + 1) + j + 1}\n a.display\n #=> [11, 12, 13]\n #=> [21, 22, 23]\n\n--- ::[](array1, array2, ..., arrayr)\n 配列 (({array1, array2, ..., arrayr})) をそれぞれ行とする配列を返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M[[1, 2, 3], [4, 5, 6]]\n a.display\n #=> [1, 2, 3]\n #=> [4, 5, 6]\n\n--- ::collect_ij{|i, j| ... }\n ((<::matrix>)) によく似ていますが、\n 返り値は Algebra::MatrixAlgebra でなく、2重配列(Array の Array)です。\n\n--- ::collect_row{|i| ... }\n 第 i 行に ... を評価して得た配列を並べた行列を返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n A = M.collect_row{|i| [i*10 + 11, i*10 + 12, i*10 + 13]}\n A.display\n #=> [11, 12, 13]\n #=> [21, 22, 23]\n\n--- ::collect_column{|j| ... }\n 第 j 列に ... を評価して得た配列を並べた行列を返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n A = M.collect_column{|j| [11 + j, 21 + j]}\n A.display\n #=> [11, 12, 13]\n #=> [21, 22, 23]\n\n--- ::*(otype)\n 2つの行列の型を掛けた新しいクラスを返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n N = Algebra.MatrixAlgebra(Integer, 3, 4)\n L = M * N\n p L.sizes #=> [3, 4]\n\n--- ::vector_type\n (()) と同じサイズの縦ベクトル(Vector)クラスを返します。\n\n--- ::covector_type\n (()) と同じサイズの横ベクトル(CoVector)クラスを返します。\n\n--- ::transpose\n 転置を行った新しい行列クラスを返します。\n\n--- ::zero\n 零行列を返します。\n\n#--- ::matrices; Matrices; end\n#--- ::regulate(x)\n\n== メソッド:\n#--- dup\n--- [](i, j)\n (({(i, j)})) 成分を返します。\n\n--- []=(i, j, x)\n (({(i, j)})) 成分を x にします。\n\n--- rsize\n 行サイズを返します。((<::rsize>)) と同じです。\n\n--- csize\n 列サイズを返します。((<::csize>)) と同じです。\n\n--- sizes\n [(()), (())] の配列を返します。\n ((<::sizes>)) と同じです。\n\n--- rows\n 各行を要素とする配列を返します。\n \n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M.new([[1, 2, 3], [4, 5, 6]])\n p a.rows #=> [[1, 2, 3], [4, 5, 6]]\n p a.row(1) #=> [4, 5, 6]\n a.set_row(1, [40, 50, 60])\n a.display #=> [1, 2, 3]\n #=> [40, 50, 60]\n\n--- row(i)\n i 行目を配列として返します。\n\n--- set_row(i, array)\n i 行目を配列 array に入れ換えます。\n\n--- columns\n 各列を要素とする配列を返します。\n \n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M.new([[1, 2, 3], [4, 5, 6]])\n p a.columns #=> [[1, 4], [2, 5], [3, 6]]\n p a.column(1) #=> [2, 5]\n a.set_column(1, [20, 50])\n a.display #=> [1, 20, 3]\n #=> [4, 50, 6]\n\n--- column(j)\n j 列目を配列として返します。\n\n--- set_column(j, array)\n j 列目を配列 array に入れ換えます。\n\n--- each{|row| ...}\n 各行を配列にして ((|row|)) に入れるイテレータです。\n\n--- each_index{|i, j| ...}\n 各添え字 (({ (i, j) })) に関するイテレータです。\n\n--- each_i{|i| ...}\n 各行の添え字 (({i})) に関するイテレータです。\n\n--- each_j{|j| ...}\n 各列の添え字 (({j})) に関するイテレータです。\n\n--- each_row{|r| ... }\n 各行を配列にして ((|r|)) に入れるイテレータです。\n (()) と同じです。\n\n--- each_column{|c| ... }\n 各列を配列にして ((|c|)) に入れるイテレータです。\n\n--- matrix{|i, j| ... }\n ((<::matrix>)) と同じです。\n\n--- collect_ij{|i, j| ... }\n ((<::collect_ij>)) と同じです。\n\n--- collect_row{|i| ... }\n ((<::collect_row>)) と同じです。\n\n--- collect_column{|j| ... }\n ((<::collect_column>)) と同じです。\n\n--- minor(i, j)\n ((|i|)) 行 ((|j|)) 列を除いた小行列を返します。\n\n--- cofactor(i, j)\n ((|i|)) 行 ((|j|)) 列を除いた小行列式に (-1)**(i+j) を掛けたものを\n 返します。(({minor(i, j) ** (i + j)})) と同じです。\n\n--- cofactor_matrix\n 余因子行列を返します。(({self.class.transpose.matrix{|i, j| cofactor(j, i)}})) と同じです。\n\n--- adjoint\n (()) と同じです。\n\n--- ==(other)\n 等しいとき真を返します。\n\n--- +(other)\n 和を計算します。\n\n--- -(other)\n 差を計算します。\n\n--- *(other)\n 積を計算します。\n \n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n N = Algebra.MatrixAlgebra(Integer, 3, 4)\n L = M * N\n a = M[[1, 2, 3], [4, 5, 6]]\n b = N[[-3, -2, -1, 0], [1, 2, 3, 4], [5, 6, 7, 8]]\n c = a * b\n p c.type #=> L\n c.display #=> [14, 20, 26, 32]\n #=> [23, 38, 53, 68]\n\n--- **(n)\n ((|n|)) 乗を計算します。\n\n--- /(other)\n 商を計算します。\n\n--- rank\n 階数を返します。\n\n--- dsum(other)\n 直和を返します。\n\n 例:\n a = Algebra.MatrixAlgebra(Integer, 2, 3)[\n [1, 2, 3],\n [4, 5, 6]\n ]\n b = Algebra.MatrixAlgebra(Integer, 3, 2)[\n [-1, -2],\n [-3, -4],\n [-5, -6]\n ]\n (a.dsum b).display #=> 1, 2, 3, 0, 0\n #=> 4, 5, 6, 0, 0\n #=> 0, 0, 0, -1, -2\n #=> 0, 0, 0, -3, -4\n #=> 0, 0, 0, -5, -6\n\n--- convert_to(ring)\n ((|self|)) の各成分を行列環 ((|ring|)) にコンバートします。\n\n Example:\n require \"matrix-algebra\"\n require \"residue-class-ring\"\n Z3 = Algebra.ResidueClassRing(Integer, 3)\n a = Algebra.MatrixAlgebra(Integer, 2, 3)[\n [1, 2, 3],\n [4, 5, 6]\n ]\n a.convert_to(Algebra.MatrixAlgebra(Z3, 2, 3)).display\n #=> 1, 2, 0\n #=> 1, 2, 0\n\n--- to_ary\n ((|to_a|)) を返します。((|to_a|)) は ((|Enumerable|)) で定義されています。\n\n--- flatten\n ((|to_a.flatten|)) を返します。\n\n--- diag\n 対角成分を配列で返します。\n\n--- transpose\n 転置行列を返します。\n\n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M.new([[1, 2, 3], [4, 5, 6]])\n Mt = M.transpose\n b = a.transpose\n p b.type #=> Mt\n b.display #=> [1, 4]\n #=> [2, 5]\n #=> [3, 6]\n\n#--- to_s\n\n--- dup\n 複製します。\n \n 例:\n M = Algebra.MatrixAlgebra(Integer, 2, 3)\n a = M.new([[1, 2, 3], [4, 5, 6]])\n b = a.dup\n b[1, 1] = 50\n a.display #=> [1, 2, 3]\n #=> [4, 5, 6]\n b.display #=> [1, 2, 3]\n #=> [4, 50, 6]\n\n--- display([out])\n 行列を ((|out|)) に表示します。((|out|)) が省略されると ((|$stdout|))\n に表示します。\n \n#--- inspect\n\n= Algebra::Vector\n((*(縦ベクトルクラス)*))\n\nベクトルのクラスです。\n\n== スーパークラス:\n\n* ((|Algebra::MatrixAlgebra|))\n\n== インクルードしているモジュール:\n\nなし\n\n== 関連する関数:\n\n--- Algebra.Vector(ring, n)\n (())(ring, n) と同じです。\n\n== クラスメソッド:\n\n--- Algebra::Vector::create(ring, n)\n 環 ((|ring|)) を要素とする, ((|n|)) 次元のベクトル(縦ベクトル)\n 表現するクラスを生成します。\n\n このメソッドの戻り値は (()) クラスのサブクラス\n です。このサブクラスにはクラスメソッドとして ((|ground|)) と\n ((|size|)) が定義され、それぞれ、基底となる環 ((|ring|))、\n サイズ ((|n|)) を返します。\n\n 実際にベクトルを作るにはクラスメソッド ((|new|)), \n ((|matrix|)), \n ((|[]|)) を使います。\n \n (()) は ((|n|)) 行 1 列の \n (()) と同一視されます。\n\n--- Algebra::Vector::new(array)\n ((|array|)) を配列とするとき、それを要素とす\n る縦ベクトルを返します。\n\n 例:\n V = Algebra.Vector(Integer, 3)\n a = V.new([1, 2, 3])\n a.display\n #=> [1]\n #=> [2]\n #=> [3]\n\n--- Algebra::Vector::vector{|i| ... }\n 第 ((|i|)) 成分を ... にしたベクトルを返します。\n\n 例:\n V = Algebra.Vector(Integer, 3)\n a = V.vector{|j| j + 1}\n a.display\n #=> [1]\n #=> [2]\n #=> [3]\n\n--- Algebra::Vector::matrix{|i, j| ... }\n 第 ((|i|)) 成分を ... にしたベクトルを返します。\n ((|j|)) には常に 0 が代入されます。\n\n== メソッド:\n\n--- size\n 次元を返します。\n\n--- to_a\n 各成分を配列にして返します。\n\n--- transpose\n 横ベクトル (()) に転置します。\n\n--- inner_product(other)\n ((|other|)) との内積を返します。\n\n--- inner_product_complex(other)\n ((|other|)) との内積を返します。\n (({inner_product(other.conjugate)}))と同じです。\n\n--- norm2\n ノルムを返します。\n (({inner_product(self)}))と同じです。\n\n--- norm2_complex\n ノルムを返します。\n (({inner_product(self.conjugate)}))と同じです。\n\n\n= Algebra::Covector\n((*(横ベクトルクラス)*))\n\nベクトルのクラスです。\n\n== スーパークラス:\n* ((|Algebra::MatrixAlgebra|))\n\n== インクルードしているモジュール:\n\nなし\n\n== 関連する関数:\n\n--- Algebra.Covector(ring, n)\n (()) (ring n)と同じです。\n\n== クラスメソッド:\n\n--- Algebra::Covector::create(ring, n)\n 環 ((|ring|)) を要素とする, ((|n|)) 次元のベクトル(横ベクトル)\n 表現するクラスを生成します。\n\n このメソッドの戻り値は (()) クラスのサブクラス\n です。このサブクラスにはクラスメソッドとして ((|ground|)) と\n ((|size|)) が定義され、それぞれ、基底となる環 ((|ring|))、\n サイズ ((|n|)) を返します。\n\n 実際にベクトルを作るにはクラスメソッド ((|new|)), \n ((|matrix|)), \n ((|[]|)) を使います。\n \n (()) は 1 行 ((|n|)) 列の (()) と\n 同一視されます。\n\n--- Algebra::Covector::new(array)\n ((|array|)) を配列とするとき、それを要素とす\n る横ベクトルを返します。\n\n 例:\n V = Algebra.Covector(Integer, 3)\n a = V.new([1, 2, 3])\n a.display\n #=> [1, 2, 3]\n\n--- Algebra::Covector::covector{|j| ... }\n 第 j 成分を ... にしたベクトルを返します。\n\n 例:\n V = Algebra.Covector(Integer, 3)\n a = V.covector{|j| j + 1}\n a.display\n #=> [1, 2, 3]\n\n--- Algebra::Covector::matrix{|i, j| ... }\n 第 j 成分を ... にしたベクトルを返します。i には常に 0 が代入されます。\n\n== メソッド:\n\n--- size\n 次元を返します。\n\n--- to_a\n 各成分を配列にして返します。\n\n--- transpose\n 横ベクトル (()) に転置します。\n\n--- inner_product(other)\n ((|other|)) との内積を返します。\n\n--- inner_product_complex(other)\n ((|other|)) との内積を返します。\n (({inner_product(other.conjugate)}))と同じです。\n\n--- norm2\n ノルムを返します。\n (({inner_product(self)}))と同じです。\n\n--- norm2_complex\n ノルムを返します。\n (({inner_product(self.conjugate)}))と同じです。\n\n= Algebra::SquareMatrix\n((*(正方行列環クラス)*))\n\n正方行列の作る環を表現するクラスです。\n\n== スーパークラス:\n\n* ((|Algebra::MatrixAlgebra|))\n\n== インクルードしているモジュール:\n\nなし\n\n== 関連する関数:\n\n--- Algebra.SquareMatrix(ring, size)\n (())(ring, n) と同じです。\n\n== クラスメソッド:\n\n--- Algebra::SquareMatrix::create(ring, n)\n\n 正方行列表現するクラスを生成します。\n\n このメソッドの戻り値は \n (()) クラスのサブクラス\n です。このサブクラスにはクラスメソッドとして \n ((|ground|)) と\n ((|size|)) が定義され、それぞれ、基底となる環 ((|ring|))、\n サイズ ((|n|)) を返します。\n\n SquareMatrix は ((|n|)) 行 ((|n|)) 列の Algebra::MatrixAlgebra と同一視されます。\n\n 実際に行列を作るにはクラスメソッド ((|new|)), \n ((|matrix|)), \n ((|[]|)) を使います。\n \n--- Algebra::SquareMatrix.determinant(aa)\n 配列の配列 ((|aa|)) の行列式を返します。\n\n--- Algebra::SquareMatrix.det(aa)\n (())と同じです。\n\n--- Algebra::SquareMatrix::unity\n 単位行列を返します。\n\n--- Algebra::SquareMatrix::zero\n 零行列を返します。\n\n--- Algebra::SquareMatrix.const(x)\n 成分が ((|x|)) のスカラー行列を返します。\n\n#--- self.regulate(x)\n\n== メソッド\n--- size\n サイズを返します。\n\n--- const(x)\n 成分が ((|x|)) のスカラー行列を返します。\n#--- self.matrices\n--- determinant\n 行列式を返します。\n\n--- inverse\n 逆行列を返します。\n\n--- /(other)\n (({self * other.inverse})) を返します。((|other|)) がスカラーなら\n 各要素を ((|other|)) で割ります。\n\n#--- sign(a)\n#--- perm\n\n--- char_polynomial(ring)\n ((|ring|)) に多項式環を与えると、特性多項式を返します。\n\n--- char_matrix(ring)\n ((|ring|)) に多項式環を与えると、特性行列を返します。\n\n--- _char_matrix(poly_ring_matrix)\n ((|poly_ring_matrix|)) に多項式成分の行列環を与えると、特性行列を返します。\n\n= Algebra::GaussianElimination\n((*(ガウスの消去法モジュール)*))\n\nガウスの掃き出し法を実現するモジュールです。\n\n== ファイル名:\n((|gaussian-elimination.rb|))\n\n== インクルードしているモジュール:\n\nなし\n\n== クラスメソッド:\n\nなし\n\n== メソッド\n\n--- swap_r!(i, j)\n ((|i|)) 行と ((|j|)) 行を入れ換えます。\n\n--- swap_r(i, j)\n ((|i|)) 行と ((|j|)) 行を入れ換えたものを返します。\n\n--- swap_c!(i, j)\n ((|i|)) 列と ((|j|)) 列を入れ換えます。\n\n--- swap_c(i, j)\n ((|i|)) 列と ((|j|)) 列を入れ換えたものを返します。\n\n--- multiply_r!(i, c)\n ((|i|)) 行目を ((|c|)) 倍します。\n\n--- multiply_r(i, c)\n ((|i|)) 行目を ((|c|)) 倍したものを返します。\n\n--- multiply_c!(j, c)\n ((|j|)) 列目を ((|c|)) 倍します。\n\n--- multiply_c(j, c)\n ((|j|)) 列目を ((|c|)) 倍したものを返します。\n\n--- divide_r!(i, c)\n ((|i|)) 行目を ((|c|)) で割ります。\n\n--- divide_r(i, c)\n ((|i|)) 行目を ((|c|)) 割ったものを返します。\n\n--- divide_c!(j, c)\n ((|j|)) 列目を ((|c|)) で割ります。\n\n--- divide_c(j, c)\n ((|j|)) 列目を ((|c|)) 割ったものを返します。\n\n--- mix_r!(i, j, c)\n ((|i|)) 行目に ((|j|)) 行目の ((|c|)) 倍を足します。\n\n--- mix_r(i, j, c)\n ((|i|)) 行目に ((|j|)) 行目の ((|c|)) 倍を足したものを返します。\n\n--- mix_c!(i, j, c)\n ((|i|)) 列目に ((|j|)) 列目の ((|c|)) 倍を足します。\n\n--- mix_c(i, j, c)\n ((|i|)) 列目に ((|j|)) 列目の ((|c|)) 倍を足したものを返します。\n\n--- left_eliminate!\n 左からの基本変形で階段行列に変形します。\n \n 戻り値は、変形するのに使った正方行列の積とその正方行列の\n 行列式と階数の配列です。\n \n 例:\n require \"matrix-algebra\"\n require \"mathn\"\n class Rational < Numeric\n def inspect; to_s; end\n end\n M = Algebra.MatrixAlgebra(Rational, 4, 3)\n a = M.matrix{|i, j| i*10 + j}\n b = a.dup\n c, d, e = b.left_eliminate!\n b.display #=> [1, 0, -1]\n #=> [0, 1, 2]\n #=> [0, 0, 0]\n #=> [0, 0, 0]\n c.display #=> [-11/10, 1/10, 0, 0]\n #=> [1, 0, 0, 0]\n #=> [1, -2, 1, 0]\n #=> [2, -3, 0, 1]\n p c*a == b#=> true\n p d #=> 1/10\n p e #=> 2\n\n--- left_inverse\n 左からの基本変形による一般逆行列です。\n\n--- left_sweep\n 左からの基本変形で階段行列にして返します。\n\n--- step_matrix?\n 階段行列であるとき、軸(pivot)の配列を返します。そうでないとき、nil\n を返します。\n\n--- kernel_basis\n 右から掛けて零になるベクトルの空間の基底の配列を返します。\n 各基底は (()) の要素です。\n\n 例:\n require \"matrix-algebra\"\n require \"mathn\"\n M = Algebra.MatrixAlgebra(Rational, 5, 4)\n a = M.matrix{|i, j| i + j}\n a.display #=>\n #[0, 1, 2, 3]\n #[1, 2, 3, 4]\n #[2, 3, 4, 5]\n #[3, 4, 5, 6]\n #[4, 5, 6, 7]\n a.kernel_basis.each do |v|\n puts \"a * #{v} = #{a * v}\"\n #=> a * [1, -2, 1, 0] = [0, 0, 0, 0, 0]\n #=> a * [2, -3, 0, 1] = [0, 0, 0, 0, 0]\n end\n\n--- determinant_by_elimination\n 体上の正方行列の行列式を掃き出し法で求めます。\n \n=end\n\n", "meta": {"hexsha": "ea17b52260c551f9ce53937ef8646120e1fe02c6", "size": 14395, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/matrix-algebra-ja.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "doc-ja/matrix-algebra-ja.rd", "max_issues_repo_name": "kunishi/algebra-ruby2", "max_issues_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc-ja/matrix-algebra-ja.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7733516484, "max_line_length": 78, "alphanum_fraction": 0.4900312609, "num_tokens": 7084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624840223698, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6040929410800715}} {"text": "#' Singular Value Decomposition\n#' \n#' TODO\n#' \n#' @details\n#' TODO\n#' \n#' @param x\n#' numeric distributed matrix\n#' @param nu\n#' number of left singular vectors to return when calculating singular values.\n#' @param nv \n#' number of right singular vectors to return when calculating singular values.\n#' \n#' @return \n#' TODO\n#' \n#' @export\nksvd = function(x, nu = min(m, n), nv = min(m, n))\n{\n m = nrow(x)\n n = ncol(x)\n min_mn = min(m, n)\n \n if (m < n)\n comm.stop(\"only m>=n is supported in ksvd()\")\n \n ICTXT = x@ICTXT\n bldim = x@bldim\n if (bldim[1] != bldim[2])\n comm.stop(paste0(\"ksvd() requires a square blocking factor; have \", bldim[1L], \"x\", bldim[2L]))\n \n dim_a = dim(x)\n ldim_a = base.numroc(dim=dim_a, bldim=bldim, ICTXT=ICTXT)\n desca = base.descinit(dim_a, bldim, ldim_a, ICTXT)\n \n dim_u = c(m, min_mn)\n if (nu == 0)\n {\n jobu = 'N'\n ldim_u = c(-1L, -1L)\n }\n else\n {\n jobu = 'V'\n ldim_u = base.numroc(dim=dim_u, bldim=bldim, ICTXT=ICTXT)\n }\n \n dim_vt = c(min_mn, n)\n if (nv == 0)\n {\n jobvt = 'N'\n ldim_vt = c(-1L, -1L)\n }\n else\n {\n jobvt = 'V'\n ldim_vt = base.numroc(dim=dim_vt, bldim=bldim, ICTXT=ICTXT)\n }\n \n descu = base.descinit(dim_u, bldim, ldim_u, ICTXT)\n descvt = base.descinit(dim_vt, bldim, ldim_vt, ICTXT)\n \n # eigtype: \"r\", \"d\"\n out = rpdgeqsvd(jobu, jobvt, eigtype='d', x@Data, desca, descu, descvt)\n \n \n if (nu > 0)\n {\n u = new(\"ddmatrix\", Data=out$u, dim=dim_u, ldim=ldim_u, bldim=bldim, ICTXT=ICTXT)\n if (nu < u@dim[2L])\n u = u[, 1L:nu]\n }\n else\n u = NULL\n \n if (nv > 0)\n {\n vt = new(\"ddmatrix\", Data=out$vt, dim=dim_vt, ldim=ldim_vt, bldim=bldim, ICTXT=ICTXT)\n if (nv < vt@dim[1L])\n vt = vt[1L:nv, ]\n }\n else\n vt = NULL\n \n ret = list(d=out$s)\n ret$u = u\n ret$vt = vt\n \n ret\n}\n", "meta": {"hexsha": "f08c91dbf57702f1b557ca19080a777c4645b6f8", "size": 1812, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ksvd.r", "max_stars_repo_name": "RBigData/ksvd", "max_stars_repo_head_hexsha": "12525711d5920c5860ea71c521c0b3fcf68ba52b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ksvd.r", "max_issues_repo_name": "RBigData/ksvd", "max_issues_repo_head_hexsha": "12525711d5920c5860ea71c521c0b3fcf68ba52b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ksvd.r", "max_forks_repo_name": "RBigData/ksvd", "max_forks_repo_head_hexsha": "12525711d5920c5860ea71c521c0b3fcf68ba52b", "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": 19.6956521739, "max_line_length": 99, "alphanum_fraction": 0.5722958057, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6040508375853001}} {"text": "##### 医学統計勉強会18第五回比率と分割表 R code #####\n\n## Low Infant Birth Data ##\n\n# birthwt2 の準備 #\nlibrary(MASS)\ndata(birthwt)\nhead(birthwt, n=2)\n\nbirthwt2 <- birthwt[, -10]\t\t# bwt: 出生体重を除く\nbirthwt2$race <- factor(birthwt2$race, label=c(\"white\", \"black\", \"other\"))\t# 因子型に変換し、水準のラベルを1, 2, 3から、white, black, otherに変更する。\nbirthwt2$ptl[birthwt2$ptl >= 1] <- \"1+\"\t\t# ptl: 1以上の値を \"1+\" とする。\nbirthwt2$ftv[birthwt2$ftv >= 1] <- \"1+\"\t\t# ftv: 1以上の値を \"1+\" とする。\nhead(birthwt2, n=2)\n\nattach(birthwt2)\t# birthwt2に含まれる変数を、個別に扱えるようにする。\n\n# 度数と相対度数 #\ntbl <- table(race)\t# 度数 #\ntbl\n\nprop.table(tbl)\t\t# 相対度数 #\n\n## event rate (person-time) : confidence interval and hypothesis testing ##\n\nlibrary(epitools)\n\n##Examples from Rothman 1998, p. 238\nbc <- c(Unexposed = 15, Exposed = 41)\npyears <- c(Unexposed = 19017, Exposed = 28010)\ndd <- matrix(c(41,15,28010,19017),2,2)\ndimnames(dd) <- list(Exposure=c(\"Yes\",\"No\"), Outcome=c(\"BC\",\"PYears\"))\ndd\n\npois.exact(15,19117)\npois.exact(41,28010)\n\nrateratio.wald(dd)\n\n\n\n## Test of Proportion : proportions test with continuity correction\nprop.test(96, 189, p=0.6)\n\n## Test of Equal or Given Proportion : Clopper-Pearson exact confidence interval ##\n\nbinom.test(0, 10)\n\n\n\n## 分割表:正答率、感度、特異度、陽性的中率、陰性的中率 ##\n\ntable(low, smoke)\n\nlibrary(pROC)\n\ntbl.coords <- roc(low, smoke)\n\ncoords(tbl.coords, x=\"best\", ret=c(\"accuracy\", \"1-sensitivity\", \"sensitivity\", \n\"1-specificity\", \"specificity\", \"ppv\", \"npv\"))\n\n\n\n## ROC曲線とAUC ##\n\nlibrary(pROC)\n\nx <- c(1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1)\t\t# 疾患あり:1,疾患なし:0\ny <- c(0,0,0,0,0,0,0,0,0,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4)\t\t# 検査数値\ntbl <- table(x, y)\ntbl\n\ny2 <- rep((0:5), each=10)\ntbl2 <- table(x, y2)\ntbl2\n\ntbl.roc <- roc(x, y)\nplot(tbl.roc, print.auc=TRUE, print.thres=TRUE)\t\t\t\t# ROC曲線の描画\nopt.sp <- tbl.roc$sp[which.max(tbl.roc$se+tbl.roc$sp)]\t\t# 最適な特異度\nopt.se <- tbl.roc$se[which.max(tbl.roc$se+tbl.roc$sp)]\t\t# 最適な感度\nabline((opt.sp+opt.se), -1)\t\t# 最適なカットポイントを通る45度線\n\ntbl.roc2 <- roc(x, y2)\nroc.test(tbl.roc, tbl.roc2)\t\t# Compare the AUC of two ROC curves \n\n### Fisherの直接法とχ二乗検定 ###\n\ntbl <- matrix(c(405, 173, 416, 152), \n\t\t\t\tnrow=2, \n\t\t\t\tdimnames=list(\"β-Blocker\" = c(\"(+)\", \"(-)\"), \n\t\t\t\t\t\t\t \"Olmesartan\" = c(\"(+)\", \"(-)\")))\ntbl\nfisher.test(tbl)\t\t\t\t# Fisherの直接法\nchisq.test(tbl)\t\t\t\t\t# カイ二乗検定(連続補正あり)\nchisq.test(tbl, correct=FALSE)\t# カイ二乗検定(連続補正なし)\n\n### McNemar検定 ###\n\ntbl2 <- matrix(c(175, 54, 16, 188), \n\t\t\t\tnrow=2, \n\t\t\t\tdimnames=list(\"2004 election\" = c(\"Democrat\", \"Repablican\"), \n\t\t\t\t\t\t\t \"2008 election\" = c(\"Democrat\", \"Repablican\")))\ntbl2\nbinom.test(16, (16 + 54))\t# 二項分布による正確検定\nmcnemar.test(tbl2)\t\t\t# McNemar検定(連続補正あり)\nmcnemar.test(tbl2)\t\t\t# McNemar検定(連続補正なし)\n\n### Mantel-Haenszel検定 ###\n\ntbl3 <- array(c(80,160,16,160, 50, 10, 452, 452), dim=c(2,2,2))\ntbl3\nmantelhaen.test(tbl3)\n\n### Cochran-Armitage Trend Test ###\n\ntbl4 <- matrix(c(17066, 14464, 788, 126, 37, 48, 38, 5, 1, 1), \n\t\t\t\tnrow=2, byrow=TRUE, \n\t\t\t\tdimnames=list(\"Malformation\" = c(\"Absent\", \"Present\"), \n\t\t\t\t\t\t\t \"Alcohol Consumption\" = c(\"0\", \"< 1\", \"1-2\", \"3-5\", \">= 6\")))\ntbl4\nevent <- tbl4[2, ]\ntotal <- apply(tbl4, 2, sum)\nprop.trend.test(event, total, score=c(0, 0.5, 1.5, 4.0, 7.0))\t\t# Cochran-Armitage Trend Test\nprop.test(event, total)\t\t\t\t# (傾向無しの)独立性の検定", "meta": {"hexsha": "9f96b2d7fce74521ddcf2c8878697eaa9a6b7ad9", "size": 3321, "ext": "r", "lang": "R", "max_stars_repo_path": "MedicalStatisticsClass/2019/5/code.r", "max_stars_repo_name": "shumez/stat", "max_stars_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MedicalStatisticsClass/2019/5/code.r", "max_issues_repo_name": "shumez/stat", "max_issues_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MedicalStatisticsClass/2019/5/code.r", "max_forks_repo_name": "shumez/stat", "max_forks_repo_head_hexsha": "53fdb0c383fc394771221c4cf2cf9c64c6e81b09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7822580645, "max_line_length": 144, "alphanum_fraction": 0.6242095754, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439708, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6040469175886763}} {"text": "### R script to demonstrate Random Fourier Features version of latent Gaussian Process model for quasar time delay estimation\n#install_tensorflow(extra_packages = \"tensorflow-probability\") \n\nlibrary(tensorflow)\n#Sys.setenv(TENSORFLOW_PYTHON=\"/Users/jburgess/.environs/tflow/bin/python3\")\nSys.setenv(\"CUDA_VISIBLE_DEVICES\" = -1) # temporary fix to avoid bug in Greta concerning GPU computations\n#use_python(\"/Users/jburgess/.environs/tflow/bin/python3\")\nuse_virtualenv(\"/Users/jburgess/.environs/tflow\")\nlibrary(greta)\n#Sys.setenv(TENSORFLOW_PYTHON=\"/Users/jburgess/.environs/tflow/bin/python3\")\n### Define imagined data generating process and draw a mock dataset\n###\n### In this toy model there are two lensed images of the quasar observed at different times over a 50 day window\n### Each image has time-series of brightness, one being offset by a fixed delay from the other\n### The brightness time-series is modelled as an exponentiated Gaussian process modulating the average brightness of each quasar image\n\nNobs_quasar_image_A <- 150\nobservation_times_quasar_image_A <- sort(runif(Nobs_quasar_image_A,0,50))\nNobs_quasar_image_B <- 75\nobservation_times_quasar_image_B <- sort(runif(Nobs_quasar_image_B,0,50))\n\ntrue_time_delay <- 1\ntrue_GP_bandwidth <- 1\ntrue_GP_scale <- 0.5\ntrue_expected_counts_quasar_image_A <- 40\ntrue_expected_counts_quasar_image_B <- 30\ntrue_expected_background_counts <- 5\n\ntrue_cov_matrix <- true_GP_scale^2*exp(-true_GP_bandwidth*as.matrix(dist(sort(c(observation_times_quasar_image_A,observation_times_quasar_image_B+true_time_delay)),upper = TRUE,diag = TRUE))^2)\ntrue_cov_matrix <- true_cov_matrix+diag(Nobs_quasar_image_A+Nobs_quasar_image_B)*0.0001\n\nlibrary(MASS)\ntrue_latent_curve <- exp(mvrnorm(1,rep(0,Nobs_quasar_image_A+Nobs_quasar_image_B),true_cov_matrix))\n\ntrue_latent_curve_quasar_image_A <- true_latent_curve[which(sort.list(c(observation_times_quasar_image_A,observation_times_quasar_image_B+true_time_delay)) %in% 1:(Nobs_quasar_image_A))]\ntrue_latent_curve_quasar_image_B <- true_latent_curve[which(!(sort.list(c(observation_times_quasar_image_A,observation_times_quasar_image_B+true_time_delay)) %in% 1:(Nobs_quasar_image_A)))]\nobserved_counts_quasar_image_A <- rpois(Nobs_quasar_image_A,true_expected_background_counts+true_expected_counts_quasar_image_A*true_latent_curve_quasar_image_A)\nobserved_counts_quasar_image_B <- rpois(Nobs_quasar_image_B,true_expected_background_counts+true_expected_counts_quasar_image_B*true_latent_curve_quasar_image_B)\n\nlayout(1:2)\nplot(observation_times_quasar_image_A,observed_counts_quasar_image_A,ylim=c(0,150))\ntitle(\"Mock Dataset: Image A\")\nplot(observation_times_quasar_image_B,observed_counts_quasar_image_B,ylim=c(0,150))\ntitle(\"Mock Dataset: Image B\")\n\n### Construct Bayesian model with RFF approximation of latent Gaussian process and sample with Greta (HMC)\n###\n### The Bayesian model mimics the mock data generating process with the parameters assigned sensible priors, close to their true values\n### The implementation of the Gaussian process is by way of the RFF approximation: https://people.eecs.berkeley.edu/~brecht/papers/07.rah.rec.nips.pdf\n### Not implemented here: RFFs are easily extensible to represent non-stationary Gaussian processes: https://www.sciencedirect.com/science/article/pii/S2211675317302890\n### The RFF code here uses a low discrepancy sequence (Quasi-Monte Carlo, rather than completely random), and works with sin/cos pairs (rather than random phases), since these have been shown to perform well\n###\n### The beauty of the greta package is that you can write your model mostly using base R commands and it will built a graph in tensorflow automatically for you to provide fast HMC\n\nlibrary(randtoolbox)\n\nk_RFF <- 500 # Number of RFF bases (will use sin&cos orthogonal pairs)\nomega_qmc_RFF <- t(qnorm(halton(k_RFF,1)))\n\ntime_delay <- normal(0,1)\nlog_GP_bandwidth <- normal(0,1)\nlog_GP_scale <- normal(0,1)\nlog_expected_counts_quasar_image_A <- normal(log(50),2)\nlog_expected_counts_quasar_image_B <- normal(log(50),2)\nlog_expected_background_counts <- normal(log(5),2)\nRFF_slopes <- normal(rep(0,k_RFF*2),1)\n\nGP_bandwidth <- exp(log_GP_bandwidth)\nGP_scale <- exp(log_GP_bandwidth)\nexpected_background_counts <- exp(log_expected_background_counts)\n\nomega_QMC_RFF_scaled <- omega_qmc_RFF*GP_bandwidth\nRFFprojections_A <- observation_times_quasar_image_A%*%omega_QMC_RFF_scaled\nRFFprojections_B <- (observation_times_quasar_image_B+time_delay)%*%omega_QMC_RFF_scaled\nRFFs_A <- cbind(sin(RFFprojections_A),cos(RFFprojections_A))\nRFFs_B <- cbind(sin(RFFprojections_B),cos(RFFprojections_B))\nlatent_GP_A <- (RFFs_A%*%RFF_slopes)*GP_scale/sqrt(k_RFF)\nlatent_GP_B <- (RFFs_B%*%RFF_slopes)*GP_scale/sqrt(k_RFF)\n\nlatent_signal_A <- exp(latent_GP_A+log_expected_counts_quasar_image_A)\nlatent_signal_B <- exp(latent_GP_B+log_expected_counts_quasar_image_B)\nobs_signal_A <- latent_signal_A+expected_background_counts\nobs_signal_B <- latent_signal_B+expected_background_counts\n\ndistribution(observed_counts_quasar_image_A) <- poisson(obs_signal_A)\ndistribution(observed_counts_quasar_image_B) <- poisson(obs_signal_B)\n\nm <- model(time_delay,log_GP_bandwidth,log_GP_scale,log_expected_counts_quasar_image_A,log_expected_counts_quasar_image_B,log_expected_background_counts,RFF_slopes)\n\noptim <- opt(m,max_iterations = 100) ## Take a few simple optimising steps to get towards the bulk of posterior mass before starting HMC\n\ndraws <- mcmc(m,n_samples = as.integer(1000),chains=as.integer(1)) ## Single chain here: there are obvious benefits to running multiple chains for a proper analysis\n\nposterior.latent.GP_A <- matrix(0,nrow=25,ncol=(Nobs_quasar_image_A+Nobs_quasar_image_B))\nposterior.latent.GP_B <- matrix(0,nrow=25,ncol=(Nobs_quasar_image_A+Nobs_quasar_image_B))\nposterior.relative_observation_times_to_A <- matrix(0,nrow=25,ncol=(Nobs_quasar_image_A+Nobs_quasar_image_B))\nposterior.relative_observation_times_to_B <- matrix(0,nrow=25,ncol=(Nobs_quasar_image_A+Nobs_quasar_image_B))\nfor (i in 1:25) {\n drawn.par <- list(\n 'time_delay'=draws[[1]][i*10,1],\n 'log_GP_bandwidth'=draws[[1]][i*10,2],\n 'log_GP_scale'=draws[[1]][i*10,3],\n 'log_expected_counts_quasar_image_A'=draws[[1]][i*10,4],\n 'log_expected_counts_quasar_image_B'=draws[[1]][i*10,5],\n 'log_expected_background_counts'=draws[[1]][i*10,6],\n 'RFF_slopes'=draws[[1]][i*10,7:(k_RFF*2+7-1)]\n )\n posterior.latent.GP_A[i,] <- as.numeric(calculate(exp(c(latent_GP_A,latent_GP_B)+log_expected_counts_quasar_image_A)+expected_background_counts,values=drawn.par))\n posterior.latent.GP_B[i,] <- as.numeric(calculate(exp(c(latent_GP_A,latent_GP_B)+log_expected_counts_quasar_image_B)+expected_background_counts,values=drawn.par))\n posterior.relative_observation_times_to_A[i,] <- c(observation_times_quasar_image_A,observation_times_quasar_image_B+drawn.par$time_delay)\n posterior.relative_observation_times_to_B[i,] <- c(observation_times_quasar_image_A-drawn.par$time_delay,observation_times_quasar_image_B)\n cat(i,\"\\n\")\n}\n\nlayout(1:2)\nplot(observation_times_quasar_image_A,observed_counts_quasar_image_A,xlim=c(0,50),ylim=c(0,125),xlab='Observation Times A',ylab=\"Observed Counts A\")\nfor (i in 1:25) {lines(sort(relative_obs_times_to_A),posterior.latent.GP_A[i,sort.list(relative_obs_times_to_A)],col=hsv(i/25*0.6,alpha=0.1))}\ntitle(\"Posterior Draws of Latent Mean Signal: Image A\")\n\nplot(observation_times_quasar_image_B,observed_counts_quasar_image_B,xlim=c(0,50),ylim=c(0,125),xlab='Observation Times B',ylab=\"Observed Counts B\")\nfor (i in 1:25) {lines(sort(relative_obs_times_to_B),posterior.latent.GP_B[i,sort.list(relative_obs_times_to_B)],col=hsv(i/25*0.6,alpha=0.1))}\ntitle(\"Posterior Draws of Latent Mean Signal: Image B\")\n\nlayout(1)\nhist(draws[[1]][1,],xlab=\"\",ylab=\"Freq. in Posterior Samples\",)\n", "meta": {"hexsha": "5475f1e0b0d200690d7cf241b4f8bfe6dfd144a3", "size": 7802, "ext": "r", "lang": "R", "max_stars_repo_path": "prototype/quasar_example_greta.r", "max_stars_repo_name": "msinghartinger/pyipn", "max_stars_repo_head_hexsha": "32d90fdbcafc01fc0b4d8df3238da0bb701ae35d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "prototype/quasar_example_greta.r", "max_issues_repo_name": "msinghartinger/pyipn", "max_issues_repo_head_hexsha": "32d90fdbcafc01fc0b4d8df3238da0bb701ae35d", "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": "prototype/quasar_example_greta.r", "max_forks_repo_name": "msinghartinger/pyipn", "max_forks_repo_head_hexsha": "32d90fdbcafc01fc0b4d8df3238da0bb701ae35d", "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": 61.9206349206, "max_line_length": 207, "alphanum_fraction": 0.8123558062, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.6039623732384343}} {"text": "# 4. faza: Analiza podatkov\n\nlibrary(mgcv)\nlibrary(forecast)\n\nDODANAVREDNOST <- DODANAVRED[seq(1, 468, 36), \"SLOVENIJA\"]\nPREBIVALSTVO <- prebivalstvo[(41:53),\"Prebivalstvo\"]\nP <- data.frame(X=DODANAVREDNOST, Y=PREBIVALSTVO)\n# plot(DODANAVREDNOST ~ PREBIVALSTVO)\n# lm <- lm(X ~ Y, data = P)\n# summary(lm)\n# predict(lm)\n# plot(predict(lm))\n# lines(DODANAVREDNOST, PREBIVALSTVO, col=\"red\", lwd=10)\n\n\n#leta 2008 največji BDP,po letu 2008 kljub rasti prebivalstva BDP začne padati(gospodarska kriza)\nattach(P)\npdf(\"slike/prebBDP.pdf\")\nplot(DODANAVREDNOST, PREBIVALSTVO, pch=20, col=\"blue\")\n\nmgam <- gam(Y ~ s(X), data = P)\ncurve(predict(mgam, data.frame(X=x)), add = TRUE, col = \"red\")\n\n\ndev.off()\ndetach(P)\n\n\n#napoved BDP\npdf(\"slike/napovedBDP.pdf\")\nleto <- DODANAVRED[seq(1, 468, 36),\"Leto\"]\nBL <- data.frame(X=leto,Y=DODANAVREDNOST)\nbdpts <- ts(data=BL$Y, start=c(2000,1)) # časovni vektor\nplot(forecast(bdpts), main=\"Napoved BDP\", ylim=c(0,50000), ylab=\"Dodana vrednost\", xlab=\"Leto\")\ndev.off()\n\n#napoved prebivalstva\npdf(\"slike/napovedPREBIVALSTVA.pdf\")\nD <- data.frame(prebivalstvo)\nprebts <- ts(data=D$Prebivalstvo, start=c(1960,1))\nplot(forecast(prebts), main=\"Napoved prebivalstva\", xlab=\"Leto\", ylab=\"število prebivalcev\")\ndev.off()\n\n\n#Stolpični graf primerjava deleža prebivalstva in deleža BDP\nprebivalcireg <-PREBIVALSTVOREGIJE[,\"Število.prebivalcev\"] \nDEJ <- as.integer(as.table(matrix(DODANAVRED[445, c(6:9, 11:18)])))\n# DEJ1 <- DEJ[order(DEJ)]\n# prebivalcireg1 <- prebivalcireg[c(5 ,8, 10, 7, 12, 1, 2, 6, 3, 9, 11, 4)]\no <- order(DEJ)\nDEJ1 <- DEJ[o]\nprebivalcireg1 <- prebivalcireg[o]\n \npdf(\"slike/delez2.pdf\")\nprebdej <- matrix(c(prebivalcireg1, DEJ1), nrow=2, byrow=TRUE)\nbarplot(prebdej, sub= \"Regije\", ylab=\"Vrednost\",\n main= \"Primerjava deleža BDP in prebivalcev po regijah\", \n col=c(\"blue\", \" green\"), width=3, beside=TRUE,\n names.arg=PREBIVALSTVOREGIJE[o,\"Regije\"], las = 2, cex.names = 0.4)\nlegend(\"topleft\", legend = c(\"delež prebivalstva\", \"delež BDP\"), \n fill = c(\"blue\", \"green\"))\ndev.off()\n\n\n\n#graf povezave BDP in dolga po letih\ndolg <- DOLG[(1:13), \"Dolg\"] #vrednost dolga\n\npdf(\"slike/dolg2.pdf\")\n\nrange1 <- range(0, dolg, DODANAVREDNOST)\nplot(DODANAVREDNOST, type=\"o\", col=\"red\",ylim=range1, axes=FALSE, ann=FALSE)\naxis(1, at=1:13, lab=c(\"2000\" ,\"2001\", \"2002\", \"2003\", \"2004\", \"2005\", \"2006\", \"2007\", \"2008\", \"2009\", \"2010\",\n \"2011\", \"2012\"))\naxis(2, at=10000*0:range1[2])\nbox()\nlines(dolg, type=\"o\", pch=22, col=\"blue\", lty=2)\ntitle(main=\"Primerjava vrednosti BDP in dolga po letih\")\ntitle(xlab=\"Leta\")\ntitle(ylab=\"vrednost\")\nlegend(\"topleft\", c(\"Vrednost BDP\",\"vrednost dolga\"), cex=0.8,\n col=c(\"red\",\"blue\"), lty=1:2)\n\n\n\ndev.off()\n", "meta": {"hexsha": "affae72b44eaabf69de01de654f72f28e7ca3381", "size": 2727, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "marushezz/APPR-2014-15", "max_stars_repo_head_hexsha": "5f5360f1f20a6bc822d5c49fbb53f39318d26974", "max_stars_repo_licenses": ["MIT"], "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": "marushezz/APPR-2014-15", "max_issues_repo_head_hexsha": "5f5360f1f20a6bc822d5c49fbb53f39318d26974", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-01-13T22:14:33.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-24T21:35:52.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "marushezz/APPR-2014-15", "max_forks_repo_head_hexsha": "5f5360f1f20a6bc822d5c49fbb53f39318d26974", "max_forks_repo_licenses": ["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.9886363636, "max_line_length": 110, "alphanum_fraction": 0.6718005134, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6039499369229775}} {"text": "\n# Josep Ll. Berral-García\n# ALOJA-BSC-MSR aloja.bsc.es\n# 2016-02-20\n# Implementation of Quadratic (or Linear) Regression Tree method recursive-partition-like\n\n# Usage:\n#\tmtree <- qrt.tree(varout = target.name, dataset = dataframe, simple = 0);\n#\tprediction <- qrt.predict(model = mtree, newdata = dataframe);\n#\tqrt.plot.tree(mtree);\n\nsuppressMessages(library(rpart));\t# Recursive Partition Trees\n\n###############################################################################\n# Regression Tree M5-Prediction-like with Linear/Quadratic Regression #\n###############################################################################\n\nqrt.tree <- function (varout, dataset, m = 30, cp = 0.001, simple = 1)\n{\n\tif (!is.numeric(m)) m <- as.numeric(m);\n\tif (!is.numeric(cp)) cp <- as.numeric(cp);\n\tif (!is.numeric(simple)) simple <- as.numeric(simple);\n\n\tvout <- varout;\n\tvin <- colnames(dataset)[(!colnames(dataset) %in% vout)];\n\tdataset <- dataset[,c(vout,vin)];\n\n\tfit <- rpart(formula=dataset[,vout]~.,data=dataset[,vin],method=\"anova\",control=rpart.control(minsplit=as.integer(m),cp=as.numeric(cp)));\n\tnodes <- as.numeric(rownames(fit$frame));\n\n\terr_branch <- regs <- preds <- list();\n\tindexes <- NULL;\n\tmae <- rae <- 0;\n\tfor (i in unique(fit$where))\n\t{\n\t\tdaux <- dataset[fit$where==i,c(vout,vin)];\n\t\tj <- nodes[i];\n\n\t\tif (simple > 0) regs[[j]] <- lm(formula=daux[,vout] ~ ., data=data.frame(daux[,vin]));\n\t\tif (simple <= 0) regs[[j]] <- lm(formula=daux[,vout] ~ . + (.)^2, data=data.frame(daux[,vin]));\n\t\tindexes <- c(indexes,j);\n\n\t\tpreds[[j]] <- regs[[j]]$fitted.values;\n\t\terr_branch[[j]] <- paste(j,nrow(daux),mean(abs(preds[[j]] - daux[,vout])),mean(abs((preds[[j]] - daux[,vout])/daux[,vout])),sep=\" \");\n\t}\n\n\tretval <- list();\n\tretval[[\"rpart\"]] <- fit;\n\tretval[[\"regs\"]] <- regs;\n\tretval[[\"indexes\"]] <- indexes;\n\n\terr_data <- data.frame(strsplit(unlist(err_branch),\" \"));\n\terr_data <- apply(err_data, 1, function(x) as.numeric(x));\n\tauxid <- if (is.null(nrow(err_data))) 1 else err_data[,1];\n\terr_data <- if (is.null(nrow(err_data))) t(data.frame(err_data[-1])) else data.frame(err_data[,-1]);\n\tcolnames(err_data) <- c(\"Instances\",\"MAE\",\"MAPE\");\n\trownames(err_data) <- auxid;\n\tretval[[\"error_branch\"]] <- err_data;\t\n\n\tpreds <- unlist(preds);\n\tretval[[\"fitted.values\"]] <- preds[order(as.integer(names(preds)))];\n\tretval[[\"mae\"]] <- mean(abs(retval$fitted.values - dataset[,vout]));\n\tretval[[\"rae\"]] <- mean(abs((retval$fitted.values - dataset[,vout])/dataset[,vout]));\n\n\tclass(retval) <- c(class(retval),\"qrt\");\n\n\tretval;\n}\n\nqrt.predict <- function (model, newdata)\n{\n\tcolnames(newdata) <- gsub(\" \",\".\",colnames(newdata));\n\n\tfit_node <- model$rpart;\n\tfit_node$frame$yval <- as.numeric(rownames(fit_node$frame));\n\n\tsapply(1:nrow(newdata), function(i) {\n\t\tnode <- as.numeric(predict(fit_node,newdata[i,]));\n\t\tpred <- as.numeric(predict(model$regs[[node]],newdata[i,]));\n\t\tpred;\n\t});\n}\n\nqrt.plot.tree <- function (model, uniform = TRUE, main = \"Classification Tree\", use.n = FALSE, all = FALSE)\n{\n\tfit_node <- model$rpart;\n\tfit_node$frame$yval <- as.numeric(rownames(fit_node$frame));\n\n\tplot(fit_node,uniform=uniform,main=main);\n\ttext(fit_node, use.n=use.n, all=all, cex=.8);\n}\n\nqrt.regressions <- function (model)\n{\n\tretval <- list()\n\tfor (i in sort(model$index)) retval[[paste(\"Reg-\",i,sep=\"\")]] <- model$regs[[i]]$coefficients[!is.na(model$regs[[i]]$coefficients)];\n\tretval;\n}\n\nqrt.regression.coefficients <- function (model, index)\n{\n\tmodel$regs[[index]]$coefficients[!is.na(model$regs[[index]]$coefficients)];\n}\n\nqrt.regression.model <- function (model, index)\n{\n\tmodel$regs[[index]]$model;\n}\n\nqrt.json <- function (model)\n{\n\tfaux <- model$rpart$frame;\n\tsaux <- model$rpart$splits;\n\tspointer <- 1;\n\n\tjaux <- '';\n\traux <- c(rownames(faux),1);\n\n\tfor (i in 1:nrow(faux))\n\t{\n\t\tif (faux$var[i] == \"\")\n\t\t{\n\t\t\tcaux <- t(model$regs[[as.numeric(raux[i])]]$coefficients);\n\t\t\teaux <- model$error_branch[raux[i],];\n\t\t\tlaux <- '';\n\t\t\tfor (j in 1:length(caux)) laux <- paste(laux,',\"',colnames(caux)[j],'\":\"',caux[j],'\"',sep=\"\");\n\t\t\tlaux <- paste('regression:{',substring(laux,2),'},mae:',eaux$MAE,',mape:',eaux$MAPE,sep=\"\");\n\n\t\t\tjaux <- paste(jaux,'{text:{name:\"',faux$var[i],'\",desc:\"',faux$n[i],':',faux$yval[i],'\"},leaf:',raux[i],',n:',faux$n[i],',yval:',faux$yval[i],',',laux,'}',sep=\"\");\n\t\t\tif (as.numeric(raux[i]) > as.numeric(raux[i+1]))\n\t\t\t{\n\t\t\t\tcurr_level <- ceil(log(as.numeric(raux[i])+1)/log(2));\n\t\t\t\tnext_level <- ceil(log(as.numeric(raux[i+1])+1)/log(2));\n\t\t\t\tfor (j in 1:(curr_level - next_level)) jaux <- paste(jaux,']}',sep=\"\");\n\t\t\t}\n\t\t\tif (i < nrow(faux)) jaux <- paste(jaux,',',sep=\"\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsplit <- saux[spointer,\"index\"];\n\t\t\tineq <- saux[spointer,\"ncat\"];\n\t\t\trelation <- if (ineq == 1) paste('>=',split,sep=\"\") else paste('<',split,sep=\"\");\n\t\t\tspointer <- spointer + faux$ncompete[i] + faux$nsurrogate[i] + 1;\n\n\t\t\tjaux <- paste(jaux,'{text:{name: \"',faux$var[i],relation,'\",desc:\"',faux$n[i],':',faux$yval[i],'\"},var:\"',faux$var[i],'\",relation:',ineq,',split:',split,',leaf:',raux[i],',n:',faux$n[i],',yval:',faux$yval[i],',children:[',sep=\"\");\n\t\t}\n\t}\n\n\tjaux;\n}\n\n###############################################################################\n# Fine-tunning parameters for QRT #\n###############################################################################\n\nqrt.select <- function (vout, vin, traux, tvaux, mintervals, quiet = 1, simple = 1, ...)\n{\n\ttrmae <- NULL;\n\ttvmae <- NULL;\n\tmmin <- 0;\n\tmminmae <- 9e+15;\n\toff_threshold <- 1e-4;\n\tfor (i in mintervals)\n\t{\n\t\tml <- qrt.tree(varout=vout,dataset=data.frame(traux[,c(vout,vin)]),m=i,simple=simple);\n\t\ttrmae <- c(trmae, ml$mae);\n\n\t\tprediction <- qrt.predict(model=ml,newdata=data.frame(tvaux[,c(vout,vin)]));\n\n\t\tmae <- mean(abs(prediction - tvaux[,vout]));\n\t\ttvmae <- c(tvmae,mae);\n\n\t\tif (mae < mminmae - off_threshold) { mmin <- i; mminmae <- mae; }\n\t\tif (quiet == 0) print(paste(\"[INFO]\",i,mae,mmin,mminmae));\n\t}\n\tif (quiet == 0) print (paste(\"Selected M:\",mmin));\t\n\n\tretval <- list();\n\tretval[[\"trmae\"]] <- trmae;\n\tretval[[\"tvmae\"]] <- tvmae;\n\tretval[[\"mmin\"]] <- mmin;\n\tretval[[\"mintervals\"]] <- mintervals;\n\t\n\tretval;\n}\n\n", "meta": {"hexsha": "3d8e9fb3c583927494159063689eb8909f12baf0", "size": 6164, "ext": "r", "lang": "R", "max_stars_repo_path": "aloja-web/resources/models.r", "max_stars_repo_name": "Aloja/aloja", "max_stars_repo_head_hexsha": "ebd336da944bc46443f9f97fe7253af850c608dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-01-23T14:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-28T08:55:01.000Z", "max_issues_repo_path": "aloja-web/resources/models.r", "max_issues_repo_name": "Aloja/aloja", "max_issues_repo_head_hexsha": "ebd336da944bc46443f9f97fe7253af850c608dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2015-10-02T10:20:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-17T15:08:50.000Z", "max_forks_repo_path": "aloja-web/resources/models.r", "max_forks_repo_name": "Aloja/aloja", "max_forks_repo_head_hexsha": "ebd336da944bc46443f9f97fe7253af850c608dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16, "max_forks_repo_forks_event_min_datetime": "2015-06-23T16:59:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T07:20:53.000Z", "avg_line_length": 32.9625668449, "max_line_length": 233, "alphanum_fraction": 0.5832251785, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6039396082263341}} {"text": "#' matmult\n#' \n#' Matrix multiplication for numeric/float matrices.\n#' \n#' @details\n#' If a numeric matrix is multiplied against a float matrix, then if the\n#' \"numeric\" matrix is integers, the integers are promoted to floats. Otherwise,\n#' the float matrix is promoted to doubles.\n#' \n#' @param x,y\n#' Numeric/float matrices.\n#' \n#' @return\n#' A matrix of the same type as the highest precision input.\n#' \n#' @examples\n#' library(float)\n#' \n#' s1 = flrunif(5, 5)\n#' s2 = flrunif(5, 2)\n#' x = matrix(1:25, 5)\n#' \n#' s1 %*% s2 # float\n#' \n#' storage.mode(x) # integer\n#' x %*% s2 # float\n#' \n#' storage.mode(x) = \"double\"\n#' x %*% s2 # double\n#' \n#' @useDynLib float R_matmult_spm\n#' @name matmult\n#' @rdname matmult\nNULL\n\n\n\nmm_float32 = function(x, y)\n{\n ret = .Call(R_matmult_spm, DATA(x), DATA(y))\n float32(ret)\n}\n\nmm_float32_mat = function(x, y)\n{\n if (is.integer(y))\n x %*% fl(y)\n else if (is.double(y))\n dbl(x) %*% y\n else\n stop(\"requires numeric/complex matrix/vector arguments\")\n}\n\nmm_mat_float32 = function(x, y)\n{\n if (is.integer(x))\n fl(x) %*% y\n else if (is.double(x))\n x %*% dbl(y)\n else\n stop(\"requires numeric/complex matrix/vector arguments\")\n}\n\n\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"float32\", y=\"float32\"), mm_float32)\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"float32\", y=\"matrix\"), mm_float32_mat)\n\n#' @rdname matmult\n#' @export\nsetMethod(\"%*%\", signature(x=\"matrix\", y=\"float32\"), mm_mat_float32)\n", "meta": {"hexsha": "96f2e7e960a9092fe3d4a71e7303828b6085311f", "size": 1485, "ext": "r", "lang": "R", "max_stars_repo_path": "R/matmult.r", "max_stars_repo_name": "david-cortes/float", "max_stars_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2017-11-08T11:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-20T20:17:08.000Z", "max_issues_repo_path": "R/matmult.r", "max_issues_repo_name": "david-cortes/float", "max_issues_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37, "max_issues_repo_issues_event_min_datetime": "2017-09-02T11:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-19T15:11:19.000Z", "max_forks_repo_path": "R/matmult.r", "max_forks_repo_name": "david-cortes/float", "max_forks_repo_head_hexsha": "df58b4040a352f006c299233c2c920e11b0dcae3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2017-11-18T18:05:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T01:23:23.000Z", "avg_line_length": 19.2857142857, "max_line_length": 80, "alphanum_fraction": 0.6296296296, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.603742795553745}} {"text": "# Script about parental age influence\nlibrary(RColorBrewer)\n\n# Import and format data:\ndata_mut <- read.csv(\"mutation_rate.txt\", sep =\" \", header=FALSE) # mutation_rate.txt is obtained during the detection of de novo mutation\nage_father=read.csv(\"male_age.txt\", sep =\" \", header=FALSE) # one column with father age\nage_mother=read.csv(\"female_age.txt\", sep =\" \", header=FALSE) # one column with mother age\nfa=read.csv(\"father.txt\", sep =\" \", header=FALSE) # one column with father ID\nmo=read.csv(\"mother.txt\", sep =\" \", header=FALSE) # one column with mother age\ndata=cbind(data_mut[,1:2],age_father, age_mother, fa, mo)\n\n# Parental correlation on mutation rate ######\n# Simple correlation:\n\n# Linear model for both age\nfit <- lm(data[,2] ~ data[,3] + data[,4], data=data)\nsummary(fit)\n\n# Predict mu with this model\nmu_list=vector()\nfor(i in seq(1,nrow(data))){\n mu = 1.355e-09+(4.588e-10*data[i,3])+(7.936e-11*data[i,4])\n mu_list=c(mu_list, mu)\n}\ncor.test(mu_list, data[,2], method=\"pearson\")\n\nfit <- lm(data[,2] ~ mu_list)\nsummary(fit) # show results\n\npng(\"model.png\", width = 1300, height = 850)\npar(mar=c(10,15,4,2), mgp=c(3, 3, 0))\nplot(mu_list, data[,2], pch=19, xlab=\"\", ylab=\"\", xlim=c(4e-9,1.2e-8), ylim=c(4e-9,1.2e-8),cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\")\naxis(1, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08, 1.2e-08),label=c(\"0.4\",\"0.5\",\"0.6\", \"0.7\", \"0.8\",\"0.9\",\"1.0\",\"1.1\",\"1.2\"), cex.axis=4)\naxis(2, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08, 1.2e-08),label=c(\"0.4\",\"0.5\",\"0.6\", \"0.7\", \"0.8\",\"0.9\",\"1.0\",\"1.1\",\"1.2\"),cex.axis=4, las=2)\nmtext(expression(\"Expected mutation rate x 10\"^-8), 1, line=8, cex=3.5)\nmtext(expression(\"Observed mutation rate x 10\"^-8), 2, line=9, cex=3.5)\nabline(3.765e-13,1.000e+00, lty=2, lwd=3, col=\"grey40\")\ntext(c(1.15e-08,1.155e-08), c(0.9e-08, 0.95e-08), labels = c(\"r = 0.54\", \"p = 0.016\"), font=2, cex=3.5)\ntext(1.00e-8, 1.18e-8, expression(paste(mu, \" = 1.36e\"^-9, \"+ 7.94e\"^-11, \"× a\"[mat], \"+ 4.59e\"^-10, \"× a\"[pat])), font=2, cex=2)\ndev.off()\n\n# Father correlation ##################################################\n\nlinearMod_father <- lm(data[,2] ~ data[,3], data=data)\nsummary(linearMod_father)\n## confidence interval with predict\na <- data[,3]\nm <- data[,2]\nlinearMod_father <- lm(m ~ a)\nnewx = seq(4,17,by = 0.5)\nconf_interval <- predict(linearMod_father, newdata=data.frame(a=newx), interval=\"confidence\",level = 0.95)\n\npng(\"father_age_pred.png\", width = 1300, height = 850)\npar(mar=c(9,23,4,2), mgp=c(3, 3, 0))\nplot(data[,3], data[,2], pch=19, xlab=\"\", ylab=\"\", xlim=c(3,16), cex=3, cex.lab=2.5, cex.axis=2.5, col=\"blue\", xaxt=\"n\", yaxt=\"n\")\nbluetrans <- rgb(204, 229, 255, 255, maxColorValue=255)\npolygon(c(newx, rev(newx)), c(conf_interval[,2], rev(conf_interval[,3])),\n col = bluetrans, border = NA)\npoints(data[,3], data[,2], pch=19, cex=3, cex.lab=2.5, cex.axis=2.5, col=\"blue\")\nabline(1.022e-09, 5.393e-10, lwd=3, lty=2, col=\"darkblue\")\naxis(1, cex.axis=4)\naxis(2, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08),label=c(expression(\"0.4 x 10\"^-8), expression(\"0.5 x 10\"^-8), expression(\"0.6 x 10\"^-8), expression(\"0.7 x 10\"^-8), expression(\"0.8 x 10\"^-8), expression(\"0.9 x 10\"^-8), expression(\"1.0 x 10\"^-8), expression(\"1.1 x 10\"^-8)),cex.axis=4, las=2)\nmtext(\"Paternal age\", 1, line=7, cex=4.5)\nmtext(\"Mutation rate (per generation)\", 2, line=20, cex=4.5)\ntext(c(4.1,4.6), c(1.12e-08, 1.06e-08), labels = c(expression(paste(R[adj]^2,\" = 0.23\")), \"p = 0.021\"), font=2, cex=3.5)\ndev.off()\n\n# Mother effect #################################################\nlinearMod_mother <- lm(data[,2] ~ data[,4], data=data)\nsummary(linearMod_mother)\na <- data[,4]\nm <- data[,2]\nlinearMod_mother <- lm(m ~ a)\nnewx = seq(3,17,by = 0.5)\nconf_interval <- predict(linearMod_mother, newdata=data.frame(a=newx), interval=\"confidence\",level = 0.95)\n\npng(\"mother_age_pred.png\", width = 1300, height = 850)\npar(mar=c(9,23,4,2), mgp=c(3, 3, 0))\nplot(data[,4], data[,2], pch=19, xlab=\"\", ylab=\"\", xlim=c(3,16), cex=3, cex.lab=2.5, cex.axis=2.5, col=\"red2\", xaxt=\"n\", yaxt=\"n\")\npinktrans <- rgb(255, 190, 190, 255, maxColorValue=255)\npolygon(c(newx, rev(newx)), c(conf_interval[,2], rev(conf_interval[,3])),\n col = pinktrans, border = NA)\npoints(data[,4], data[,2], pch=19, cex=3, cex.lab=2.5, cex.axis=2.5, col=\"red2\")\nabline(6.200e-09, 1.818e-10, lwd=3, lty=2, col=\"red3\")\naxis(1, cex.axis=4)\naxis(2, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08),label=c(expression(\"0.4 x 10\"^-8), expression(\"0.5 x 10\"^-8), expression(\"0.6 x 10\"^-8), expression(\"0.7 x 10\"^-8), expression(\"0.8 x 10\"^-8), expression(\"0.9 x 10\"^-8), expression(\"1.0 x 10\"^-8), expression(\"1.1 x 10\"^-8)),cex.axis=4, las=2)\nmtext(\"Maternal age\", 1, line=7, cex=4.5)\nmtext(\"Mutation rate (per generation)\", 2, line=20, cex=4.5)\ntext(c(4.1,4.6), c(1.12e-08, 1.06e-08), labels = c(expression(paste(R[adj]^2,\" = 0.09\")), \"p = 0.111\"), font=2, cex=3.5)\ndev.off()\n\n## Age parents and phasing ##########################################\npoo <- read.csv(\"assigned_each.tab\", sep =\"\\t\") # obtained from the phasing script\npoo_p_p <- poo$prop_paternal[-20]\npoo_p_m <- poo$prop_maternal[-20]\npoo_p <- poo$paternal[-20]\npoo_m <- poo$maternal[-20]\npoo_n_p <- poo$paternal[-20]/poo$tot_pat[-20]\npoo_n_m <- poo$maternal[-20]/poo$tot_mat[-20]\npoo_np_p <- (poo_n_p)/(poo_n_p+poo_n_m)\npoo_np_m <- (poo_n_m)/(poo_n_p+poo_n_m)\npoo_i_p <- round((poo$unassigned+poo$assigned)[-20]*poo_np_p)\npoo_i_m <- round((poo$unassigned+poo$assigned)[-20]*poo_np_m)\n##\ndata_p <- cbind(data, poo_p_p, poo_p_m)\ncolnames(data_p)<-c(\"name\", \"mut\", \"p_age\", \"m_age\", \"p\", \"m\", \"poo_p_p\", \"poo_p_m\")\nlim_inf=min(data_p$p_age, data_p$m_age)\nlim_sup=max(data_p$p_age, data_p$m_age)\n##\n\n## MODEL on upscaled LINEAR\ndata_i <- cbind(data, poo_i_p, poo_i_m)\ncolnames(data_i)<-c(\"name\", \"mut\", \"p_age\", \"m_age\", \"p\", \"m\", \"poo_i_p\", \"poo_i_m\")\nlim_inf=min(data_p$p_age, data_p$m_age)\nlim_sup=max(data_p$p_age, data_p$m_age)\n\nreg_age_f <- lm(data_i$poo_i_p ~ data_i$p_age)\nsummary(reg_age_f)\nreg_age_m <- lm(data_i$poo_i_m ~ data_i$m_age)\nsummary(reg_age_m)\ncor.test(data_i$poo_i_p, data_i$p_age, method=\"pearson\")\ncor.test(data_i$poo_i_m, data_i$m_age, method=\"pearson\")\nconfint(reg_age_f)\nconfint(reg_age_m)\n\n## confidence interval\na1=data_i$p_age\nm=data_i$poo_i_p\nfit<- lm(m ~ a1)\nnew1 = seq(4,17,by = 1)\nconf_interval <- predict(fit, newdata=data.frame(a1=new1), interval=\"confidence\",level = 0.95)\na_f=new1\nconf_f=conf_interval\n#\na1=data_i$m_age\nm=data_i$poo_i_m\nfit<- lm(m ~ a1)\nnew1 = seq(3,17,by = 1)\nconf_interval <- predict(fit, newdata=data.frame(a1=new1), interval=\"confidence\",level = 0.95)\na_m=new1\nconf_m=conf_interval\n\n# Plot model\npng(\"infer_given.png\", width = 1300, height = 850)\npar(mar=c(9,12,4,2), mgp=c(3, 3, 0))\nplot(data_i$p_age, data_i$poo_i_p, col=\"blue\", pch=19, ylim=c(0,40), xlim=c(0, lim_sup), xlab=\"\", ylab=\"\",cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\")\nbluetrans <- rgb(204, 229, 255, 255, maxColorValue=255)\npolygon(c(a_f, rev(a_f)), c(conf_f[,2], rev(conf_f[,3])), col = bluetrans, border = NA)\npinktrans <- rgb(255, 190, 190, 255, maxColorValue=255)\npolygon(c(a_m, rev(a_m)), c(conf_m[,2], rev(conf_m[,3])), col = pinktrans, border = NA)\npoints(data_i$p_age, data_i$poo_i_p, col=\"blue\", pch=19,cex=3)\npoints(data_i$m_age, data_i$poo_i_m, col=\"red2\", pch=19,cex=3)\nsegments(4, 4.8399 + (1.8364*4), 20, 4.8399 + (1.8364*20), lwd=3, lty=2, col=\"blue\")\ntext(c(14.5,15), c(21.5, 18.5), labels = c(expression(paste(R[adj]^2,\" = 0.41\")), \"p = 0.002\"), font=2, cex=3, col=\"blue\")\nsegments(3, 4.6497+ (0.3042*3), 20, 4.6497+ (0.3042*20), lwd=3, lty=2, col=\"red2\")\ntext(c(14.5,15), c(4.5, 1.5), labels = c(expression(paste(R[adj]^2,\" = -0.01\")), \"p = 0.38\"), font=2, cex=3, col=\"red2\")\narrows(3,20,3,4.6497+ (0.3042*3), lwd=2, lty=1, col=\"red2\")\narrows(4,20,4,4.8399 + (1.8364*4), lwd=2, lty=1, col=\"blue\")\ntext(3.5, 22, \"Puberty\", cex=3.5, font=2)\nlegend(\"topleft\", legend=c(\"Maternal\", \"Paternal\"), pch=c(19,19), col=c(\"red2\", \"blue\"), text.font=2, cex=3.5, bty = \"n\")\naxis(1, cex.axis=4)\naxis(2, cex.axis=4, las=2)\nmtext(\"Parental age\", 1, line=7, cex=4)\nmtext(\"Upscaled phased mutations\", 2, line=8, cex=4)\ndev.off()\n\n\n## Test of the model\n# Predict mu with this model\nnb_list=vector()\nfor(i in seq(1,nrow(data))){\n nb = (4.8399 + 1.8364*data[i,3]) + (4.6497+ 0.3042*data[i,4])\n nb_list=c(nb_list, nb)\n}\ncall <- read.csv(\"../../de_novo_mutation/callability.txt\", sep =\" \", header=FALSE)\ncallability=mean(call[,2])\nfnr=0.04020232294960846\nmu_infer=(nb_list*(1-0.10887096774193548))/(2*callability*(1-fnr))\n\ncor.test(mu_infer, data[,2], method=\"pearson\")\nfit <- lm(data[,2] ~ mu_infer)\nsummary(fit) # show results\n\npng(\"model_upscaled_mu.png\", width = 1300, height = 850)\npar(mar=c(10,15,4,2), mgp=c(3, 3, 0))\nplot(mu_infer, data[,2], pch=19, xlab=\"\", ylab=\"\", xlim=c(4.0e-9,1.2e-8), ylim=c(4.0e-9,1.2e-8),cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\")\naxis(1, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08, 1.2e-08),label=c(\"0.4\", \"0.5\", \"0.6\", \"0.7\", \"0.8\",\"0.9\",\"1.0\",\"1.1\",\"1.2\"), cex.axis=4)\naxis(2, at=c(4.0e-09, 5.0e-09, 6.0e-09, 7.0e-09, 8.0e-09, 9.0e-09, 1.0e-08, 1.1e-08, 1.2e-08),label=c(\"0.4\", \"0.5\", \"0.6\", \"0.7\", \"0.8\",\"0.9\",\"1.0\",\"1.1\",\"1.2\"),cex.axis=4, las=2)\nmtext(expression(\"Expected mutation rate x 10\"^-8), 1, line=8, cex=3.5)\nmtext(expression(\"Observed mutation rate x 10\"^-8), 2, line=9, cex=3.5)\nabline(-1.064e-09, 1.277, lty=2, lwd=3, col=\"grey40\")\ntext(c(1.15e-08,1.155e-08), c(1.0e-08, 1.05e-08), labels = c(\"r = 0.54\", \"p = 0.016\"), font=2, cex=3.5)\ntext(0.77e-8, 1.165e-8, expression(paste(mu, \" =\")), font=2, cex=2)\nsegments(0.8e-8, 1.165e-8, 1.2e-8, 1.165e-8, lwd=2, lty=1)\ntext(1.0e-8, 1.19e-8, expression(paste(\"(4.65 + 0.30 × a\"[mat], \" + 4.84 + 1.84 × a\"[pat],\") x (1-0.089)\")), font=2, cex=2)\ntext(1.0e-8, 1.14e-8, expression(paste(\"2 x 2351302179 x (1-0.0402)\")), font=2, cex=2)\ndev.off()\n\n\n### Same with Poisson #################################\n## MODEL on upscaled POISSON\ndata_i <- cbind(data, poo_i_p, poo_i_m)\ncolnames(data_i)<-c(\"name\", \"mut\", \"p_age\", \"m_age\", \"p\", \"m\", \"poo_i_p\", \"poo_i_m\")\nlim_inf=min(data_p$p_age, data_p$m_age)\nlim_sup=max(data_p$p_age, data_p$m_age)\n\n# Regression\nreg_age_f <- glm(data_i$poo_i_p ~ data_i$p_age, family = poisson)\nsummary(reg_age_f)\n##reg_age_f <- glm(data_i$poo_i_p ~ data_i$p_age*data_i$p, family = poisson)\nreg_age_m <- glm(data_i$poo_i_m ~ data_i$m_age, family = poisson)\nsummary(reg_age_m)\n##\na1=data_i$p_age\nm=data_i$poo_i_p\nfit<- glm(m ~ a1, family = poisson)\nnew1 = seq(4,17,by = 0.5)\nconf_interval <- predict(fit, newdata=data.frame(a1=new1), interval=\"confidence\", type=\"response\", level = 0.95, se.fit = TRUE)\na_f=new1\nconf_f=conf_interval$fit\nuci_f=conf_interval$fit+1.96*conf_interval$se.fit\nlci_f=conf_interval$fit-1.96*conf_interval$se.fit\n#\n# Female\na1=data_i$m_age\nm=data_i$poo_i_m\nfit<- glm(m ~ a1, family = poisson)\nnew1 = seq(3,17,by = 0.5)\nconf_interval <- predict(fit, newdata=data.frame(a1=new1), interval=\"confidence\", type=\"response\", level = 0.95, se.fit = TRUE)\na_m=new1\nconf_m=conf_interval$fit\nuci_m=conf_interval$fit+1.96*conf_interval$se.fit\nlci_m=conf_interval$fit-1.96*conf_interval$se.fit\n#\n\n##plot\npng(\"infer_given_poisson.png\", width = 1300, height = 850)\npar(mar=c(9,12,4,2), mgp=c(3, 3, 0))\nplot(data_i$p_age, data_i$poo_i_p, col=\"blue\", pch=19, ylim=c(0,40), xlim=c(0, lim_sup), xlab=\"\", ylab=\"\",cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\")\nbluetrans <- rgb(204, 229, 255, 255, maxColorValue=255)\npolygon(c(a_f, rev(a_f)), c(lci_f, rev(uci_f)),col = bluetrans, border = NA)\npinktrans <- rgb(255, 190, 190, 255, maxColorValue=255)\npolygon(c(a_m, rev(a_m)), c(lci_m, rev(uci_m)),col = pinktrans, border = NA)\nlines(a_f, conf_f, lwd=3, lty=2, col=\"blue\")\nlines(a_m, conf_m, lwd=3, lty=2, col=\"red2\")\npoints(data_i$p_age, data_i$poo_i_p, col=\"blue\", pch=19, cex=3)\npoints(data_i$m_age, data_i$poo_i_m, col=\"red2\", pch=19, cex=3)\n##text(c(9,6.2), c(39, 36), labels = c(\"nb = exp(2.14+0.089xage)\", \"p < 0.001\"), font=2, cex=3, col=\"blue\")\n##text(c(13,10.8), c(6, 3), labels = c(\"nb = exp(1.35+0.067xage)\", \"p < 0.01\"), font=2, cex=3, col=\"red2\")\nlegend(\"topleft\", legend=c(\"Maternal\", \"Paternal\"), pch=c(19,19), col=c(\"red2\", \"blue\"), text.font=2, cex=3.5, bty = \"n\")\naxis(1, cex.axis=4)\naxis(2, cex.axis=4, las=2)\nmtext(\"Parental age\", 1, line=7, cex=4)\nmtext(\"Upscaled phased mutations\", 2, line=8, cex=4)\ndev.off()\n\n\n### Box plot contribution ##################################################################\npng(\"norm_prop_box.png\", width = 1300, height = 850)\n##png(\"norm_prop_box.png\", width = 950, height = 850)\npar(mar=c(9,17,4,2), mgp=c(3, 3, 0))\nboxplot(poo_np_m, poo_np_p, ylim=c(0,1), names=c(\"\",\"\"), ylab=\"\", cex=3, cex.lab=2.5, cex.axis=2.5, col=c(\"red2\",\"blue\"), yaxt=\"n\")\naxis(2, cex.axis=3.5, las=2)\nmtext(\"Proportion of phased\", 2, line=12, cex=4)\nmtext(expression(italic(de~novo)~mutations), 2, line=9, cex=4)\naxis(1, at=c(1,2), label=c(\"Maternal\", \"Paternal\"), cex.axis=4)\ndev.off()\n#\n\n# Stats\nse=sd(poo_np_p)/sqrt(length(poo_np_p))\nse\nmean(poo_np_p)-(2.1*se)\nmean(poo_np_p)+(2.1*se)\n\n# t test ####################################################\nt.test(poo_np_p,poo_np_m)\n", "meta": {"hexsha": "721f72ac00d10ad5f79d4093ec86202876038038", "size": 13315, "ext": "r", "lang": "R", "max_stars_repo_path": "7_analysis/age.r", "max_stars_repo_name": "lucieabergeron/germline_mutation_rate", "max_stars_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7_analysis/age.r", "max_issues_repo_name": "lucieabergeron/germline_mutation_rate", "max_issues_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7_analysis/age.r", "max_forks_repo_name": "lucieabergeron/germline_mutation_rate", "max_forks_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8956834532, "max_line_length": 327, "alphanum_fraction": 0.6334209538, "num_tokens": 5718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6030502360571453}} {"text": "#hierarchically aggregate multivariate composition data c/p/s using dirchlet.\n#start 3 groups, 4 sites, plots w/in site, cores w/in plots.\n#works ignoring plots within sites.\n#Next add plots in between core and site level.\nrm(list=ls())\nlibrary(runjags)\n\n#1. generate pseudo data.----\n#3 species relative abundances across 4 sites.\nspp1 <- c(0.2,0.8,0.5,0.1)\nspp2 <- c(0.3,0.1,0.4,0.1)\nspp3 <- 1 - (spp1 + spp2)\ny <- data.frame(spp1,spp2,spp3)\ny <- as.matrix(y)\nsite_sd <- 0.02\n\n#get some numbevr of pltos and cores within plots.\nn.site <- nrow(y)\nn.plot <- 15\nn.core <- 10\n\n#simulate from dirichlet distribution.\nsite.list <- list()\nfor(i in 1:n.site){\n plot.list <- list()\n for(j in 1:n.plot){\n cores <- DirichletReg::rdirichlet(n.core,y[i,])\n cores <- data.frame(cbind(rep(LETTERS[i],n.core),rep(LETTERS[j],n.core),LETTERS[1:n.core],cores))\n colnames(cores) <- c('siteID','plotID','coreID','spp1','spp2','spp3')\n plot.list[[j]] <- cores\n }\n site.list[[i]] <- do.call(rbind,plot.list)\n}\ndat <- do.call(rbind,site.list)\ndat[,4:6] <- sapply(dat[4:6],as.character)\ndat[,4:6] <- sapply(dat[4:6],as.numeric)\ny <- dat[,4:6]\n\n#core_plot, plot_site factors.\ndat$plotID <- paste0(dat$siteID,'_',dat$plotID)\ncore_plot = dat$plotID\nplot_site = dat[seq(1, nrow(dat), 3), ]$siteID\n\n\n#2. specify JAGS model.----\njags.model = \"\nmodel {\n#get plot level means.\nfor(i in 1:N.core){\n for(j in 1:N.spp){\n log(core.hat[i,j]) <- alpha + plot_mu[core_plot[i],j]\n }\n y[i,1:N.spp] ~ ddirch(core.hat[i,1:N.spp]) \n}\n\n#get site level means.\nfor(i in 1:N.plot){\n for(j in 1:N.spp){\n #log(plot.hat[i,j]) <- alpha + site_mu[plot_site[i],j]\n log(plot.hat[i,j]) <- site_mu[plot_site[i],j]\n }\n plot_mu[i,1:N.spp] ~ ddirch(plot.hat[i,1:N.spp])\n}\n\n#prior\n#for(i in 1:N.site){for(j in 1:N.spp){site_mu[i,j] ~ dnorm(0,1E-3)}}\nalpha ~ dnorm(0, 1.0E-3) \nfor(i in 1:N.site){\n site_mu[i,1] <- 0\n for(j in 2:N.spp){\n site_mu[i,j] ~ dnorm(0,1E-3)\n }\n}\n\n#map to something useful.\n#for(i in 1:N.site){\n# final_mu[i,1] <- alpha\n# for(j in 2:N.spp){\n# final_mu[i,j] <- site_mu[i,j] + alpha\n# }\n# }\n}\"\n\n#3. Setup JAGS data object.----\njd <- list(y=as.matrix(y), N.site = n.site, N.core = nrow(y), N.plot = length(unique(dat$plotID)), N.spp = ncol(y), \n core_plot = as.factor(core_plot),\n plot_site = as.factor(plot_site))\n\n#4. Run JAGS model.----\ntest <- run.jags(model = jags.model,\n data = jd,\n n.chains = 3,\n monitor = c('site_mu'),\n adapt = 200,\n burnin = 2000,\n sample = 1000)\nout <- summary(test)\nspp.sum <- matrix(out[,4], nrow = n.site, ncol = ncol(y))\nspp.sum <- boot::inv.logit(spp.sum) / rowSums(boot::inv.logit(spp.sum))\nspp.sum\n", "meta": {"hexsha": "e3834dd86300863656152370759336d4ce825ab0", "size": 2770, "ext": "r", "lang": "R", "max_stars_repo_path": "testing_development/hierarchical means ddirch JAGS.r", "max_stars_repo_name": "bhackos/NEFI_microbe", "max_stars_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing_development/hierarchical means ddirch JAGS.r", "max_issues_repo_name": "bhackos/NEFI_microbe", "max_issues_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-10-23T16:09:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T16:01:10.000Z", "max_forks_repo_path": "testing_development/hierarchical means ddirch JAGS.r", "max_forks_repo_name": "bhackos/NEFI_microbe", "max_forks_repo_head_hexsha": "e08694f4fe8d4b524df5c3854d19da49787716ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2017-10-09T18:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-06T19:17:07.000Z", "avg_line_length": 27.4257425743, "max_line_length": 116, "alphanum_fraction": 0.5992779783, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6030122248981784}} {"text": "powers = function(m)\n {n = -1\n function()\n {n <<- n + 1\n n^m}}\n\nnoncubic.squares = local(\n {squares = powers(2)\n cubes = powers(3)\n cube = cubes()\n function()\n {square = squares()\n while (1)\n {if (square > cube)\n {cube <<- cubes()\n next}\n else if (square < cube)\n {return(square)}\n else\n {square = squares()}}}})\n\nfor (i in 1:20)\n noncubic.squares()\nfor (i in 1:10)\n message(noncubic.squares())\n", "meta": {"hexsha": "35919593be98322cc423c71125fef58b48076ecf", "size": 532, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Generator-Exponential/R/generator-exponential.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Generator-Exponential/R/generator-exponential.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/Generator-Exponential/R/generator-exponential.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 20.4615384615, "max_line_length": 39, "alphanum_fraction": 0.4454887218, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6027299718130705}} {"text": "model_soilheatflux <- function (netRadiationEquivalentEvaporation = 638.142,\n tau = 0.9983,\n soilEvaporation = 448.24){\n #'- Name: SoilHeatFlux -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: SoilHeatFlux Model\n #' * Author: Pierre Martre\n #' * Reference: Modelling energy balance in the wheat crop model SiriusQuality2:\n #' Evapotranspiration and canopy and soil temperature calculations\n #' * Institution: INRA/LEPSE Montpellier\n #' * Abstract: The available energy in the soil \n #'- inputs:\n #' * name: netRadiationEquivalentEvaporation\n #' ** variablecategory : state\n #' ** description : net Radiation Equivalent Evaporation\n #' ** datatype : DOUBLE\n #' ** default : 638.142\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: tau\n #' ** description : plant cover factor\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** default : 0.9983\n #' ** min : 0\n #' ** max : 100\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: soilEvaporation\n #' ** description : soil Evaporation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 448.240\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #'- outputs:\n #' * name: soilHeatFlux\n #' ** description : soil Heat Flux \n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : g m-2 d-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n soilHeatFlux <- tau * netRadiationEquivalentEvaporation - soilEvaporation\n return (list('soilHeatFlux' = soilHeatFlux))\n}", "meta": {"hexsha": "a8d0d92d277f9cd655f71ae2cd75e8d573580ae0", "size": 2941, "ext": "r", "lang": "R", "max_stars_repo_path": "test/Models/energybalance_pkg/src/r/Soilheatflux.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/Models/energybalance_pkg/src/r/Soilheatflux.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/Models/energybalance_pkg/src/r/Soilheatflux.r", "max_forks_repo_name": "brichet/PyCrop2ML", "max_forks_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-01-15T04:33:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-09T07:29:46.000Z", "avg_line_length": 54.462962963, "max_line_length": 96, "alphanum_fraction": 0.399183951, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6026458294015855}} {"text": "subroutine sknotl(x,n,knot,k)\nimplicit double precision(a-h,o-z) \ndouble precision x(n),knot(n+6),a1,a2,a3,a4\ninteger n,k,ndk,j\n\n\n # Allocate knots acording to the cutoffs given below\n\n\n\t# Cutoff constants\n\n\t a1 = log(50d0)/log(2d0) ; a2 = log(100d0)/log(2d0)\n\t a3 = log(140d0)/log(2d0) ; a4 = log(200d0)/log(2d0)\n\n\t# Cutoff Criteria\n\n if(n<50) { ndk = n }\n else if (n>=50 & n<200) { ndk = 2.**(a1+(a2-a1)*(n-50.)/150.) }\n else if (n>=200 & n<800) { ndk = 2.**(a2+(a3-a2)*(n-200.)/600.) }\n else if (n>=800 & n<3200) { ndk = 2.**(a3+(a4-a3)*(n-800.)/2400.) }\n else if (n>=3200) { ndk = 200. + float(n-3200)**.2 }\n\t\t \n\t\t k = ndk + 6\n\n \n # Allocate Knots ( note no account is taken of any weighting vector )\n\n\tdo j=1,3 { knot(j) = x(1) }\n\tdo j=1,ndk { knot(j+3) = x( 1 + (j-1)*(n-1)/(ndk-1) ) }\n\tdo j=1,3 { knot(ndk+3+j) = x(n) }\n\nreturn\nend\nsubroutine splsm(x,y,w,n,match,nef,spar,dof,smo,s0,cov,ifcov,work)\n#This subroutine performs a smoothing spline fit\n# This was written by Trevor Hastie in 1990\n# It has been modified from the S3 version by Trevor Hastie\n# in July 2004, to accommodate the modified sbart routine in R\n# and also to accommodate only the gam bakfit routine.\n# Note that spar has changed, and we change it here to conform with\n# the smooth.spline routine in R\n#All arguments are either double precision or integer\n#INPUT\n#\n#x\tdouble length n ; x variable for smoothing\n#y\tdouble length n\t; y variable for smoothing\n#w\tdouble length n ; weights for smoothing, > 0\n#n\tinteger length above\n#match \tinteger length n -- in S language x[i] == sort(unique(x)[match[i]]\n#\t\tmatch is produced by subroutine namat\n#nef\tnumber of unique elements in x; so match has values between 1 and nef+1\n#\t\tmissing data are given the match number nef+1\n#spar\tdouble smoothing parameter -1.5 =1, dof is used\n#\t\tnote: dof does not use the constant term\n#ifcov\tinteger if 1, the unscaled variance information is computed\n#work\tdouble workspace of length (10+2*4)*(nef+2)+5*nef+n+15\n#\n#OUTPUT\n#\n#x,y,w,n,match,nef are untouched\n#spar\tif dof > 1, then spar is that which achieves dof\n#dof\tthe dof of the fitted smooth. Note: even if dof was given\n#\t\tas 4, it will be returned as say 3.995 which is what\n#\t\tspar produces\n#smo\tdouble length n the fitted values, with weighted average 0\n#s0\tdouble weighted mean of y\n#cov\tdouble length nef the unscaled variance elements for the NONLINEAR\n#\t\tand UNIQUE part of smo, in the order of sort(unique(x))\n#\t\tcov is lev(i)/w(i) -h(i)/w where h(i) is the hat element from\n#\t\tthe simple weighted least squares fit. This is passed on\n#\t\tto bakfit and used in gamcov\n#\n# splsm calls (eventually after some memory management dummy calls)\n# sbart, the spline routine of Finbarr O'Sullivan, slightly modified\n# by Trevor Hastie, 8/2/89\t\n\nimplicit double precision(a-h,o-z)\ndouble precision x(*),y(*),w(*),spar,dof,smo(*),s0,cov(*),work(*)\ninteger n,match(*),nef\ninteger ifcov\n# work should be (10+2*ld4)*nk+5*nef+n+15 double\n# ld4 =4 nk<= nef+2\ncall splsm1(x,y,w,n,match,nef,spar,dof,smo,s0,cov,ifcov,\n#\txin(nef+1),yin(nef+1), win(nef+1), knot(n+6),\n\twork(1), work(nef+2),work(2*nef+3),work(3*nef+4),\n\twork(3*nef+n+10))\nreturn\nend\n\nsubroutine splsm1(x,y,w,n,match,nef,spar,dof,smo,s0,lev,ifcov,\n\t\txin,yin,win,knot,\n\t\twork)\nimplicit double precision(a-h,o-z)\ndouble precision x(*),y(*),w(*),spar,dof,smo(*),s0,lev(*),work(*)\ninteger n,match(*),nef\ninteger ifcov\ndouble precision xin(nef+1),yin(nef+1),win(nef+1),knot(nef+6)\ninteger nk,ldnk,ld4,k\ndouble precision xmin,xrange\ncall suff(n,nef,match,x,y,w,xin,yin,win,work(1))\nxmin=xin(1)\nxrange=xin(nef)-xin(1)\ndo i=1,nef {xin(i)=(xin(i)-xmin)/xrange}\ncall sknotl(xin,nef,knot,k)\nnk=k-4\nld4=4\nldnk=1 # p21p nd ldnk is not used\ncall splsm2(x,y,w,n,match,nef,spar,dof,smo,s0,lev,ifcov,\n\t\txin,yin,win,knot,\n# coef(nk),sout(nef+1), levout(nef+1), xwy(nk),\n#\ths0(nk), hs1(nk), hs2(nk),\n# hs3(nk),\n#\tsg0(nk), sg1(nk), sg2(nk),\n# sg3(nk),\n#\tabd(ld4,nk), p1ip(ld4,nk),\n# p2ip(ldnk,nk)\n\twork(1), work(nk+1), work(nk+nef+2),work(nk+2*nef+3),\n\twork(2*nk+2*nef+3),work(3*nk+2*nef+3),work(4*nk+2*nef+3),\n\twork(5*nk+2*nef+3),\n\twork(6*nk+2*nef+3),work(7*nk+2*nef+3),work(8*nk+2*nef+3),\n\twork(9*nk+2*nef+3),\n\twork(10*nk+2*nef+3),work((10+ld4)*nk+2*nef+3),\n\twork((10+2*ld4)*nk+2*nef+3),\n\tld4,ldnk,nk)\n\nreturn\nend\nsubroutine splsm2(x,y,w,n,match,nef,spar,dof,smo,s0,lev,ifcov,\n\t\txin,yin,win,knot,\n\t\tcoef,sout,levout,xwy,\n\t\ths0,hs1,hs2,hs3,\n\t\tsg0,sg1,sg2,sg3,\n\t\tabd,p1ip,p2ip,ld4,ldnk,nk)\nimplicit double precision(a-h,o-z)\ndouble precision x(*),y(*),w(*),spar,dof,smo(*),s0,lev(*)\ninteger n,match(*),nef\ninteger nk,ldnk,ld4\ninteger ifcov\ndouble precision xin(nef+1),yin(nef+1),win(nef+1),knot(nk+4)\ndouble precision coef(nk),sout(nef+1),levout(nef+1),xwy(nk),\n\t \ths0(nk),hs1(nk),hs2(nk),hs3(nk),\n \tsg0(nk),sg1(nk),sg2(nk),sg3(nk),\n\t \tabd(ld4,nk),p1ip(ld4,nk),p2ip(ldnk,*)\n# local variables\ninteger ispar,icrit,isetup,ier\ndouble precision lspar,uspar,tol,penalt,\n\t\tsumwin,dofoff,crit,xbar,dsum,xsbar\ndouble precision yssw, eps\ninteger maxit\n# yssw is an additional parameter introduced in R version of sbart\ndouble precision wmean\ncrit=0d0\n# Note we only allow limited options here\nif(dof <= 0d0){\n# use spar \n ispar=1\n icrit=3\n dofoff=0d0\n }\nelse{\n if( dof < 1d0 )dof=1d0\n ispar=0\n icrit=3\n dofoff=dof+1d0\n}\n#Here we set some default parameters similar to the smooth.spline in R\nisetup=0\nier=1\npenalt=1d0\nlspar= -1.5\nuspar= 2.0\ntol=1d-4\neps=2d-8\nmaxit=200\ndo i=1,nef\n sout(i)=yin(i)*yin(i)\nsumwin=0d0\ndo i=1,nef \n\tsumwin=sumwin+win(i)\nyssw=wmean(nef,sout,win)\ns0=wmean(n,y,w)\n# which should be equal to wmean(nef,yin,win)\nyssw=yssw*(sumwin-s0*s0)\n\ncall sbart(penalt,dofoff,xin,yin,win,yssw,nef,knot,nk,\n\t\t coef,sout,levout,crit,\n icrit,spar,ispar,maxit,\n lspar,uspar,tol,eps,\n\t\t isetup,\n\t\t xwy,\n\t\t hs0,hs1,hs2,hs3,\n\t\t sg0,sg1,sg2,sg3,\n\t\t abd,p1ip,p2ip,ld4,ldnk,ier)\n#return\n#now clean up \ndo i=1,nef {\n\twin(i)=win(i)*win(i) #we sqrted them in sbart\n\t}\nsbar=wmean(nef,sout,win)\nxbar=wmean(nef,xin,win)\n\n\n#now remove the linear leverage from the leverage for the smooths\n# will be altered at this stage\ndo i=1,nef {lev(i)=(xin(i)-xbar)*sout(i)\t}\nxsbar=wmean(nef,lev,win)\ndo i=1,nef {lev(i)=(xin(i)-xbar)**2\t}\ndsum=wmean(nef,lev,win)\ndo i=1,nef {\n\tif(win(i)>0d0) {\n\t\tlev(i)=levout(i)/win(i)-1d0/sumwin -lev(i)/(sumwin*dsum)\n\t\t}\n\telse {lev(i)=0d0}\n\t}\ndof=0d0\ndo i=1,nef {dof=dof+lev(i)*win(i)}\ndof=dof+1d0\ndo i=1,nef\n\tsout(i)=sout(i)-sbar -(xin(i)-xbar)*xsbar/dsum\ncall unpck(n,nef,match,sout,smo)\nreturn\nend\n\ndouble precision function wmean(n,y,w)\ninteger n\ndouble precision y(n),w(n),wtot,wsum\nwtot=0d0\nwsum=0d0\ndo i=1,n{\n\twsum=wsum+y(i)*w(i)\n\twtot=wtot+w(i)\n}\nif(wtot > 0d0) {wmean=wsum/wtot} else {wmean=0d0}\nreturn\nend\n", "meta": {"hexsha": "f2c999365d972e1931d184b02eb004b6c0d35c5d", "size": 7079, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/splsm.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/splsm.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/splsm.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 29.4958333333, "max_line_length": 78, "alphanum_fraction": 0.6575787541, "num_tokens": 2850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6026458270330728}} {"text": "# Generate and plot Brownian tree. Version #4.\n# 7/27/16 aev\n# gpBrownianTree4(m, n, clr, fn, ttl, dflg, seed, psz)\n# Where: m - defines matrix m x m; n - limit of the number of moves;\n# fn - file name (.ext will be added); ttl - plot title; dflg - 0-no dump,\n# 1-dump; seed - 0-center, 1-random: psz - picture size.\ngpBrownianTree4 <- function(m, n, clr, fn, ttl, dflg=0, seed=0, psz=600)\n{\n cat(\" *** START:\", date(), \"m=\",m, \"n=\",n, \"clr=\",clr, \"psz=\",psz, \"\\n\");\n M <- matrix(c(0), ncol=m, nrow=m, byrow=TRUE);\n # Random seed\n if(seed==1)\n {x <- sample(1:m, 1, replace=FALSE);y <- sample(1:m, 1, replace=FALSE)}\n # Seed in center\n else {x <- m%/%2; y <- m%/%2}\n M[x,y]=1;\n pf=paste0(fn,\".png\");\n cat(\" *** Plot file -\",pf,\"Seed:\",x,\"/\",y,\"\\n\");\n # Main loops\n for (i in 1:n) {\n if(i>1) {\n x <- sample(1:m, 1, replace=FALSE)\n y <- sample(1:m, 1, replace=FALSE)}\n while((x<=m && y<=m && x>0 && y>0)) {\n if(!(x+1<=m && y+1<=m && x-1>0 && y-1>0)) {break;}\n b=M[x+1,y+1]+M[x,y+1]+M[x-1,y+1]+M[x+1,y];\n b=b+M[x-1,y-1]+M[x-1,y]+M[x,y-1]+M[x+1,y-1];\n if(b!=0) {break;}\n x <- x + sample(-1:1, 1, replace=FALSE)\n y <- y + sample(-1:1, 1, replace=FALSE)\n if(!(x<=m && y<=m && x>0 && y>0))\n { x <- sample(1:m, 1, replace=FALSE)\n y <- sample(1:m, 1, replace=FALSE)\n }\n }\n M[x,y]=1;\n }\n plotmat(M, fn, clr, ttl, dflg, psz);\n cat(\" *** END:\",date(),\"\\n\");\n}\ngpBrownianTree4(400,15000,\"navy\", \"BT4R\", \"Brownian Tree v.4\", 1);\n", "meta": {"hexsha": "61220c9fed10adfc9d8cb2e7586cb9c3e5786926", "size": 1515, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Brownian-tree/R/brownian-tree-5.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Brownian-tree/R/brownian-tree-5.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/Brownian-tree/R/brownian-tree-5.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 36.0714285714, "max_line_length": 76, "alphanum_fraction": 0.504290429, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6025631564340376}} {"text": "####################################################################\n## Double Seasonal Holt Winters method as per Taylor (2003)\n## Periods must be nested.\n## y can be an msts object, or periods can be passed explicitly.\n####################################################################\n\n\n\n#' Double-Seasonal Holt-Winters Forecasting\n#'\n#' Returns forecasts using Taylor's (2003) Double-Seasonal Holt-Winters method.\n#'\n#' Taylor's (2003) double-seasonal Holt-Winters method uses additive trend and\n#' multiplicative seasonality, where there are two seasonal components which\n#' are multiplied together. For example, with a series of half-hourly data, one\n#' would set \\code{period1=48} for the daily period and \\code{period2=336} for\n#' the weekly period. The smoothing parameter notation used here is different\n#' from that in Taylor (2003); instead it matches that used in Hyndman et al\n#' (2008) and that used for the \\code{\\link{ets}} function.\n#'\n#' @param y Either an \\code{\\link{msts}} object with two seasonal periods or a\n#' numeric vector.\n#' @param period1 Period of the shorter seasonal period. Only used if \\code{y}\n#' is not an \\code{\\link{msts}} object.\n#' @param period2 Period of the longer seasonal period. Only used if \\code{y}\n#' is not an \\code{\\link{msts}} object.\n#' @param h Number of periods for forecasting.\n#' @param alpha Smoothing parameter for the level. If \\code{NULL}, the\n#' parameter is estimated using least squares.\n#' @param beta Smoothing parameter for the slope. If \\code{NULL}, the parameter\n#' is estimated using least squares.\n#' @param gamma Smoothing parameter for the first seasonal period. If\n#' \\code{NULL}, the parameter is estimated using least squares.\n#' @param omega Smoothing parameter for the second seasonal period. If\n#' \\code{NULL}, the parameter is estimated using least squares.\n#' @param phi Autoregressive parameter. If \\code{NULL}, the parameter is\n#' estimated using least squares.\n#' @param lambda Box-Cox transformation parameter. Ignored if \\code{NULL}.\n#' Otherwise, data transformed before model is estimated.\n#' @param biasadj Use adjusted back-transformed mean for Box-Cox\n#' transformations. If TRUE, point forecasts and fitted values are mean\n#' forecast. Otherwise, these points can be considered the median of the\n#' forecast densities. By default, the value is taken from what was used when\n#' fitting the model.\n#' @param armethod If TRUE, the forecasts are adjusted using an AR(1) model for\n#' the errors.\n#' @param model If it's specified, an existing model is applied to a new data\n#' set.\n#' @return An object of class \"\\code{forecast}\" which is a list that includes the\n#' following elements:\n#' \\item{model}{A list containing information about the fitted model}\n#' \\item{method}{The name of the forecasting method as a character string}\n#' \\item{mean}{Point forecasts as a time series}\n#' \\item{x}{The original time series.}\n#' \\item{residuals}{Residuals from the fitted model. That is x minus fitted values.}\n#' \\item{fitted}{Fitted values (one-step forecasts)}\n#'\n#' The function \\code{summary} is used to obtain and print a summary of the\n#' results, while the function \\code{plot} produces a plot of the forecasts.\n#'\n#' The generic accessor functions \\code{fitted.values} and \\code{residuals}\n#' extract useful features of the value returned by \\code{dshw}.\n#'\n#' @author Rob J Hyndman\n#' @seealso \\code{\\link[stats]{HoltWinters}}, \\code{\\link{ets}}.\n#' @references Taylor, J.W. (2003) Short-term electricity demand forecasting\n#' using double seasonal exponential smoothing. \\emph{Journal of the\n#' Operational Research Society}, \\bold{54}, 799-805.\n#'\n#' Hyndman, R.J., Koehler, A.B., Ord, J.K., and Snyder, R.D. (2008)\n#' \\emph{Forecasting with exponential smoothing: the state space approach},\n#' Springer-Verlag. \\url{http://www.exponentialsmoothing.net}.\n#' @keywords ts\n#' @examples\n#'\n#' \\dontrun{\n#' fcast <- dshw(taylor)\n#' plot(fcast)\n#'\n#' t <- seq(0,5,by=1/20)\n#' x <- exp(sin(2*pi*t) + cos(2*pi*t*4) + rnorm(length(t),0,.1))\n#' fit <- dshw(x,20,5)\n#' plot(fit)\n#' }\n#'\n#' @export\ndshw <- function(y, period1=NULL, period2=NULL, h=2*max(period1,period2),\n alpha=NULL, beta=NULL, gamma=NULL, omega=NULL, phi=NULL, lambda=NULL, biasadj=FALSE,\n armethod=TRUE, model = NULL)\n{\n if(min(y,na.rm=TRUE) <= 0)\n stop(\"dshw not suitable when data contain zeros or negative numbers\")\n seriesname <- deparse(substitute(y))\n if (!is.null(model) && model$method == \"DSHW\") {\n period1 <- model$period1\n period2 <- model$period2\n } else if(any(class(y) == \"msts\") & (length(attr(y, \"msts\")) == 2)) {\n\t period1 <- as.integer(sort(attr(y, \"msts\"))[1])\n\t period2 <- as.integer(sort(attr(y, \"msts\"))[2])\n } else if(is.null(period1) | is.null(period2)) {\n\t stop(\"Error in dshw(): y must either be an msts object with two seasonal periods OR the seasonal periods should be specified with period1= and period2=\")\n } else {\n if(period1 > period2)\n {\n tmp <- period2\n period2 <- period1\n period1 <- tmp\n }\n }\n if(any(class(y) != \"msts\"))\n y <- msts(y, c(period1, period2))\n\n if(length(y) < 2*max(period2))\n stop(\"Insufficient data to estimate model\")\n\n if(!armethod)\n phi <- 0\n\n if(period1 < 1 | period1 == period2)\n stop(\"Inappropriate periods\")\n ratio <- period2/period1\n if(ratio-trunc(ratio) > 1e-10)\n stop(\"Seasonal periods are not nested\")\n\n if (!is.null(model)) {\n lambda <- model$model$lambda\n }\n\n if (!is.null(lambda))\n {\n origy <- y\n y <- BoxCox(y, lambda)\n }\n\n if (!is.null(model)) {\n pars <- model$model\n alpha <- pars$alpha\n beta <- pars$beta\n gamma <- pars$gamma\n omega <- pars$omega\n phi <- pars$phi\n } else {\n pars <- rep(NA,5)\n if(!is.null(alpha))\n pars[1] <- alpha\n if(!is.null(beta))\n pars[2] <- beta\n if(!is.null(gamma))\n pars[3] <- gamma\n if(!is.null(omega))\n pars[4] <- omega\n if(!is.null(phi))\n pars[5] <- phi\n }\n\n # Estimate parameters\n if(sum(is.na(pars)) > 0)\n {\n pars <- par_dshw(y,period1,period2,pars)\n alpha <- pars[1]\n beta <- pars[2]\n gamma <- pars[3]\n omega <- pars[4]\n phi <- pars[5]\n }\n\n ## Allocate space\n n <- length(y)\n yhat <- numeric(n)\n\n ## Starting values\n I <- seasindex(y,period1)\n wstart <- seasindex(y,period2)\n wstart <- wstart / rep(I,ratio)\n w <- wstart\n x <- c(0,diff(y[1:period2]))\n t <- t.start <- mean(((y[1:period2]- y[(period2+1):(2*period2)])/period2 ) + x )/2\n s <- s.start <- (mean(y[1:(2*period2)])-(period2+0.5)*t)\n\n ## In-sample fit\n for(i in 1: n)\n {\n yhat[i] <- (s+t) * I[i]*w[i]\n snew <- alpha*(y[i]/(I[i]*w[i]))+(1-alpha)*(s+t)\n tnew <- beta*(snew-s)+(1-beta)*t\n I[i+period1] <- gamma*(y[i]/(snew*w[i])) + (1-gamma)*I[i]\n w[i+period2] <- omega*(y[i]/(snew*I[i])) + (1-omega)*w[i]\n s <- snew\n t <- tnew\n }\n\n\t# Forecasts\n fcast <- (s + (1:h)*t) * rep(I[n+(1:period1)],h/period1 + 1)[1:h] * rep(w[n+(1:period2)],h/period2 + 1)[1:h]\n fcast <- ts(fcast,frequency=frequency(y),start=tsp(y)[2]+1/tsp(y)[3])\n\n # Calculate MSE and MAPE\n yhat <- ts(yhat)\n tsp(yhat) <- tsp(y)\n yhat <- msts(yhat, c(period1, period2))\n e <- y - yhat\n e <- msts(e, c(period1, period2))\n if(armethod)\n\t{\n\t\tyhat <- yhat + phi * c(0,e[-n])\n\t\te <- y - yhat\n\t fcast <- fcast + phi^(1:h)*e[n]\n\t}\n\tmse <- mean(e^2)\n\tmape <- mean(abs(e)/y)*100\n\n\n end.y <- end(y)\n if(end.y[2] == frequency(y)) {\n\t end.y[1] <- end.y[1]+1\n\t end.y[2] <- 1\n } else {\n\t end.y[2] <- end.y[2]+1\n }\n\n fcast <- msts(fcast, c(period1, period2))\n\n if(!is.null(lambda))\n {\n y <- origy\n fcast <- InvBoxCox(fcast, lambda, biasadj, var(e))\n attr(lambda, \"biasadj\") <- biasadj\n #Does this also need a biasadj backtransform?\n yhat <- InvBoxCox(yhat,lambda)\n }\n\n return(structure(list(mean=fcast,method=\"DSHW\",x=y,residuals=e,fitted=yhat,series=seriesname,\n model=list(mape=mape,mse=mse,alpha=alpha,beta=beta, gamma=gamma,omega=omega,phi=phi,\n lambda = lambda, l0=s.start,b0=t.start,s10=wstart,s20=I), period1 = period1,\n period2 = period2),class=\"forecast\"))\n\n}\n\n### Double Seasonal Holt-Winters smoothing parameter optimization\n\npar_dshw <- function(y, period1, period2, pars)\n{\n start <- c(0.1,0.01,0.001,0.001,0.0)[is.na(pars)]\n out <- optim(start, dshw.mse, y=y, period1=period1, period2=period2, pars=pars)\n pars[is.na(pars)] <- out$par\n return(pars)\n}\n\ndshw.mse <- function(par, y, period1, period2, pars)\n{\n pars[is.na(pars)] <- par\n if(max(pars) > 0.99 | min(pars) < 0 | pars[5] > .9)\n return(1e20)\n else\n return(dshw(y, period1, period2, h=1, pars[1], pars[2], pars[3], pars[4], pars[5], armethod=(abs(pars[5]) >1e-7))$model$mse)\n}\n\n### Calculating seasonal indexes\nseasindex <- function(y,p)\n{\n #require(zoo)\n n <- length(y)\n n2 <- 2*p\n shorty <- y[1:n2]\n average <- numeric(n)\n simplema <- zoo::rollmean.default(shorty, p)\n if (identical(p%%2,0)) # Even order\n {\n centeredma <- zoo::rollmean.default(simplema[1:(n2-p+1)],2)\n average[p/2 + 1:p] <- shorty[p/2 + 1:p]/centeredma[1:p]\n si <- average[c(p+(1:(p/2)),(1+p/2):p)]\n }\n else # Odd order\n {\n average[(p-1)/2 + 1:p] <- shorty[(p-1)/2 + 1:p]/simplema[1:p]\n si <- average[c(p+(1:((p-1)/2)),(1+(p-1)/2):p)]\n }\n return(si)\n}\n", "meta": {"hexsha": "e0b0c0dcd4d55f9aa2a08eccb4c8b0aff3b24bc9", "size": 9312, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dshw.r", "max_stars_repo_name": "ykang/forecast", "max_stars_repo_head_hexsha": "9183f25f5f739d8efc6bd85dde2f2636b9b1b761", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-22T20:29:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T20:29:11.000Z", "max_issues_repo_path": "R/dshw.r", "max_issues_repo_name": "ykang/forecast", "max_issues_repo_head_hexsha": "9183f25f5f739d8efc6bd85dde2f2636b9b1b761", "max_issues_repo_licenses": ["Xnet", "X11"], "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/dshw.r", "max_forks_repo_name": "ykang/forecast", "max_forks_repo_head_hexsha": "9183f25f5f739d8efc6bd85dde2f2636b9b1b761", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.376344086, "max_line_length": 156, "alphanum_fraction": 0.6301546392, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.602434402283397}} {"text": "# 4. faza: Analiza podatkov\n\n#LINEARNA REGRESIJA\n\n#Linearen model za skupno število stanovanj s slabo kakovostjo v odvisnosti od leta\n\npodatki <- stanovanjske_razmere %>% group_by(leto) %>% \n summarize(stanovanja_skupno = sum(stevilo_stanovanj))\npodatki$leto <- as.numeric(podatki$leto)\nfit <- lm(stanovanja_skupno ~ leto , data=podatki)\n\n\ngraf <- ggplot(podatki, aes(x = leto, y = stanovanja_skupno)) + \n geom_point() + geom_smooth(method=lm, se=FALSE) + \n labs(x = \"Leto\" , y = \"SKupno število stanovanj\" , title = \"Ponazoritev premice linearne regresije - \\n skupno število stanovanj v odvisnosti od leta\")\n\npredict(fit, data.frame(leto =c(2021, 2022)))\n\n\n\n\n\n", "meta": {"hexsha": "2831730d1cb40b11f1e2448659f53a035792545b", "size": 666, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "marijajaneva/APPR-2020-21", "max_stars_repo_head_hexsha": "dad0cbc3ca5d5eda89ff982db4568ba8385af741", "max_stars_repo_licenses": ["MIT"], "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": "marijajaneva/APPR-2020-21", "max_issues_repo_head_hexsha": "dad0cbc3ca5d5eda89ff982db4568ba8385af741", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-08-20T20:26:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T09:22:46.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "marijajaneva/APPR-2020-21", "max_forks_repo_head_hexsha": "dad0cbc3ca5d5eda89ff982db4568ba8385af741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9565217391, "max_line_length": 153, "alphanum_fraction": 0.7252252252, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.602434396456129}} {"text": "N = 20\nn = 9\np1 = 5 / 20\np2 = 6 / 20\np3 = 9 / 20\n\nX <- t(as.matrix(expand.grid(0:n, 0:n)))\nX <- X[, colSums(X) <= n]\nX <- rbind(X, n - colSums(X))\ndimnames(X) <- list(letters[1:3])\nmul <- X[1,] * X[2,]\nmul <- mul * X[3,]\nmul_nonzero_idx = which(mul!=0, arr.ind=T)\nY <- X[, mul_nonzero_idx]\n\nresult <- round(apply(Y, 2, function(x) dmultinom(x, prob=c(p1, p2, p3))), 4)\n\nprint(sum(result))\n", "meta": {"hexsha": "8d37966176d0f58bfb63096322165cb20fd88252", "size": 389, "ext": "r", "lang": "R", "max_stars_repo_path": "TASK2/sem2/benches.r", "max_stars_repo_name": "mortarsynth/StatisticalModelling", "max_stars_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TASK2/sem2/benches.r", "max_issues_repo_name": "mortarsynth/StatisticalModelling", "max_issues_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TASK2/sem2/benches.r", "max_forks_repo_name": "mortarsynth/StatisticalModelling", "max_forks_repo_head_hexsha": "ebb6c76cd8defa7dcb2a4d16515328b55989dedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4736842105, "max_line_length": 77, "alphanum_fraction": 0.5629820051, "num_tokens": 174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6023220940743126}} {"text": "# Number Names\n\nones <- c(\"\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\",\n \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\")\ntens <- c(\"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\")\nmags <- c(\"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\")\n\n\nreturn_hund <- function(input_number){\n if (input_number == 0) return(\"\")\n num_text <- as.character()\n input_hund <- trunc(input_number / 100)\n input_ten <- trunc((input_number - input_hund * 100) / 10)\n input_one <- input_number %% 10\n if (input_number > 99) num_text <- paste0(ones[trunc(input_number / 100) + 1], \"-hundred\")\n if (input_ten < 2){\n if (input_ten == 0 & input_one == 0) return(num_text)\n if (input_hund > 0) return(paste0(num_text, \" \", ones[input_ten * 10 + input_one + 1]))\n return(paste0(ones[input_ten * 10 + input_one + 1]))\n }\n ifelse(input_hund > 0,\n num_text <- paste0(num_text, \" \", tens[input_ten]),\n num_text <- paste0(tens[input_ten])\n )\n if (input_one != 0) num_text <- paste0(num_text, \"-\", ones[input_one + 1])\n return(num_text)\n}\n\n\nmake_number <- function(number){\n if (number == 0) return(\"zero\")\n a <- abs(number)\n num_text <- as.character()\n g <- trunc(log(a, 10)) + 1\n for (i in c(seq(g, 1))){\n b <- floor(a / 1000 ^ (i - 1))\n x <- return_hund(b)\n if (x != \"\") num_text <- paste0(num_text, return_hund(b), \" \", mags[i], \" \")\n a <- a - b * 1000 ^ (i - 1)\n }\n return(ifelse(sign(number) > 0, num_text, paste(\"negative\", num_text)))\n}\n\nmy_num <- data.frame(nums = c(\n 0, 1, -11, 13, 99, 100, -101, 113, -120, 450, -999, 1000, 1001, 1017, 3000, 3001,\n 9999, 10000, 10001, 10100, 10101, 19000, 20001, 25467, 99999, 100000, 1056012,\n -200000, 200001, -200012, 2012567, -5685436, 5000201, -11627389, 100067652, 456000342)\n)\n\nmy_num$text <- as.character(lapply(my_num$nums, make_number))\nprint(my_num, right=F)\n", "meta": {"hexsha": "9122caf2af999e561726d8d5bd43ac3dc2cabf37", "size": 2008, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Number-names/R/number-names.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Number-names/R/number-names.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/Number-names/R/number-names.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": 38.6153846154, "max_line_length": 119, "alphanum_fraction": 0.609561753, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6023220841553417}} {"text": "#Dati\r\n\r\nintervallo1 <- 1.74\r\nintervallo2 <- 3.2\r\nsingoletto <- 13.33\r\n\r\ndenominatore <- 2.3216\r\n\r\ndomanda1 <- 1.92\r\n\r\ndomanda2_a <- 1.92\r\ndomanda2_b <- 2.06\r\ndomanda2_c <- 1.74\r\ndomanda2_d <- 3.2\r\n\r\ndomanda3_a <- 2.06\r\ndomanda3_b <- 2.1\r\ndomanda3_c <- 1.74\r\ndomanda3_d <- 1.92\r\n\r\n#Svolgimento\r\n\r\nEPSILON <- 0.001\r\n\r\nf <- function(x) {\r\n ifelse(x < intervallo1, 0,\r\n ifelse(x >= intervallo1 && x < intervallo2, ((x - intervallo1)^2)/denominatore,\r\n ifelse(x >= intervallo2 && x < singoletto, 0.81,\r\n ifelse(x >= singoletto, 1, NaN))))\r\n}\r\n\r\nf_calc <- function(x) {\r\n (x - intervallo1)^2/denominatore\r\n}\r\n\r\npar(bg = \"black\", fg = \"White\")\r\nplot.new()\r\npar(new = TRUE)\r\nplot(Vectorize(f), xlab = \"x\", from = intervallo1-1, to = singoletto+1,\r\n type = \"l\", ylab = \"F(x)\", col = \"Yellow2\",\r\n col.axis = \"white\", col.lab = \"white\", lwd = 2)\r\n\r\nfor(i in seq(0, 1, 0.5)) {\r\n abline(h = i, lty=\"dotted\", col = \"Gray\")\r\n}\r\n\r\nfor(i in seq(0, singoletto+2, 0.5)) {\r\n abline(v = i, lty=\"dotted\", col = \"Gray\")\r\n}\r\n\r\ndomanda2 <- (f(domanda2_b)- f(domanda2_a))/(f(domanda2_d)-f(domanda2_c))\r\n\r\nprint(f(domanda1)-f(domanda1), digits=22)\r\nprint(domanda2, digits=22)\r\nprint(f(domanda3_b)-f(domanda3_a) + f(domanda3_d)- f(domanda3_c), digits=22)", "meta": {"hexsha": "df626d6ea867d64fa83a55bdbd7ac83fef39d47a", "size": 1283, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio Extra (25.1).r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio Extra (25.1).r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio Extra (25.1).r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3272727273, "max_line_length": 89, "alphanum_fraction": 0.5837879969, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6021599087451847}} {"text": "\nlibrary(R0)\nlibrary(uuid)\nlibrary(igraph)\nlibrary(ggnetwork)\nlibrary(data.table)\nlibrary(EpiDynamics)\nlibrary(scales)\nlibrary(tidyverse)\n\n# https://www.ijidonline.com/article/S1201-9712(20)30119-3/pdf\nweibull_mean = 6.4\n# weibull_mean = 4.8\nweibull_sd = 2.3\n# \n# > 10977 / (19e6 * .2)\n# [1] 0.002888684\n\n# get shape/scale for weibull distribution\nfit_weibull = function(pars) {\n shape = pars[1]\n scale = pars[2]\n the_dist = rweibull(10000, shape, scale)\n the_sd = abs(sd(the_dist) - weibull_sd)\n the_mean = abs(mean(the_dist) - weibull_mean)\n return(\n (the_sd * the_mean)^2 \n )\n}\nweibull_params = optim(par = c(3, 7), fn = fit_weibull)\nthe_weibull_dist = rweibull(10000, weibull_params$par[1], weibull_params$par[2])\nsummary(the_weibull_dist)\n\nfit_weibull_r0 = function(pars) {\n shape = pars[1]\n scale = pars[2]\n the_dist = rweibull(10000, shape, scale)\n mean_dist = mean(the_dist) - 2.5\n min_dist = min(the_dist) - 0.75\n \n return(\n (mean_dist)^2 + min_dist^2\n )\n}\nr0_params = optim(par = c(3, 7), fn = fit_weibull_r0)\n\n\nrun_case_simulation = function(initial_susceptible = 20e6, the_r0, \n lockdown_date = NULL, lockdown_effect = NULL, r0_type = NULL) {\n this_r0 = the_r0\n current_susceptible = initial_susceptible\n \n case_info_list = list()\n \n generation = 0\n \n cases_gen_df = tibble(\n parent_id = NA,\n incubation_start = 0\n )\n n_cases_generated = 1\n \n continue_loop = T\n \n while (continue_loop) {\n loop_start = proc.time()\n \n # print(generation)\n \n if (n_cases_generated > current_susceptible) {\n # cat('too many cases generated!\\n', n_cases_generated, '\\n')\n n_cases_generated = current_susceptible\n suseptible_by_id = current_susceptible - 1:n_cases_generated\n # cat('n_cases_generated is now', n_cases_generated, '\\n')\n cases_gen_df = head(cases_gen_df, n_cases_generated)\n } else {\n suseptible_by_id = current_susceptible - 1:n_cases_generated\n }\n # cat('n_cases_generated:', n_cases_generated, '\\n')\n # cat('current_susceptible:', current_susceptible, '\\n')\n # \n \n # suseptible_by_id = suseptible_by_id[suseptible_by_id > 0]\n \n if (current_susceptible < 0) {\n # cat('no more susceptible')\n break\n }\n \n the_id = initial_susceptible - suseptible_by_id\n # https://wwwnc.cdc.gov/eid/article/26/6/20-0357_article\n # https://www.ijidonline.com/article/S1201-9712(20)30119-3/pdf\n \n # incubation_time = rnorm(n_cases_generated, 3.96, 4.75)\n # incubation_time = rgamma(n_cases_generated, 4.37, scale = 1.25) \n # incubation_time = rweibull(n_cases_generated, weibull_params$par[1], weibull_params$par[2])\n incubation_time = 5\n incubation_start_date = cases_gen_df$incubation_start\n incubation_end_date = incubation_start_date + incubation_time \n prob_running_into_someone_else = suseptible_by_id / initial_susceptible\n \n if (r0_type == 'weibull') {\n the_r0 = rweibull(n_cases_generated, r0_params$par[1], r0_params$par[2]) \n } else if (r0_type == 'unif') {\n the_r0 = runif(n_cases_generated, this_r0*0.75, this_r0*1.25) \n }\n \n if (!is.null(lockdown_date)) {\n lockdown_effects = ifelse(incubation_start_date >= lockdown_date, lockdown_effect, 1)\n r0_adj = the_r0 * prob_running_into_someone_else * lockdown_effects\n } else {\n r0_adj = the_r0 * prob_running_into_someone_else\n }\n \n cases_generated = floor(r0_adj) + rbinom(length(r0_adj), 1, r0_adj - floor(r0_adj))\n n_cases_generated = sum(cases_generated)\n \n these_cases_df = data.table(\n the_id = the_id %>% as.integer(),\n generation = generation,\n parent_id = cases_gen_df$parent_id,\n incubation_time,\n incubation_start_date,\n incubation_end_date,\n prob_running_into_someone_else,\n r0_adj,\n cases_generated\n ) %>% \n setkey(the_id)\n \n case_info_list[[length(case_info_list) + 1]] = these_cases_df\n \n if (n_cases_generated > 0) {\n # important to sort by cases generated so the recyling works\n with_gen_cases = filter(these_cases_df, cases_generated > 0) %>% arrange(-cases_generated)\n \n cases_gen_df = data.table(\n parent_id = rep(with_gen_cases$the_id, length.out = n_cases_generated),\n incubation_start = runif(n_cases_generated, with_gen_cases$incubation_start_date, with_gen_cases$incubation_end_date)\n ) %>% \n setorder(incubation_start)\n \n stopifnot(nrow(cases_gen_df) == n_cases_generated)\n }\n \n # print(proc.time() - loop_start)\n generation = generation + 1\n current_susceptible = min(suseptible_by_id)\n continue_loop = n_cases_generated > 0 & current_susceptible > 0\n }\n \n \n case_info_df = rbindlist(case_info_list) %>%\n mutate(\n start_day = floor(incubation_start_date),\n end_day = floor(incubation_end_date)\n )\n return(rbindlist(case_info_list))\n}\n\n\ncovid_ifr = 0.003\nflu_ifr = 0.001\nn_susceptible = 10e6\n\ncovid_case_simulation = run_case_simulation(r0_type = 'covid', the_r0 = 2.5, \n initial_susceptible = n_susceptible/2) %>% \n mutate(\n start_day = floor(incubation_start_date),\n died = rbinom(length(the_id), 1, covid_ifr),\n death_date = ifelse(died, start_day + 14, NA)\n )\n\ngeneration_stats = group_by(covid_case_simulation, generation) %>%\n summarize(\n obs = n(),\n mean_cases = mean(cases_generated),\n mean_r0 = mean(r0_adj),\n mean_prob = mean(prob_running_into_someone_else ),\n min_prob = min(prob_running_into_someone_else),\n max_prob = max(prob_running_into_someone_else),\n start = min(incubation_start_date),\n end = max(incubation_end_date),\n mean_start = mean(incubation_start_date),\n mean_end = mean(incubation_end_date)\n )\n\nggplot(generation_stats, aes(start, max_prob, colour = factor(generation))) +\n geom_point() +\n geom_point(aes(y = min_prob))\n\ncovid_case_simulation$incubation_time\ncovid_case_simulation %>% pull(cases_generated) %>% summary()\n\nggplot(covid_case_simulation, aes(incubation_start_date, cases_generated, size = r0_adj)) +\n geom_point()\n\nincubation_period = 5\ninitial_r0 = 2.5\ngamma = 1/incubation_period\ninitial_beta = initial_r0 / incubation_period\ninitial_parameters <- c(beta = initial_beta, gamma = gamma)\ninitials <- c(S = 1 - 1e-06, I = 1e-06, R = 1 - (1 - 1e-06 - 1e-06))\n# initials <- c(S = 1 - 1e-06, I = 1e-06, R = 1 - (1 - 1e-06 - 1e-06))\ninitial_covid_sir <- SIR(pars = initial_parameters, init = initials, time = 0:240)\n\ncounts_by_day = group_by(covid_case_simulation, start_day) %>%\n summarize(\n obs = n_distinct(the_id)\n )\n\nsir_results = initial_covid_sir$results %>%\n mutate(\n n_susceptible = n_susceptible/2 * S,\n n_cases = lag(n_susceptible, 1) - n_susceptible \n )\nb = left_join(sir_results, counts_by_day, by = c('time' = 'start_day')) %>%\n mutate(\n obs= ifelse(is.na(obs), 0, obs),\n n_cases = ifelse(is.na(n_cases), 0, n_cases)\n )\nwith(b, cor(obs, n_cases))\n\nggplot(counts_by_day, aes(start_day, obs)) +\n geom_area(alpha = 0.3) +\n geom_area(data = sir_results, aes(time, n_cases), alpha = 0.3, fill = 'blue') +\n scale_y_continuous(labels = comma)\n\n\n\ncovid_case_simulation_lockdown = run_case_simulation(the_r0 = 2.5, r0_type = 'covid', \n lockdown_date = 15, lockdown_effect = 0.65, \n initial_susceptible = n_susceptible/2) %>% \n mutate(\n start_day = floor(incubation_start_date),\n died = rbinom(length(the_id), 1, covid_ifr),\n death_date = ifelse(died, start_day + 14, NA)\n )\n\n\nflu_case_simulation = run_case_simulation(the_r0 = 1.3, r0_type = 'flu', \n initial_susceptible = 327e6/4) %>% \n mutate(\n start_day = floor(incubation_start_date),\n died = rbinom(length(the_id), 1, flu_ifr),\n death_date = ifelse(died, start_day + 14, NA)\n )\n\ncovid_cases_by_day = dplyr::group_by(covid_case_simulation, start_day) %>%\n dplyr::summarize(\n obs = n_distinct(the_id),\n died = sum(died)\n ) %>%\n mutate(\n cum_obs = cumsum(obs),\n Virus = 'COVID-19',\n with_lockdown = 'No'\n )\n\ncovid_cases_by_day_lockdown = dplyr::group_by(covid_case_simulation_lockdown, start_day) %>%\n dplyr::summarize(\n obs = n_distinct(the_id),\n died = sum(died)\n ) %>%\n mutate(\n cum_obs = cumsum(obs),\n Virus = 'COVID-19 Early Lockdown',\n with_lockdown = 'Yes'\n )\n\nflu_cases_by_day = dplyr::group_by(flu_case_simulation, start_day) %>%\n dplyr::summarize(\n obs = n_distinct(the_id),\n died = sum(died)\n ) %>%\n mutate(\n cum_obs = cumsum(obs),\n Virus = 'Influenza',\n with_lockdown = 'No'\n )\nsum(flu_cases_by_day$died)\n\nstacked_stats = bind_rows(\n covid_cases_by_day, flu_cases_by_day,\n covid_cases_by_day_lockdown) %>%\n mutate(\n week = start_day %/% 7\n )\n\ngroup_by(stacked_stats, Virus, with_lockdown) %>%\n summarize(\n t_obs = sum(obs),\n pct_infected = t_obs / n_susceptible,\n t_died = sum(died),\n crude_mortality_rate = t_died / n_susceptible,\n infection_fatality_rate = t_died / t_obs,\n time_period = as.numeric(max(start_day)-min(start_day))\n )\nweekly_stats = group_by(stacked_stats, week, Virus, with_lockdown) %>%\n summarize(\n weekly_deaths = sum(died),\n weekly_cases = sum(obs)\n )\nmax(weekly_stats$weekly_deaths * 32.7)\n\nggplot(stacked_stats, aes(start_day, obs, fill = Virus)) +\n geom_area(alpha = 0.3, position = 'identity')\n\nggplot(weekly_stats, aes(week, weekly_deaths*32.7, colour = Virus)) +\n # facet_wrap(~Virus, scales = 'free_y') +\n geom_line() +\n geom_point() \n # geom_bar(stat = 'identity', position = 'identity')\n\n\n\n# mGT_weibull <- generation.time(\"weibull\", c(6.4, 2.3))\n# mGT_weibull <- generation.time(\"gamma\", c(5, 1.5))\n# est.R0.EG(cases_by_day$obs, mGT_weibull, t = cases_by_day$start_day, begin = 0, end = 20)\n# \n", "meta": {"hexsha": "97e4a2536701c9d344737d424914730394db08a8", "size": 9903, "ext": "r", "lang": "R", "max_stars_repo_path": "Projects/COVID-19/scripts/investigations/simulate_covid_networks_optim.r", "max_stars_repo_name": "vishalbelsare/Public_Policy", "max_stars_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-03-09T01:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T19:11:44.000Z", "max_issues_repo_path": "Projects/COVID-19/scripts/investigations/simulate_covid_networks_optim.r", "max_issues_repo_name": "vishalbelsare/Public_Policy", "max_issues_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-03T20:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-07T00:03:58.000Z", "max_forks_repo_path": "Projects/COVID-19/scripts/investigations/simulate_covid_networks_optim.r", "max_forks_repo_name": "vishalbelsare/Public_Policy", "max_forks_repo_head_hexsha": "4f57140f85855859ff2e49992f4b7673f1b72857", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-06-04T22:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T14:00:22.000Z", "avg_line_length": 30.8504672897, "max_line_length": 125, "alphanum_fraction": 0.6737352317, "num_tokens": 3042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6021598972137178}} {"text": "#' Results from drawing different color balls from an urn\n#'\n#' @param n.iter The number of iterations in the monte carlo simulation (integer > 0)\n#' @param n.colors The number of different colored balls (integer > 0)\n#' @param n.balls The count of each color balls (vector of integers with same length as \\code{n.colors})\n#' @param n.drawn The number of balls drawn from the urn in each iteration\n#' @param replacement Are the balls placed back in the urn after they're drawn? (defaults to \\code{FALSE})\n#' @param collapse Should the return be the draws or the count of each color? (defaults to \\code{FALSE})\n#' @param parallel Should the simulation take advantage of multiple cores (defaults to \\code{TRUE} -\n#' highly recommended if \\code{n.iter > 1e5})\n#'\n#' @return If \\code{collapse == TRUE} the return is a \\code{n.iter x n.colors} integer matrix\n#' where each row is the count of the colors of balls drawn. Otherwise, the return is a\n#' \\code{n.iter x n.drawn} integer matrix where each row is the order that colors were drawn in.\n#' @export\n#'\ndraw.urn = function(n.iter = 1e5, n.colors = 2, n.balls = c(10,10),\n n.drawn = 5, replacement = FALSE,\n collapse = FALSE, parallel = TRUE) {\n stopifnot(n.iter %% 1 == 0 & n.iter > 0)\n stopifnot(n.colors %% 1 == 0 & n.colors > 0)\n stopifnot(all(n.balls %% 1 == 0) & all(n.balls > 0))\n stopifnot(length(n.balls) == n.colors)\n stopifnot(n.drawn %% 1 == 0 & n.drawn > 0)\n urn = unlist(lapply(seq_len(n.colors), FUN = function(i) rep(i, n.balls[i])))\n total.balls = sum(n.balls)\n if(!parallel) {\n results = lapply(seq_len(n.iter), FUN = function(i) {\n indices = sample(seq_len(total.balls), size = n.drawn, replace = replacement)\n urn[indices]\n })\n } else {\n results = mclapply(seq_len(n.iter), FUN = function(i) {\n indices = sample(seq_len(total.balls), size = n.drawn, replace = replacement)\n urn[indices]\n })\n }\n if(collapse) {\n return(t(sapply(results, FUN = function(x) {\n vapply(seq_len(n.colors), function(i) sum(x == i),1)\n })))\n }\n return(do.call(rbind, results))\n}\n", "meta": {"hexsha": "794229592cc8f62865b780ab1695f94273084140", "size": 2123, "ext": "r", "lang": "R", "max_stars_repo_path": "R/draw.urn.r", "max_stars_repo_name": "David-Statistics/Clancy-Functions", "max_stars_repo_head_hexsha": "2921e42a14f1cd39c5208d5772ebdbb915bb6d03", "max_stars_repo_licenses": ["MIT"], "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/draw.urn.r", "max_issues_repo_name": "David-Statistics/Clancy-Functions", "max_issues_repo_head_hexsha": "2921e42a14f1cd39c5208d5772ebdbb915bb6d03", "max_issues_repo_licenses": ["MIT"], "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/draw.urn.r", "max_forks_repo_name": "David-Statistics/Clancy-Functions", "max_forks_repo_head_hexsha": "2921e42a14f1cd39c5208d5772ebdbb915bb6d03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1777777778, "max_line_length": 106, "alphanum_fraction": 0.6556759303, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6020324563164935}} {"text": "library(MDPtoolbox)\n\nMoveUp=matrix(c(0.3, 0.7, 0, 0,\n 0, 0.9, 0.1, 0,\n 0, 0.1, 0.9, 0,\n 0, 0, 0.7, 0.3),\n nrow=4,ncol=4,byrow=TRUE)\n\nMoveDown=matrix(c( 1, 0, 0, 0,\n 0.7, 0.2, 0.1, 0,\n 0, 0.1, 0.2, 0.7,\n 0, 0, 0, 1),\n nrow=4,ncol=4,byrow=TRUE)\n\n\nMoveLeft=matrix(c( 0.9, 0.1, 0, 0,\n 0.1, 0.9, 0, 0,\n 0, 0.7, 0.2, 0.1,\n 0, 0, 0.1, 0.9),\n nrow=4,ncol=4,byrow=TRUE)\n\n\nMoveRight=matrix(c( 0.9, 0.1, 0, 0,\n 0.1, 0.2, 0.7, 0,\n 0, 0, 0.9, 0.1,\n 0, 0, 0.1, 0.9),\n nrow=4,ncol=4,byrow=TRUE)\n\n\nAllActions=list(up=MoveUp, down=MoveDown, left=MoveLeft, right=MoveRight)\n\n\nAllRewards=matrix(c( -2, -2, -2, -2,\n -2, -2, -2, -2,\n -2, -2, -2, -2,\n 20, 20, 20, 20),\n nrow=4,ncol=4,byrow=TRUE)\n\nmdp_check(AllActions, AllRewards)\n\n\nGridModel=mdp_policy_iteration(P=AllActions, R=AllRewards, discount = 0.1)\n\n\nGridModel$policy \nnames(AllActions)[GridModel$policy] \n\nGridModel$V \n\nGridModel$iter\n\nGridModel$time ", "meta": {"hexsha": "5eb3469839b7fb733c7872baa89030089c9b1e96", "size": 1159, "ext": "r", "lang": "R", "max_stars_repo_path": "Chapter05/GridWorld2x2.r", "max_stars_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_stars_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2020-01-19T06:32:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T06:37:07.000Z", "max_issues_repo_path": "Chapter05/GridWorld2x2.r", "max_issues_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_issues_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter05/GridWorld2x2.r", "max_forks_repo_name": "CiaburroGiuseppe/Hands-On-Reinforcement-Learning-with-R", "max_forks_repo_head_hexsha": "5966656378792ea3d65a62e283e2bf3c74467ffc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-12-25T17:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:19:18.000Z", "avg_line_length": 22.2884615385, "max_line_length": 74, "alphanum_fraction": 0.4616048318, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6019047266311213}} {"text": "#' @export\n#' @title dist.plt\n#' @description plots distributions in R, useful for setting up priors in Bayesian analyses\n#' @param \\code{dist} \n#' @param \\code{par1} \n#' @param \\code{par2} \n#' @param \\code{x} \n#' @param \\code{xl} \n#' @param \\code{col} \n#' @return \\code{add}\n#' @return \\code{alpha}\n#' @return \\code{plot.lines}\n#' @family plotting\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\ndist.plt<-function(dist=\"beta\",par1,par2,x,xl=c(0,1),col=1,add=F,alpha=0.05,plot.lines=F,title=''){\n\n\t\n\tz<-get(paste(\"r\",dist,sep=''))(1000,par1,par2)\n\tif(missing(xl))xl<-range(z)\n\tif(missing(x))x<-seq(xl[1],xl[2],length=1000)\n\ty<-get(paste(\"d\",dist,sep=''))(x,par1,par2)\n\t\n\tif(add==F){\n#\t\tplot.new()\n\t\tplot(x,y,type='l',col=col,xlab='',ylab='',main=title)\n\t}\n\t\n\tif(add==T)lines(x,y,col=col)\n\tout<-list(c(quantile(z, alpha/2),quantile(z, 0.5),quantile(z, 1-alpha/2)),mode=x[which(y==max(y))],mean=mean(z),var=var(z))\n\tif(plot.lines){\n \tabline(v=out[[1]][2],lty=2)\n\tabline(v=out$mean,lty=3)\n\tabline(v=out$mode,lty=4)\n\t}\n\t\n\tout\n\t\n}\n", "meta": {"hexsha": "36cec3e5f77b8591aeab7b1aac4d85cb7e5c210c", "size": 1045, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dist.plt.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/dist.plt.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/dist.plt.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": 26.125, "max_line_length": 124, "alphanum_fraction": 0.6229665072, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7341195210831261, "lm_q1q2_score": 0.6018997095616014}} {"text": "fileName <- \"rounds.txt\"\nrounds <- as.numeric(readChar(fileName, file.info(fileName)$size))\n\nx = 1.0\npi = 1.0\n\nfor (i in 2:(rounds + 2)){\n x = x * -1\n pi = pi + (x / (2 * i - 1))\n}\n\npi = pi * 4\n\nprintf <- function(...) cat(sprintf(...))\nprintf(\"%.16f\\n\", pi)\n", "meta": {"hexsha": "3c2159e502978c1a56a5362fa33df3eb8fc2c7a3", "size": 261, "ext": "r", "lang": "R", "max_stars_repo_path": "src/leibniz.r", "max_stars_repo_name": "ducla5/speed-comparison", "max_stars_repo_head_hexsha": "214bd0440195606b191c1f30f37bf468668c2f6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101, "max_stars_repo_stars_event_min_datetime": "2018-03-07T07:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T09:27:55.000Z", "max_issues_repo_path": "src/leibniz.r", "max_issues_repo_name": "Tanishq-Banyal/speed-comparison", "max_issues_repo_head_hexsha": "7725cf8d2338e20ea35b9cbfd1fbad8445891e3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2018-12-12T19:53:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T08:44:18.000Z", "max_forks_repo_path": "src/leibniz.r", "max_forks_repo_name": "Tanishq-Banyal/speed-comparison", "max_forks_repo_head_hexsha": "7725cf8d2338e20ea35b9cbfd1fbad8445891e3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:08:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T22:25:12.000Z", "avg_line_length": 16.3125, "max_line_length": 66, "alphanum_fraction": 0.5402298851, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6016472323171331}} {"text": "# 4. faza: Napredna analiza podatkov\n\nobrisi = function(podatki, hc = TRUE, od = 2, do = NULL) {\n n = nrow(podatki)\n if (is.null(do)) {\n do = n - 1\n }\n \n razdalje = dist(podatki)\n \n k.obrisi = tibble()\n for (k in od:do) {\n if (hc) {\n o.k = hclust(razdalje) %>%\n cutree(k) %>%\n silhouette(razdalje)\n } else {\n set.seed(42) # zato, da so rezultati ponovljivi\n o.k = kmeans(podatki, k)$cluster %>%\n silhouette(razdalje)\n }\n k.obrisi = k.obrisi %>% bind_rows(\n tibble(\n k = rep(k, n),\n obrisi = o.k[, \"sil_width\"]\n )\n )\n }\n k.obrisi$k = as.ordered(k.obrisi$k)\n \n k.obrisi\n}\n\nobrisi.povprecje = function(k.obrisi) {\n k.obrisi.povprecje = k.obrisi %>%\n group_by(k) %>%\n summarize(obrisi = mean(obrisi))\n}\n\nobrisi.k = function(k.obrisi) {\n obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n summarize(k = min(k)) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\ndiagram.obrisi = function(k.obrisi) {\n ggplot() +\n geom_boxplot(\n data = k.obrisi,\n mapping = aes(x = k, y = obrisi)\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = k, y = obrisi),\n color = \"red\"\n ) +\n geom_line(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = as.integer(k), y = obrisi),\n color = \"red\"\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n filter(k == min(k)),\n mapping = aes(x = k, y = obrisi),\n color = \"blue\"\n ) +\n xlab(\"število skupin (k)\") +\n ylab(\"obrisi (povprečje obrisov)\") +\n ggtitle(paste(\"Maksimalno povprečje obrisov pri k =\", obrisi.k(k.obrisi))) +\n theme_classic()\n}\n\nnakupi = tabela2 %>% dplyr::select(\n Year, Country, Stopnja, Koliko_vseh_nakupov_je_opravila_ta_skupina\n) %>%\n filter(\n Year == 2019\n ) %>%\n pivot_wider(\n names_from = Stopnja,\n values_from = Koliko_vseh_nakupov_je_opravila_ta_skupina\n ) %>%\n dplyr::select(-Year)\nnakupi[5, 1] = 'Germany'\nnakupi[38, 1] = 'Kosovo'\n\n#dendrogram, hierarhično razvrščanje v skupine\ndrzave = nakupi[, 1] %>% unlist()\nrazdalje = nakupi[, -1] %>% dist()\ndendrogram = razdalje %>% hclust(method = \"ward.D\")\n#dendrogramcek <- plot(\n# dendrogram,\n# labels = drzave,\n# ylab = \"višina\",\n# main = NULL\n#)\n#Zgornjo kodo, ki nariše dendrogram, sem zakomentirala, saj se mi je dendrogramcek kljub temu, da sem ga shranila \n#pod spremenljivko in ga ne poklicala v poročilu, še zmeraj prikazoval.\n\nhc.kolena = function(dendrogram, od = 1, do = NULL, eps = 0.5) {\n # število primerov in nastavitev parametra do\n n = length(dendrogram$height) + 1\n if (is.null(do)) {\n do = n - 1\n }\n # k.visina je tabela s štirimi stolpci\n # (1) k, število skupin\n # (2) višina združevanja\n # (3) sprememba višine pri združevanju\n # (4) koleno: ali je točka koleno?\n k.visina = tibble(\n k = as.ordered(od:do),\n visina = dendrogram$height[do:od]\n ) %>%\n # sprememba višine\n mutate(\n dvisina = visina - lag(visina)\n ) %>%\n # ali se je intenziteta spremembe dovolj spremenila?\n mutate(\n koleno = lead(dvisina) - dvisina > eps\n )\n k.visina\n}\n\n# iz tabele k.visina vrne seznam vrednosti k,\n# pri katerih opazujemo koleno\nhc.kolena.k = function(k.visina) {\n k.visina %>%\n filter(koleno) %>%\n dplyr::select(k) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\n# izračunamo tabelo s koleni za dendrogram\nr = hc.kolena(dendrogram)\n\n# narišemo diagram višin združevanja\ndiagram.kolena = function(k.visina) {\n k.visina %>% ggplot() +\n geom_point(\n mapping = aes(x = k, y = visina),\n color = \"red\"\n ) +\n geom_line(\n mapping = aes(x = as.integer(k), y = visina),\n color = \"red\"\n ) +\n geom_point(\n data = k.visina %>% filter(koleno),\n mapping = aes(x = k, y = visina),\n color = \"blue\", size = 2\n ) +\n ggtitle(paste(\"Kolena:\", paste(hc.kolena.k(k.visina), collapse = \", \"))) +\n xlab(\"število skupin (k)\") +\n ylab(\"razdalja pri združevanju skupin\") +\n theme_classic()\n}\ndiagram.kolena(r)\n\ndiagram.skupine = function(podatki, oznake, skupine, k) {\n podatki = podatki %>%\n bind_cols(skupine) %>%\n dplyr::rename(skupina = ...4)\n \n d = podatki %>%\n ggplot(\n mapping = aes(\n x = x, y = y, color = skupina\n )\n ) +\n geom_point() +\n geom_label(label = oznake, size = 2) +\n scale_color_hue() +\n theme_classic()\n \n for (i in 1:k) {\n d = d + geom_encircle(\n data = podatki %>%\n filter(skupina == i)\n )\n }\n d\n}\n\n\n#k-ti voditelji\n\nb <- transform(nakupi, No_or_low= as.numeric(unlist(nakupi[,2])), \n Med = as.numeric(unlist(nakupi[,3])),\n High = as.numeric(unlist(nakupi[,4])),\n Students = as.numeric(unlist(nakupi[,5])))%>% dplyr::select(Students, No_or_low, Med, High)\nskupine = b[, -1] %>%\n kmeans(centers = 3) %>%\n getElement(\"cluster\") %>%\n as.ordered()\n\nprint(skupine)\nr.hc = nakupi[, -1] %>% obrisi(hc = TRUE)\nr.km = nakupi[, -1] %>% obrisi(hc = FALSE)\n\ndiagram.obrisi(r.hc)\ndiagram.obrisi(r.km)\n\n#Optimalno število skupin je torej 2 ali 4/5.\n\ndrzave.x.y =\n as_tibble(razdalje %>% cmdscale(k = 2)) %>%\n bind_cols(drzave) %>%\n dplyr::select(drzava = ...3, x = V1, y = V2)\n\nk = obrisi.k(r.hc)\nskupine = nakupi[, -1] %>%\n dist() %>%\n hclust(method = \"ward.D\") %>%\n cutree(k = k) %>%\n as.ordered()\ndiagram.skupine(drzave.x.y, drzave.x.y$drzava, skupine, k)\n\nk = obrisi.k(r.km)\nset.seed(42) # ne pozabimo na ponovljivost rezultatov\nskupine = nakupi[, -1] %>%\n kmeans(centers = k) %>%\n getElement(\"cluster\") %>%\n as.ordered()\ndiagram.skupine(drzave.x.y, drzave.x.y$drzava, skupine, k)\n\nset.seed(42)\nskupine = nakupi[, -1] %>%\n kmeans(centers = 4) %>%\n getElement(\"cluster\") %>%\n as.ordered()\nskup <- diagram.skupine(drzave.x.y, drzave.x.y$drzava, skupine, 2)\n\ndownload.file(url='https://kt.ijs.si/~ljupco/lectures/appr/zemljevidi/svet/TM_WORLD_BORDERS-0.3.shp',\n destfile='TM_WORLD_BORDERS-0.3.shp', method='curl')\ndownload.file(url='https://kt.ijs.si/~ljupco/lectures/appr/zemljevidi/svet/TM_WORLD_BORDERS-0.3.dbf',\n destfile='TM_WORLD_BORDERS-0.3.dbf', method='curl')\ndownload.file(url='https://kt.ijs.si/~ljupco/lectures/appr/zemljevidi/svet/TM_WORLD_BORDERS-0.3.shx',\n destfile='TM_WORLD_BORDERS-0.3.shx', method='curl')\nsvet.sp <- readOGR(getwd(), \"TM_WORLD_BORDERS-0.3\")\nsvet.sp = gBuffer(svet.sp, byid = TRUE, width = 0)\n\nsvet.centroidi = read_csv(\"podatki/drzave-centroidi.csv\")\nevropske.drzave = tibble(\n drzava = c(\n \"Albania\", \"Andorra\", \"Armenia\",\n \"Austria\", \"Azerbaijan\", \"Belarus\",\n \"Belgium\", \"Bosnia and Herzegovina\",\n \"Bulgaria\", \"Croatia\", \"Cyprus\",\n \"Czechia\", \"Denmark\", \"Estonia\",\n \"Finland\", \"France\", \"Georgia\",\n \"Germany\", \"Greece\", \"Hungary\",\n \"Iceland\", \"Ireland\", \"Italy\",\n \"Kazakhstan\", \"Latvia\",\n \"Liechtenstein\", \"Lithuania\",\n \"Luxembourg\", \"Malta\", \"Moldova\",\n \"Monaco\", \"Montenegro\",\n \"Netherlands\", \"North Macedonia\",\n \"Norway\", \"Poland\", \"Portugal\",\n \"Romania\", \"Russia\", \"San Marino\",\n \"Serbia\", \"Slovakia\", \"Slovenia\",\n \"Spain\", \"Sweden\", \"Switzerland\",\n \"Turkey\", \"Ukraine\", \"United Kingdom\",\n \"Holy See (Vatican City)\"\n )\n)\n\n\nevropa.izsek = as(extent(-25, 60, 30, 75), \"SpatialPolygons\")\nsp::proj4string(evropa.izsek) <- sp::proj4string(svet.sp)\n\nevropske.drzave = tibble(\n drzava = c(\n \"Albania\", \"Andorra\", \"Armenia\",\n \"Austria\", \"Azerbaijan\", \"Belarus\",\n \"Belgium\", \"Bosnia and Herzegovina\",\n \"Bulgaria\", \"Croatia\", \"Cyprus\",\n \"Czechia\", \"Denmark\", \"Estonia\",\n \"Finland\", \"France\", \"Georgia\",\n \"Germany\", \"Greece\", \"Hungary\",\n \"Iceland\", \"Ireland\", \"Italy\",\n \"Kazakhstan\", \"Latvia\",\n \"Liechtenstein\", \"Lithuania\",\n \"Luxembourg\", \"Malta\", \"Moldova\",\n \"Monaco\", \"Montenegro\",\n \"Netherlands\", \"North Macedonia\",\n \"Norway\", \"Poland\", \"Portugal\",\n \"Romania\", \"Russia\", \"San Marino\",\n \"Serbia\", \"Slovakia\", \"Slovenia\",\n \"Spain\", \"Sweden\", \"Switzerland\",\n \"Turkey\", \"Ukraine\", \"United Kingdom\",\n \"Holy See (Vatican City)\"\n )\n)\n\n# Evropa se po zemljepisni dolžini razteza\n# od -25 do 60, po širini pa od 30 do 75\nevropa.izsek = as(extent(-25, 60, 30, 75), \"SpatialPolygons\")\nsp::proj4string(evropa.izsek) <- sp::proj4string(svet.sp)\ncolnames(evropske.drzave)[1] <- \"NAME\"\nevropa.poligoni = svet.sp %>% crop(evropa.izsek) %>% fortify() %>% tibble() %>%\nleft_join(\n evropske.drzave,\n by = \"NAME\"\n)\ncolnames(svet.centroidi)[1] <- \"NAME\"\nevropa.centroidi = evropske.drzave %>%\n left_join(\n svet.centroidi,\n by = \"NAME\"\n )\n\n\ncolnames(evropa.poligoni)[12] <- \"drzava\"\ncolnames(evropa.centroidi)[1] <- \"drzava\"\n\nprostorski.diagram.skupine = function(drzave, skupine, k) {\n drzave %>%\n bind_cols(skupine) %>%\n dplyr::select(drzava = ...1, skupina = ...2) %>%\n left_join(\n evropa.poligoni,\n by = \"drzava\"\n ) %>%\n ggplot() +\n geom_polygon(\n mapping = aes(long, lat, group = group, fill = skupina),\n color = \"grey\"\n ) +\n scale_fill_brewer() +\n coord_map() +\n xlim(-25, 50) +\n theme_classic() +\n theme(\n axis.line = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank(),\n axis.title = element_blank()\n )\n}\n\nset.seed(42)\nskupine = nakupi[, -1] %>%\n kmeans(centers = 2) %>%\n getElement(\"cluster\") %>%\n as.ordered()\n\nz1 <- prostorski.diagram.skupine(drzave, skupine, 2)\n\nk = dendrogram %>%\n hc.kolena %>%\n hc.kolena.k() %>%\n getElement(1)\n\nskupine = dendrogram %>%\n cutree(k = 4) %>%\n as.ordered()\n\nz2<- prostorski.diagram.skupine(drzave, skupine, k)\n\npodatki.ucni <- tabela1 %>%\n filter(\n Year == 2019\n ) %>%\n dplyr::select(-Year, - Area)\npodatki.ucni <- podatki.ucni[-c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68), ]\n\npodatki.ucni <- podatki.ucni[(-c(32, 33, 34)),]\ng <- ggplot(podatki.ucni, aes(x=BDPpc, y=Value)) + geom_point()\ng + geom_smooth(method=\"lm\")\n\nlin <- lm(data=podatki.ucni, Value ~ BDPpc + Education)\nlin\nnapovedi <- predict(lin)\n\nkv <- lm(data=podatki.ucni, Value ~ Education + I(BDPpc^2))\n\nmls <- loess(data=podatki.ucni, Value ~ BDPpc + Education)\n\n\nsapply(list(lin, kv, mls), function(x) mean((x$residuals^2)))\n\n\n\n\npodatki.ucni <- transform(podatki.ucni, Education = as.numeric(as.character(Education)))\nk <- 5\nformula <- Value ~ BDPpc\n\nnapaka.cv <- function(podatki, k, formula) {\n n <- nrow(podatki)\n r <- sample(1:n)\n \n razrez <- cut(1:n, k, labels = FALSE)\n \n razbitje <- split(r, razrez)\n \n pp.napovedi = rep(0, n)\n for (i in 1:length(razbitje)) {\n #Naučimo se modela na množici S/Si\n model = podatki[ -razbitje[[i]], ] %>% lm(formula = formula)\n #Naučen model uporabimo za napovedi na Si\n pp.napovedi[ razbitje[[i]] ] = predict(object = model, newdata = podatki[ razbitje [[i]], ] )\n \n }\n \n #model so učni podatki in ostalo ( razbitje[[i]]) so testni podatki. \n \n napaka <- mean((pp.napovedi - podatki$Value)^2)\n return(napaka)\n}\nnapaka.cv(podatki.ucni, 5, formula)\n\nformule <- c(Value ~ BDPpc,\n Value ~ BDPpc + I(BDPpc^2),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3) + I(BDPpc^4),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3) + I(BDPpc^4) +I(BDPpc^5))\nnapake <- rep(0, 5)\nfor (i in 1:5){\n formula <- formule[[i]]\n napaka <- napaka.cv(podatki.ucni, 5, formula) \n napake[i] <- napaka\n}\nwhich.min(napake)\nlin.model <- lm(data = podatki.ucni, formula = Value ~ BDPpc + I(BDPpc^2))\n\n\nnapaka_regresije = function(podatki, model) {\n podatki %>%\n bind_cols(Value.hat = predict(model, podatki)) %>%\n mutate(\n izguba = (Value - Value.hat) ^ 2\n ) %>%\n dplyr::select(izguba) %>%\n unlist() %>%\n mean()\n}\n\n\n\nlibrary(ranger)\nlibrary(janitor)\np.ucni <- janitor::clean_names(podatki.ucni)\nset.seed(42)\n\nucenje = function(podatki, formula, algoritem) {\n switch(\n algoritem,\n lin.reg = lm(formula, data = podatki),\n ng = ranger(formula, data = podatki)\n )\n}\n\nnapovedi = function(podatki, model, algoritem) {\n switch(\n algoritem,\n lin.reg = predict(model, podatki),\n ng = predict(model, podatki)$predictions\n )\n}\n\nnapaka_regresije = function(podatki, model, algoritem) {\n podatki %>%\n bind_cols(value.hat = napovedi(podatki, model, algoritem)) %>%\n mutate(\n izguba = (value - value.hat) ^ 2\n ) %>%\n dplyr::select(izguba) %>%\n unlist() %>%\n mean()\n}\n\nnapaka_razvrscanja = function(podatki, model, algoritem) {\n podatki %>%\n bind_cols(value.hat = napovedi(podatki, model, algoritem)) %>%\n mutate(\n izguba = (value != value.hat)\n ) %>%\n dplyr::select(izguba) %>%\n unlist() %>%\n mean()\n}\n\n\n\n\n\nlin.model = p.ucni %>% ucenje(value ~ bd_ppc, \"lin.reg\")\np.ucni %>% napaka_regresije(lin.model, \"lin.reg\")\n\nset.seed(42)\nng.reg.model = p.ucni %>% ucenje(value ~ bd_ppc, \"ng\")\nprint(p.ucni %>% napaka_regresije(ng.reg.model, \"ng\"))\n\nk <- 5\nformula2 <- value ~ bd_ppc\n\nnapaka.cv2 <- function(podatki, k, formula) {\n n <- nrow(podatki)\n r <- sample(1:n)\n \n razrez <- cut(1:n, k, labels = FALSE)\n \n razbitje <- split(r, razrez)\n \n pp.napovedi = rep(0, n)\n for (i in 1:length(razbitje)) {\n #Naučimo se modela na množici S/Si\n model = podatki[ -razbitje[[i]], ] %>% ranger(formula = formula)\n #Naučen model uporabimo za napovedi na Si\n pp.napovedi[ razbitje[[i]] ] = predict(object = model, data = podatki[ razbitje [[i]], ])$predictions\n \n }\n \n #model so učni podatki in ostalo ( razbitje[[i]]) so testni podatki. \n \n napaka <- mean((pp.napovedi - podatki$value)^2)\n return(napaka)\n}\nnapaka.cv(p.ucni, 5, formula2)\n\nformule <- c(Value ~ BDPpc,\n Value ~ BDPpc + I(BDPpc^2),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3) + I(BDPpc^4),\n Value ~ BDPpc + I(BDPpc^2) + I(BDPpc^3) + I(BDPpc^4) +I(BDPpc^5))\nnapake <- rep(0, 5)\nfor (i in 1:5){\n formula <- formule[[i]]\n napaka <- napaka.cv(podatki.ucni, 5, formula) \n napake[i] <- napaka\n}\nwhich.min(napake)\nlin.model <- lm(data = podatki.ucni, formula = Value ~ BDPpc + I(BDPpc^2))\n\nlibrary(iml)\n\n# Pripravimo le napovedne spremenljivke,\n# kot jih rabi funkcija Predictor$new\n\nX = p.ucni %>% dplyr::select(bd_ppc, education)\n\n# Funkciji Predictor$new moramo povedati\n# kako napovedujemo z modelom naključnih gozdov \n\npfun = function(model, newdata) {\n predict(model, data = newdata, predict.all = FALSE)$predictions\n}\n\n# pripravimo najprej objekt razreda Prediktor\n# prvi argument funkcije je model,\n# drugi in tretji so podatki o napovednih\n# in ciljni spremenljivki,\n# zadnji pa funkcija za napovedovanje\n\nreg.pred = Predictor$new(\n ng.reg.model,\n data = X, y = p.ucni$value,\n predict.fun = pfun\n)\n\n# na koncu uporabimo funkcijo FeatureImp$new\nreg.moci = FeatureImp$new(reg.pred, loss = \"mse\")\n\nplot(reg.moci)\n\n\nslo <- tabela1 %>% filter(Country == \"Slovenia\")\nslo <- slo[-c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32),]\nslo <- slo[-c(1, 2),]\n\n\nCAC <- slo[,4]\nCACs <- slo[,c(1,4)]\nCACs %>% ggplot() +\n geom_line(\n mapping = aes(x = Year, y = Value),\n color = \"pink\"\n )\nlibrary(ranger)\nLag <- function(x, n){\n (c(rep(NA, n), x)[1 : length(x)] )\n}\nnaredi.df <- function(x){data.frame(Value = x,\n Value1 = Lag(x, 1),\n Value2 = Lag(x, 2) ,\n Value3 = Lag(x, 3),\n Value4 = Lag(x, 4)\n)\n}\ndf <- naredi.df(CAC$Value)\nmodel.bi = ranger(Value ~ Value1 + Value2 + Value3 + Value4, data=df %>% drop_na())\nlllll <- nrow(df)\nfor (i in 1:5){\n df <- naredi.df(c(df$Value, NA))\n napoved = predict(model.bi, data = df[lllll + i, ] )$predictions\n df[lllll+i, 1] = napoved\n}\nnapovedi = df[c(15, 16, 17, 18, 19), 1]\nCACs2 <- CACs\nCACs2[c(15, 16, 17, 18, 19),2] = napovedi\nCACs2[c(15, 16, 17, 18, 19),1] = c(2020, 2021, 2022, 2023, 2024)\n\nnap <- ggplot(CACs2) + geom_point(aes(x = Year, y = Value, colour = Year > 2019)) +\n scale_colour_manual(name = 'Napovedi', values = setNames(c('magenta','blue'),c(T, F))) +\n xlab('Leto') + ylab('Odstotek ljudi, ki spletno nakupuje')\n\n\n\n\n\n", "meta": {"hexsha": "7914303e5826a9cd9a3e6e8fdc3935ddb6b10359", "size": 16336, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "pavlanovak/APPR-2021-22", "max_stars_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_stars_repo_licenses": ["MIT"], "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": "pavlanovak/APPR-2021-22", "max_issues_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-03T11:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T22:29:08.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "pavlanovak/APPR-2021-22", "max_forks_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_forks_repo_licenses": ["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.305958132, "max_line_length": 166, "alphanum_fraction": 0.6016160627, "num_tokens": 6068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6016472172305779}} {"text": "## Dati\r\n\r\nmi.1 <- 1.02\r\nvar.1 <- 2.17\r\n\r\nmi.2 <- 1.85\r\nvar.2 <- 4.65\r\n\r\n## Svolgimento\r\n\r\n\r\ny.negativa <- pnorm(0, mi.2, sqrt(var.2))\r\nx.negativa <- pnorm(0, mi.1, sqrt(var.1))\r\n\r\npr.1 <- 1 - (x.negativa*y.negativa)\r\npr.2 <- (1 - x.negativa)/pr.1\r\n\r\nprint(pr.1)\r\nprint(pr.2)", "meta": {"hexsha": "06714a45c6af4d83ea099820430440a68cd5dc5c", "size": 275, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Esercizio 50.r", "max_stars_repo_name": "mfranzil/PSUniTN", "max_stars_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Esercizio 50.r", "max_issues_repo_name": "mfranzil/PSUniTN", "max_issues_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Esercizio 50.r", "max_forks_repo_name": "mfranzil/PSUniTN", "max_forks_repo_head_hexsha": "c4baecf5b01fb7cc2cfc66f4881ae47451475dac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.4736842105, "max_line_length": 42, "alphanum_fraction": 0.5345454545, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.6015953164935091}} {"text": "#' Obtain 2x2 contingency table from marginal parameters and odds ratio\n#'\n#' Columns are the case and control frequencies\n#' Rows are the frequencies for allele 1 and allele 2\n#'\n#' @param af Allele frequency of effect allele \n#' @param prop Proportion of cases\n#' @param odds_ratio Odds ratio\n#' @param eps tolerance. Default = 1e-15\n#'\n#' @export\n#' @return 2x2 contingency table as matrix\ncontingency <- function(af, prop, odds_ratio, eps=1e-15)\n{\n\ta <- odds_ratio-1\n\tb <- (af+prop)*(1-odds_ratio)-1\n\tc_ <- odds_ratio*af*prop\n\n\tif (abs(a) < eps)\n\t{\n\t\tz <- -c_ / b\n\t} else {\n\t\td <- b^2 - 4*a*c_\n\t\tif (d < eps*eps) \n\t\t{\n\t\t\ts <- 0\n\t\t} else {\n\t\t\ts <- c(-1,1)\n\t\t}\n\t\tz <- (-b + s*sqrt(max(0, d))) / (2*a)\n\t}\n\ty <- vapply(z, function(a) zapsmall(matrix(c(a, prop-a, af-a, 1+a-af-prop), 2, 2)), matrix(0.0, 2, 2))\n\ti <- apply(y, 3, function(u) all(u >= 0))\n\treturn(y[,,i])\n}\n\n#' Estimate allele frequency from SNP\n#'\n#' @param g Vector of 0/1/2\n#'\n#' @export\n#' @return Allele frequency \nallele_frequency <- function(g)\n{\n\t(sum(g == 1) + 2 * sum(g == 2)) / (2 * sum(!is.na(g)))\n}\n\n\n#' Estimate the allele frequency in population from case/control summary data\n#'\n#' @param af Effect allele frequency (or MAF)\n#' @param prop Proportion of samples that are cases\n#' @param odds_ratio Odds ratio\n#' @param prevalence Population disease prevalence\n#'\n#' @export\n#' @return Population allele frequency\nget_population_allele_frequency <- function(af, prop, odds_ratio, prevalence)\n{\n\tco <- contingency(af, prop, odds_ratio)\n\taf_controls <- co[1,2] / (co[1,2] + co[2,2])\n\taf_cases <- co[1,1] / (co[1,1] + co[2,1])\n\taf <- af_controls * (1 - prevalence) + af_cases * prevalence\n\treturn(af)\n}\n\n\n#' Estimate proportion of variance of liability explained by SNP in general population\n#'\n#' This uses equation 10 in Genetic Epidemiology 36 : 214–224 (2012)\n#' \n#' @param b Log odds ratio\n#' @param af allele frequency\n#' @param ncase Number of cases\n#' @param ncontrol number of controls\n#' @param prevalence prevalence\n#' @param model Is the effect size estiamted in \"logit\" (default) or \"probit\" model\n#'\n#' @export\n#' @return Rsq\nlor_to_rsq <- function(b, af, ncase, ncontrol, prevalence, model=\"logit\")\n{\n\tif(model == \"logit\")\n\t{\n\t\tve <- pi^2/3\n\t} else if(model == \"probit\") {\n\t\tve <- 1\n\t} else {\n\t\tstop(\"Model must be probit or logit\")\n\t}\n\taf <- get_population_allele_frequency(af, ncase / (ncase + ncontrol), exp(b), prevalence)\n\tvg <- b^2 * af * (1-af)\n\treturn(vg / (vg + ve) / 0.58)\n}\n\n", "meta": {"hexsha": "8ab2efae779eebe4f90bfb2cd245086a04fb7275", "size": 2477, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rsq_liability.r", "max_stars_repo_name": "explodecomputer/simulateGP", "max_stars_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T16:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T16:58:46.000Z", "max_issues_repo_path": "R/rsq_liability.r", "max_issues_repo_name": "aeaswar81/simulateGP", "max_issues_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T16:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:14:15.000Z", "max_forks_repo_path": "R/rsq_liability.r", "max_forks_repo_name": "aeaswar81/simulateGP", "max_forks_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T19:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T16:59:02.000Z", "avg_line_length": 25.8020833333, "max_line_length": 103, "alphanum_fraction": 0.6487686718, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.6014349609050025}} {"text": "#' Function that creates a sinusoidal Sea Surface Temperature (SST) curve\n#' from a list of parameters\n#' \n#' Takes the specified parameters for amplitude, period, phase and average value\n#' as well as the number of years specified and the time interval. It then \n#' creates a sinusoid based on the boundary conditions. Used as intermediate\n#' step during iterative modeling.\n#' \n#' @param T_par List of four parameters describing (in order) amplitude\n#' (\\code{T_amp}; in degrees C), period (\\code{T_per}; in days), phase\n#' (\\code{T_pha} in day of the year) and average temperature (\\code{T_av};\n#' in degrees C)\n#' @param years Length of the preferred sinusoid in number of years (defaults\n#' to 1)\n#' @param t_int Time interval of sinusoidal record (in days)\n#' @return A matrix containing columns for time (in days) and SST (in degrees C)\n#' @examples\n#' # Set parameters\n#' T_amp <- 20\n#' T_per <- 365\n#' T_pha <- 150\n#' T_av <- 15\n#' T_par <- c(T_amp, T_per, T_pha, T_av)\n#' SST <- temperature_curve(T_par, 1, 1) # Run the function\n#' @export\ntemperature_curve <- function(T_par, # Function to create temperature as function of time based on sinusoidal parameters\n years = 1, # Default number of years of the record = 1\n t_int = 1 # Default time interval = 1 day\n ){\n\n T_amp <- T_par[1] # Seasonal SST range (degr. C)\n T_per <- T_par[2] # Period of SST seasonality (days)\n T_pha <- T_par[3] # Timing of peak in SST sinusoid (day of the year)\n T_av <- T_par[4] # Annual average SST (degr. C)\n\n t <- seq(0, years * T_per, t_int) # Define time axis based on the number of days in a year and the time interval. Model multiple years (default = 3) to accommodate changes in growth rate over lifetime.\n\n SST <- T_av + T_amp/2 * sin((2 * pi * (t - T_pha + T_per/4)) / T_per) # Create SST sinusoid based on parameters and time vector\n\n # Collate results and export\n res <- cbind(t, SST)\n return(res)\n}", "meta": {"hexsha": "eafabf87508d28a5bdc3f342d2f529fce43c647a", "size": 1936, "ext": "r", "lang": "R", "max_stars_repo_path": "R/temperature_curve.r", "max_stars_repo_name": "nhoeche/ShellChron.jl", "max_stars_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/temperature_curve.r", "max_issues_repo_name": "nhoeche/ShellChron.jl", "max_issues_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/temperature_curve.r", "max_forks_repo_name": "nhoeche/ShellChron.jl", "max_forks_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.023255814, "max_line_length": 205, "alphanum_fraction": 0.6911157025, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.601404529574498}} {"text": "longmult <- function(xstr, ystr)\n{\n #get the number described in each string\n getnumeric <- function(xstr) as.numeric(unlist(strsplit(xstr, \"\")))\n\n x <- getnumeric(xstr)\n y <- getnumeric(ystr)\n\n #multiply each pair of digits together\n mat <- apply(x %o% y, 1, as.character)\n\n #loop over columns, then rows, adding zeroes to end of each number in the matrix to get the correct positioning\n ncols <- ncol(mat)\n cols <- seq_len(ncols)\n for(j in cols)\n {\n zeroes <- paste(rep(\"0\", ncols-j), collapse=\"\")\n mat[,j] <- paste(mat[,j], zeroes, sep=\"\")\n }\n\n nrows <- nrow(mat)\n rows <- seq_len(nrows)\n for(i in rows)\n {\n zeroes <- paste(rep(\"0\", nrows-i), collapse=\"\")\n mat[i,] <- paste(mat[i,], zeroes, sep=\"\")\n }\n\n #add zeroes to the start of the each number, so they are all the same length\n len <- max(nchar(mat))\n strcolumns <- formatC(cbind(as.vector(mat)), width=len)\n strcolumns <- gsub(\" \", \"0\", strcolumns)\n\n #line up all the numbers below each other\n strmat <- matrix(unlist(strsplit(strcolumns, \"\")), byrow=TRUE, ncol=len)\n\n #convert to numeric and add them\n mat2 <- apply(strmat, 2, as.numeric)\n sum1 <- colSums(mat2)\n\n #repeat the process on each of the totals, until each total is a single digit\n repeat\n {\n ntotals <- length(sum1)\n totals <- seq_len(ntotals)\n for(i in totals)\n {\n zeroes <- paste(rep(\"0\", ntotals-i), collapse=\"\")\n sum1[i] <- paste(sum1[i], zeroes, sep=\"\")\n }\n len2 <- max(nchar(sum1))\n strcolumns2 <- formatC(cbind(as.vector(sum1)), width=len2)\n strcolumns2 <- gsub(\" \", \"0\", strcolumns2)\n strmat2 <- matrix(unlist(strsplit(strcolumns2, \"\")), byrow=TRUE, ncol=len2)\n mat3 <- apply(strmat2, 2, as.numeric)\n sum1 <- colSums(mat3)\n if(all(sum1 < 10)) break\n }\n\n #Concatenate the digits together\n ans <- paste(sum1, collapse=\"\")\n ans\n}\n\na <- \"18446744073709551616\"\nlongmult(a, a)\n", "meta": {"hexsha": "aa91151788b9e864a46eb482525bac15f8cc7ef0", "size": 1962, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Long-multiplication/R/long-multiplication-2.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "Task/Long-multiplication/R/long-multiplication-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Long-multiplication/R/long-multiplication-2.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 29.2835820896, "max_line_length": 114, "alphanum_fraction": 0.6116207951, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6013139497289386}} {"text": "# ......................................................................................\n# .................. Cvičení 11. Dvou-výběrové testy/Intervalové odhady.................\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# Přehled testů/konstrukcí IO ####\n# * Párová vs. dvouvýběrová data ####\n# - Párová data označují data, která jsou vstažena k dvěma měřením stejných entit ->\n# datové sloupce jsou závislé. \n# - Pokud jsou nezávislé, jedná se o dvouvýběrový test. \n# - Pro párová data napočítáme rozdíl mezi sloupci (případně jinou funkci dle zadání) a\n# použijeme jednovýběrové testy na tento rozdíl.\n\n\n# ** Příklady párových dat: ####\n# - měření žárovek při dvou různých teplotách (pokud každý kus je měřen dvakrát - při\n# teplotě 1 a teplotě 2)\n# - zde pozor, může se stát, že jsou testy např. destruktivní a nelze měřit dvakrát\n# stejnou entitu (výrobek). Potom bychom uvažovali dva nezávislé výběry, každý pro jeden\n# typ měření -> nezávislé datové sloupce -> dvouvýběrové testy\n# - měření hodnot v krvi pacienta před a po podání léčiva\n# - opět pozor na například testování léků ve dvou skupinách (placebo/skutečný lék)\n# -> dvě nezávislé skupiny -> dvouvýběrové testy\n\n\n# * Obecně k dvouvýběrovým testům/IO ####\n# - test je vždy svázán s příslušným IO -> stejné podmínky pro použití\n# - pokud má test podmínky použití (např.: normalita dat, symetrie dat) pak musí tuto\n# podmínku splnit **oba soubory**, pokud alespoň jeden nesplňuje, považujeme předpoklad\n# za porušený\n# - jeden z velmi důležitých předpokladů je nezávislost dat\n# - např.: měření výrobků výrobce A a výrobků výrobce B - zde je rozumné\n# předpokládat, že výrobky výrobce A jsou samostatné entity od výrobků výrobce B\n\n\n# * Dvouvýběrové testy/IO - rozdíl měr polohy ####\n\n\n# vyrobíme si testovací data - tak je lze použít všude\ndata1 = rnorm(n = 30, mean = 105, sd = 10)\ndata2 = rnorm(n = 30, mean = 100, sd = 10)\nboxplot(data1,data2)\n\n# ** Dvouvýběrový Studentův t-test ####\n# - Testuje/odhaduje rozdíl středních hodnot: $H_0: \\mu_{1} - \\mu_{2} = a$\n# - požadavky:\n# - Normalita dat\n# - Homoskedasticita (shoda rozptlyů)\n# - nezávislost výběrů\n# - funkce musí mít parametr var.equal = TRUE\n\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 != 2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n var.equal = TRUE, conf.level = 0.95)\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 > 2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"greater\",\n var.equal = TRUE, conf.level = 0.95)\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 < 2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"less\",\n var.equal = TRUE, conf.level = 0.95)\n\n# ** Aspinové-Welshův test ####\n# - Testuje/odhaduje rozdíl středních hodnot: $H_0: \\mu_{1} - \\mu_{2} = a$\n# - požadavky:\n# - Normalita dat\n# - nezávislost výběrů\n# - funkce musí mít parametr var.equal = FALSE\n\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 != 2\n\nt.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n var.equal = FALSE, conf.level = 0.95)\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 > 2\n\nt.test(x = data1, y = data2, mu = 0, alternative = \"greater\",\n var.equal = FALSE, conf.level = 0.95)\n\n# H0: mu1 - mu2 = 2 \n# HA: mu1 - mu2 < 2\n\nt.test(x = data1, y = data2, mu = 0, alternative = \"less\",\n var.equal = FALSE, conf.level = 0.95)\n\n# ** Mannův-Whitneyův test ####\n# - Testuje/odhaduje rozdíl mediánů: $H_0: X_{0.5,1} - X_{0.5,2} = a$\n# - požadavky:\n# - nezávislost výběrů\n# - (stejný typ rozdělení)\n# - vyžaduje conf.int = TRUE, pro spočtení IO\n\n\n# H0: X0.5,1 - X0.5,2 = 2 \n# HA: X0.5,1 - X0.5,2 != 2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"two.sided\",\n conf.level=0.95, conf.int = TRUE)\n\n# H0: X0.5,1 - X0.5,2 = 2 \n# HA: X0.5,1 - X0.5,2 > 2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"greater\",\n conf.level=0.95, conf.int = TRUE)\n\n# H0: X0.5,1 - X0.5,2 = 2 \n# HA: X0.5,1 - X0.5,2 < 2\n\nwilcox.test(x = data1, y = data2, mu = 2, alternative = \"less\",\n conf.level=0.95, conf.int = TRUE)\n\n# * Dvouvýběrové testy/IO - podíl rozptylů ####\n# ** F-test ####\n# - Testuje/odhaduje podíl rozptylů: $H_0: \\sigma^2_{1} / \\sigma^2_{2} = a$\n# - požadavky:\n# - normalita dat\n# - nezávislost výběrů\n\n\n# H0: sigma1^2/sigma2^2 = 1\n# H0: sigma1^2/sigma2^2 != 1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"two.sided\",\n conf.level = 0.95)\n\n# H0: sigma1^2/sigma2^2 = 1\n# H0: sigma1^2/sigma2^2 > 1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"greater\",\n conf.level = 0.95)\n\n# H0: sigma1^2/sigma2^2 = 1\n# H0: sigma1^2/sigma2^2 < 1\n\nvar.test(x = data1, y = data2, ratio = 1, alternative = \"less\",\n conf.level = 0.95)\n\n# ** Leveneův test ####\n# - Testuje rovnost rozptylů: $H_0: \\sigma^2_{1} = \\sigma^2_{2}$ !\n# - požadavky:\n# - nezávislost výběrů\n# - vyžaduje data ve standardním datovém formátu\n# - funkce leveneTest v balíčku car\n\n\n# vyrobíme data ve standardním datovém formátu\n\ndata1.df = as.data.frame(data1)\ndata1.df$typ = \"d1\"\ncolnames(data1.df) = c(\"data\", \"typ\")\n\ndata2.df = as.data.frame(data2)\ndata2.df$typ = \"d2\"\ncolnames(data2.df) = c(\"data\", \"typ\")\n\ndata = rbind(data1.df, data2.df)\ndata$typ = as.factor(data$typ)\n\nhead(data)\n\n# install.packages(\"car\")\n\n# H0: sigma1^2 = sigma2^2\n# HA: sigma1^2 != sigma2^2\n\ncar::leveneTest(data$data ~ data$typ)\n\n# * Dvouvýběrové testy/IO - rozdíl pravděpodobností ####\n# ** Test homogenity dvou binomických rozdělení ####\n# - Testuje shodu/odhaduje rozdíl pravděpodobností: $H_0: \\pi_{1} - \\pi_{2} = 0$\n# - požadavky:\n# - dostatečná velikost výběrů: $n_i>\\frac{9}{p_i(1-p_i)}$\n# - nezávislost výběrů\n\n\n# vyrobíme si vhodná data\npi1 = 0.4\npi2 = 0.3\n\ndp1 = runif(n = 100, min = 0, max = 1) < pi1\ndp2 = runif(n = 130, min = 0, max = 1) < pi2\n\nx1 = sum(dp1)\nn1 = length(dp1)\n\nx2 = sum(dp2)\nn2 = length(dp2)\n\nx1\nn1\nx2\nn2\n\n# H0: pi1 - pi2 = 0\n# HA: pi1 - pi2 != 0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"two.sided\",\n conf.level=0.95)\n\n# H0: pi1 - pi2 = 0\n# HA: pi1 - pi2 > 0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"greater\",\n conf.level=0.95)\n\n# H0: pi1 - pi2 = 0\n# HA: pi1 - pi2 < 0\n\nprop.test(x = c(x1, x2), n = c(n1, n2), alternative=\"less\",\n conf.level=0.95)\n\n# Příklady ####\n# * Příkald 1. ####\n# Data v souboru cholesterol2.xls udávají hladinu cholesterolu v krvi mužů dvou různých\n# věkových skupin (20-30 letých a 40-50 letých). Ověřte na hladině významnosti 0,05\n# hypotézu, zda se hladina cholesterolu v krvi starších mužů neliší od hladiny\n# cholesterolu v krvi mladších mužů.\n\n# Načtení dat\nchol = readxl::read_excel(\"./CV11/data/testy_dvouvyberove.xlsx\",\n sheet = \"cholesterol2\",\n skip = 1) \ncolnames(chol)=c(\"mladsi\",\"starsi\")\nhead(chol)\n\n# Převod do standardního datového formátu\nchol.s = stack(chol)\nchol.s = na.omit(chol.s)\ncolnames(chol.s) = c (\"hodnoty\",\"skupina\")\nhead(chol.s)\n\n# Explorační analýza\nboxplot(chol.s$hodnoty ~ chol.s$skupina)\n\n# Odstranění odlehlých pozorování:\nchol.s$hodnoty.bez = chol.s$hodnoty\n\npom = boxplot(chol.s$hodnoty[chol.s$skupina == \"mladsi\"], plot = FALSE)\nchol.s$hodnoty.bez[chol.s$skupina == \"mladsi\" & \n chol.s$hodnoty %in% pom$out] = NA\n\npom = boxplot(chol.s$hodnoty[chol.s$skupina == \"starsi\"], plot = FALSE)\nchol.s$hodnoty.bez[chol.s$skupina == \"starsi\" & \n chol.s$hodnoty %in% pom$out] = NA\n\nboxplot(chol.s$hodnoty.bez~chol.s$skupina)\n\n# pozor v datech máme NA a musíme s tím dále počítat!!! \n# (např. u zjištění délky)\n\nlibrary(dplyr)\n\nchol.s %>% group_by(skupina) %>% \n summarise(pocet = sum(!is.na(hodnoty.bez)),\n prumer = mean(hodnoty.bez, na.rm = TRUE), \n smer.odch = sd(hodnoty.bez, na.rm = TRUE))\n\n# zaokrouhlování -> 3 platné cifry -> dle sd na tisíciny\n\n# **Test o shodě středních hodnot / mediánů**\n\n\n# Ověření normality\nchol.s %>% group_by(skupina) %>% \n summarise(norm.pval = shapiro.test(hodnoty.bez)$p.value)\n\n# normalita na hl. významnosti 0.05 OK\n\n# Ověření shody rozptylů\n\n# Exploračně\nrozptyly = chol.s %>% group_by(skupina) %>% \n summarise(rozptyl = sd(hodnoty.bez, na.rm = TRUE)^2)\nrozptyly\nmax(rozptyly$rozptyl)/min(rozptyly$rozptyl)\n\n# explorační posouzení: poměr nejvetšího ku nejmenšímu je > než 2\n# -> nepředpokládám shodu rozptylu\n\n# Exaktně pomocí F-testu\n\n# H0: sigma.starsi = sigma.mladsi\n# Ha: sigma.starsi <> sigma.mladsi\n\n# vyberu si žádaná data\nstarsi.bez = chol.s$hodnoty.bez[chol.s$skupina == \"starsi\"]\nmladsi.bez = chol.s$hodnoty.bez[chol.s$skupina == \"mladsi\"]\n\nvar.test(x = starsi.bez, y = mladsi.bez, ratio = 1, conf.level=0.95)\n\n# Na hl. významnosti 0.05 zamítáme předpoklad o shodě rozptylů\n# Pozorovanou neshodu mezi rozptyly lze na hladině významnosti 0,05 \n# označit za statisticky významnou.\n\n# Ověření shody středních hodnot (Aspinové-Welchův test)\n\n# H0: mu.starsi - mu.mladsi = 0\n# Ha: mu.starsi - mu.mladsi != 0\n\nt.test(x = starsi.bez, y = mladsi.bez, mu = 0, \n alternative = \"two.sided\", var.equal=FALSE, conf.level=0.95)\n\n# na hl. významnosti 0.05 zamítáme H0-> existuje stat. významný rozdíl.\n\n# H0: mu.starsi = mu.mladsi (mu.starsi - mu.mladsi = 0)\n# Ha: mu.starsi > mu.mladsi (mu.starsi - mu.mladsi > 0)\n\nt.test(x = starsi.bez, y = mladsi.bez, mu = 0, alternative = \"greater\",\n var.equal = FALSE, conf.level = 0.95)\n\n# Na hladině významnosti 0,05 zamítáme předpoklad o shodě středních \n# hodnot cholesterolu ve skupinách mladších a starších mužů ve prospěch\n# alternativy, že starší muži mají vyšší střední hladinu cholesterolu \n# než muži mladší\n# Dle výsledků výběrového šetření očekáváme, že střední obsah \n# cholesterolu v krvi straších mužů bude cca o 0,524 mmol/l vyšší než \n# střední obsah chol. u mladších mužů. Dle 95% levostranný interv.\n# odhadu daného rozdílu očekáváme střední obsah cholesterolu u \n# starších mužů minimálně o 0,457 mmol/l větší než stř. hodnota \n# cholesterolu u mladších mužů. \n\n# * Příklad 2. ####\n# Údaje v souboru deprese.xls představují délku remise ve dnech z prostého náhodného\n# výběru ze dvou různých skupin pacientů (pacienti s endogenní depresi a pacienti s\n# neurotickou depresí). Ověřte, zda je pozorovaný rozdíl mezi průměrnou délkou remise u\n# těchto dvou skupin pacientů statisticky významný.\n\n\n# Načtení dat z xlsx souboru (pomoci balíčku readxl)\ndeprese = readxl::read_excel(\"data/testy_dvouvyberove.xlsx\",\n sheet = \"deprese\") \ncolnames(deprese)=c(\"endo\",\"neuro\")\n\nhead(deprese)\n\n# Převod do standardního datového formátu\ndeprese.s = stack(deprese)\ndeprese.s = na.omit(deprese.s)\ncolnames(deprese.s) = c (\"hodnoty\",\"skupina\")\n\nhead(deprese.s)\n\n# Explorační analýza\nboxplot(deprese.s$hodnoty~deprese.s$skupina)\n\n# Data neobsahují odlehlá pozorování.\n\nlibrary(dplyr)\n\ndeprese.s %>% group_by(skupina) %>% \n summarise(pocet = length(hodnoty),\n prumer = mean(hodnoty), \n smer.odch = sd(hodnoty))\n\n# zaokrouhlování -> 3 platné cifry -> dle sd na jednotky\n\n# **Test o shodě středních hodnot / mediánů**\n\n\n# Ověření normality\n# Předpoklad normality ověříme Shapirovovým - Wilkovovým testem.\ndeprese.s %>% group_by(skupina) %>% \n summarise(norm.pval = shapiro.test(hodnoty)$p.value)\n\n\n# Na hl. významnosti 0,05 zamítáme předpoklad normality \n\n# alespoň orientačne zkontrolujeme podobnost rozdělení\n\n# vybereme si data pro jednodušší spracování\n\nneuro = deprese.s$hodnoty[deprese.s$skupina == \"neuro\"]\nendo = deprese.s$hodnoty[deprese.s$skupina == \"endo\"]\n\n\npar(mfrow = c(1,2))\nhist(neuro)\nhist(endo)\n\n# Ověření shody mediánů (Mannův - Whitneyho test)\n\n# Dle histogramů předpokládáme, že data mají stejný typ rozdělení.\n\n# H0: med.neuro = med.endo (med.neuro - med.endo = 0)\n# Ha: med.neuro != med.endo (med.neuro - med.endo != 0)\n\nwilcox.test(x = neuro, y = endo, mu = 0, alternative = \"two.sided\",\n conf.level=0.95, conf.int = TRUE)\n\n# na hl. významnosti 0.05 zamítáme H0-> existuje stat. významný rozdíl\n\n# H0: med.neuro = med.endo (med.neuro - med.endo = 0)\n# Ha: med.neuro > med.endo (med.neuro - med.endo > 0)\n\nwilcox.test(x = neuro, y = endo, mu = 0, alternative = \"greater\",\n conf.level=0.95, conf.int = TRUE)\n\n# Na hladině významnosti 0,05 zamítáme hyp. o shodě mediánů dob do\n# remise onemocnění pro obě skupiny pacientů ve prospěch alternativy \n\n# Medián doby remise je u pacientů s neurotickou depresí statisticky\n# významně větší než u pacientů s endogenní depresí.\n\n# Doba remise pacientů s neurotickou depresí je cca o 191 dnů delší \n# než u pacientů s endogenní depresí. Dle 95% levostranného \n# intervalového odhadu očekáváme, že pacienti s neuro. depresí mají \n# minimálně o 168 dní delší dobu remise než pacienti s endo. depresí.\n\n# * Příklad 3. ####\n# Sledujeme osmolalitu moči na lůžkové stanici v 08:00 hodin a v 11:00 hodin u 16 mužů.\n# Na základě výsledků uvedených v souboru osmolalita.xls ověřte, zda se osmolalita\n# statisticky významně zvýšila.\n\n\n# Načtení dat \nosmolalita = readxl::read_excel(\"data/testy_dvouvyberove.xlsx\",\n sheet = \"osmolalita\", skip = 1) \nosmolalita = osmolalita[,c(2,3)]\ncolnames(osmolalita)=c(\"o8\",\"o11\")\nhead(osmolalita)\n\n# Výpočet nárůstu osmolality\nosmolalita$narust = osmolalita$o11 - osmolalita$o8\n\n# Explorační analýza \npar(mfrow = c(1,1))\nboxplot(osmolalita$narust)\n\n# Data obsahují odlehlá pozorování.\n\n# Odstranění odlehlých hodnot\npom = boxplot(osmolalita$narust,plot = F)\n\nosmolalita$narust.bez = osmolalita$narust\nosmolalita$narust.bez[osmolalita$narust %in% pom$out] = NA\n\nboxplot(osmolalita$narust.bez)\n\n# Explorační analýza pro data bez odlehlých pozorování\nlibrary(dplyr)\n\nosmolalita %>% summarise(pocet = sum(!is.na(narust.bez)),\n prumer = mean(narust.bez, na.rm = TRUE), \n smer.odch = sd(narust.bez, na.rm = TRUE))\n\n# zaokrouhlování -> 2 platné cifry -> dle sd na jednotky\n\n# Ověření normality\n# Předpoklad normality ověříme Shapirovým - Wilkovým testem.\nshapiro.test(osmolalita$narust.bez)\n# Na hl. významnosti 0.05 nelze předpoklad normality zamítnout \n# (Shapirův-Wilkův test, W = 0,949, p-hodnota=0,545).\n\n# Párový t-test\n# H0: mu.narust = 0 mm\n# Ha: mu.narust > 0 mm\n\nt.test(osmolalita$narust.bez, mu = 0, alternative = \"greater\")\n\n# Dle výběrového šetření lze očekávat, že osmolalita moči se\n# mezi 8 a 11 hodinou zvýší o cca 24 mmol/kg. Dle 95% intervalového odhadu\n# lze očekávat, že dojde k navýšení osmolality minimálně o 10 mmol/kg).\n# Na hladině významnosti 0,05 lze tento nárůst označit za statisticky\n# významný (párový t-test, t = 3,1, df = 13, p-hodnota = 0,005).\n\n# * Příklad 4. ####\n# Byly testovány polovodičové součástky dvou výrobců - MM a PP. MM prohlašuje, že její\n# výrobky mají nižší procento vadných kusů. Pro ověření tohoto tvrzení bylo z produkce\n# MM náhodně vybráno 200 součástek, z nichž 14 bylo vadných. Podobný experiment byl\n# proveden u firmy PP s výsledkem 10 vadných ze 100 náhodně vybraných součástek.\n# ** a) ####\n# Otestujte tvrzení firmy MM čistým testem významnosti.\n\n\nx.MM = 14\nn.MM = 200\np.MM = x.MM/n.MM\np.MM\n\nx.PP = 10\nn.PP = 100\np.PP = x.PP/n.PP\np.PP\n\n# Ověření předpokladů\n9/(p.MM*(1-p.MM))\n9/(p.PP*(1-p.PP))\n\n# Dále pro obě firmy předpokládáme, že n/N < 0.05, tj. že daná populace (součástek) má\n# rozsah \n# alespoň 20 * n, tj. 20 * 200 (4 000), resp. 20 * 150 (3 000) součástek, což je asi\n# vcelku reálný předpoklad.\n\n\n# Pearsonův X2 test \n# H0: pi.PP = pi.MM\n# Ha: pi.PP > pi.MM\n\nprop.test(x = c(x.PP,x.MM),n = c(n.PP,n.MM), alternative = \"greater\",\n conf.level = 0.95)\n\n# Vzhledem k p-hodnotě > hl. významnosti 0.05 nezamítáme H0 - tedy předpokl.\n# shodné chybovosti. Nelze tedy říci, že firma MM má kvalitnější produkci.\n\n# Pearsonův X2 test \n# H0: pi.PP = pi.MM\n# Ha: pi.PP != pi.MM\n\nprop.test(x = c(x.PP,x.MM),n = c(n.PP,n.MM), alternative = \"two.sided\",\n conf.level = 0.95)\n\n# ** b) ####\n# Otestujte tvrzení firmy MM prostřednictvím intervalového odhadu na hladině významnosti\n# 0,05.\n\n\n# Na základě 95% Clopperova - Pearsonova pravostranného intervalového odhadu\n# (-0,036; 1,000) lze pozorovaný rozdíl v kvalitě výroby označit za \n# statisticky nevýznamný. Ke stejným závěrům můžeme dojít i na základě \n# Pearsonova pravostranného testu\n\n", "meta": {"hexsha": "aa43cf6b9a3b338ff981c1922f9e1ae1240a1796", "size": 16639, "ext": "r", "lang": "R", "max_stars_repo_path": "CV11/cv11.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": "CV11/cv11.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": "CV11/cv11.r", "max_forks_repo_name": "Atheloses/VSB-S8-PS", "max_forks_repo_head_hexsha": "fdef214f8169094b6366ce0489f92ef20b460702", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9851024209, "max_line_length": 88, "alphanum_fraction": 0.661277721, "num_tokens": 7001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6008730888049798}} {"text": "###############################################\n######### Data Analysis French MTPL2\n######### GLM, Regression Trees and Boosting\n######### Author: Mario Wuthrich\n######### Version May 6, 2018\n######### See also: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3164764\n###############################################\n\n###############################################\n######### load packages and data\n###############################################\n \nrequire(MASS)\nlibrary(CASdatasets)\nrequire(stats)\nlibrary(data.table)\nlibrary(plyr)\nlibrary(rpart)\nlibrary(rpart.plot)\nlibrary(Hmisc)\n\n\n\ndata(freMTPL2freq)\ndat <- freMTPL2freq\ndat$VehGas <- factor(dat$VehGas) # consider VehGas as categorical\ndat$n <- 1 # intercept\ndat$ClaimNb <- pmin(dat$ClaimNb, 4) # correct for unreasonable observations (that might be data error)\ndat$Exposure <- pmin(dat$Exposure, 1) # correct for unreasonable observations (that might be data error)\nstr(dat)\n\n\n###############################################\n######### Poisson deviance statistics\n###############################################\n\nPoisson.Deviance <- function(pred, obs){\n 2*(sum(pred)-sum(obs)+sum(log((obs/pred)^(obs))))/length(pred)\n }\n\n###############################################\n######### feature pre-processing for GLM\n###############################################\n\ndat2 <- dat\ndat2$AreaGLM <- as.integer(dat2$Area)\ndat2$VehPowerGLM <- as.factor(pmin(dat2$VehPower,9))\nVehAgeGLM <- cbind(c(0:110), c(1, rep(2,10), rep(3,100)))\ndat2$VehAgeGLM <- as.factor(VehAgeGLM[dat2$VehAge+1,2])\ndat2[,\"VehAgeGLM\"] <-relevel(dat2[,\"VehAgeGLM\"], ref=\"2\")\nDrivAgeGLM <- cbind(c(18:100), c(rep(1,21-18), rep(2,26-21), rep(3,31-26), rep(4,41-31), rep(5,51-41), rep(6,71-51), rep(7,101-71)))\ndat2$DrivAgeGLM <- as.factor(DrivAgeGLM[dat2$DrivAge-17,2])\ndat2[,\"DrivAgeGLM\"] <-relevel(dat2[,\"DrivAgeGLM\"], ref=\"5\")\ndat2$BonusMalusGLM <- as.integer(pmin(dat2$BonusMalus, 150))\ndat2$DensityGLM <- as.numeric(log(dat2$Density))\ndat2[,\"Region\"] <-relevel(dat2[,\"Region\"], ref=\"R24\")\ndat2$AreaRT <- as.integer(dat2$Area)\ndat2$VehGasRT <- as.integer(dat2$VehGas)\nstr(dat2)\n\n###############################################\n######### choosing learning and test sample\n###############################################\n\nset.seed(100)\nll <- sample(c(1:nrow(dat2)), round(0.9*nrow(dat2)), replace = FALSE)\nlearn <- dat2[ll,]\ntest <- dat2[-ll,]\n(n_l <- nrow(learn))\n(n_t <- nrow(test))\n\n###############################################\n######### GLM analysis\n###############################################\n\n### Model GLM1\nd.glm1 <- glm(ClaimNb ~ VehPowerGLM + VehAgeGLM + DrivAgeGLM + BonusMalusGLM\n + VehBrand + VehGas + DensityGLM + Region + AreaGLM, \n data=learn, offset=log(Exposure), family=poisson())\n \nsummary(d.glm1) \n#anova(d.glm1) # this calculation takes a bit of time \n\nlearn$fitGLM <- fitted(d.glm1)\ntest$fitGLM <- predict(d.glm1, newdata=test, type=\"response\")\n\nglmfit_alldata<-c(as.vector(learn$fitGLM),as.vector(test$fitGLM))\nids<-c(learn$IDpol,test$IDpol)\nsrtperm<-order(ids)\nids[srtperm]\nis.unsorted(ids[srtperm])\n\n\n# in-sample and out-of-sample losses (in 10^(-2))\n(insampleGLM <- 100*Poisson.Deviance(learn$fitGLM, learn$ClaimNb))\n100*Poisson.Deviance(test$fitGLM, test$ClaimNb)\n\n\n###############################################\n######### Regressionn tree analysis\n###############################################\n\n### Model RT2\nt0<-Sys.time()\ntree1 <- rpart(cbind(Exposure,ClaimNb) ~ AreaRT + VehPower + VehAge + DrivAge + BonusMalus + VehBrand + VehGasRT + Density + Region, \n learn, method=\"poisson\",\n control=rpart.control(xval=1, minbucket=10000, cp=0.00001)) \nela<-Sys.time()-t0\nrpart.plot(tree1) # plot tree\ntree1 # show tree with all binary splits\nprintcp(tree1) # cost-complexit statistics\n\nlearn$fitRT <- predict(tree1)*learn$Exposure\ntest$fitRT <- predict(tree1, newdata=test)*test$Exposure\n100*Poisson.Deviance(learn$fitRT, learn$ClaimNb)\n100*Poisson.Deviance(test$fitRT, test$ClaimNb)\n\n\naverage_loss <- cbind(tree1$cptable[,2], tree1$cptable[,3], tree1$cptable[,3]* tree1$frame$dev[1] / n_l)\nplot(x=average_loss[,1], y=average_loss[,3]*100, type='l', col=\"blue\", ylim=c(30.5,33.5), xlab=\"number of splits\", ylab=\"average in-sample loss (in 10^(-2))\", main=\"decrease of in-sample loss\")\npoints(x=average_loss[,1], y=average_loss[,3]*100, pch=19, col=\"blue\")\nabline(h=c(insampleGLM), col=\"green\", lty=2)\nlegend(x=\"topright\", col=c(\"blue\", \"green\"), lty=c(1,2), lwd=c(1,1), pch=c(19,-1), legend=c(\"Model RT2\", \"Model GLM1\"))\n\n\n# cross-validation and cost-complexity pruning\nK <- 10 # K-fold cross-validation value\nset.seed(100)\nxgroup <- rep(1:K, length = nrow(learn))\nxfit <- xpred.rpart(tree1, xgroup)\n(n_subtrees <- dim(tree1$cptable)[1])\nstd1 <- numeric(n_subtrees)\nerr1 <- numeric(n_subtrees)\nerr_group <- numeric(K)\nfor (i in 1:n_subtrees){\n for (k in 1:K){\n ind_group <- which(xgroup ==k) \n err_group[k] <- Poisson.Deviance(learn[ind_group,\"Exposure\"]*xfit[ind_group,i],learn[ind_group,\"ClaimNb\"])\n }\n err1[i] <- mean(err_group) \n std1[i] <- sd(err_group)\n }\n\nx1 <- log10(tree1$cptable[,1])\nxmain <- \"cross-validation error plot\"\nxlabel <- \"cost-complexity parameter (log-scale)\"\nylabel <- \"CV error (in 10^(-2))\"\nerrbar(x=x1, y=err1*100, yplus=(err1+std1)*100, yminus=(err1-std1)*100, xlim=rev(range(x1)), col=\"blue\", main=xmain, ylab=ylabel, xlab=xlabel)\nlines(x=x1, y=err1*100, col=\"blue\")\nabline(h=c(min(err1+std1)*100), lty=1, col=\"orange\")\nabline(h=c(min(err1)*100), lty=1, col=\"magenta\")\nabline(h=c(insampleGLM), col=\"green\", lty=2)\nlegend(x=\"topright\", col=c(\"blue\", \"orange\", \"magenta\", \"green\"), lty=c(1,1,1,2), lwd=c(1,1,1,1), pch=c(19,-1,-1,-1), legend=c(\"tree1\", \"1-SD rule\", \"min.CV rule\", \"Model GLM1\"))\n\n# prune to appropriate cp constant\nprintcp(tree1)\ntree2 <- prune(tree1, cp=0.00003)\nprintcp(tree2)\n\nlearn$fitRT2 <- predict(tree2)*learn$Exposure\ntest$fitRT2 <- predict(tree2, newdata=test)*test$Exposure\n100*Poisson.Deviance(learn$fitRT2, learn$ClaimNb)\n100*Poisson.Deviance(test$fitRT2, test$ClaimNb)\n\n\n\n###############################################\n######### Poisson regression tree boosting\n###############################################\n\n### Model PBM3\nJ0 <- 3 # depth of tree\nM0 <- 50 # iterations\nnu <- 1 # shrinkage constant \n\nlearn$fitPBM <- learn$Exposure\ntest$fitPBM <- test$Exposure\n\nfor (m in 1:M0){\n PBM.1 <- rpart(cbind(fitPBM,ClaimNb) ~ AreaRT + VehPower + VehAge + DrivAge + BonusMalus + VehBrand + VehGasRT + Density + Region, \n data=learn, method=\"poisson\",\n control=rpart.control(maxdepth=J0, maxsurrogate=0, xval=1, minbucket=10000, cp=0.00001)) \n if(m>1){\n learn$fitPBM <- learn$fitPBM * predict(PBM.1)^nu\n test$fitPBM <- test$fitPBM * predict(PBM.1, newdata=test)^nu\n } else {\n learn$fitPBM <- learn$fitPBM * predict(PBM.1)\n test$fitPBM <- test$fitPBM * predict(PBM.1, newdata=test)\n }\n }\n\n100*Poisson.Deviance(learn$fitPBM, learn$ClaimNb)\n100*Poisson.Deviance(test$fitPBM, test$ClaimNb)\n", "meta": {"hexsha": "b4a2e0d3ec035c7f77ee9c9784b481647bec2eb5", "size": 7353, "ext": "r", "lang": "R", "max_stars_repo_path": "RCode/Noll Salzmann Wuethrich FreMTPL2 Part 1 (GLM, RT, PBM).r", "max_stars_repo_name": "kafisatz/DecisionTrees.jl", "max_stars_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2018-08-05T03:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T10:00:56.000Z", "max_issues_repo_path": "RCode/Noll Salzmann Wuethrich FreMTPL2 Part 1 (GLM, RT, PBM).r", "max_issues_repo_name": "kafisatz/DecisionTrees.jl", "max_issues_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2018-06-19T07:50:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T16:08:11.000Z", "max_forks_repo_path": "RCode/Noll Salzmann Wuethrich FreMTPL2 Part 1 (GLM, RT, PBM).r", "max_forks_repo_name": "kafisatz/DecisionTrees.jl", "max_forks_repo_head_hexsha": "f36e55da257d3a58c6eb9ac4ba98e396ddb7e1bc", "max_forks_repo_licenses": ["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.9020618557, "max_line_length": 193, "alphanum_fraction": 0.5778593771, "num_tokens": 2268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6007658197131971}} {"text": "##################################################################################################################\r\n######### WHO 2007 #####\r\n######### Department of Nutrition for Health and Development #####\r\n######### World Health Organization #####\r\n######### Last modified on 08/10/2013 - Developed using R version 3.0.1 (2013-05-16) #####\r\n######### This code corcerns the the calculation of prevalences using all vallid z-scores (non-missing) #####\r\n######### for three indicators: weight-for-age (5 to 10 years), height-for-age (5 to 19 years) and BMI-for- #####\r\n######### age (5 to 19 years) based on the WHO 2007 references. #####\r\n######### Exact age must be given in months (no rounding necessary), height in centimeters and weight in #####\r\n######### kilograms. #####\r\n##################################################################################################################\r\n##################################################################################################################\r\n\r\n##################################################################################################################\r\n######### Functions for calculating the z-scores and prevalences for a nutritional survey #####\r\n##################################################################################################################\r\n\r\n\r\n########################################################################\r\n#### Auxiliar functions\r\n########################################################################\r\n\r\n#############################################################################\r\n##### Prevalence calculation for the upper bound and corresponding 95% C.I.\r\n#############################################################################\r\n\r\nprevph.L <- function(a,x,w) { \r\n ph <- sum((x > a)*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum((!is.na(x))*w,na.rm=T))+(1/(2*sum((!is.na(x))*w,na.rm=T)))\r\n vec <- c(rounde(sum((!is.na(x))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), min(1,ph+aux))*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#### With oedema (only for weight-for-age and bmi-for-age)\r\n\r\nprevph <- function(a,x,w,f) { \r\n f<-as.character(f)\r\n ph <- sum((x > a)*w,na.rm=T)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T))+(1/(2*sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)))\r\n vec <- c(rounde(sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), min(1,ph+aux))*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#############################################################################\r\n##### Prevalence calculation for the lower bound and corresponding 95% C.I.\r\n#############################################################################\r\n\r\n#### Without oedema (for height-for-age)\r\n\r\nprevnh.L <- function(a,x,w) { \r\n ph <- sum((x < a)*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum((!is.na(x))*w,na.rm=T))+(1/(2*sum((!is.na(x))*w,na.rm=T)))\r\n vec <- c(rounde(sum((!is.na(x))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), min(1,ph+aux))*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n#### With oedema (for all weight-related indicators)\r\n\r\nprevnh <- function(a,x,w,f) { \r\n f<-as.character(f)\r\n ph <- sum((x < a | f==\"y\")*w,na.rm=T)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)\r\n aux <- 1.96*sqrt(ph*(1-ph)/sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T))+(1/(2*sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T)))\r\n vec <- c(rounde(sum(((!is.na(x)) | (f==\"y\"))*w,na.rm=T),digits=0),rounde(c(ph, max(0,ph-aux), min(1,ph+aux))*100,digits=1))\r\n return(vec)\r\n } \r\n\r\n###########################################\r\n#### Weighted mean and standard deviation\r\n###########################################\r\n\r\nwmean <- function(x,w) { return(rounde(sum(x*w,na.rm=T)/sum(w[!is.na(x)]),digits=2) ) }\r\n\r\nwsd <- function(x,w) { \r\n mh <- sum(x*w,na.rm=T)/sum((!is.na(x))*w,na.rm=T)\r\n sdh<-ifelse(length(x[!is.na(x)])>0,rounde(sqrt(sum(((x-mh)^2)*w,na.rm=T)/(sum((!is.na(x))*w,na.rm=T) - 1)),digits=2),NA)\r\n return( sdh )\r\n }\r\n\r\n\r\n###########################################################################################\r\n#### Rounding function - SPlus default rounding function uses the nearest even number rule\r\n###########################################################################################\r\n\r\nrounde <- function(x,digits=0) {\r\n\texpo<-10^digits\r\n\treturn(ifelse(abs(x*expo) - floor(abs(x*expo)) < 0.5, sign(x*expo) * floor(abs(x*expo)), sign(x*expo) * (floor(abs(x*expo)) + 1))/expo)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual height-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zhfa<-function(mat,hfawho2007){\r\n\r\nfor(i in 1:length(mat$age.mo)) {\r\n\t\r\n\tif(!is.na(mat$age.mo[i]) & mat$age.mo[i]>=61 & mat$age.mo[i]<229) {\r\n\t\t\r\n\t### Interpolated l,m,s values\r\n \r\n\t\t\tlow.age<-trunc(mat$age.mo[i])\r\n upp.age<-trunc(mat$age.mo[i]+1)\r\n\t\t\tdiff.age<-(mat$age.mo[i]-low.age)\r\n\t\t\t\r\n\t\t\tif(diff.age>0) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\tl.val<-hfawho2007$l[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]+diff.age*( hfawho2007$l[hfawho2007$age==upp.age & hfawho2007$sex==mat$sex[i]]-hfawho2007$l[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]] )\r\n\t\t\tm.val<-hfawho2007$m[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]+diff.age*( hfawho2007$m[hfawho2007$age==upp.age & hfawho2007$sex==mat$sex[i]]-hfawho2007$m[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]] )\r\n\t\t\ts.val<-hfawho2007$s[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]+diff.age*( hfawho2007$s[hfawho2007$age==upp.age & hfawho2007$sex==mat$sex[i]]-hfawho2007$s[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]] )\r\n\t\t\t} else {\r\n\t\t\t\tl.val<-hfawho2007$l[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]\r\n\t\t\t\tm.val<-hfawho2007$m[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]\r\n\t\t\t\ts.val<-hfawho2007$s[hfawho2007$age==low.age & hfawho2007$sex==mat$sex[i]]\r\n\t\t\t}\r\n\t\tmat$zhfa[i]<-(((mat$height[i]/m.val)^l.val)-1)/(s.val*l.val)\t\r\n\t\n\t}\telse mat$zhfa[i]<- NA\r\n\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calculating individual weight-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zwei<-function(mat,wfawho2007){\r\n\r\nfor(i in 1:length(mat$age.mo)) {\r\n\r\n\tif(!is.na(mat$age.mo[i]) & mat$age.mo[i]>=61 & mat$age.mo[i]<121 & mat$oedema[i]!=\"y\") {\r\n\t\t\r\n\t### Interpolated l,m,s values\r\n\r\n\t\t\tlow.age<-trunc(mat$age.mo[i])\r\n upp.age<-trunc(mat$age.mo[i]+1)\r\n\t\t\tdiff.age<-(mat$age.mo[i]-low.age)\r\n\t\t\t\r\n\t\t\tif(diff.age>0) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\tl.val<-wfawho2007$l[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]+diff.age*( wfawho2007$l[wfawho2007$age==upp.age & wfawho2007$sex==mat$sex[i]]-wfawho2007$l[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]] )\r\n\t\t\tm.val<-wfawho2007$m[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]+diff.age*( wfawho2007$m[wfawho2007$age==upp.age & wfawho2007$sex==mat$sex[i]]-wfawho2007$m[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]] )\r\n\t\t\ts.val<-wfawho2007$s[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]+diff.age*( wfawho2007$s[wfawho2007$age==upp.age & wfawho2007$sex==mat$sex[i]]-wfawho2007$s[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]] )\r\n\t\t\t} else {\r\n\t\t\t\tl.val<-wfawho2007$l[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]\r\n\t\t\t\tm.val<-wfawho2007$m[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]\r\n\t\t\t\ts.val<-wfawho2007$s[wfawho2007$age==low.age & wfawho2007$sex==mat$sex[i]]\r\n\t\t\t}\r\n\r\n\t\tmat$zwfa[i]<-(((mat$weight[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zwfa[i]) & mat$zwfa[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zwfa[i]<- 3+((mat$weight[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zwfa[i]) & mat$zwfa[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zwfa[i]<- (-3)+((mat$weight[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zwfa[i]<-NA\r\n}\r\nreturn(mat)\r\n}\r\n\r\n######################################################################################\r\n### Function for calulating individual BMI-for-age z-scores\r\n######################################################################################\r\n\r\ncalc.zbmi<-function(mat,bfawho2007){\r\n\r\nfor(i in 1:length(mat$age.mo)) {\r\n\t\r\n\tif(!is.na(mat$age.mo[i]) & mat$age.mo[i]>=61 & mat$age.mo[i]<229 & mat$oedema[i]!=\"y\") {\r\n\t\r\n\t### Interpolated l,m,s values\r\n\r\n\t\t\tlow.age<-trunc(mat$age.mo[i])\r\n upp.age<-trunc(mat$age.mo[i]+1)\r\n\t\t\tdiff.age<-(mat$age.mo[i]-low.age)\r\n\t\t\t\r\n\t\t\tif(diff.age>0) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\tl.val<-bfawho2007$l[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]+diff.age*( bfawho2007$l[bfawho2007$age==upp.age & bfawho2007$sex==mat$sex[i]]-bfawho2007$l[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]] )\r\n\t\t\tm.val<-bfawho2007$m[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]+diff.age*( bfawho2007$m[bfawho2007$age==upp.age & bfawho2007$sex==mat$sex[i]]-bfawho2007$m[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]] )\r\n\t\t\ts.val<-bfawho2007$s[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]+diff.age*( bfawho2007$s[bfawho2007$age==upp.age & bfawho2007$sex==mat$sex[i]]-bfawho2007$s[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]] )\r\n\t\t\t} else {\r\n\t\t\t\tl.val<-bfawho2007$l[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]\r\n\t\t\t\tm.val<-bfawho2007$m[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]\r\n\t\t\t\ts.val<-bfawho2007$s[bfawho2007$age==low.age & bfawho2007$sex==mat$sex[i]]\r\n\t\t\t}\r\n\r\n\t\tmat$zbfa[i]<-(((mat$cbmi[i]/m.val)^l.val)-1)/(s.val*l.val)\r\n\t\tif(!is.na(mat$zbfa[i]) & mat$zbfa[i]>3) {\r\n\t\t\t\t\t\tsd3pos<- m.val*((1+l.val*s.val*3)^(1/l.val))\r\n\t\t\t\t\t\tsd23pos<- sd3pos- m.val*((1+l.val*s.val*2)^(1/l.val))\r\n\t\t\t\t\t\tmat$zbfa[i]<- 3+((mat$cbmi[i]-sd3pos)/sd23pos)\n\t\t\t\t\t\t}\r\n\t\tif(!is.na(mat$zbfa[i]) & mat$zbfa[i]< (-3)) {\r\n\t\t\t\t\t\tsd3neg<- m.val*((1+l.val*s.val*(-3))**(1/l.val))\r\n\t\t\t\t\t\tsd23neg<- m.val*((1+l.val*s.val*(-2))**(1/l.val))-sd3neg\r\n\t\t\t\t\t\tmat$zbfa[i]<- (-3)+((mat$cbmi[i]-sd3neg)/sd23neg)\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t} else mat$zbfa[i]<-NA\r\n\t\t\t\r\n}\r\n\r\nreturn(mat)\r\n}\r\n\r\n\r\n###################################################################################\r\n#### Main function starts here: who2007\r\n###################################################################################\r\n\r\n###############################################################################################################################################\r\n#### This function can be used to: \r\n#### 1. Calculate the z-scores for the indicators: height-for-age, weight-for-age and body mass index-for-age\r\n#### The output file with z-scores values is exported the file to an Excel spreadsheet (see readme file);\r\n#### 2. Calculate the prevalence rates of stunting, underweight, wasting and overweight, and z-scores means and standard deviations. Results\r\n#### are exported to an Excel spreadsheet, displayed by age group.\r\n###############################################################################################################################################\r\n\r\n\r\n#############################################################################\r\n##### Function for calculating the z-scores for all indicators\r\n#############################################################################\r\n\r\nwho2007 <- function(FileLab=\"Temp\",FilePath=\"C:\\\\Documents and Settings\",mydf,sex,age,weight,height,oedema=rep(\"n\",dim(mydf)[1]),sw=rep(1,dim(mydf)[1])) {\r\n\t\r\n#############################################################################\r\n########### Calculating the z-scores for all indicators\r\n#############################################################################\r\n \r\n old <- options(warn=(-1))\r\n \r\n sex.x<-as.character(get(deparse(substitute(mydf)))[,deparse(substitute(sex))])\r\n age.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(age))])\r\n weight.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(weight))])\r\n height.x<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(height))])\r\n if(!missing(oedema)) oedema.vec<-as.character(get(deparse(substitute(mydf)))[,deparse(substitute(oedema))]) else oedema.vec<-oedema\r\n if(!missing(sw))\tsw<-as.double(get(deparse(substitute(mydf)))[,deparse(substitute(sw))])\telse sw<-as.double(sw)\r\n sw<-ifelse(is.na(sw),0,sw)\r\n\r\n\tsex.vec<-NULL\r\n sex.vec<-ifelse(sex.x!=\"NA\" & (sex.x==\"m\" | sex.x==\"M\" | sex.x==\"1\"),1,ifelse(sex.x!=\"NA\" & (sex.x==\"f\" | sex.x==\"F\" | sex.x==\"2\"),2,NA))\r\n\tage.vec<-age.x\r\n\theight.vec<-height.x\r\n oedema.vec<-ifelse(oedema.vec==\"n\" | oedema.vec==\"N\",\"n\",ifelse(oedema.vec==\"y\" | oedema.vec==\"Y\",\"y\",\"n\"))\r\n\r\n mat<-cbind.data.frame(age.x,as.double(sex.vec),weight.x,height.x,oedema.vec,sw,stringsAsFactors=F)\r\n\tnames(mat)<-c(\"age.mo\",\"sex\",\"weight\",\"height\",\"oedema\",\"sw\")\r\n\t\r\n\tmat$cbmi<-mat$weight/((height.vec/100)^2)\r\n\tmat$zhfa<-NULL\r\n\tmat$fhfa<-NULL\r\n\tmat$zwfa<-NULL\r\n\tmat$fwfa<-NULL\r\n\tmat$zbfa<-NULL\r\n\tmat$fbfa<-NULL\r\n\r\n#############################################################################\r\n########### Calculating the z-scores for all indicators\r\n#############################################################################\r\n\r\ncat(\"Please wait while calculating z-scores...\\n\") \r\n\r\n### Height-for-age z-score\r\n\r\nmat<-calc.zhfa(mat,hfawho2007)\r\n\r\n### Weight-for-age z-score\r\n\r\nmat<-calc.zwei(mat,wfawho2007)\r\n\r\n### BMI-for-age z-score\r\n\r\nmat<-calc.zbmi(mat,bfawho2007)\r\n\r\n\r\n#### Rounding the z-scores to two decimals\r\n\r\n\t\t\tmat$zhfa<-rounde(mat$zhfa,digits=2)\r\n\t\t\tmat$zwfa<-rounde(mat$zwfa,digits=2)\r\n\t\t\tmat$zbfa<-rounde(mat$zbfa,digits=2)\r\n\r\n#### Flagging z-score values for individual indicators\r\n\r\n\t\t\tmat$fhfa<-ifelse(abs(mat$zhfa) > 6,1,0)\r\n\t\t\tmat$fwfa<-ifelse(mat$zwfa > 5 | mat$zwfa < (-6),1,0)\r\n\t\t\tmat$fbfa<-ifelse(abs(mat$zbfa) > 5,1,0)\r\n\t\t\t\r\nif(is.na(mat$age.mo) & mat$oedema==\"y\") {\r\nmat$fhfa<-NA\r\nmat$zwfa<-NA\r\nmat$zbfa<-NA\r\n}\r\n\r\nmat<-cbind.data.frame(mydf,mat[,-c(2:6)])\r\n\r\n###################################################################################################\r\n######### Export data frame with z-scores and flag variables\r\n###################################################################################################\r\n\r\n\r\nassign(\"matz\",mat,envir = .GlobalEnv)\r\n\r\nwrite.table(matz, file=paste(FilePath,\"\\\\\",FileLab,\"_z.csv\",sep=\"\"),na=\"\",row.names = FALSE,sep=\",\",quote = TRUE)\r\n\r\n\r\ncat(paste(\"Z-scores calculated and exported to \",FilePath,\"\\\\\",FileLab,\"_z.csv\\n\\n\",sep=\"\")) \r\n\r\n\r\n#######################################################################################################\r\n#### Calculating prevalences and summary statistics. \r\n#######################################################################################################\r\n\r\nif(any(sw <0)) stop(\"Negative weights are not allowed and program will stop. Prevalence tables will not be produced.\")\r\n\r\nmat.out<-mat\r\n\r\nmat.out$sw.vec<-sw\r\nmat.out$sex.vec<-as.double(sex.vec)\r\nmat.out$oedema.vec<-as.character(oedema.vec)\r\nmat.out$oedema.vec1<-as.character(oedema.vec)\r\n\r\nmat.out<-mat.out[!is.na(mat.out$age.mo) & mat.out$age.mo>=61 & mat.out$age.mo<229,]\r\n\r\n####################################################\r\n#### Creating age group variable in completed years\r\n####################################################\r\n\r\nmat.out$agegr <- floor(mat.out$age.mo/12)\r\n\r\n##############################################\r\n#### Make z-score as missing if it is flagged\r\n##############################################\r\n\r\nmat.out$zhfa<-ifelse(!is.na(mat.out$fhfa) & mat.out$fhfa!=0,NA,mat.out$zhfa)\r\nmat.out$zwfa<-ifelse(!is.na(mat.out$fwfa) & mat.out$fwfa!=0,NA,mat.out$zwfa)\r\nmat.out$zbfa<-ifelse(!is.na(mat.out$fbfa) & mat.out$fbfa!=0,NA,mat.out$zbfa)\r\n\r\nif(dim(mat.out)[1]==0) stop(\"\\n\\nNo non-missing z-score values are available for calculating prevalences. Program will stop!\\n\\n.\")\r\n\r\n\r\n##############################################\r\n#### Include all levels of age group variable\r\n##############################################\r\n\r\nmat.aux<-as.data.frame(cbind(array(rep(NA,((dim(mat.out)[2]-1)*15)),dim=c(15,(dim(mat.out)[2]-1)) ),seq(5,19,1)))\r\n\r\nnames(mat.aux)<-names(mat.out)\r\n\r\nmat.out<-rbind(mat.out,mat.aux)\r\n\r\ncat(\" starting \")\r\n\r\n########################################################################################################\r\n#### Make Oedema variable to be \"n\" if age smaller than 61 mo or greater than 120 mo (for weight-for-age)\r\n#### or smaller than 61 mo or greater than 228 mo (for bmi-for-age).\r\n#### This is because children with oedema counts in the prevalence even if z-score is missing\r\n#### for weight related indicators.\r\n########################################################################################################\r\n\r\nmat.out$oedema.vec<-ifelse((!is.na(mat.out$age.mo) & (mat.out$age.mo<61 | mat.out$age.mo>=229)) | mat.out$oedema.vec==\"NA\",\"n\",mat.out$oedema.vec)\r\nmat.out$oedema.vec1<-ifelse((!is.na(mat.out$age.mo) & (mat.out$age.mo<61 | mat.out$age.mo>=121)) | mat.out$oedema.vec==\"NA\",\"n\",mat.out$oedema.vec)\r\n\r\n#####################################################################################################################################################\r\n#### Creating matrix with estimated prevalences, confidence intervals, and means and standard deviations of z-scores and exporting it to Excel file.\r\n#####################################################################################################################################################\r\n\r\ncat(\"\\nPlease wait while calculating prevalences and z-score summary statistics...\\n\") \r\n\r\n#### Sexes combined\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<- t(cbind.data.frame(#\r\n prevnh(-3,mat.out$zwfa,mat.out$sw.vec,mat.out$oedema.vec1),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-3, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevnh.L(-3,mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-3, z$zhfa, z$sw.vec)),#\r\n prevnh(-3,mat.out$zbfa,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-3, z$zbfa, z$sw.vec, z$oedema.vec))))\r\n \r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh(-2,mat.out$zwfa,mat.out$sw.vec,mat.out$oedema.vec1),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-2, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevnh.L(-2,mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevnh.L(-2, z$zhfa, z$sw.vec)),#\r\n prevnh(-2,mat.out$zbfa,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevnh(-2, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +1 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(1,mat.out$zwfa,mat.out$sw.vec,mat.out$oedema.vec1),lapply(split(mat.out, mat.out$agegr),function(z) prevph(1, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(1,mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(1, z$zhfa, z$sw.vec)),#\r\n prevph(1,mat.out$zbfa,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(1, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(2,mat.out$zwfa,mat.out$sw.vec,mat.out$oedema.vec1),lapply(split(mat.out, mat.out$agegr),function(z) prevph(2, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(2,mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(2, z$zhfa, z$sw.vec)),#\r\n prevph(2,mat.out$zbfa,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(2, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +3 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(3,mat.out$zwfa,mat.out$sw.vec,mat.out$oedema.vec1),lapply(split(mat.out, mat.out$agegr),function(z) prevph(3, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(3,mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr), function(z) prevph.L(3, z$zhfa, z$sw.vec)),#\r\n prevph(3,mat.out$zbfa,mat.out$sw.vec,mat.out$oedema.vec),lapply(split(mat.out, mat.out$agegr),function(z) prevph(3, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out$zwfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zwfa,z$sw.vec)),#\r\n wmean(mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zhfa,z$sw.vec)),#\r\n wmean(mat.out$zbfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wmean(z$zbfa,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out$zwfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zwfa,z$sw.vec)),#\r\n wsd(mat.out$zhfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zhfa,z$sw.vec)),#\r\n wsd(mat.out$zbfa,mat.out$sw.vec),lapply(split(mat.out, mat.out$agegr),function(z) wsd(z$zbfa,z$sw.vec)))))\r\n\r\n####################################################################################################################\r\n##### Exporting matrix to Excel file\r\n\r\nrm(mat1)\r\n\r\nmat1<-rbind(c(\"Set 1:\",\"Sexes\",\"combined\",rep(\"\",15)),\r\n c(\"Weight\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[1:16,],#\r\n c(\"Height\",\"-for-\",\"age\",rep(\"\",15)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[17:32,],#\r\n c(\"BMI\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[33:48,])\r\n\r\nfor(j in 1:dim(mat1)[2]) mat1[,j]<-ifelse(mat1[,j]==\"NA\" | mat1[,j]==\"NaN\",\"\",mat1[,j])\r\n\r\nmat1<-cbind(c(\"\",rep(c(\"\",\"Age\",\"5-19\",as.character(5:19)),3)),mat1)\r\n\r\n\t\r\n####################################################################################################################\r\n\r\n##### For boys and girls\r\n\r\nfor(i in 1:2) {\r\n\r\nmat.out.sex<-mat.out[!is.na(mat.out$sex.vec) & mat.out$sex.vec==i,]\t\r\n\r\nmat.aux<-as.data.frame(cbind(array(rep(NA,((dim(mat.out.sex)[2]-1)*15)),dim=c(15,(dim(mat.out.sex)[2]-1)) ),seq(5,19,1)))\r\nnames(mat.aux)<-names(mat.out.sex)\r\nmat.out.sex<-rbind.data.frame(mat.out.sex,mat.aux)\r\nmat.out.sex$oedema.vec<-ifelse((!is.na(mat.out.sex$age.mo) & (mat.out.sex$age.mo<61 | mat.out.sex$age.mo>=229)) | mat.out.sex$oedema.vec==\"NA\",\"n\",mat.out.sex$oedema.vec)\r\n\r\n#### % < -3 SD for all the indicators\r\nmat<- t(cbind.data.frame(#\r\n prevnh(-3,mat.out.sex$zwfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec1),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-3, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevnh.L(-3,mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-3, z$zhfa, z$sw.vec)),#\r\n prevnh(-3,mat.out.sex$zbfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-3, z$zbfa, z$sw.vec, z$oedema.vec))))\r\n \r\n#### % < -2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevnh(-2,mat.out.sex$zwfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec1),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-2, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevnh.L(-2,mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevnh.L(-2, z$zhfa, z$sw.vec)),#\r\n prevnh(-2,mat.out.sex$zbfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevnh(-2, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +1 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(1,mat.out.sex$zwfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec1),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(1, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(1,mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(1, z$zhfa, z$sw.vec)),#\r\n prevph(1,mat.out.sex$zbfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(1, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +2 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(2,mat.out.sex$zwfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec1),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(2, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(2,mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(2, z$zhfa, z$sw.vec)),#\r\n prevph(2,mat.out.sex$zbfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(2, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### % > +3 SD for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n prevph(3,mat.out.sex$zwfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec1),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(3, z$zwfa, z$sw.vec, z$oedema.vec1)),#\r\n prevph.L(3,mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr), function(z) prevph.L(3, z$zhfa, z$sw.vec)),#\r\n prevph(3,mat.out.sex$zbfa,mat.out.sex$sw.vec,mat.out.sex$oedema.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) prevph(3, z$zbfa, z$sw.vec, z$oedema.vec))))[,-1])\r\n\r\n#### Means of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wmean(mat.out.sex$zwfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zwfa,z$sw.vec)),#\r\n wmean(mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zhfa,z$sw.vec)),#\r\n wmean(mat.out.sex$zbfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wmean(z$zbfa,z$sw.vec)))))\r\n\r\n#### Standard deviations of z-scores for all the indicators\r\nmat<-cbind.data.frame(mat,t(cbind.data.frame(#\r\n wsd(mat.out.sex$zwfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zwfa,z$sw.vec)),#\r\n wsd(mat.out.sex$zhfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zhfa,z$sw.vec)),#\r\n wsd(mat.out.sex$zbfa,mat.out.sex$sw.vec),lapply(split(mat.out.sex, mat.out.sex$agegr),function(z) wsd(z$zbfa,z$sw.vec)))))\r\n\r\n####################################################################################################################\r\n##### Exporting matrix to Excel file\r\n\r\nmat2<-rbind.data.frame(c(paste(\"Set \",i+1,\":\",sep=\"\"),c(\"Males\",\"Females\")[i],rep(\"\",16)),\r\n c(\"Weight\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[1:16,],#\r\n c(\"Height\",\"-for-\",\"age\",rep(\"\",15)),#\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[17:32,],#\r\n c(\"BMI\",\"-for-\",\"age\",rep(\"\",15)),\r\n c(\"N\",\"% < -3 SD\",\"95%\", \"C.I.\",\"% < -2 SD\",\"95%\", \"C.I.\",\"% > +1 SD\",\"95%\", \"C.I.\",\"% > +2 SD\",\"95%\", \"C.I.\",\"% > +3 SD\",\"95%\", \"C.I.\",\"Mean\",\"SD\"),mat[33:48,])\r\n\r\nfor(j in 1:dim(mat2)[2]) mat2[,j]<-ifelse(mat2[,j]==\"NA\" | mat2[,j]==\"NaN\",\"\",mat2[,j])\r\n\r\nmat2<-cbind(c(\"\",rep(c(\"\",\"Age\",\"5-19\",as.character(5:19)),3)),mat2)\r\n\r\nnames(mat2)<-names(mat1)\r\n\r\nmat1<-rbind(mat1,mat2)\r\n\r\n} #### End of loop for sex\r\n\r\nmat1<-mat1[-c(11:19,66:74,121:129),]\r\n\r\n###################################################################################################################\r\n######### Export table with prevalence values and their confidence intervals, and mean and SD of the z-scores\r\n###################################################################################################################\r\n\r\n\r\nassign(\"matprev\",mat1,envir = .GlobalEnv)\r\n\r\nwrite.table(matprev, file=paste(FilePath,\"\\\\\",FileLab,\"_prev.csv\",sep=\"\"),na=\" \",row.names = FALSE,col.names=F,sep=\",\",quote = TRUE)\r\n\r\ncat(paste(\"Prevalences and z-score summary statistics calculated and exported to \",FilePath,\"\\\\\",FileLab,\"_prev.csv\\n\",sep=\"\")) \r\n\r\non.exit(options(old))\r\n\r\ninvisible()\r\n\r\n\r\n} #### End of main function who2007\r\n\r\n# wfawho2007<-read.table(\"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\\\\wfawho2007.txt\",header=T,sep=\"\",skip=0)\r\n# hfawho2007<-read.table(\"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\\\\hfawho2007.txt\",header=T,sep=\"\",skip=0)\r\n# bfawho2007<-read.table(\"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\\\\bfawho2007.txt\",header=T,sep=\"\",skip=0)\r\n\r\n# survey.who2007<-read.csv(\"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\\\\survey_who2007.csv\",header=T,sep=\",\",skip=0,na.strings=\"\")\r\n\r\n# source(\"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\\\\who2007.r\")\r\n\r\n# who2007(FileLab = \"survey_who2007\", FilePath = \"D:\\\\References 5-20y\\\\Macro R\\\\who2007_R\", mydf = survey.who2007,sex = sex, age = agemons, weight = weight, height = height, sw=sw, oedema=oedema)\r\n\r\n\r\n\r\n", "meta": {"hexsha": "2f4c3ef1c3f81db9029a64ac2afa9c766e10d9e3", "size": 30609, "ext": "r", "lang": "R", "max_stars_repo_path": "data_preprocess/data/who2007_R/who2007.r", "max_stars_repo_name": "hathawayj/growthstandards", "max_stars_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-07-26T16:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-06T21:28:52.000Z", "max_issues_repo_path": "data_preprocess/data/who2007_R/who2007.r", "max_issues_repo_name": "hathawayj/growthstandards", "max_issues_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2019-02-24T01:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-03T14:29:51.000Z", "max_forks_repo_path": "data_preprocess/data/who2007_R/who2007.r", "max_forks_repo_name": "hathawayj/growthstandards", "max_forks_repo_head_hexsha": "3e765845b0940048a5af877f596a90b67eea39ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2019-10-24T15:41:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T04:20:50.000Z", "avg_line_length": 56.3701657459, "max_line_length": 224, "alphanum_fraction": 0.5121042831, "num_tokens": 9342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.600745617470675}} {"text": "\nlibrary(ggplot2)\nlibrary(plyr)\nlibrary(rstan)\nrstan_options(auto_write = TRUE)\noptions(mc.cores = parallel::detectCores())\n\ncox_model <- \n\"data {\n int Nsubj; \n int T;\n vector[Nsubj] pscenter;\n vector[Nsubj] hhcenter;\n int ncomact[Nsubj];\n int rleader[Nsubj];\n int dleader[Nsubj];\n vector[Nsubj] inter1;\n vector[Nsubj] inter2;\n int FAIL[Nsubj];\n int obs_t[Nsubj];\n int t[T+1];\n \n} \n\ntransformed data {\n int Y[Nsubj, T];\n int dN[Nsubj, T];\n \n # Set up data\n for(i in 1:Nsubj) {\n for(j in 1:T) {\n # risk set = 1 if obs_t >= t\n Y[i,j] <- int_step(obs_t[i] - t[j]);\n # counting process \n dN[i,j] <- Y[i, j] * int_step(t[j + 1] - obs_t[i]) * FAIL[i];\n }\n }\n}\n\nparameters {\n vector[7] beta;\n real c;\n real r;\n vector[T] dL0; \n}\n\ntransformed parameters {\n vector[T] mu;\n matrix[Nsubj, T] Idt;\n vector[T] dL0_star;\n \n for(j in 1:T) {\n for(i in 1:Nsubj) {\n # Intensity\n Idt[i, j] <- Y[i, j] * exp(beta[1]*pscenter[i] + beta[2]*hhcenter[i] + beta[3]*ncomact[i] \n + beta[4]*rleader[i] + beta[5]*dleader[i] + beta[6]*inter1[i] + beta[7]*inter2[i]) * dL0[j];\n } \n # prior mean hazard \n mu[j] <- dL0_star[j] * c; \n \n dL0_star[j] <- r * (t[j + 1] - t[j]);\n }\n} \n\nmodel {\n \n for(j in 1:T) {\n for(i in 1:Nsubj) {\n # Likelihood\n dN[i, j] ~ poisson(Idt[i, j]); \n } \n dL0[j] ~ gamma(mu[j], c);\n }\n \n c ~ gamma(0.0001, 0.00001);\n r ~ gamma(0.001, 0.0001);\n \n beta ~ normal(0.0, 100000);\n}\"\n\ndata <- read_rdump('survival.data.r')\n\ninits <- list(c1=list(beta=c(-.36,-.26,-.29,-.22,-.61,-9.73,-.23), c=0.01, r=0.01, \n dL0=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)))\n\n\nfit <- stan(model_code=cox_model, data=data, init=inits, iter=2000, chains=1, verbose=F)\n\nprint(fit)\n", "meta": {"hexsha": "52ac9969e97610348d317ee76a0ac5b7322d3319", "size": 2280, "ext": "r", "lang": "R", "max_stars_repo_path": "tutorials/stan_workshop__16__fonnesbeck/code/survival.r", "max_stars_repo_name": "nguyentu1602/stan-exp", "max_stars_repo_head_hexsha": "0484ee4d3bddeff75ed8b1764b5ac2839aa6e2e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53, "max_stars_repo_stars_event_min_datetime": "2016-06-01T23:07:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T19:07:14.000Z", "max_issues_repo_path": "code/survival.r", "max_issues_repo_name": "fonnesbeck/stan_workshop_2016", "max_issues_repo_head_hexsha": "0999b8ba1ecbec6739ff44e4d9e1bf15e766e757", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/survival.r", "max_forks_repo_name": "fonnesbeck/stan_workshop_2016", "max_forks_repo_head_hexsha": "0999b8ba1ecbec6739ff44e4d9e1bf15e766e757", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 37, "max_forks_repo_forks_event_min_datetime": "2016-06-01T23:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T16:36:50.000Z", "avg_line_length": 25.3333333333, "max_line_length": 230, "alphanum_fraction": 0.4929824561, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.6007366873192307}} {"text": "#Bodyfatpercentage function: \r\nbodyfatpercentage<-function(Weight, Neck, Chest, Abdomen, Hip, Thigh, Biceps, Forearm, Wrist){return (-20.70744484 + (Weight * -0.12231521) + (Neck * -0.55247243) + (Chest * 0.04107781) + (Abdomen * 1.04805259) + (Hip * -0.23442407) + (Thigh * 0.19800909) + (Biceps * 0.21621033) + (Forearm * 0.39878499) + (Wrist * -1.37931563))}", "meta": {"hexsha": "05003110c9e69c3c674d485c9ff605f8bbea9ca2", "size": 361, "ext": "r", "lang": "R", "max_stars_repo_path": "bodyfatfunction.r", "max_stars_repo_name": "dallasmcgroarty/Body-Fat-Prediction-Project", "max_stars_repo_head_hexsha": "533a135fb56e3d7536f633fa99f3c4b56895a548", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bodyfatfunction.r", "max_issues_repo_name": "dallasmcgroarty/Body-Fat-Prediction-Project", "max_issues_repo_head_hexsha": "533a135fb56e3d7536f633fa99f3c4b56895a548", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bodyfatfunction.r", "max_forks_repo_name": "dallasmcgroarty/Body-Fat-Prediction-Project", "max_forks_repo_head_hexsha": "533a135fb56e3d7536f633fa99f3c4b56895a548", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 180.5, "max_line_length": 330, "alphanum_fraction": 0.6731301939, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062237, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.6007098297756243}} {"text": "#' initiales a data.frame with the data for the loto analysis\n#'\n#' @return a data.frame with rows containing the numbers and winnings for\n#' various draws\nread.data <- function(numberSource = \"numbers.csv\", payoutSource = \"winnings.csv\") {\n numbers <- read.csv(numberSource)\n numbers$Date <- as.POSIXct(numbers$Date, format = \"%Y-%m-%d\")\n\n winnings <- read.csv(payoutSource)\n winnings$Date <- as.POSIXct(winnings$Date, format = \"%Y-%m-%d\")\n\n return(merge(numbers, winnings, by = \"Date\"))\n}\n\n#' calculates and returns the probabilities for every win category in lotto\n#'\n#' @return a data.frame containing the probabilities to win various combinations\n#' in lotto\nget.Prob <- function() {\n ret <- data.frame(\n Win6s = choose(43, 0) * choose(6, 6) / choose(49, 6) * 1 / 10,\n Win6 = choose(43, 0) * choose(6, 6) / choose(49, 6) * 9 / 10,\n Win5s = choose(43, 1) * choose(6, 5) / choose(49, 6) * 1 / 10,\n Win5 = choose(43, 1) * choose(6, 5) / choose(49, 6) * 9 / 10,\n Win4s = choose(43, 2) * choose(6, 4) / choose(49, 6) * 1 / 10,\n Win4 = choose(43, 2) * choose(6, 4) / choose(49, 6) * 9 / 10,\n Win3s = choose(43, 3) * choose(6, 3) / choose(49, 6) * 1 / 10,\n Win3 = choose(43, 3) * choose(6, 3) / choose(49, 6) * 9 / 10,\n Win2s = choose(43, 4) * choose(6, 2) / choose(49, 6) * 1 / 10\n )\n return(ret)\n}\n\n#' calculates the expected prices for each win class\n#'\n#' @return a data.frame with the first row containing the probabilites of\n#' winning and the second row containing the expected winnings\nget.ExpWin <- function(date) {\n prob <- get.Prob()\n\n if (date > as.POSIXct(\"2020-09-20\")) {\n # payout rate is the probability of winning in the lowest win class\n # times the payout ratio (6 € for 0.6 € contributed to the pool)\n lowest <- prob[1, 9] * 10\n\n # payout rate is fixed for the highest win class\n highest <- 0.15\n\n # for other win classes it is relative to highest and lowest\n remaining <- (1 - highest - lowest)\n payout_rate <- c(\n highest,\n remaining * 0.15,\n remaining * 0.052,\n remaining * 0.155,\n remaining * 0.043,\n remaining * 0.102,\n remaining * 0.087,\n remaining * 0.411,\n lowest\n )\n\n # for every 1.2 € played 60 cents are payed out\n expect <- 0.6 * payout_rate / prob\n\n # the draw2s class has a fixed payout rate\n expect[1, 9] <- 6\n return(rbind(prob, expect))\n }\n\n if (date > as.POSIXct(\"2013-05-03\")) {\n # payout rate is the probability of winning in the lowest win class\n # times the payout ratio (5 € for 0.5 € contributed to the pool)\n lowest <- prob[1, 9] * 10\n\n # payout rate is fixed for the highest win class\n highest <- 0.128\n\n # for other win classes it is relative to highest and lowest\n remaining <- (1 - highest - lowest)\n payout_rate <- c(\n highest,\n remaining * 0.10,\n remaining * 0.05,\n remaining * 0.15,\n remaining * 0.05,\n remaining * 0.10,\n remaining * 0.10,\n remaining * 0.45,\n lowest\n )\n\n # for every 1 € played 50 cents are payed out\n expect <- 0.5 * payout_rate / prob\n\n # the draw2s class has a fixed payout rate\n expect[1, 9] <- 5\n return(rbind(prob, expect))\n }\n\n stop(\"Date not supported\")\n}\n\n#' calculates the ratios between the expected winnings and the actual payed\n#' out amounts\n#'\n#' @return ratios of realized and expected winnings\nget.WinRatios <- function(data) {\n m <- apply(data, 1, function(row) {\n exp.win <- get.ExpWin(row[\"Date\"])[2, ]\n ratio.win2S <- as.numeric(row[\"Win2S\"]) / exp.win$Win2s\n\n ratio.win3 <- exp.win$Win3 / as.numeric(row[\"Win3\"])\n ratio.win3S <- exp.win$Win3s / as.numeric(row[\"Win3S\"])\n ratio.win3zz <- ratio.win3S / ratio.win3\n\n ratio.win4 <- exp.win$Win4 / as.numeric(row[\"Win4\"])\n ratio.win4S <- exp.win$Win4s / as.numeric(row[\"Win4S\"])\n ratio.win4zz <- ratio.win4S / ratio.win4\n\n return(data.frame(\n Date = row[\"Date\"],\n data.ZZ = row[\"ZZ\"],\n ratio.win2S,\n ratio.win3,\n ratio.win3S,\n ratio.win3zz,\n ratio.win4,\n ratio.win4S,\n ratio.win4zz\n ))\n })\n m <- Reduce(function(...) merge(..., all = T), m)\n return(m)\n}\n\n#' given a vector representing a row of the data.frame returned by\n#' @link read.data return a vector of exponents for the model.\n#' correctDrawn modifies the exponents for the data set (e.g. 3 if\n#' used for win3, 4 for win4, etc.)\n#'\n#' @return exponents for every lotto number used in the model for the\n#' general analysis\ngetExponents <- function(row, correctDrawn) {\n exponent <- rep((6 - correctDrawn) / 43, 49)\n exponent[as.integer(row[2])] <- correctDrawn / 6\n exponent[as.integer(row[3])] <- correctDrawn / 6\n exponent[as.integer(row[4])] <- correctDrawn / 6\n exponent[as.integer(row[5])] <- correctDrawn / 6\n exponent[as.integer(row[6])] <- correctDrawn / 6\n exponent[as.integer(row[7])] <- correctDrawn / 6\n return(exponent)\n}", "meta": {"hexsha": "19c0b2c848fbc974eed7747de8adaab91093ced3", "size": 5330, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/helpers.r", "max_stars_repo_name": "fasmat/lotto-analysis", "max_stars_repo_head_hexsha": "f6a22b55f79c2ab57b13ec5e8396a88505794452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-13T19:19:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T19:19:07.000Z", "max_issues_repo_path": "analysis/helpers.r", "max_issues_repo_name": "fasmat/lotto-analysis", "max_issues_repo_head_hexsha": "f6a22b55f79c2ab57b13ec5e8396a88505794452", "max_issues_repo_licenses": ["MIT"], "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/helpers.r", "max_forks_repo_name": "fasmat/lotto-analysis", "max_forks_repo_head_hexsha": "f6a22b55f79c2ab57b13ec5e8396a88505794452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-23T10:55:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T10:55:09.000Z", "avg_line_length": 34.8366013072, "max_line_length": 84, "alphanum_fraction": 0.5782363977, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.6006002308653592}} {"text": "require(faraway)\n\nG <- function(x){\n\tval <- logit(x)\n\treturn(val)\n}\n\nG_Inv <- function(x){\n\tval <- ilogit(x)\n\treturn(val)\n}\n\nAgg <- function(p_i, N_i){\n\treturn(sum(p_i * N_i)/sum(N_i))\n}\n\n\nEvalK <- function(K, p_i, p_N, N_i){\n\tif (Mult == TRUE){\n\t\tp_tilde <- G_Inv(G(p_i) * K)\n\t} else {\n\t\tp_tilde <- G_Inv(G(p_i) + K)\n\t}\n\tLHS <- Agg(p_tilde, N_i)\n\tRHS <- p_N\n\tSE <- (LHS-RHS)^2\n\treturn(SE)\n}\n\n# p_i = our grid of probabilities\n# p_N = national target\n# sim_N_i = our grid of sample sizes (population raster)\n# a = bounds for raking factor, perhaps return warning if optimal is on edge of limits \nFindK <- function(p_i, p_N, N_i, a) { \n\tif (Mult == TRUE){\n\t\tLimits <- c(0,a)\n\t} else {\n\t\tLimits <- c(-a,a)\n\t}\n\titer <- 1\n\tBoundary = TRUE\n\twhile (Boundary & iter < 10){\n\t\tLimits <- Limits * iter\n\t\tval <- optimize(EvalK, Limits, p_i = p_i, p_N = p_N, N_i = N_i, tol = 1e-20)$min\n\t\tBoundary <- (round(abs(val)) == Limits[2])\n\t\titer <- iter + 1\n\t}\n\treturn(val)\n}\n\nNumLocs <- 100\nsim_p_i <- runif(NumLocs)\nsim_N_i <- round(runif(NumLocs)+runif(NumLocs)*100*runif(NumLocs))\n\nMult <- FALSE\na <- 2\n\nTry <- 99\n\np_Ns <- seq(0, 1, length = Try + 2)[-c(1,Try+2)]\nScale <- seq(-10, 10, length = Try + 2)[-c(1,Try+2)]\nAggP <- rep(NA, length=Try)\n\nRF <- matrix(0, Try, Try)\n\nfor (i in 1:Try){\n\ttmp_p_i <- ilogit(logit(sim_p_i) + Scale[i])\n\tAggP[i] <- Agg(tmp_p_i, sim_N_i)\n\tfor (j in 1:Try){\n\t\ttmp_p <- p_Ns[j]\n\t\tRF[i,j] <- FindK(tmp_p_i, tmp_p, sim_N_i, a)\n\t}\n}\n\npersp(AggP,p_Ns,RF,phi=35,theta=45)\n\n\n", "meta": {"hexsha": "216213d678225a619459421b6cc5609fb465d303", "size": 1485, "ext": "r", "lang": "R", "max_stars_repo_path": "antibiotic_usage/mbg_central/dev/Raking_code.r", "max_stars_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_stars_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-24T15:23:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:23:42.000Z", "max_issues_repo_path": "antibiotic_usage/mbg_central/dev/Raking_code.r", "max_issues_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_issues_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "antibiotic_usage/mbg_central/dev/Raking_code.r", "max_forks_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_forks_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-13T23:06:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T23:06:52.000Z", "avg_line_length": 19.0384615385, "max_line_length": 87, "alphanum_fraction": 0.604040404, "num_tokens": 578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6005917510580353}} {"text": "library(Matrix)\nlibrary(igraph)\nsource('C:\\\\RDS\\\\code\\\\RDS3.R')\n\n#Function to exponentiate a matrix\n# r-help, https://stat.ethz.ch/pipermail/r-help/2006-September/113542.html\n# This one has trouble with numerical stability. \n# expM <- function(X,e) { v <- La.svd(X); v$u %*% diag(v$d^e) %*% v$vt }\n\n# Slower but more numerically stable\nmat_pow = function(G, e) {\n\tresult = matrix(G, nrow=nrow(G), ncol=ncol(G))\n\tif(e == 1) { return(result)}\n\tfor (i in 2:e) {\n\t\tresult = result %*% G\n\t\t#print(\"EXP Mat\")\n\t}\n return( result )\n}\n\t\n\n\nvar_rw = function(g, steps, covar_fn='RW') {\n\t# covar_fn is \n\t# 'RW' for random walk\n\t# 'RDS' for RDS weighted\n\t#cov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t#cov_mat = outer(1:steps, 1:steps, FUN=covar_fn, g=g, cv_type=covar_fn )\n\t\n\t# Set up a matrix for results:\n\tnode_count = vcount(g)\n\tcov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t\n\t# Precompute some values:\n\tW = outer(degree(g), degree(g))^-1\n\tsum_W = sum(W)\n\t#norm_W = sum_W/W\n\tnorm_W = W / sum_W\n\n\t\n\tval_Y = V(g)$aids ## This depends on name of attibute\n\t\n\tP_s = degree(g)/sum(degree(g)) # assume node is selected at random proportional to degree\n\tmean_Y = t(P_s) %*% val_Y\n\tY = outer(val_Y-mean_Y, val_Y-mean_Y)\n\t\n\tM_tran_probs = get.adjacency(g) / degree(g)\n\t\n\t\n\t#cov_mat = norm_W * P_s * P_q * Y\n\t\n\tdiag(cov_mat) = P_s %*% (val_Y - mean_Y)^2\n\t# cov_mat_pre = norm_W * P_s * Y #( P_q * Y )\n\tif( identical(covar_fn, 'RDS_WRONG') ){\n cov_mat_pre = norm_W * P_s * Y\n\t} else { #Use the RW - random walk model\n\t\tcov_mat_pre = P_s * Y\n\t}\n\t\n\tstep_diff = abs(outer(1:steps, 1:steps, '-'))\n\tmat_pow_res = M_tran_probs\n\t\n\tfor(i in 1:(steps-1)) {\n\t\tP_q = diag(1, node_count, node_count) %*% mat_pow_res\n\t\tcov_mat[which(step_diff==i)] = sum( cov_mat_pre * P_q )\n\t\tif( i != (steps-1) ) {\n\t\t\tmat_pow_res = mat_pow_res %*% M_tran_probs\t\n\t\t}\n\t}\n\t\n\t# for(i in 1:steps){\n\t\t# for(j in i:steps){\n\t\t\t# if(i!=j) {\n\t\t\t\t# # P_q[i,j] gives probability of reaching j at q-s steps starting at node i \n\t\t\t\t# P_q = diag(1, node_count, node_count) %*% mat_pow( M_tran_probs, abs(j-i) )\n\t\t\t\t# cov_mat[i,j] = sum( cov_mat_pre * P_q)\n\t\t\t\t# cov_mat[j,i] = cov_mat[i,j]\n\t\t\t# }\n\t\t# }\n\t# }\n\t\n\treturn( sum(cov_mat)/(steps^2) )\n}\n\nvar_rw_srs = function(g, steps) {\n\t#cov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t#cov_mat = outer(1:steps, 1:steps, FUN=covar_fn, g=g, cv_type=covar_fn )\n\t\n\t# Set up a matrix for results:\n\tnode_count = vcount(g)\n\tcov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t\n\t# Precompute some values:\n\t# W = outer(degree(g), degree(g))^-1\n\t# sum_W = sum(W)\n\t# norm_W = sum_W/W\n\t\n\t\n\tval_Y = V(g)$aids ## This depends on name of attibute\n\t\n\t#P_s = as.vector(rep(1/vcount(g), vcount(g))) # assume node is selected at random (NOT proportional to degree)\n\tP_s = degree(g)/sum(degree(g)) # assume node is selected at random proportional to degree\n\tmean_Y = t(P_s) %*% val_Y\n\tY = outer(val_Y-mean_Y, val_Y-mean_Y)\n\t\n\tM_tran_probs = get.adjacency(g) / degree(g)\n\t##M_tran_probs = matrix(P_s, vcount(g), vcount(g), byrow=TRUE)\n\t\n\t#cov_mat = norm_W * P_s * P_q * Y\n\t\n\tdiag(cov_mat) = P_s %*% (val_Y - mean_Y)^2\n\t#cov_mat_pre = norm_W * P_s * Y\n\tcov_mat_pre = P_s * Y\n\n\t\n\tstep_diff = abs(outer(1:steps, 1:steps, '-'))\n\tmat_pow_res = M_tran_probs\n\t\n\tfor(i in 1:(steps-1)) {\n\t\tP_q = diag(1, node_count, node_count) %*% mat_pow_res\n\t\tcov_mat[which(step_diff==i)] = sum( cov_mat_pre * P_q )\n\t\tif( i != (steps-1) ) {\n\t\t\tmat_pow_res = mat_pow_res %*% M_tran_probs\t\n\t\t}\n\t}\n\t\n\t# for(i in 1:steps){\n\t\t# for(j in i:steps){\n\t\t\t# if(i!=j) {\n\t\t\t\t# # P_q[i,j] gives probability of reaching j at q-s steps starting at node i \n\t\t\t\t# P_q = diag(1, node_count, node_count) %*% mat_pow( M_tran_probs, abs(j-i) )\n\t\t\t\t# cov_mat[i,j] = sum( cov_mat_pre * P_q)\n\t\t\t\t# cov_mat[j,i] = cov_mat[i,j]\n\t\t\t# }\n\t\t# }\n\t# }\n\t\n\treturn( sum(cov_mat)/(steps^2) )\n}\n\nvar_rds = function(g, steps, covar_fn='RDS') {\n\t# covar_fn is \n\t# 'RW' for random walk\n\t# 'RDS' for RDS weighted\n\t#cov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t#cov_mat = outer(1:steps, 1:steps, FUN=covar_fn, g=g, cv_type=covar_fn )\n\t\n\t# Set up a matrix for results:\n\tnode_count = vcount(g)\n\tcov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t\n\t# Precompute some values:\n\tW = degree(g)^-1\n\tsum_W = sum(W)\n\t#norm_W = sum_W/W\n\tnorm_W = 1 / sum_W\n\n\t\n\tval_Y = V(g)$aids ## This depends on name of attibute\n\t\n\tP_s = degree(g)/sum(degree(g)) # assume node is selected at random proportional to degree\n\tmean_Y = mean( norm_W*(val_Y/degree(g)) )\n\tY = outer((norm_W*val_Y/degree(g))-mean_Y, (norm_W*val_Y/degree(g))-mean_Y)\n\t\n\tM_tran_probs = get.adjacency(g) / degree(g)\n\t\n\t\n\t#cov_mat = norm_W * P_s * P_q * Y\n\t\n\tdiag(cov_mat) = mean((val_Y - mean_Y)^2)\n\t# cov_mat_pre = norm_W * P_s * Y #( P_q * Y )\n\tif( identical(covar_fn, 'RDS') ){\n cov_mat_pre = P_s * Y\n\t} else { #Use the RW - random walk model\n\t\tcov_mat_pre = P_s * Y\n\t}\n\t\n\tstep_diff = abs(outer(1:steps, 1:steps, '-'))\n\tmat_pow_res = M_tran_probs\n\t\n\tfor(i in 1:(steps-1)) {\n\t\tP_q = diag(1, node_count, node_count) %*% mat_pow_res\n\t\tcov_mat[which(step_diff==i)] = sum( cov_mat_pre * P_q )\n\t\tif( i != (steps-1) ) {\n\t\t\tmat_pow_res = mat_pow_res %*% M_tran_probs\t\n\t\t}\n\t}\n\t\n\t# for(i in 1:steps){\n\t\t# for(j in i:steps){\n\t\t\t# if(i!=j) {\n\t\t\t\t# # P_q[i,j] gives probability of reaching j at q-s steps starting at node i \n\t\t\t\t# P_q = diag(1, node_count, node_count) %*% mat_pow( M_tran_probs, abs(j-i) )\n\t\t\t\t# cov_mat[i,j] = sum( cov_mat_pre * P_q)\n\t\t\t\t# cov_mat[j,i] = cov_mat[i,j]\n\t\t\t# }\n\t\t# }\n\t# }\n\t\n\treturn( mean(cov_mat) )\n}\n\nvar_srs = function(g, steps) {\n\t#cov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t#cov_mat = outer(1:steps, 1:steps, FUN=covar_fn, g=g, cv_type=covar_fn )\n\t\n\t# Set up a matrix for results:\n\tnode_count = vcount(g)\n\tcov_mat = matrix(NA, nrow=steps, ncol=steps)\n\t\n\t# Precompute some values:\n\t# W = outer(degree(g), degree(g))^-1\n\t# sum_W = sum(W)\n\t# norm_W = sum_W/W\n\t\n\t\n\tval_Y = V(g)$aids ## This depends on name of attibute\n\t\n\tP_s = as.vector(rep(1/vcount(g), vcount(g))) # assume node is selected at random (NOT proportional to degree)\n\tmean_Y = t(P_s) %*% val_Y\n\tY = outer(val_Y-mean_Y, val_Y-mean_Y)\n\t\n\t#M_tran_probs = get.adjacency(g) / degree(g)\n\tM_tran_probs = matrix(P_s, vcount(g), vcount(g), byrow=TRUE)\n\t\n\t#cov_mat = norm_W * P_s * P_q * Y\n\t\n\tdiag(cov_mat) = P_s %*% (val_Y - mean_Y)^2\n\t#cov_mat_pre = norm_W * P_s * Y\n\tcov_mat_pre = P_s * Y\n\n\t\n\tstep_diff = abs(outer(1:steps, 1:steps, '-'))\n\tmat_pow_res = M_tran_probs\n\t\n\tfor(i in 1:(steps-1)) {\n\t\tP_q = diag(1, node_count, node_count) %*% mat_pow_res\n\t\tcov_mat[which(step_diff==i)] = sum( cov_mat_pre * P_s )\n\t\tif( i != (steps-1) ) {\n\t\t\tmat_pow_res = mat_pow_res %*% M_tran_probs\t\n\t\t}\n\t}\n\t\n\t# for(i in 1:steps){\n\t\t# for(j in i:steps){\n\t\t\t# if(i!=j) {\n\t\t\t\t# # P_q[i,j] gives probability of reaching j at q-s steps starting at node i \n\t\t\t\t# P_q = diag(1, node_count, node_count) %*% mat_pow( M_tran_probs, abs(j-i) )\n\t\t\t\t# cov_mat[i,j] = sum( cov_mat_pre * P_q)\n\t\t\t\t# cov_mat[j,i] = cov_mat[i,j]\n\t\t\t# }\n\t\t# }\n\t# }\n\t\n\treturn( sum(cov_mat)/(steps^2) )\n}\n\n\ncovar_fn = function(s, q, g, cv_type='covar_fn') {\n\t# Set up a matrix for results:\n\tnode_count = vcount(g)\n\tcov_mat = matrix(NA, nrow= node_count, ncol= node_count)\n\t\n\t# Precompute some values:\n\tW = outer(degree(g), degree(g))^-1\n\tsum_W = sum(W)\n\tnorm_W = sum_W/W\n\t\n\t\n\tval_Y = V(g)$aids ## This depends on name of attibute\n\tmean_Y = mean(Y)\n\tY = outer(val_Y-mean_Y, val_Y-mean_Y)\n\t\n\tP_s = degree(g)/sum(degree(g)) # assume node is selected at random\n\tM_tran_probs = get.adjacency(g) / degree(g)\n\t# P_q[i,j] gives probability of reaching j at q-s steps starting at node i \n\tP_q = diag(1, node_count, node_count) %*% mat_pow( M_tran_probs, abs(q-s) )\n\t\n\t#for(i in 1:node_count){\n\t#\tfor(j in 1:node_count){\n\t#\t\tcov_mat[i,j] = norm_W[i,j] * P_s[i] * P_q[i,j] * Y[i,j]\n\t#\t}\n\t#}\n\t\n\tcov_mat = norm_W * P_s * P_q * Y\n\treturn(sum(cov_mat))\n}\n\n\ngenerate_node_seq = function( M_trans_probs, seq_length = 10, initial_node = NA ) {\n\tret_seq = rep(0, seq_length)\n\trand_list = runif(seq_length)\n\tif (is.na(initial_node[1])) { ret_seq[1]=sample.int(nrow(M_trans_probs), 1) }\n\telse{\n\t\tif(length(initial_node)>1){ ret_seq[1]=sample(nrow(M_trans_probs), 1, prob=initial_node) }\n\t\telse{ ret_seq[1] = initial_node }\n\t}\n\tcum_prob = t(apply(M_trans_probs, 1, cumsum))\n\tcum_prob[,nrow(cum_prob)] = 1 #Set the last column to 1 to avoid rounding errors\n\tfor (i in 2: seq_length){\n\t\t ret_seq[i] = 1+sum(cum_prob[ret_seq[i-1],] <= rand_list[i] )\n\t}\n\t# Could add code to replace the state_index with the state code (as.factor)\n\treturn(ret_seq)\n\t\n}\n\n\nsim_rds_var = function(ggraph, trials=10, seq_length = 10 ) {\n\tM_trans_probs = get.adjacency(ggraph)/degree(ggraph)\n\tresults=matrix(nrow=trials,ncol=2)\n\tfor( i in seq(trials) ) {\n\t\tsample_nodes = generate_node_seq(M_trans_probs, seq_length, initial_node=degree(ggraph)/sum(degree(ggraph)))\n\t\tsample_attr = V(ggraph)$aids[sample_nodes]\n\t\tsample_deg = degree(ggraph)[sample_nodes]\n\t\tsample_rid = c(NA, head(sample_nodes, -1))\n\t\t\n\t\tresults[i,] = rds.set_groups_estimate(sample_attr, sample_nodes, sample_rid, sample_deg, groups=c('0','1'), est.only=TRUE, minXrec=0)$P.hat\n\t}\n\t#return(diag(var(results)))\n\treturn(results)\n}\n\nsim_rw_var = function(ggraph, trials=10, seq_length = 10 ) {\n\tM_trans_probs = get.adjacency(ggraph)/degree(ggraph)\n\tresults=matrix(nrow=trials,ncol=2)\n\tfor( i in seq(trials) ) {\n\t\tsample_nodes = generate_node_seq(M_trans_probs, seq_length, initial_node=degree(ggraph)/sum(degree(ggraph)))\n\t\tsample_attr = V(ggraph)$aids[sample_nodes]\n\t\t#sample_deg = degree(ggraph)[sample_nodes]\n\t\t#sample_rid = c(NA, tail(sample_nodes, -1))\n\t\t\n\t\tresults[i,] = prop.table(table(factor(sample_attr, levels=c(0,1))))\n\t}\n\t#return(diag(var(results)))\n\treturn(results)\n}\n\nsim_srs_var = function(ggraph, trials=10, seq_length = 10 ) {\n\t#M_trans_probs = get.adjacency(ggraph)/degree(ggraph)\n\tresults=matrix(nrow=trials,ncol=2)\n\tfor( i in seq(trials) ) {\n\t\tsample_nodes = sample(V(ggraph), size= seq_length, replace=TRUE)\n\t\tsample_attr = V(ggraph)$aids[sample_nodes]\n\t\t#sample_deg = degree(ggraph)[sample_nodes]\n\t\t#sample_rid = c(NA, tail(sample_nodes, -1))\n\t\t\n\t\tresults[i,] = prop.table(table(factor(sample_attr, levels=c(0,1))))\n\t}\n\treturn(diag(var(results)))\n\t#return(results)\n}\n\nsim_vh_var = function(ggraph, trials=10, seq_length = 10 ) {\n\tM_trans_probs = get.adjacency(ggraph)/degree(ggraph)\n\tresults=matrix(nrow=trials,ncol=2)\n\tfor( i in seq(trials) ) {\n\t\tsample_nodes = generate_node_seq(M_trans_probs, seq_length, initial_node=degree(ggraph)/sum(degree(ggraph)))\n\t\tsample_attr = V(ggraph)$aids[sample_nodes]\n\t\tsample_deg = degree(ggraph)[sample_nodes]\n\t\tsample_rid = c(NA, head(sample_nodes, -1))\n\t\t\n\t\tresults[i,] = rds.VH.estimate(sample_attr, sample_nodes, sample_rid, sample_deg, groups=c('0','1'))$RDS.VH\n\t}\n\t#return(diag(var(results, na.rm=TRUE)))\n\treturn(results)\n}\n\n\n\n\n\n\n\n\n\na_edge_list = c( \n1,2,\n1,3,\n1,5,\n2,1,\n2,4,\n2,6,\n3,1,\n3,5,\n4,2,\n4,6,\n5,1,\n5,3,\n5,6,\n5,7,\n6,2,\n6,4,\n6,5,\n7,5,\n7,8,\n7,9,\n7,12,\n8,7,\n8,10,\n8,11,\n9,7,\n9,10,\n9,11,\n10,8,\n10,9,\n10,12,\n11,8,\n11,9,\n11,12,\n12,7,\n12,10,\n12,11,\n12,14,\n13,14,\n13,15,\n13,17,\n14,12,\n14,13,\n14,16,\n14,18,\n15,13,\n15,17,\n16,14,\n16,18,\n17,13,\n17,15,\n17,18,\n18,14,\n18,16,\n18,17\n)\n\n#edge_list_a = matrix(a_edge_list, ncol=2, byrow=TRUE)\n\nattrib_a = rep(0,18)\nattrib_a[c(8,9,12:18)] = 1\n\ng_a = graph.empty(directed=FALSE)\ng_a = add.vertices( g_a, 18, aids=attrib_a)\n\n\ng_a = add.edges(g_a, a_edge_list)\n\n\ng_a = simplify(g_a)\n\n\n\n\n\nb_edge_list = c( \n1,2,\n1,9,\n1,10,\n2,1,\n2,3,\n2,11,\n3,2,\n3,5,\n3,12,\n4,5,\n4,13,\n5,3,\n5,7,\n5,14,\n6,7,\n6,15,\n7,5,\n7,6,\n7,8,\n7,16,\n8,7,\n8,9,\n8,17,\n9,1,\n9,8,\n9,18,\n10,1,\n10,11,\n10,18,\n11,2,\n11,10,\n11,12,\n12,3,\n12,11,\n12,14,\n13,4,\n13,12,\n14,5,\n14,12,\n14,15,\n14,16,\n15,6,\n15,14,\n16,7,\n16,17,\n17,8,\n17,16,\n17,18,\n18,9,\n18,10,\n18,17\n)\n\nattrib_b = rep(0,18)\nattrib_b[10:18] = 1\n\ng_b = graph.empty(directed=FALSE)\ng_b = add.vertices( g_b, 18, aids=attrib_b)\ng_b = add.edges(g_b, b_edge_list)\ng_b = simplify(g_b)\n\n\n\n\ncomparison_plot_data = function(ggraph, steps_list=c(10, 20), trials=1000 ){\n\tcompare_list = c(\"sim_rw\", \"sim_vh\", \"sim_rds\", \"var_srs\", \"var_rw\", \"var_vh\", \"var_rds\")\n\tresults = matrix(ncol=length(steps_list), nrow=7, dimnames=list(compare_list, steps_list) )\n\tfor (i in seq(from=length(steps_list)) ){\n\t\tresults[1:3,i] = sim_all_var(ggraph, trials, steps_list[i] )\n\t\tresults[4,i] = var_srs(ggraph, steps_list[i]) \n\t\tresults[5,i] = var_rw(ggraph, steps_list[i]) \n\t\tresults[6,i] = var_rds(ggraph, steps_list[i]) \n\t\tresults[7,i] = var_rds(ggraph, steps_list[i]) \n\t}\n\treturn(results)\n}\n\n\nsim_all_var = function(ggraph, trials=10, seq_length = 10 ) {\n\tM_trans_probs = get.adjacency(ggraph)/degree(ggraph)\n\tcompare_list = c(\"sim_rw\", \"sim_vh\", \"sim_rds\")\n\tresults=matrix(nrow=trials,ncol=3)\n\tfor( i in seq(trials) ) {\n\t\tsample_nodes = generate_node_seq(M_trans_probs, seq_length, initial_node=degree(ggraph)/sum(degree(ggraph)))\n\t\tsample_attr = V(ggraph)$aids[sample_nodes]\n\t\tsample_deg = degree(ggraph)[sample_nodes]\n\t\tsample_rid = c(NA, head(sample_nodes, -1))\n\t\t\n\t\tresults[i,3] = rds.set_groups_estimate(sample_attr, sample_nodes, sample_rid, sample_deg, groups=c('0','1'), est.only=TRUE, minXrec=0)$P.hat[1]\n\t\tresults[i,2] = rds.VH.estimate(sample_attr, sample_nodes, sample_rid, sample_deg, groups=c('0','1'))$RDS.VH[1]\n\t\tresults[i,1] = prop.table(table(factor(sample_attr, levels=c(0,1))))[1]\n\t}\n\treturn(apply(results, 2, var, na.rm=TRUE))\n\t#return(results)\n}\n\ncomparison_plot_data = function(ggraph, steps_list=c(10, 20), trials=1000 ){\n\tcompare_list = c(\"sim_rw\", \"sim_vh\", \"sim_rds\", \"var_srs\", \"var_rw\", \"var_vh\", \"var_rds\")\n\tresults = matrix(ncol=length(steps_list), nrow=7, dimnames=list(compare_list, steps_list) )\n\tfor (i in seq(from=length(steps_list)) ){\n\t\tresults[1:3,i] = sim_all_var(ggraph, trials, steps_list[i] )\n\t\tresults[4,i] = var_srs(ggraph, steps_list[i]) \n\t\tresults[5,i] = var_rw(ggraph, steps_list[i]) \n\t\tresults[6,i] = var_rds(ggraph, steps_list[i]) \n\t\tresults[7,i] = var_rds(ggraph, steps_list[i]) \n\t}\n\treturn(results)\n}\n\nplot(x=1, type='n',xlim=c(0,100), ylim=c(0,.15), xlab=\"Sequence Length\", ylab=\"Variance\")\nplot_lines = function(plot_data) {\t\n\tx_cords = as.numeric(dimnames(plot_data)[[2]])\n\tfor (i in 1:nrow(plot_data)){\n\t\tlines(x_cords, plot_data[i,], col=c(\"lightblue\", \"blue\", \"darkblue\", \"red\", \"lightgreen\", \"green\", \"darkgreen\")[i])\n\t}\n}\n\nplot_cf_lines = function(plot_data_a, plot_data_b) {\t\n\ttitles = dimnames(plot_data_a)[[1]]\n\tx_cords = as.numeric(dimnames(plot_data_b)[[2]])\n\tfor (i in 1:nrow(plot_data_a)){\n\t\tplot(x=1, type='n',xlim=c(0,200), ylim=c(0,.25), xlab=\"Sequence Length\", ylab=\"Variance\", main=titles[i])\n\t\tlines(x_cords, plot_data_a[i,], col=\"blue\")\n\t\tlines(x_cords, plot_data_b[i,], col=\"lightblue\")\n\t}\n}\n", "meta": {"hexsha": "649ec85c540bf4bc25a014ff7f6fe13db71d853f", "size": 14678, "ext": "r", "lang": "R", "max_stars_repo_path": "RDS/code/misc_code/random_walks.r", "max_stars_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_stars_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RDS/code/misc_code/random_walks.r", "max_issues_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_issues_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RDS/code/misc_code/random_walks.r", "max_forks_repo_name": "chrisjcameron/chrisjcameron.github.io", "max_forks_repo_head_hexsha": "98bae30c1227465aba09ee50083688857b573cd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3506044905, "max_line_length": 145, "alphanum_fraction": 0.6552663851, "num_tokens": 5327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.6004206592869591}} {"text": "library(orthopolynom)\nlibrary(igraph)\nlibrary(parallel)\nlegendre_Pl_array<-function(m,y){\n pf<-polynomial.functions(legendre.polynomials(m,normalized=T))\n lv<-sapply(X=1:(m+1),FUN=function(x){\n pf[[x]](y) #*sqrt(2*(x-1)+1)\n })\n return(t(lv)*sqrt(2))\n}\n\nlen_deriv<-function(m,y){\n\t#y varies from [0,1]\n\t#returns x(1-x)deriv\n\tout=matrix(0,m+1,length(y))\n\tout[1,]=0\n\tlpa<-legendre_Pl_array(m,2*y-1)[,,drop=F]\n\tfor(i in 2:(m+1)){\n\t\tk=i-1\n\t\tout[i,]<- -(k/2)*( (2*y-1)*lpa[i,]-sqrt((2*k+1)/(2*k-1))*lpa[i-1,] )\n\t}\n\treturn(out)\n} \t\n\nlen_deriv2<-function(m,y){\n\t#y varies from [0,1]\n\t#x(1-x)deriv2\n\tout=matrix(0,m+1,length(y))\n\tout[1,]=0\n\tout[2,]=0\n\tif(m==1) return(out)\n\t#lpa<-legendre_Pl_array(m,2*y-1)\n\tld = len_deriv(m,y)[,,drop=F]\n\tfor(i in 3:(m+1)){\n\t\tk=i-1\n\t\t#out[i,]<- sqrt(2*(i-1)+1)*(out[i-2,]/sqrt(2*(i-3)+1)+(1/2)*(2*(i-2)+1)*ld[i-1,]/sqrt(2*(i-2)+1) )\n\t\tout[i,] = out[i-2,]*sqrt((2*k+1)/(2*k-3)) + 2*(2*k-1)*sqrt(2*k+1)*ld[i-1,]/sqrt(2*k-1)\n\t}\n\treturn(out)\n}\n\nKvec.node<-function(dat,m){\n\td=dim(dat)[2]\n\tout=matrix(0,d,m)\n\tout=lapply(1:d,function(i){\n\t\tld1= t(-2*len_deriv(m,dat[,i])[-1,,drop=F])*(2*dat[,i]-1)\n\t\tld2= dat[,i]*(1-dat[,i])*t(len_deriv2(m,dat[,i])[-1,,drop=F])\n\t\trowMeans(t(ld1+ld2))\n\t})\n\tt(simplify2array(out))\n}\n\nKvec.edge<-function(dat,m,edgelist=NULL){\n\td=dim(dat)[2]\n\tg=graph.full(d)\n\tif(is.null(edgelist)) edgelist=get.edgelist(g)\n\te=dim(edgelist)[1]\n\tif(d>=100){\n\t\tcores=detectCores()\n\t}else{\n\t\tcores=1\n\t}\n\tret=mclapply(1:e,function(i){\n\t\ts=edgelist[i,1]\n\t\tt=edgelist[i,2]\n\t\t#out= crossprod(2*len_deriv(m,dat[,s])[-1,]*(2*dat[,s]-1) ,legendre_Pl_array(m,2*dat[,t]-1)[-1,] )\n\t\t#out = out + crossprod(legendre_Pl_array(m,2*dat[,s]-1)[-1,], 2*len_deriv(m,dat[,t])[-1,]*(2*dat[,t]-1) )\n\t\t#out= out+ crossprod(2*len_deriv2(m,dat[,s])[-1,]*(2*dat[,s]-1) ,legendre_Pl_array(m,2*dat[,t]-1)[-1,] )\n\t\t#out = out + crossprod(legendre_Pl_array(m,2*dat[,s]-1)[-1,], 2*len_deriv2(m,dat[,t])[-1,]*(2*dat[,t]-1) )\n\t\tout1= crossprod(-2*t(len_deriv(m,dat[,s])[-1,,drop=F])*(2*dat[,s]-1) , t(legendre_Pl_array(m,2*dat[,t]-1)[-1,,drop=F]) )\n\t\tout2 = legendre_Pl_array(m,2*dat[,s]-1)[-1,,drop=F] %*% (-2*t(len_deriv(m,dat[,t])[-1,,drop=F])*(2*dat[,t]-1) )\n\t\tout1= out1+ crossprod(dat[,s]*(1-dat[,s])*t(len_deriv2(m,dat[,s])[-1,,drop=F]) ,t(legendre_Pl_array(m,2*dat[,t]-1)[-1,,drop=F]) )\n\t\tout2 = out2 + legendre_Pl_array(m,2*dat[,s]-1)[-1,,drop=F] %*% (dat[,t]*(1-dat[,t])*t(len_deriv2(m,dat[,t])[-1,,drop=F]) )\n\t\treturn(list(out1=out1/dim(dat)[1],out2=out2/dim(dat)[1]))\n\t},mc.cores=cores)\n\treturn(list(array(unlist(lapply(ret,function(x)x$out1)),dim=c(m,m,e)),\n\t\tarray(unlist(lapply(ret,function(x)x$out2)),dim=c(m,m,e))))\n}\n\n# Gamma.ret<-function(dat,m1,m2){\n# \td=dim(dat)[2]\n# \tg=graph.full(d)\n# \tge=get.edgelist(g)\t\n# \tnedge=dim(ge)[1]\n# \tout=mclapply(1:d,function(i){\n# \t\teout=mclapply(1:nedge,function(e){\n# \t\t\ts=ge[e,1];t=ge[e,2]\n# \t\t\tif(s==i){\n# \t\t\t\tl1= len_deriv(m1,dat[,i])[-1,]\n# \t\t\t}else{\n# \t\t\t\tl1=numeric()\n# \t\t\t\tlpa=legendre_Pl_array(m2,2*dat[,s]-1)[-1,]\n# \t\t\t\tfor(l in 1:m2){\n# \t\t\t\t\tif(imax_o){\n\t \tpos=2\n\t\tmax_o =temp\n\t}\n\n\ttemp = (dens_b*Pc_b)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_R[[i,3]] = temp;\t\n\tif(temp>max_o){\n\t \tpos=3\n\t\tmax_o =temp\n\t}\n\n\tclassification_r[[i,1]] = label_class[pos];\n\n}\n\n\n#calculating posterior and classification training set 2\nvector_a = c(0,0);\nmax_o = 0;\ntemp=0;\nclassification_g= matrix(nrow=3000,ncol=1)\npost_G = matrix(nrow=3000,ncol=3) #posterior for G dataset\n\nfor (i in 1:Nk[2]){\t\t\t\n\n\tvector_a = c(gauss_G[[1]][i]-mean_R[1], gauss_G[[2]][i]-mean_R[2])\n\tvector_trans = t(vector_a)\n\tvector_trans= t(vector_a)\n\tdens_r = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\n\tvector_a = c(gauss_G[[1]][i]-mean_G[1], gauss_G[[2]][i]-mean_G[2])\n\tvector_trans = t(vector_a)\n\tdens_g = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\t\t\n\tvector_a = c(gauss_G[[1]][i]-mean_B[1], gauss_G[[2]][i]-mean_B[2])\n\tvector_trans = t(vector_a)\n\tdens_b = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\n\ttemp = (dens_r*Pc_r)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_G[[i,1]] = temp;\t\n\tmax_o = temp;\n\tpos=1;\t\t\n\n\ttemp = (dens_g*Pc_g)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_G[[i,2]] = temp;\t\n\tif(temp>max_o){\n\t \tpos=2\n\t\tmax_o =temp\n\t}\n\n\ttemp = (dens_b*Pc_b)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_G[[i,3]] = temp;\t\n\tif(temp>max_o){\n\t \tpos=3\n\t\tmax_o =temp\n\t}\n\n\tclassification_g[[i,1]] = label_class[pos];\n\n}\n\n\n#calculating posterior and classification training set 3\nvector_a = c(0,0);\nmax_o = 0;\ntemp=0;\nclassification_b= matrix(nrow=3000,ncol=1)\npost_B = matrix(nrow=3000,ncol=3) #posterior for B dataset\n\nfor (i in 1:Nk[2]){\t\t\t\n\n\tvector_a = c(gauss_B[[1]][i]-mean_R[1], gauss_B[[2]][i]-mean_R[2])\n\tvector_trans = t(vector_a)\n\tvector_trans= t(vector_a)\n\tdens_r = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\n\tvector_a = c(gauss_B[[1]][i]-mean_G[1], gauss_B[[2]][i]-mean_G[2])\n\tvector_trans = t(vector_a)\n\tdens_g = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\t\t\n\tvector_a = c(gauss_B[[1]][i]-mean_B[1], gauss_B[[2]][i]-mean_B[2])\n\tvector_trans = t(vector_a)\n\tdens_b = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\t\n\ttemp = (dens_r*Pc_r)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_B[[i,1]] = temp;\t\n\tmax_o = temp;\n\tpos=1;\t\t\n\t\n\ttemp = (dens_g*Pc_g)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_B[[i,2]] = temp;\t\n\tif(temp>max_o){\n\t \tpos=2\n\t\tmax_o =temp\n\t}\n\n\ttemp = (dens_b*Pc_b)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_B[[i,3]] = temp;\t\n\tif(temp>max_o){\n\t \tpos=3\n\t\tmax_o =temp\n\t}\n\n\tclassification_b[[i,1]] = label_class[pos];\n\n}\n\n#all data together\n#final_class shows class of each spot\n#final is the matrix with the corresponding spots\n\nfinal_class=c(0,0);\nfinal = matrix(nrow=N,ncol=2)\nfor (i in 1:Nk[1]){\t\n\nfinal[i,1]=gauss_R[[1]][i]\nfinal[i,2]=gauss_R[[2]][i]\nfinal_class[i]=classification_r[[i,1]]\n\nfinal[i+Nk[1],1]=gauss_G[[1]][i]\nfinal[i+Nk[1],2]=gauss_G[[2]][i]\nfinal_class[i+Nk[1]]=classification_g[[i,1]]\n\nfinal[i+Nk[1]+Nk[2],1]=gauss_B[[1]][i]\nfinal[i+Nk[1]+Nk[2],2]=gauss_B[[2]][i]\nfinal_class[i+Nk[1]+Nk[2]]=classification_b[[i,1]]\n\n}\n\n\n#data with their max posteriors\npost = matrix(nrow=9000,ncol=1)\nfor (i in 1:Nk[1]){\npost[i,1]=max(post_R[[i,1]],post_R[[i,2]],post_R[[i,3]])\npost[i+Nk[1],1]=max(post_G[[i,1]],post_G[[i,2]],post_G[[i,3]])\npost[i+Nk[1]+Nk[2],1]=max(post_B[[i,1]],post_B[[i,2]],post_B[[i,3]])\t\n}\n\n\n\n\n#classifying the whole data from beginning to the 3 classes\n#1->x,2->y,3->probability\na=0;\na=sum(final_class == \"r\") #sum of elements in r class\nclass_r=matrix(nrow=a,ncol=3)\n\n\na=0;\na=sum(final_class == \"g\") #sum of elements in g class\nclass_g=matrix(nrow=a,ncol=3)\n\n\na=0;\na=sum(final_class == \"b\") #sum of elements in b class\nclass_b=matrix(nrow=a,ncol=3)\n\n\n\ncounter1=1;\ncounter2=1;\ncounter3=1;\nfor (i in 1:N){\n \tif(final_class[i]==\"r\"){\n\t\tclass_r[counter1,1] = final[i,1];\n\t\tclass_r[counter1,2] = final[i,2];\n\t\tclass_r[counter1,3] = post[i,1];\n\t\tcounter1=counter1+1;\n\t}\n\tif(final_class[i]==\"g\"){\n\t\tclass_g[counter2,1] = final[i,1];\n\t\tclass_g[counter2,2] = final[i,2];\n\t\tclass_g[counter2,3] = post[i,1];\n\t\tcounter2=counter2+1;\n\t}\n\tif(final_class[i]==\"b\"){\n\t\tclass_b[counter3,1] = final[i,1];\n\t\tclass_b[counter3,2] = final[i,2];\n\t\tclass_b[counter3,3] = post[i,1];\n\t\tcounter3=counter3+1;\n\t}\n\n}\n\n#calculation to find the outliers\ne = which(class_r[,3]<0.4);\ntr1=matrix(nrow=length(e),ncol=2)\ncounter1=1;\n#spots in the boundaries\nfor (i in e){\ntr1[counter1,1]=class_r[i,1]\ntr1[counter1,2]=class_r[i,2]\ncounter1= counter1+1\n}\n\n#calculation to find the outliers\ne = which((class_g[,3])<0.4);\ntr2=matrix(nrow=length(e),ncol=2)\ncounter1=1;\n#spots in the boundaries\nfor (i in e){\ntr2[counter1,1]=class_g[i,1]\ntr2[counter1,2]=class_g[i,2]\ncounter1= counter1+1\n}\n\n#calculation to find the outliers\ne = which(class_b[,3]<0.4);\ntr3=matrix(nrow=length(e),ncol=2)\ncounter1=1;\n#spots in the boundaries\nfor (i in e){\ntr3[counter1,1]=class_b[i,1]\ntr3[counter1,2]=class_b[i,2]\ncounter1= counter1+1\n}\n\n\nplot(class_b[,1],class_b[,2],col=\"blue\",xlim=c(-1.6,1.6),ylim=c(-1.7,1.7),pch=1,panel.first = grid(),xlab=\"x\",ylab=\"y\")\npoints(class_g[,1],class_g[,2],col=\"green\",pch=1)\npoints(class_r[,1],class_r[,2],col=\"red\",pch=1)\n\nt=( colMeans(tr1) + colMeans(tr2) + colMeans(tr3) )/3\nt2=( colMeans(tr1) + colMeans(tr2) )/2\nlines( c(-1.7,t[1]),c(t[2],t[2]) ,lwd=1)\n\nt=( colMeans(tr1) + colMeans(tr2) + colMeans(tr3) )/3\nt2=(colMeans(tr2) + colMeans(tr3) )/2;\nf= (t[2]-t2[2])/(t[1]-t2[1]) ;\nx=f*10;\ny=f*x\nlines( c(t[1],x),c(t[2],y+2) ,lwd=1)\n\nt=( colMeans(tr1) + colMeans(tr2) + colMeans(tr3) )/3\nt2=(colMeans(tr1) + colMeans(tr3) )/2;\nf= (-t[2]+t2[2])/(t[1]-t2[1]) ;\nx=f*10;\ny=f*x\nlines( c(t[1],x),c(t[2],-y-8.5) ,lwd=1)\n\n\n\n\n\n\n#------------------------------------------------------\n\n#install.packages(\"plot3D\") #package for plotting 2d and 3d\nlibrary(\"plot3D\")\n\n\npar(mfrow=c(2,2))\nx = class_r[,1]\ny = class_r[,2]\nz = class_r[,3]\npoints3D(x,y,z)\n\n\nx = class_g[,1]\ny = class_g[,2]\nz = class_g[,3]\npoints3D(x,y,z)\n\n\nx = class_b[,1]\ny = class_b[,2]\nz = class_b[,3]\npoints3D(x,y,z)\n\n\n\ne=which(final_class==\"r\");\nx1= matrix(nrow=length(e),ncol=1) \ny1= matrix(nrow=length(e),ncol=1) \nz1= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx1[counter1,1] = final[i,1]\ny1[counter1,1] = final[i,2]\nz1[counter1,1] = post[i,1];\ncounter1= counter1+1\n}\npoints3D(x1,y1,z1, col=\"red\",xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),zlim=c(0,1))\n\n\ne=which(final_class==\"g\");\nx2= matrix(nrow=length(e),ncol=1) \ny2= matrix(nrow=length(e),ncol=1) \nz2= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx2[counter1,1] = final[i,1]\ny2[counter1,1] = final[i,2]\nz2[counter1,1] = post[i,1];\ncounter1= counter1+1\n}\npoints3D(x2,y2,z2, col=\"green\",add = TRUE)\n\n\ne=which(final_class==\"b\");\nx1= matrix(nrow=length(e),ncol=1) \ny1= matrix(nrow=length(e),ncol=1) \nz1= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx1[counter1,1] = final[i,1]\ny1[counter1,1] = final[i,2]\nz1[counter1,1] = post[i,1];\ncounter1= counter1+1\n}\npoints3D(x1,y1,z1, col=\"blue\",add = TRUE)\n\n\n\n\n\npar(mfrow=c(1,1))\nplot(class_b[,1],class_b[,2],col=\"blue\",xlim=c(-1.6,1.6),ylim=c(-1.7,1.7),pch=20,panel.first = grid())\npoints(class_g[,1],class_g[,2],col=\"green\",pch=20)\npoints(class_r[,1],class_r[,2],col=\"red\",pch=20)\n\n\n\n\n\n\n\n#==================================================================\n#task3\n\n#read csv file in the working directory\ngauss_T = read.csv(file=\"/home/stelios/test_set.csv\", header=TRUE, sep=\";\") \n\nt=length(gauss_T[,1])\n\n\n\n\n\n#calculating posterior and classification of test set\nvector_a = c(0,0);\nmax_o = 0;\ntemp=0;\nclassification_t= matrix(nrow=t,ncol=1) #classification of the first dataset\npost_T = matrix(nrow=t,ncol=1) #Max posterior for test dataset\npost_T_all = matrix(nrow=t,ncol=3) #Max posterior for test dataset\n\n\nfor (i in 1:t){\t\t\t\n\n\tvector_a = c(gauss_T[[1]][i]-mean_R[1], gauss_T[[2]][i]-mean_R[2])\n\tvector_trans = t(vector_a)\n\tvector_trans= t(vector_a)\n\tdens_r = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\n\n\t\n\t\n\t\n\tvector_a = c(gauss_T[[1]][i]-mean_G[1], gauss_T[[2]][i]-mean_G[2])\n\tvector_trans = t(vector_a)\n\tdens_g = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\n\t\t\t\n\tvector_a = c(gauss_T[[1]][i]-mean_B[1], gauss_T[[2]][i]-mean_B[2])\n\tvector_trans = t(vector_a)\n\tdens_b = ( 1/( (2*pi)^(3/2) ) ) * (1/((det(S))^(1/2)) ) * exp(-0.5*vector_trans%*%(solve(S))%*%vector_a)\n\t\n\t\n\t\n\t\n\ttemp = (dens_r)*Pc_r/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_T_all[[i,1]] = temp;\t\n\tmax_o = temp;\n\tpos=1;\t\t\n\n\ttemp = (dens_g)*Pc_g/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_T_all[[i,2]] = temp;\t\n\n\tif(temp>max_o){\n\t \tpos=2\n\t\tmax_o =temp\n\t}\n\n\ttemp = (dens_b*Pc_b)/(dens_r*Pc_r+dens_g*Pc_g+dens_b*Pc_b);\n\tpost_T_all[[i,3]] = temp;\n\n\tif(temp>max_o){\n\t \tpos=3\n\t\tmax_o =temp\n\t}\n\t\n\tpost_T[[i,1]] = max_o ;\t\n\tclassification_t[[i,1]] = label_class[pos];\n\n}\n\n\n\n#---------------plotting classified training data ---------------------\n\n\n\npar(mfrow=c(1,1))\nplot(c(0,0),c(0,0),col=\"white\",xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),pch=20,panel.first = grid(),xlab=\"x\",ylab=\"y\")\n\n\nfor (i in 1:t){\n\tif(classification_t[[i,1]]==\"r\"){\n\t\tpoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"red\",pch=1)\n\t}\n\tif(classification_t[[i,1]]==\"g\"){\n\t\tpoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"green\",pch=1)\n\t}\n\tif(classification_t[[i,1]]==\"b\"){\n\t\tpoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"blue\",pch=1)\n\t}\n}\n\n\n\n\n\n\n\n\n\nplot(c(0,0),c(0,0),col=\"white\",xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),pch=20,panel.first = grid(),xlab=\"x\",ylab=\"y\")\n\nfor (i in 1:t){\nif(classification_t[[i,1]]==\"r\"){\npoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"coral\",pch=20)\n}\nif(classification_t[[i,1]]==\"g\"){\npoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"chartreuse1\",pch=20)\n}\nif(classification_t[[i,1]]==\"b\"){\npoints(gauss_T[[1]][i],gauss_T[[2]][i],col=\"cadetblue2\",pch=20)\n}\n}\n\n\n\n\n\n\n#calculation to find the outliers\ne = which((post_T)<0.5);\ntr1=matrix(nrow=length(e),ncol=2)\ncounter1=1;\n#spots in the boundaries\nfor (i in e){\ntr1[counter1,1]=gauss_T[[1]][i];\ntr1[counter1,2]=gauss_T[[2]][i];\ncounter1= counter1+1\n}\n\npoints(tr1,col=\"black\",pch=5)\n\n\n\n\n#======================plotting test data=================\n\n\n\ne=which(classification_t[,1]==\"r\");\nx1= matrix(nrow=length(e),ncol=1) \ny1= matrix(nrow=length(e),ncol=1) \nz1= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx1[counter1,1] = gauss_T[i,1]\ny1[counter1,1] = gauss_T[i,2]\nz1[counter1,1] = post_T[i,1];\ncounter1= counter1+1\n}\npoints3D(x1,y1,z1, col=\"red\",xlim=c(-2.5,2.5),ylim=c(-2.5,2.5),zlim=c(0,1))\n\n\ne=which(classification_t[,1]==\"g\");\nx2= matrix(nrow=length(e),ncol=1) \ny2= matrix(nrow=length(e),ncol=1) \nz2= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx2[counter1,1] = gauss_T[i,1]\ny2[counter1,1] = gauss_T[i,2]\nz2[counter1,1] = post_T[i,1];\ncounter1= counter1+1\n}\npoints3D(x2,y2,z2, col=\"green\",add = TRUE)\n\n\ne=which(classification_t[,1]==\"b\");\nx1= matrix(nrow=length(e),ncol=1) \ny1= matrix(nrow=length(e),ncol=1) \nz1= matrix(nrow=length(e),ncol=1) \ncounter1=1;\nfor (i in e){\nx1[counter1,1] = gauss_T[i,1]\ny1[counter1,1] = gauss_T[i,2]\nz1[counter1,1] = post_T[i,1];\ncounter1= counter1+1\n}\npoints3D(x1,y1,z1, col=\"blue\",add = TRUE)\n\n\n\n#==========================================================\n\n\n#calculation to find the outliers\ne = which((post_T)<0.5);\ntr1=matrix(nrow=length(e),ncol=3)\ncounter1=1;\n#spots in the boundaries\nfor (i in e){\ntr1[counter1,1]=gauss_T[[1]][i];\ntr1[counter1,2]=gauss_T[[2]][i];\ntr1[counter1,3]=post_T[i,1];\ncounter1= counter1+1\n}\n\npoints3D(tr1[,1],tr1[,2],tr1[,3],pch=5,xlim=c(-1,1),ylim=c(-1,1),zlim=c(0,1))\n\n\n\n\ndev.off()\n\n\n\n\n\n#outlier The resulting decision boundaries, corresponding to the minimum misclassification rate, will occur when two of the posterior probabilities (the two largest) are equal, and so will be defined by linear functions of x, and so again we have a generalized linear model.\n\n\n", "meta": {"hexsha": "30b703d8ca5fa556375d9307d0ec15e14ae49c68", "size": 16073, "ext": "r", "lang": "R", "max_stars_repo_path": "MachineLearning/Project2/Task3_code.r", "max_stars_repo_name": "StylianosChatzichronis/R", "max_stars_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearning/Project2/Task3_code.r", "max_issues_repo_name": "StylianosChatzichronis/R", "max_issues_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearning/Project2/Task3_code.r", "max_forks_repo_name": "StylianosChatzichronis/R", "max_forks_repo_head_hexsha": "f13509fab53ff70f601a124f2965c2a4ff695bdc", "max_forks_repo_licenses": ["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.6699576869, "max_line_length": 274, "alphanum_fraction": 0.6193616624, "num_tokens": 6477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6004206478054515}} {"text": "#' Unesco 1983. Algorithms for computation of fundamental properties of seawater, 1983\n\npressure2Depth <- function (pressure, lat = 45) {\n lat <- lat * 0.0174532925199433\n x <- sin(lat)^2\n gr <- 9.780318 * (1 + (0.0052788 + 2.36e-05 * x) * x) + 1.092e-06 * pressure\n d <- (((-1.82e-15 * pressure + 2.279e-10) * pressure - 2.2512e-05) * \n pressure + 9.72659) * pressure/gr\n \n return(d)\n}\n", "meta": {"hexsha": "c33c0e6d04e4a2540ff78bef6f80a104b9f4f978", "size": 414, "ext": "r", "lang": "R", "max_stars_repo_path": "R/pressure2Depth.r", "max_stars_repo_name": "PEDsnowcrab/aegis", "max_stars_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/pressure2Depth.r", "max_issues_repo_name": "PEDsnowcrab/aegis", "max_issues_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/pressure2Depth.r", "max_forks_repo_name": "PEDsnowcrab/aegis", "max_forks_repo_head_hexsha": "92d4b045c17773c184df4ff3ed47c226ba4eddbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:58:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:58:58.000Z", "avg_line_length": 34.5, "max_line_length": 86, "alphanum_fraction": 0.5966183575, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6004206316897329}} {"text": "factIter <- function(n) {\n f = 1\n if (n > 1) {\n for (i in 2:n) f <- f * i\n }\n f\n}\n", "meta": {"hexsha": "ffd155da8da2dbc4a6669cb9fa0f27bcb79a0d69", "size": 89, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Factorial/R/factorial-2.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/Factorial/R/factorial-2.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Factorial/R/factorial-2.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": 11.125, "max_line_length": 29, "alphanum_fraction": 0.393258427, "num_tokens": 43, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6001973876689426}} {"text": "# This is the Script for 06_Lab Exercise 1\n# By Ryan McWay\n# Setting the directory\nsetwd(\"~/LiDAR-McWay/06_Class/LidarDataAnalysis\")\n# Importing the database\nlidarData <- read.csv(\"~/LiDAR-McWay/06_Class/LidarDataAnalysis/BA_lidarData.csv\")\n# View the database\nView(lidarData)\n# Name the variables from the database\nnames(lidarData)\n# Create the response variable as total Basel Area\nResponseV <- lidarData$BAtotal\n# Mean for the response variable\nmean(ResponseV)\n# Plot Hieght Mean against the response variable\nplot(lidarData$HMean, ResponseV, xlab = \"Mean Height\", ylab = \"Response Variable\")\n# Learn more about plot\n?plot\n# correlation between mean hieght to basal area\ncor(lidarData$HMean, lidarData$BAtotal)\n# plot 10th percentile to the response variable\nplot(lidarData$P10, ResponseV)\n# correlation between 10th percentile to basal area\ncor(lidarData$P10, lidarData$BAtotal)\n# plot 95th percentile to response variable\nplot(lidarData$P95, ResponseV)\n# correlation between 95th percentile to basal area\ncor(lidarData$P95, lidarData$BAtotal)\n# plot 1st cover mean to response variable\nplot(lidarData$all_1st_cover_mean, ResponseV)\n# correlation between 1st cover mean to basal area\ncor(lidarData$all_1st_cover_mean, lidarData$BAtotal)\n# plot 1st cover 3 to response variable\nplot(lidarData$all_1st_cover_3, ResponseV)\n# correlation between 1st cover 3 to basal area\ncor(lidarData$all_1st_cover_3, lidarData$BAtotal)\n# creates correlation matrix for database expect the first column \"Plots\", because \"That's Silly.\"\ncorrMat <- cor(lidarData[,-1])\n# Print out the correlation matrix so it can be read\nprint(corrMat)\n# range for Hieght max\nrange(lidarData$HMax)\n# 5 statistic summary for every variable in the database\nsummary(lidarData)\n# create histogram of basal area (frequency graph)\nhist(lidarData$BAtotal)\n# Learn more about histograms\n?hist\n# variance for basal area\nvar(lidarData$BAtotal)\n# standard deviation for basal area\nsd(lidarData$BAtotal)\n\n", "meta": {"hexsha": "7011671c405b9810d2a0481aa193b55d30202f31", "size": 1960, "ext": "r", "lang": "R", "max_stars_repo_path": "GIS_USF/Lidar/BaselArea1.r", "max_stars_repo_name": "mcwayrm/Stata-Econ-672--Econ-Dev", "max_stars_repo_head_hexsha": "069a59e8862e37db9e86ada2505e982dc616415b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GIS_USF/Lidar/BaselArea1.r", "max_issues_repo_name": "mcwayrm/Stata-Econ-672--Econ-Dev", "max_issues_repo_head_hexsha": "069a59e8862e37db9e86ada2505e982dc616415b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-06-12T08:11:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-12T08:11:28.000Z", "max_forks_repo_path": "GIS_USF/Lidar/BaselArea1.r", "max_forks_repo_name": "mcwayrm/Stata-Econ-672--Econ-Dev", "max_forks_repo_head_hexsha": "069a59e8862e37db9e86ada2505e982dc616415b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-01T14:43:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T08:33:03.000Z", "avg_line_length": 36.2962962963, "max_line_length": 98, "alphanum_fraction": 0.7989795918, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6001973793724366}} {"text": "# 4. faza: Analiza podatkov\n\n#napoved št. priseljencev v Slovenijo\n\nskupno_leta <- tabela1 %>% group_by(Leto) %>% summarise(Stevilo_priseljenih_iz_tujine=sum(Priseljeni_iz_tujine))\nskupno_leta$Vrsta <- \"Meritev\"\nmodel <- lm(Stevilo_priseljenih_iz_tujine~Leto, data=skupno_leta)\npr <- predict(model, data.frame(Leto=seq.int(2021, 2025, 1)))\nnapoved_preseljevanja <- data.frame(Leto = c(2021, 2022, 2023, 2024, 2025), Stevilo_priseljenih_iz_tujine = c(pr[1], pr[2], pr[3], pr[4], pr[5]))\nnapoved_preseljevanja$Vrsta <- \"Napoved\"\nskupna_tabela <- rbind(skupno_leta, napoved_preseljevanja)\n\ngraf_napoved <- ggplot(skupna_tabela, aes(x=Leto, y=Stevilo_priseljenih_iz_tujine, shape=Vrsta)) +\n geom_smooth(formula = y ~ x, method=lm, se=TRUE, fullrange = TRUE, color=\"#ff6d44\") +\n geom_point(data=skupno_leta, aes(x=Leto, y=Stevilo_priseljenih_iz_tujine), color=\"blue\", size=1) +\n labs(title=\"Napoved števila priseljenih ljudi v Slovenijo\", y=\"Število priseljenih\", x=\"Leto\") + geom_point(color=\"blue\")\n \n#napoved št. izseljencev iz Slovenije\n\nskupno_leta_iz <- tabela2 %>% group_by(Leto) %>% summarise(Stevilo_odseljenih_v_tujino=sum(Odseljeni_v_tujino))\nskupno_leta_iz$Vrsta <- \"Meritev\"\nmodel2 <- lm(Stevilo_odseljenih_v_tujino~Leto, data=skupno_leta_iz)\npr2 <- predict(model2, data.frame(Leto=seq.int(2020, 2025, 1)))\nnapoved_izseljevanja <- data.frame(Leto = c(2020, 2021, 2022, 2023, 2024, 2025), Stevilo_odseljenih_v_tujino = c(pr2[1], pr2[2], pr2[3], pr2[4], pr2[5], pr2[6]))\nnapoved_izseljevanja$Vrsta <- \"Napoved\"\nskupna_tabela2 <- rbind(skupno_leta_iz, napoved_izseljevanja)\n\ngraf_napoved2 <- ggplot(skupna_tabela2, aes(x=Leto, y=Stevilo_odseljenih_v_tujino, shape=Vrsta)) +\n geom_smooth(formula = y ~ x, method=lm, se=TRUE, fullrange = TRUE, color=\"#01c659\") +\n geom_point(data=skupno_leta_iz, aes(x=Leto, y=Stevilo_odseljenih_v_tujino), color=\"orange\", size=1) +\n labs(title=\"Napoved števila odseljenih iz Slovenije\", y=\"Število odseljenih\", x=\"Leto\") + geom_point(color=\"yellow\")\n\n\n#Razvrščanje v skupine na zemljevidu - Evropa\n#združevanje tabel\ntabela11skupno <- tabela11 %>% filter(between(Leto,2016,2019)) %>% group_by(Leto,Drzava) %>% summarise(\"Stevilo_priseljenih\"=sum(Stevilo))\n\ntabela12skupno <- tabela12 %>% filter(between(Leto,2016,2019)) %>% group_by(Leto,Drzava) %>% summarise(\"Stevilo_izseljenih\"=sum(Stevilo))\nt1 <- inner_join(tabela11skupno, tabela12skupno)\nt2 <- inner_join(t1, tabela15)\nevropa_master <- inner_join(t2, tabela10)\n\npovprecjeevropa <- evropa_master %>% group_by(Drzava) %>% \n summarise(emigracija = mean(Stevilo_izseljenih, na.rm = TRUE),\n imigracija = mean(Stevilo_priseljenih, na.rm = TRUE), \n populacija = mean(Prebivalstvo, na.rm = TRUE),\n GDP = mean(GDP_per_capita_dolarji, na.rm = TRUE)) %>%\n mutate(emigracija = emigracija / populacija, imigracija = imigracija / populacija) \n\n\n#clustering emigracija (izseljeni)\nskupineEmigracija <- kmeans(povprecjeevropa$emigracija, 4, nstart = 1500)\ncentersEmi <- sort(skupineEmigracija$centers)\nskupineEmigracija <- kmeans(povprecjeevropa$emigracija, centers = centersEmi, nstart = 1500)\n\n#zemljevid glede na skupine - izseljevanje\nzemljevidskupineemi <- tm_shape(merge(zemljevid, data.frame(Drzava = povprecjeevropa$Drzava, \n skupina = factor(skupineEmigracija$cluster)), \n by.x = \"SOVEREIGNT\", by.y = \"Drzava\"), xlim=c(-20,32), ylim=c(32,80)) + \n tmap_options(max.categories = 4) + \n tm_polygons(\"skupina\", title = \"Skupina\") + \n tm_layout(main.title = \"Države razdeljene glede na \\n povprečno emigracijo\", main.title.size = 1, legend.title.size = 1) +\n tm_legend(position = c(\"left\", \"bottom\"))\n\n#clustering imigracija (priseljeni)\nskupineImigracija <- kmeans(povprecjeevropa$imigracija, 4, nstart = 1500)\ncentersImi <- sort(skupineImigracija$centers)\nskupineImigracija <- kmeans(povprecjeevropa$imigracija, centers = centersImi, nstart = 1500) \n\n#clustering imigracija (priseljeni)\nzemljevidskupineimi <- tm_shape(merge(zemljevid, data.frame(Drzava = povprecjeevropa$Drzava, \n skupina = factor(skupineImigracija$cluster)), \n by.x = \"SOVEREIGNT\", by.y = \"Drzava\"), xlim=c(-20,32), ylim=c(32,80)) + \n tmap_options(max.categories = 4) + \n tm_polygons(\"skupina\", title = \"Skupina\") + \n tm_layout(main.title = \"Države razdeljene glede na \\n povprečno imigracijo\", main.title.size = 1, legend.title.size = 1) +\n tm_legend(position = c(\"left\", \"bottom\"))\n\n\n#Še eno razvrščanje: REGIJE_____________________\n#združimo tabele:\ntab14 <- tabela14 %>% group_by(Leto,Regija) %>% summarise(\"Stevilo_priseljenih\"=sum(Stevilo_priseljenih_iz_tujine))\ntab13 <- tabela13 %>% group_by(Leto,Regija) %>% summarise(\"Stevilo_odseljenih\"=sum(Stevilo_odseljenih_v_tujino))\nta1 <- inner_join(tab13,tab14)\nta2 <- inner_join(tabela16,tabela17)\nta3 <- inner_join(ta2,vsezares)\nmaster_regije <- inner_join(ta3,ta1)\n\npovprecjeregije <- master_regije %>% group_by(Regija) %>% \n summarise(emigracija = mean(Stevilo_odseljenih, na.rm = TRUE),\n imigracija = mean(Stevilo_priseljenih, na.rm = TRUE), \n populacija = mean(Prebivalstvo, na.rm = TRUE),\n BDP = mean(BDP_na_prebivalca, na.rm = TRUE),\n SS = mean(razSS, na.rm = TRUE),\n VS = mean(razVS, na.rm = TRUE)) %>%\n mutate(emigracija = emigracija / populacija, imigracija = imigracija / populacija) \n\n#clustering emigracija -regije\nskupineEmigracijaReg <- kmeans(povprecjeregije$emigracija, 4, nstart = 1500)\ncentersEmiReg <- sort(skupineEmigracijaReg$centers)\nskupineEmigracijaReg <- kmeans(povprecjeregije$emigracija, centers = centersEmiReg, nstart = 1500)\n\nzemljevid_reg_skup_emi <- tm_shape(merge(Slovenija, data.frame(Regija = povprecjeregije$Regija, \n skupina = factor(skupineEmigracijaReg$cluster)), \n by.x = \"NAME_1\", by.y = \"Regija\")) + \n tmap_options(max.categories = 4) + \n tm_polygons(\"skupina\", title = \"Skupina\") + \n tm_layout(main.title=\"Skupine glede na povprečno število izseljenih ljudi v regijah\", legend.position = c(0.75,0.1)) + \n tm_text(text='NAME_1', size=0.6)\n\n#clustering imigracija - regije\nskupineImigracijaReg <- kmeans(povprecjeregije$imigracija, 4, nstart = 1500)\ncentersImiReg <- sort(skupineImigracijaReg$centers)\nskupineImigracijaReg <- kmeans(povprecjeregije$imigracija, centers = centersImiReg, nstart = 1500)\n\nzemljevid_reg_skup_imi <- tm_shape(merge(Slovenija, data.frame(Regija = povprecjeregije$Regija, \n skupina = factor(skupineImigracijaReg$cluster)), \n by.x = \"NAME_1\", by.y = \"Regija\")) + \n tmap_options(max.categories = 4) + \n tm_polygons(\"skupina\", title = \"Skupina\") + \n tm_layout(main.title=\"Skupine glede na povprečno število priseljenih ljudi v regijah\", legend.position = c(0.75,0.1)) + \n tm_text(text='NAME_1', size=0.6)\n\n\n\n\n\n\n", "meta": {"hexsha": "d4d17d984b832de250399e7ee5a8941e05ed8ed1", "size": 7066, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "klarasirca/APPR-2020-21", "max_stars_repo_head_hexsha": "1f3e7b1b8015b238cad2da48bcd9cdf159e3b646", "max_stars_repo_licenses": ["MIT"], "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": "klarasirca/APPR-2020-21", "max_issues_repo_head_hexsha": "1f3e7b1b8015b238cad2da48bcd9cdf159e3b646", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-08-28T18:16:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:06:42.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "klarasirca/APPR-2020-21", "max_forks_repo_head_hexsha": "1f3e7b1b8015b238cad2da48bcd9cdf159e3b646", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.7751937984, "max_line_length": 161, "alphanum_fraction": 0.6981318992, "num_tokens": 2505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6000824886800196}}