{"text": "### Copyright (C) 2017 Rafael Laboissière\n###\n### This program is free software: you can redistribute it and/or modify it\n### under the terms of the GNU General Public License as published by the\n### Free Software Foundation, either version 3 of the License, or (at your\n### option) any later version.\n###\n### This program is distributed in the hope that it will be useful, but\n### WITHOUT ANY WARRANTY; without even the implied warranty of\n### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n### General Public License for more details.\n###\n### You should have received a copy of the GNU General Public License along\n### with this program. If not, see .\n\n### * Statistical analyses\n\n### ** Load the necessary libraries\nlibrary (lme4)\nlibrary (lmerTest)\nlibrary (HDInterval)\nlibrary (shape)\nlibrary (car)\n\n### ** Function for computing confidence intervals of predicted values\nci.pred <- function (fit.model, new.data = NA, pred.fun = NA, nb.sim = 1000) {\n if (! is.function (pred.fun))\n pred.fun <- function (fit.model)\n predict (fit.model, newdata = new.data, re.form = NA)\n n <- length (pred.fun (fit.model))\n b <- bootMer (fit.model, pred.fun, nsim = nb.sim)\n ci <- c ()\n for (i in seq (1, n))\n ci <- rbind (ci, hdi (b$t [, i]))\n return (list (ci = ci, t = b$t))\n}\n\n### ** Load the results\nobj.stab.psycho <- read.csv (\"obj-stab-psycho.csv\")\n\n### ** Transform the discrete factors chair and object into numeric\nobj.stab.psycho$object.num <- c (1, -1, 0) [as.numeric(obj.stab.psycho$object)]\nobj.stab.psycho$chair.num <- c (-1, 1, 0) [as.numeric (obj.stab.psycho$chair)]\nobj.stab.psycho$table.side.num <- (c (-0.5, 0, 0.5)\n [as.numeric (obj.stab.psycho$table.side)])\n\n### ** Boxplot parameters\nobj.col <- c (\"pink\", \"cyan\", \"wheat\")\nexp.col <- c (\"aquamarine\", \"coral\")\nside.col <- c (\"firebrick1\", \"deepskyblue\")\nboxplot.pars <- list (boxwex = 0.5, bty = \"n\")\nboxplot.ylab <- \"threshold angle (degrees)\"\n\n\n### ** Plot labels\n\n### *** Labels for the conditions\nchair.lab <- c (\"Left Tilt\", \"Upright\", \"Right Tilt\")\nbg.lab <- c (\"Static Surround\", \"Rotating Surround\")\nscene.lab <- c (\"Scene on the Left\", \"Scene on the Right\")\ntable.lab <- c (\"Table to the Left\", \"Table to the Right\")\ncom.lab <- c (\"Low COM\", \"Mid COM\", \"High COM\")\n\n### *** Labels for the axes\ndsvh.xlab <- expression (paste (Delta, \"TU (degrees)\"))\ndca.ylab = expression (paste (Delta, \"CA (degrees)\"))\nca.ylab <- \"Critical Angle (degrees)\"\nsvh.ylab <- \"Table Uprightness (degrees)\"\n\n### ** Experiments\n\n### *** Room 126\n\n### **** Select the data\nroom.126 <- subset (obj.stab.psycho, experiment == \"room-126\")\n\n### **** Drop subject S066 (it's Corinne Cian!))\nroom.126 <- subset (room.126, subject != \"S066\")\n\n### **** Linear mixed models\n\n## ***** Effect of chair inclination & object shape in static background\ndf.r126.chair.obj <- subset (room.126,\n stimulus == \"object\" & background == \"static\")\nfm.r126.chair.obj <- lmer (threshold ~ object.num * chair.num\n + (1 | subject), df.r126.chair.obj)\n\nanova (fm.r126.chair.obj)\nfixef (fm.r126.chair.obj)\nconfint (fm.r126.chair.obj)\n\npdf (file = \"room-126-chair-object.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ object.num * chair.num, df.r126.chair.obj,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n xaxt = \"n\", pars = boxplot.pars,\n col = rep (obj.col, 3), add = (i == 2))\n if (i == 1)\n polygon (c (3.5, 6.5, 6.5, 3.5), c (0, 0, 100, 100),\n col = \"#eeeeee\", border = NA)\n}\naxis (1, at = c (2, 5, 8), tick = FALSE, labels = chair.lab)\nlegend (\"topright\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = obj.col,\n legend = com.lab)\ndummy <- dev.off ()\n\n### ***** Effect of object shape and background in upright position\ndf.r126.bg.obj <- subset (room.126,\n stimulus == \"object\" & chair == \"upright\")\nfm.r126.bg.obj <- lmer (threshold ~ background * object.num\n + (1 | subject), df.r126.bg.obj)\nanova (fm.r126.bg.obj)\nfixef (fm.r126.bg.obj)\nconfint (fm.r126.bg.obj)\n\nfe.r126.bg.obj <- fixef (fm.r126.bg.obj)\nre.r126.bg.obj <- ranef (fm.r126.bg.obj)\n\npdf (file = \"room-126-background-object.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ object.num * background, df.r126.bg.obj, frame = FALSE,\n las = 1, xlab = \"\", ylab = boxplot.ylab, xaxt = \"n\",\n pars = boxplot.pars, col = rep (obj.col, 2), add = (i == 2))\n if (i == 1)\n polygon (c (3.5, 6.5, 6.5, 3.5), c (0, 0, 100, 100),\n col = \"#eeeeee\", border = NA)\n}\naxis (1, at = c (2, 5), tick = FALSE, labels = bg.lab)\nlegend (\"topright\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = obj.col,\n legend = com.lab)\ndummy <- dev.off ()\n\n### ***** Power analysis\n\n### ****** Home-made simulation\n### (Taken from the web somewhere. Look at https://goo.gl/zOUgFy)\nnsim <- 1000\np.value <- rep (NA, nsim)\nsim.r126.bg.obj <- simulate (fm.r126.bg.obj, nsim = nsim)\n\ncat (\"Computing power effect for Exp. 1 (surround effect)\\n\")\nflush.console ()\n\nfor (i in seq (1, nsim)) {\n df <- df.r126.bg.obj\n df$threshold <- sim.r126.bg.obj [, i]\n fm <- lmer (threshold ~ background * object.num + (1 | subject), df)\n p.value [i] <- anova (fm) [[\"Pr(>F)\"]] [1]\n cat (sprintf (\"\\r%4d\", i))\n flush.console ()\n}\n\ncat (sprintf (\"Power for surround effect is %f\\n\",\n (nsim - length (which (p.value > 0.05))) / nsim))\nflush.console ()\n\n### ****** Using SIMR package\nlibrary (simr)\npowerSim (fm.r126.bg.obj, test = fixed (\"background\"), nsim = 100)\n\n### ***** Effect of background in upright position on horizontal estimation\ndf.r126.bg.hor <- subset (room.126,\n stimulus == \"horizontal\" & chair == \"upright\")\nfm.r126.bg.hor <- lmer (threshold ~ background + (1 | subject), df.r126.bg.hor)\n\nanova (fm.r126.bg.hor)\nfixef (fm.r126.bg.hor)\nconfint (fm.r126.bg.hor)\n\nfe.r126.bg.hor <- fixef (fm.r126.bg.hor)\nre.r126.bg.hor <- ranef (fm.r126.bg.hor)\n\npdf (file = \"room-126-background-horizontal.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nboxplot (threshold ~ background, df.r126.bg.hor, frame = FALSE,\n las = 1, xlab = \"\", ylab = boxplot.ylab,\n xaxt = \"n\", pars = list (boxwex = 0.2, bty = \"n\"))\naxis (1, at = c (1, 2), tick = FALSE, labels = bg.lab)\ndummy <- dev.off ()\n\n### ***** Efect of inclination in static background on horizontal estimation\ndf.r126.chair.hor <- subset (room.126,\n stimulus == \"horizontal\" & background == \"static\")\ndf.r126.chair.hor$object <- factor (as.character (df.r126.chair.hor$object))\nfm.r126.chair.hor <- lmer (threshold ~ chair.num + (0 + chair.num | subject),\n df.r126.chair.hor)\n\nanova (fm.r126.chair.hor)\nfixef (fm.r126.chair.hor)\nconfint (fm.r126.chair.hor)\n\npdf (file = \"room-126-chair-horizontal.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nboxplot (threshold ~ chair.num, df.r126.chair.hor, frame = FALSE,\n las = 1, xlab = \"\", ylab = boxplot.ylab,\n xaxt = \"n\", pars = list (boxwex = 0.4, bty = \"n\"))\naxis (1, at = seq (1, 3), tick = FALSE, labels = chair.lab)\ndummy <- dev.off ()\n\n### **** Plot random effects for horizontality vs. object stability models\n\npdf (file = \"room-126-ranef-cor.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nplot (fe.r126.bg.hor [2] + re.r126.bg.hor$subject [, 1],\n fe.r126.bg.obj [2] + re.r126.bg.obj$subject [, 1],\n pch = 19, bty = \"n\", las = 1, xlim = c (0,7),\n xlab = dsvh.xlab, ylab = dca.ylab)\ndummy <- dev.off ()\n\npdf (file = \"room-126-ranef-cor-diag.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nplot (fe.r126.bg.hor [2] + re.r126.bg.hor$subject [, 1],\n fe.r126.bg.obj [2] + re.r126.bg.obj$subject [, 1],\n pch = 19, bty = \"n\", las = 1, xlim = c (0,7),\n xlab = dsvh.xlab, ylab = dca.ylab)\nabline (0, 1, lty = 2, col = \"gray\", lwd = 2)\ndummy <- dev.off ()\n\n### **** Select representative subjects\n\n### ***** Object stability experiment\n\n### Get the data frame for the room-126 (background/object) experiment\n### in condition \"static\"\ndf <- subset (df.r126.bg.obj, background == \"static\")\n### Compute the differences in threshold high-mid and mid-low\nag <- aggregate (threshold ~ subject, df,\n function (x) c(x[2] - x[3], x [3] - x [1]))\ndiff.t <- ag$threshold\n### Get the size of the effect\ndiff.ca <- -fixef (fm.r126.bg.obj) [3]\n### Find the subject\nidx <- which.min ((diff.t [, 1] - diff.ca) ^ 2 + (diff.t [, 2] - diff.ca) ^ 2)\ncat (sprintf (\"Representative subject is %s\\n\", ag$subject [idx]))\n\n### ***** Horizontality experiment\n\n### Get the data frame for the room-126 (background/horizontal) experiment\n### in condition \"vection\"\ndf <- subset (df.r126.bg.hor, background == \"vection\")\n### Get the indivual thresholds\nthres <- df$threshold\n### Get the size of the effect\nfe <- fixef (fm.r126.bg.hor) [2]\n### Find the subject\nidx <- which.min ((thres - fe) ^ 2)\ncat (sprintf (\"Representative subject is %s\\n\", df$subject [idx]))\n\n### *** New screen\n\n### **** Select the data\nnew.screen <- subset (obj.stab.psycho, experiment == \"new-screen\")\nnew.screen$subject <- factor (as.character (new.screen$subject))\n\n### **** Select the same subjects from room 126 experiment\nfor (s in levels (new.screen$subject)) {\n new.screen <- rbind (new.screen,\n subset (obj.stab.psycho, subject == s\n & experiment == \"room-126\"\n & stimulus == \"horizontal\"\n & chair == \"upright\"))\n}\nnew.screen$subject <- factor (as.character (new.screen$subject))\nnew.screen$experiment <- factor (as.character (new.screen$experiment),\n levels = c (\"room-126\", \"new-screen\"))\n\n\npdf (file = \"room-126-new-screen.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ experiment * background, new.screen, frame = FALSE,\n las = 1, xlab = \"\", ylab = boxplot.ylab, col = rep (exp.col, 2),\n xaxt = \"n\", pars = list (boxwex = 0.4, bty = \"n\"), add = (i == 2))\n if (i == 1)\n polygon (c (2.5, 4.5, 4.5, 2.5), c (-50, -50, 50, 50),\n col = \"#eeeeee\", border = NA)\n}\naxis (1, at = c (1.5, 3.5), tick = FALSE, labels = bg.lab)\nlegend (\"topleft\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = exp.col,\n legend = c (\"computer screen\", \"wall screen\"))\ndummy <- dev.off ()\n\n### **** Fit model\nfm <- lmer (threshold ~ experiment * background + (1 | subject), new.screen)\nshow (anova (fm))\nshow (fixef (fm))\nshow (ranef (fm))\n\n### **** Results Exp. 1 (Fig. 2)\n\n### ***** General plot paramaters\nobj.pch <- c (18, 16, 15) # diamond, circle, square\nobj.cex <- c (2.5, 2, 2) # diamond, circle, square\ngray.box <- \"#eeeeee\"\npdf.wd <- 4.5\npdf.ht <- 4.5\n\n### ***** Panel A\nnd <- expand.grid (object.num = c (-1, 0, 1),\n background = c (\"static\", \"vection\"))\npred <- predict (fm.r126.bg.obj, nd, re.form = NA)\nci <- ci.pred (fm.r126.bg.obj, nd)$ci\ny.min <- 26\ny.max <- 39\npdf (file = \"Fig-2-a.pdf\", width = pdf.wd, height = pdf.ht)\npar (mar = c (2, 4, 1, 1))\nplot (0, 0, xlim = c (0.5, 6.5), bty = \"n\", xaxt = \"n\", las = 1,\n ylim = c (y.min, y.max), xlab = \"\", ylab = ca.ylab, type = \"n\")\naxis (1, at = c (2, 5), tick = FALSE, labels = bg.lab)\npolygon (c (3.5, 6.5, 6.5, 3.5), c (-50, -50, y.max, y.max), col = gray.box,\n border = NA)\npoints (pred, pch = obj.pch, cex = obj.cex)\nfor (i in seq (1, 6))\n lines (rep (i, 2), ci [i, ], lwd = 3)\nlegend (\"bottomleft\", inset = c (0.05, 0.05), pch = obj.pch, bty = \"n\",\n pt.cex = 0.75 * obj.cex, legend = com.lab)\npar (xpd = NA)\ntext (-0.2, y.max, adj = c (0, 0), labels = \"a\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Panel C\nnd <- expand.grid (object.num = c (-1, 0, 1), chair.num = c (-1, 0, 1))\npred <- predict (fm.r126.chair.obj, nd, re.form = NA)\nci <- ci.pred (fm.r126.chair.obj, nd)$ci\npdf (file = \"Fig-2-c.pdf\", width = pdf.wd, height = pdf.ht)\npar (mar = c (2, 4, 1, 1))\nplot (0, 0, xlim = c (0.5, 9.5), bty = \"n\", xaxt = \"n\", las = 1, type = \"n\",\n ylim = c (y.min, y.max), xlab = \"\", ylab = ca.ylab)\naxis (1, at = c (2, 5, 8), tick = FALSE, labels = chair.lab)\npolygon (c (3.5, 6.5, 6.5, 3.5), c (-50, -50, y.max, y.max), col = gray.box,\n border = NA)\npoints (pred, pch = obj.pch, cex = obj.cex)\nfor (i in seq (1, 9))\n lines (rep (i, 2), ci [i, ], lwd = 3)\npar (xpd = NA)\ntext (-0.2, y.max, adj = c (0, 0), labels = \"c\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Panel B\nnd <- expand.grid (background = c (\"static\", \"vection\"))\npred <- predict (fm.r126.bg.hor, nd, re.form = NA)\nci <- ci.pred (fm.r126.bg.hor, nd)$ci\ny.min <- -5\ny.max <- 8\npdf (file = \"Fig-2-b.pdf\", width = pdf.wd, height = 0.8 * pdf.ht)\npar (mar = c (4.5, 4, 2.0, 1))\nplot (0, 0, xlim = c (0.5, 6.5), bty = \"n\", xaxt = \"n\", las = 1,\n ylim = c (y.min, y.max), xlab = \"\", ylab = svh.ylab, type = \"n\")\naxis (1, at = c (2, 5), tick = FALSE, labels = bg.lab)\npolygon (c (3.5, 6.5, 6.5, 3.5), c (-50, -50, 38, 38), col = gray.box,\n border = NA)\nfor (i in seq (1, 2))\n lines (rep ((i - 1) * 3 + 2, 2), ci [i, ], lwd = 3)\npoints (c (2, 5), pred, pch = 21, cex = 1.8, bg = \"white\")\npar (xpd = NA)\ntext (-0.2, y.max + 1.2, adj = c (0, -0.2), labels = \"b\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Panel D\nnd <- expand.grid (chair.num = c (-1, 0, 1))\npred <- predict (fm.r126.chair.hor, nd, re.form = NA)\nci <- ci.pred (fm.r126.chair.hor, nd)$ci\npdf (file = \"Fig-2-d.pdf\", width = pdf.wd, height = 0.8 * pdf.ht)\npar (mar = c (4.5, 5, 2.0, 1))\nplot (0, 0, xlim = c (0.5, 9.5), bty = \"n\", xaxt = \"n\", las = 1,\n ylim = c (y.min, y.max), xlab = \"\", ylab = svh.ylab, type = \"n\")\naxis (1, at = c (2, 5, 8), tick = FALSE, labels = chair.lab)\npolygon (c (3.5, 6.5, 6.5, 3.5), c (-50, -50, 38, 38), col = gray.box,\n border = NA)\nfor (i in seq (1, 3))\n lines (rep ((i - 1) * 3 + 2, 2), ci [i, ], lwd = 3)\npoints (c (2, 5, 8), pred, pch = 21, cex = 1.8, bg = \"white\")\npar (xpd = NA)\ntext (-0.2, y.max + 1.2, adj = c (0, -0.2), labels = \"d\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Compose Figure\nsystem (paste (\"pdfjam Fig-2-a.pdf Fig-2-c.pdf Fig-2-b.pdf Fig-2-d.pdf\",\n \"--no-landscape --frame true --nup 2x2 --frame false\",\n \"--outfile tmp.pdf\"))\nsystem (\"pdfcrop --margins 10 tmp.pdf Fig-2.pdf\")\n\n### **** Correlation figure (Fig. 3)\ndf.hor <- subset(room.126, stimulus == \"horizontal\" & chair == \"upright\")\ndelta.hor <- aggregate (threshold ~ subject, df.hor, diff)\ndf.ca <- subset(room.126, stimulus == \"object\" & chair == \"upright\")\ndelta.ca <- aggregate (threshold ~ subject,\n aggregate (threshold ~ subject * background, df.ca, mean),\n diff)\npdf (file = \"Fig-3.pdf\", width = pdf.wd, height = pdf.ht)\npar (mar = c (5, 4, 0, 0))\nplot (delta.hor$threshold, delta.ca$threshold, bty = \"n\", las = 1, pch = 19,\n xlab = dsvh.xlab, ylab = dca.ylab, type = \"n\")\nabline (0, 1, col = \"gray\", lwd = 2)\npoints (delta.hor$threshold, delta.ca$threshold, pch = 19)\npoints (mean (delta.hor$threshold), mean (delta.ca$threshold), pch = 18,\n col = \"#ff000080\", cex = 3)\ndummy <- dev.off ()\n\n\n### *** Scene mirror\n\n### **** Select the data\ndf.scene.mirror <- subset (obj.stab.psycho, experiment == \"scene-mirror\")\ndf.scene.mirror$subject <- factor (as.character (df.scene.mirror$subject))\n\n### **** Effect of object CG height and secene side\n\n### ***** Extract the data\ndf.scene.mirror.obj <- subset (df.scene.mirror, stimulus == \"object\")\n\n### ***** Plot the raw results\npdf (file = \"scene-mirror-object.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ object.num * object.side, df.scene.mirror.obj,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n xaxt = \"n\", pars = boxplot.pars,\n col = rep (obj.col, 2), add = (i == 2))\n if (i == 1)\n polygon (c (3.5, 6.5, 6.5, 3.5), c (0, 0, 100, 100),\n col = gray.box, border = NA)\n}\naxis (1, at = c (2, 5), tick = FALSE, labels = scene.lab)\nlegend (\"topright\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = obj.col,\n legend = com.lab)\ndummy <- dev.off ()\n\n### ***** Fit the model\nfm.scene.mirror.obj <- lmer (threshold ~ object.num * table.side.num\n + (1 | subject)\n + (0 + table.side.num | subject),\n df.scene.mirror.obj)\nshow (anova (fm.scene.mirror.obj))\nshow (fixef (fm.scene.mirror.obj))\nshow (ranef (fm.scene.mirror.obj))\n\nfm.no.Intercept <- lmer (threshold ~ object.num * table.side.num\n + (0 + table.side.num | subject),\n df.scene.mirror.obj)\nfm.no.table.side.num <- lmer (threshold ~ object.num * table.side.num\n + (1 | subject),\n df.scene.mirror.obj)\nshow (anova (fm.no.Intercept, fm.scene.mirror.obj))\nshow (anova (fm.no.table.side.num, fm.scene.mirror.obj))\n\n### ***** Plot the results\nnd <- expand.grid (object.num = c (-1, 0, 1), table.side.num = c (-0.5, 0.5))\npred <- predict (fm.scene.mirror.obj, nd, re.form = NA)\nci <- ci.pred (fm.scene.mirror.obj, nd)$ci\ny.min <- min (ci [, 1])\ny.max <- max (ci [, 2])\npdf (file = \"Fig-5-a.pdf\", width = pdf.wd, height = pdf.ht)\npar (mar = c (4.5, 5, 2.0, 0))\nplot (0, 0, type = \"n\", xlim = c (0.5, 6.5), bty = \"n\", xaxt = \"n\", las = 1,\n ylim = c (y.min, y.max), xlab = \"\", ylab = ca.ylab)\naxis (1, at = c (2, 5), tick = FALSE, labels = scene.lab)\npolygon (c (3.5, 6.5, 6.5, 3.5), c (-50, -50, 42, 42), col = gray.box,\n border = NA)\nfor (i in seq (1, 6))\n lines (rep (i, 2), ci [i, ], lwd = 3)\npoints (pred, pch = obj.pch, cex = obj.cex)\nlegend (\"bottomleft\", inset = 0.05, pch = obj.pch, pt.cex = 0.75 * obj.cex,\n bty = \"n\", legend = com.lab)\npar (xpd = NA)\ntext (-0.2, y.max + 0.8, adj = c (0, -0.2), labels = \"a\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Plot the BLUP\nre <- ranef (fm.scene.mirror.obj)$subject\nn <- nrow (re)\nfe <- fixef (fm.scene.mirror.obj)\n\npdf (file = \"Fig-5-b.pdf\", width = pdf.wd, height = pdf.ht)\npar (mar = c (5, 5.5, 2, 0.1))\nx <- re [,1] + fe [1]\ny <- - (re [,2] + fe [3])\nshow (max (y))\ny.min <- min (y)\ny.max <- 18\nplot (x, y, pch = 19, cex = 1.5, las = 1, xlim = c (20, 40), col = \"#00000080\",\n bty = \"n\", xlab = \"Mean Critical Angle (degrees)\",\n ylab = \"Left/Right Side Effect (degrees)\")\nabline (h = -fe [3], col = \"#00000080\", lwd = 2, lty = \"21\")\nabline (v = fe [1], col = \"#00000080\", lwd = 2, lty = \"21\")\npar (xpd = NA)\ntext (20, 14.5, adj = c (1, 0), labels = \"b\", cex = 2)\ndummy <- dev.off ()\n\n### ***** Compose the Fig. 5\nsystem (paste (\"pdfjam Fig-5-a.pdf Fig-5-b.pdf\",\n \"--no-landscape --frame true --nup 2x1 --frame false\",\n \"--outfile tmp.pdf\"))\nsystem (\"pdfcrop --margins 10 tmp.pdf Fig-5.pdf\")\n\n### **** Check age effect on the random factors\n\n### ****** Plot the ranef with age as size of points\nsubjects <- read.csv (\"cohort-info.csv\")\nage <- sapply (row.names (re),\n function (x)\n subjects$age [which (x == as.character (subjects$subject))])\npdf (file = \"scene-mirror-ranef-age.pdf\")\npar (xpd = NA)\nplot (fe [1] + re [, 1], -(fe [3] + re [, 2]), bty = \"n\",\n las = 1, col = \"#00000080\", pch = 19,\n cex = 1 + 5 * (age - min (age)) / (max (age) - min (age)),\n xlab = \"individual intercept effect (degrees)\",\n ylab = \"individual table-sode effect (degrees)\")\nlegend.years <- c (20, 30)\nlegend.cex <- 1 + 5 * (legend.years - min (age)) / (max (age) - min (age))\nlegend (\"topleft\", inset = 0.2, pt.cex = legend.cex, pch = 1, cex = 1.8,\n legend = sapply (legend.years, function (x) sprintf (\"%.0f years\", x)),\n text.col = \"#bbbbbb\")\nArrows (19, 0, 19, -5, lwd = 2, col = \"red\")\ntext (19.5, -2.5, label = \"- gravity\", adj = c (0.5, 1), srt = 90, col = \"red\",\n cex = 1.2)\nArrows (19, 8, 19, 13, lwd = 2, col = \"red\")\ntext (19.5, 10.5, label = \"+ gravity\", adj = c (0.5, 1), srt = 90, col = \"red\",\n cex = 1.2)\nArrows (24, 15, 20, 15, lwd = 2, col = \"red\")\ntext (22, 15.5, label = \"cautious\", adj = c (0.5, 0), col = \"red\", cex = 1.2)\nArrows (32, 15, 36, 15, lwd = 2, col = \"red\")\ntext (34, 15.5, label = \"risky\", adj = c (0.5, 0), col = \"red\", cex = 1.2)\ndummy <- dev.off ()\n\n### ****** Pilai statistical test\nfm.scene.mirror.age <- lm (cbind (fe [1] + re [, 1], -(fe [3] + re [, 2])) ~ age)\nManova (fm.scene.mirror.age)\n\n### **** Effect of background on horizontal detection\ndf.scene.mirror.hor <- subset (df.scene.mirror, stimulus == \"horizontal\")\nidx <- which (df.scene.mirror.hor$table.side == \"right\")\ndf.scene.mirror.hor$threshold [idx] <- -df.scene.mirror.hor$threshold [idx]\n\npdf (file = \"scene-mirror-horizontal.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ table.side * background, df.scene.mirror.hor,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n col = rep (side.col, 2), xaxt = \"n\",\n pars = list (boxwex = 0.4, bty = \"n\"), add = (i == 2))\n if (i == 1)\n polygon (c (2.5, 4.5, 4.5, 2.5), c (-50, -50, 50, 50),\n col = gray.box, border = NA)\n}\naxis (1, at = c (1.5, 3.5), tick = FALSE, labels = bg.lab)\nlegend (\"topleft\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = side.col,\n legend = table.lab)\ndummy <- dev.off ()\n\nfm.scene.mirror.hor <- lmer (threshold ~ table.side.num * background\n + (1 | subject),\n df.scene.mirror.hor)\nshow (anova (fm.scene.mirror.hor))\nshow (fixef (fm.scene.mirror.hor))\nshow (ranef (fm.scene.mirror.hor))\n\n### *** Flip table\n\n### **** Select the data\nflip.table <- subset (obj.stab.psycho, experiment == \"flip-table\")\nflip.table$subject <- factor (as.character (flip.table$subject))\n\n### **** Effect of scene side and background on object stability\nflip.table.obj <- subset (flip.table, stimulus == \"object\")\n\npdf (file = \"flip-table-object.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ table.side * background, flip.table.obj,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n col = rep (side.col, 2), xaxt = \"n\",\n pars = list (boxwex = 0.4, bty = \"n\"), add = (i == 2))\n if (i == 1)\n polygon (c (2.5, 4.5, 4.5, 2.5), c (-50, -50, 50, 50),\n col = gray.box, border = NA)\n}\naxis (1, at = c (1.5, 3.5), tick = FALSE, labels = bg.lab)\nlegend (\"bottomleft\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = side.col,\n legend = c (\"table to the left\", \"table to the right\"))\ndummy <- dev.off ()\n\nfm <- lmer (threshold ~ background * table.side + (1 | subject),\n flip.table.obj)\nshow (anova (fm))\nshow (fixef (fm))\nshow (ranef (fm))\n\n### **** Effect of scene side and background on horizontal detection\nflip.table.hor <- subset (flip.table, stimulus == \"horizontal\")\nidx <- which (flip.table.hor$table.side == \"right\")\nflip.table.hor$threshold [idx] <- -flip.table.hor$threshold [idx]\n\npdf (file = \"flip-table-horizontal.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ background * table.side, flip.table.hor,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n col = rep (side.col, 2), xaxt = \"n\",\n pars = list (boxwex = 0.4, bty = \"n\"), add = (i == 2))\n if (i == 1)\n polygon (c (2.5, 4.5, 4.5, 2.5), c (-50, -50, 50, 50),\n col = gray.box, border = NA)\n}\naxis (1, at = c (1.5, 3.5), tick = FALSE,\n labels = c (\"table to the left\", \"table to the right\"))\nlegend (\"topleft\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = side.col,\n legend = bg.lab)\ndummy <- dev.off ()\n\nfm <- t.test (threshold ~ background, paired = TRUE,\n data = subset (flip.table.hor, table.side == \"left\"))\nshow (fm)\n\nfm <- t.test (threshold ~ background, paired = TRUE,\n data = subset (flip.table.hor, table.side == \"right\"))\nshow (fm)\n\n### *** No table\n\n### **** Select the data\ndf.no.table <- subset (obj.stab.psycho, experiment == \"no-table\")\n\n### **** Plot the raw results\npdf (file = \"no-table-object.pdf\")\npar (mar = c (4, 5, 0.5, 0))\nfor (i in c (1, 2)) {\n boxplot (threshold ~ object.num * background * table.side, df.no.table,\n frame = FALSE, las = 1, xlab = \"\", ylab = boxplot.ylab,\n xaxt = \"n\", pars = boxplot.pars,\n col = rep (obj.col, 2), add = (i == 2))\n if (i == 1)\n polygon (c (3.5, 6.5, 6.5, 3.5), c (0, 0, 100, 100),\n col = gray.box, border = NA)\n}\naxis (1, at = c (2, 5), tick = FALSE, labels = bg.lab)\nlegend (\"topright\", inset = 0.05, pch = 22, pt.cex = 2, pt.bg = obj.col,\n legend = com.lab)\ndummy <- dev.off ()\n\nfm.no.table <- lmer (threshold ~ background * object.num * table.side\n + (1 | subject),\n df.no.table)\nshow (anova (fm.no.table))\nshow (fixef (fm.no.table))\nshow (ranef (fm.no.table))\nshow (confint (fm.no.table))\n\nfe <- fixef (fm.no.table)\n\n### **** Rudimentary plot of results\npdf (file = \"no-table-object.pdf\", width = 4, height = 5)\npar (mar = c (4, 5, 0.5, 0))\nplot (c (1, 1, 2, 2),\n c (fe[1], fe [1] + fe [2], fe [1] + fe [4],\n fe [1] + fe [2] + fe [4] + fe [6]),\n pch = 19, col = rep (c (\"blue\", \"red\"), 2), bty = \"n\",\n xlim = c (0.7, 2.3), cex = 1.3,\n las = 1, xaxt = \"n\", xlab = \"\", ylab = ca.ylab)\nlines (c (1, 2), c (fe[1], fe [1] + fe [4]), col = \"blue\")\nlines (c (1, 2), c (fe [1] + fe [2], fe [1] + fe [2] + fe [4] + fe [6]),\n col = \"red\")\naxis (1, at = c (1, 2), labels = c (\"table\", \"no table\"))\nlegend (\"right\", col = c (\"red\", \"blue\"), legend = c (\"rotating\", \"static\"),\n pch = 19)\ndummy <- dev.off ()\n\n### ***** Plot the results\nnd <- expand.grid (object.num = c (-1, 0, 1),\n background = c (\"static\", \"vection\"),\n table.side = c (\"left\", \"none\"))\npred <- predict (fm.no.table, nd, re.form = NA)\nci <- ci.pred (fm.no.table, nd)$ci\ny.min <- min (ci [, 1])\ny.max <- max (ci [, 2])\npdf (file = \"Fig-6.pdf\", width = 7, height = 5)\npar (mar = c (4.5, 5, 4.5, 0), xpd = FALSE)\nplot (0, 0, type = \"n\", xlim = c (0.5, 12.5), bty = \"n\", xaxt = \"n\", las = 1,\n ylim = c (y.min, y.max), xlab = \"\", ylab = ca.ylab)\ngroup.axis <- function (pos, at, lab) {\n axis (pos, at = at, labels = rep (\"\", 2), line = 1)\n axis (pos, at = mean (at), tick = FALSE, line = 0.5, labels = lab)\n}\nfor (i in c (1, 2)) {\n polygon (6 * (i - 1) + c (3.5, 6.5, 6.5, 3.5),\n c (0, 0, 100, 100), col = gray.box, border = NA)\n group.axis (3, at = 6 * (i - 1) + c (1, 3), \"Static\")\n group.axis (3, at = 6 * (i - 1) + c (4, 6), \"Rotating\")\n}\ngroup.axis (1, c (1, 6), \"With Table\")\ngroup.axis (1, c (7, 12), \"Without Table\")\nfor (i in seq (1, 12))\n lines (rep (i, 2), ci [i, ], lwd = 3)\npoints (pred, pch = obj.pch, cex = obj.cex)\nlegend (\"topleft\", inset = c (0.05, 0), pch = obj.pch, pt.cex = 0.75 * obj.cex,\n bty = \"n\", legend = com.lab)\ndummy <- dev.off ()\n\n### ** Verify age effects for background effect in Exp. 1 and Exp. 3\n\ndf.age <- subset (obj.stab.psycho,\n experiment %in% c (\"room-126\", \"no-table\")\n & table.side == \"left\" & chair == \"upright\"\n & subject != \"S066\" & stimulus == \"object\")\nfm.age <- lmer (threshold ~ background * object + (background | subject),\n df.age)\nre <- ranef (fm.age)$subject\nage <- sapply (row.names (re),\n function (x)\n subjects$age [which (x == as.character (subjects$subject))])\ncor.test (re [, 1], age)\ncor.test (re [, 2], age)\n", "meta": {"hexsha": "fb9b574bf64021fdf9f9385398fa2fe15024b8f1", "size": 27957, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/statistical-analysis.r", "max_stars_repo_name": "rlaboiss/vextab-data", "max_stars_repo_head_hexsha": "229686bd7dba7b25641bd3e1df57b44e50d61b0f", "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": "analysis/statistical-analysis.r", "max_issues_repo_name": "rlaboiss/vextab-data", "max_issues_repo_head_hexsha": "229686bd7dba7b25641bd3e1df57b44e50d61b0f", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/statistical-analysis.r", "max_forks_repo_name": "rlaboiss/vextab-data", "max_forks_repo_head_hexsha": "229686bd7dba7b25641bd3e1df57b44e50d61b0f", "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": 39.0460893855, "max_line_length": 81, "alphanum_fraction": 0.5492720964, "num_tokens": 9597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.44992933035600075}}
{"text": "subroutine rqfnb(n,p,a,y,rhs,d,u,beta,eps,wn,wp,nit,info)\ninteger n,p,info,nit(3)\ndouble precision a(p,n),y(n),rhs(p),d(n),u(n),wn(n,9),wp(p,p+3)\ndouble precision one,beta,eps\nparameter( one = 1.0d0)\ncall lpfnb(n,p,a,y,rhs,d,u,beta,eps,wn(1,1),wn(1,2),\n wp(1,1),wn(1,3),wn(1,4),wn(1,5),wn(1,6),\n wp(1,2),wn(1,7),wn(1,8),wn(1,9),wp(1,3),wp(1,4),nit,info)\nreturn\nend\n# This is a revised form of my primal-dual log barrier form of the\n# interior point LP solver based on Lustig, Marsten and Shanno ORSA J Opt 1992.\n# It is a projected Newton primal-dual logarithmic barrier method which uses\n# the predictor-corrector approach of Mehrotra for the mu steps.\n# For the sake of brevity we will call it a Frisch-Newton algorithm.\n# Problem:\n# \tmin c'x s.t. Ax=b, 0<=x<=u\n# \n# Denote dx,dy,dw,ds,dz as the steps for the respective variables x,y,w,s,z\n# \nsubroutine lpfnb(n,p,a,c,b,d,u,beta,eps,x,s,y,z,w,\n\tdx,ds,dy,dz,dw,dr,rhs,ada,nit,info)\n\ninteger n,p,pp,i,info,nit(3),maxit\ndouble precision a(p,n),c(n),b(p)\ndouble precision zero,one,mone,big,ddot,dmax1,dmin1,dxdz,dsdw\ndouble precision deltap,deltad,beta,eps,mu,gap,g\ndouble precision x(n),u(n),s(n),y(p),z(n),w(n),d(n),rhs(p),ada(p,p)\ndouble precision dx(n),ds(n),dy(p),dz(n),dw(n),dr(n)\n\nparameter( zero = 0.0d0)\nparameter( one = 1.0d0)\nparameter( mone = -1.0d0)\nparameter( big = 1.0d+20)\nparameter( maxit = 500)\n\n# Initialization: We follow the notation of LMS\n# On input we require:\n# \n# \tc = n-vector of marginal costs (-y in the rq problem)\n# \ta = p by n matrix of linear constraints (x' in rq)\n# \tb = p-vector of rhs ((1-tau)x'e in rq)\n# u = upper bound vector ( e in rq)\n# \tbeta = barrier parameter, LMS recommend .99995\n# \teps = convergence tolerance, LMS recommend 10d-8\n# \t\n# \tthe integer vector nit returns iteration counts\n# \tthe integer info contains an error code from the Cholesky in stepy\n# \t\tinfo = 0 is fine\n# \t\tinfo < 0 invalid argument to dposv \n# \t\tinfo > 0 singular matrix\nnit(1)=0\nnit(2)=0\nnit(3)=n\npp=p*p\n# Start at the OLS estimate for the dual vector y\ncall dgemv('N',p,n,one,a,p,c,1,zero,y,1)\ndo i=1,n\n\td(i)=one\ncall stepy(n,p,a,d,y,ada,info)\nif(info != 0) return\n# put current residual vector in s (temporarily)\ncall dcopy(n,c,1,s,1)\ncall dgemv('T',p,n,mone,a,p,y,1,one,s,1)\n# Initialize remaining variables\ndo i=1,n{\n\tif(dabs(s(i)) eps && nit(1) A'dy - ds\n\tdeltap=big\n\tdeltad=big\n\tdo i=1,n{\n\t\tdx(i)=d(i)*ds(i)\n\t\tds(i)=-dx(i)\n\t\tdz(i)=-z(i)*(dx(i)/x(i) + one)\n\t\tdw(i)=-w(i)*(ds(i)/s(i) + one)\n\t\tif(dx(i)<0)deltap=dmin1(deltap,-x(i)/dx(i))\n\t\tif(ds(i)<0)deltap=dmin1(deltap,-s(i)/ds(i))\n\t\tif(dz(i)<0)deltad=dmin1(deltad,-z(i)/dz(i))\n\t\tif(dw(i)<0)deltad=dmin1(deltad,-w(i)/dw(i))\n\t\t}\n\tdeltap=dmin1(beta*deltap,one)\n\tdeltad=dmin1(beta*deltad,one)\n\tif(min(deltap,deltad) < one){\n\t\tnit(2)=nit(2)+1\n\t\t# Update mu\n\t\tmu = ddot(n,x,1,z,1)+ddot(n,s,1,w,1)\n\t\tg = mu + deltap*ddot(n,dx,1,z,1)+\n\t\t\tdeltad*ddot(n,dz,1,x,1) +\n\t\t\tdeltap*deltad*ddot(n,dz,1,dx,1)+\n\t\t\tdeltap*ddot(n,ds,1,w,1)+\n\t\t\tdeltad*ddot(n,dw,1,s,1) +\n\t\t\tdeltap*deltad*ddot(n,ds,1,dw,1)\n\t\tmu = mu * ((g/mu)**3) /dfloat(2*n)\n\t\t# Compute modified step\n\t\tdo i=1,n{\n\t\t\tdr(i)=d(i)*(mu*(1/s(i)-1/x(i))+\n\t\t\t\tdx(i)*dz(i)/x(i)-ds(i)*dw(i)/s(i))\n\t\t\t}\n\t\tcall dswap(p,rhs,1,dy,1)\n\t\tcall dgemv('N',p,n,one,a,p,dr,1,one,dy,1)# new rhs\n\t\tcall dpotrs('U',p,1,ada,p,dy,p,info)# backsolve for dy\n\t\tcall dgemv('T',p,n,one,a,p,dy,1,zero,u,1)#ds=A'ddy\n\t\tdeltap=big\n\t\tdeltad=big\n\t\tdo i=1,n{\n\t\t\tdxdz = dx(i)*dz(i)\n\t\t\tdsdw = ds(i)*dw(i)\n\t\t\tdx(i)= d(i)*(u(i)-z(i)+w(i))-dr(i)\n\t\t\tds(i)= -dx(i)\n\t\t\tdz(i)= -z(i)+(mu - z(i)*dx(i) - dxdz)/x(i)\n\t\t\tdw(i)= -w(i)+(mu - w(i)*ds(i) - dsdw)/s(i)\n\t\t\tif(dx(i)<0)deltap=dmin1(deltap,-x(i)/dx(i))\n\t\t\tif(ds(i)<0)deltap=dmin1(deltap,-s(i)/ds(i))\n\t\t\tif(dz(i)<0)deltad=dmin1(deltad,-z(i)/dz(i))\n\t\t\tif(dw(i)<0)deltad=dmin1(deltad,-w(i)/dw(i))\n\t\t\t}\n\t\tdeltap=dmin1(beta*deltap,one)\n\t\tdeltad=dmin1(beta*deltad,one)\n\t\t}\n\tcall daxpy(n,deltap,dx,1,x,1)\n\tcall daxpy(n,deltap,ds,1,s,1)\n\tcall daxpy(p,deltad,dy,1,y,1)\n\tcall daxpy(n,deltad,dz,1,z,1)\n\tcall daxpy(n,deltad,dw,1,w,1)\n\tgap = ddot(n,z,1,x,1)+ddot(n,w,1,s,1)\n\t}\n# return residuals in the vector x\ncall daxpy(n,mone,w,1,z,1)\ncall dswap(n,z,1,x,1)\nreturn\nend\nsubroutine stepy(n,p,a,d,b,ada,info)\ninteger n,p,pp,i,info\ndouble precision a(p,n),b(p),d(n),ada(p,p),zero\nparameter( zero = 0.0d0)\n# Solve the linear system ada'x=b by Choleski -- d is diagonal\n# Note that a isn't altered, and on output ada returns the upper\n# triangle Choleski factor, which can be reused, eg with blas dtrtrs\npp=p*p\ndo j=1,p\n\tdo k=1,p\n\t\tada(j,k)=zero\ndo i=1,n\n\tcall dsyr('U',p,d(i),a(1,i),1,ada,p)\ncall dposv('U',p,1,ada,p,b,p,info)\nreturn\nend\n", "meta": {"hexsha": "7a40a45ad765e10dbec55a652b12e08b4948b931", "size": 5216, "ext": "r", "lang": "R", "max_stars_repo_path": "fortran/ratfor/rqfnb.r", "max_stars_repo_name": "mhoward2718/quantreg", "max_stars_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-02T22:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T22:15:54.000Z", "max_issues_repo_path": "fortran/ratfor/rqfnb.r", "max_issues_repo_name": "mhoward2718/quantreg", "max_issues_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fortran/ratfor/rqfnb.r", "max_forks_repo_name": "mhoward2718/quantreg", "max_forks_repo_head_hexsha": "48478aee30b3dcbd6204c287f99cb287f005d6c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5029239766, "max_line_length": 79, "alphanum_fraction": 0.6246165644, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.449386622407476}}
{"text": "# ......................................................................................\n# ........................Cvičení 3 - Diskrétní 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# Příklady ####\n# * Příklad 1. ####\n# Majitel servisního střediska nabídl prodejně automobilů, která si zřídila autopůjčovnu\n# své\n# služby. Za každý automobil zapůjčený jeho prostřednictvím obdrží od autopůjčovny 500,-\n# Kč.\n# Zároveň se však zavázal, že každý den investuje do údržby zapůjčených automobilů 800,-\n# Kč.\n# Počet automobilů zapůjčených prostřednictvím servisního střediska za 1 den je popsán\n# následující pravděpodobnostní funkcí:\n# Obrázek viz sbírka úloh.\n# ** 1. a) ####\n# Hodnota pravděpodobnostní funkce pro 5 automobilů byla špatně čitelná. Určete ji:\n\n\nx = c(0,1,2,3,4,5,6)\np = c(0.01,0.40,0.25,0.15,0.10,0,0.03)\n1 - sum(p) # počítačová aritmetika zde může zlobit\nround(1 - sum(p), digits=2) # zaokrouhlíme na setiny\np[6] = round(1 - sum(p), digits=2) # zápis pro x=5 je 6-tá pozice\np\n\nplot(x, p)\n\nplot(x, p, type=\"h\")\n\n# Začínáme s grafikou -> graf dále upravujeme - používáme další parametry\nplot(x, p, \n ylim=c(0,0.5), # parametr pro rozsah osy y\n ylab=\"p(x)\", # parametr pro popis osy y\n main=\"Pravděpodobnostní funkce\", # parametr pro název grafu\n type=\"p\", # určuje o jaký typ grafu se jedná (p -> points, bodový)\n pch=19, # parametr pro vzhled zobrazovaných bodů\n col=c(\"blue\",\"red\",\"green\"), # barvy\n cex=2, # parametr pro upravení velikosti celého grafu (ve smyslu zvětší 2x)\n cex.lab=1.3, # parametr zvlášť pro velikost názvů os\n cex.axis=1.3, # parametr zvlášť pro velikost hodnot na osách\n cex.main=1.3) # parametr pro velikost názvu grafu\n\ntext(0.5,0.0,\"X ... počet zapůjčených automobilů\", cex=1.3, col=\"blue\", adj=c(0,0))\n\n# Pravděpodobnostní funkce\npravd.f = function(x,p){\n plot(x, p, # plná kolečka - v skutečných hodnotách\n ylab='p(x)',xaxt='n',pch=19,ylim=c(0,max(p)),main=\"Pravdepodobnostni funkce\") \n lines(c(min(x)-100,max(x)+100),c(0, 0))\n for(i in 1:length(x)){\n lines(c(min(x)-100,max(x)+100), c(p[i],p[i]),\n type = 'l', lty = 3, lwd=0.5) # horizontální grid\n lines(c(x[i],x[i]), c(-0.1,1.1), \n type = 'l', lty = 3, lwd=0.5) # vertikální grid\n }\n par(new=TRUE) # že chceme kreslit do jednoho grafu\n plot(x, p*0, # prázdná kolečka - tam kde je definovaná nenulová hodnota\n ylab='p(x)', xaxt='n', ylim=c(0,max(p)))\n axis(1, at=x,labels=x) # nastavení hodnot na X\n axis(4, at=p,labels=p, las=2, cex.axis=0.7, tck=-.01) # a Y\n}\n\npravd.f(x, p)\n\n# Poznámky k úvodu do grafiky \n# základem jsou tzv. high-level funkce, které vytvoří graf (tj. otevřou grafické okno a\n# vykreslí dle zadaných parametrů)\n# na ně navazují tzv. low-level funkce, které něco do aktviního grafického okna\n# přidají, samy o sobě neotevřou nové\n# výše použitá funkce \"text\" je low-level funkce - přidá text do stávajícího aktivního\n# grafického okna\n# další low-level funkce - např. abline, points, lines, legend, title, axis ... které\n# přidají přímku, body, legendu...\n# tzn. před použitím \"low-level\" funkce je potřeba, volat \"high-level\" funkci (např.\n# plot, boxplot, hist, barplot, pie,...)\n# \n# další grafické parametry naleznete v nápovědě\n# nebo např. zde http://www.statmethods.net/advgraphs/parameters.html\n# nebo zde https://flowingdata.com/2015/03/17/r-cheat-sheet-for-graphical-parameters/\n# nebo http://bcb.dfci.harvard.edu/~aedin/courses/BiocDec2011/2.Plotting.pdf\n\n\n# ** 1. b) ####\n# Určete a zakreslete distribuční funkci náhodné veličiny X, která je definována jako\n# počet\n# zapůjčených automobilů.\n\n\np\nF = cumsum(p)\nF\n\nplot(x, F, type=\"s\") # zjednodušený graf distribuční funkce\n\n# Funkce pro výpočet a vykreslení distribuční funkce\ndist.f = function(x,p){\n F = cumsum(p)\n F_ext = c(0, F) # natáhneme F o 0 na začátku\n x_ext = c(x[1]-1, x, x[length(x)]+1) # a x z obou stran\n \n plot(x, F, ylab=\"F(x)\", xaxt='n', ylim=c(0,1), # prazdná kolečka\n type='p', main=\"Distribucni funkce\") \n par(new=TRUE) # že chceme kreslit do jednoho grafu\n plot(x, F_ext[1:(length(F_ext)-1)], # plná kolečka\n ylab=\"F(x)\", xaxt='n', ylim=c(0,1), type='p', pch=19) \n \n for(i in 1:(length(x_ext)-1)){\n lines(c(min(x)-100,max(x)+100), c(F_ext[i],F_ext[i]),\n type = 'l', lty = 3, lwd=0.5) # horizontální grid\n lines(c(x_ext[i],x_ext[i]), c(-0.1,1.1), \n type = 'l', lty = 3, lwd=0.5) # vertikální grid\n lines(x_ext[i:(i+1)], c(F_ext[i],F_ext[i])) # graf - čáry\n }\n axis(1, at=x,labels=x) # nastavení hodnot na X\n axis(4, at=F,labels=F, las=2, cex.axis=0.7, tck=-.01) # a Y\n return(F)\n}\n\ndist.f(x,p)\n\n# ** 1. c) ####\n# Určete střední hodnotu, rozptyl, směrodatnou odchylku a modus počtu zapůjčených\n# automobilů během jednoho dne.\n\n\n# Střední hodnota\nx*p\nEX = sum(x*p)\nEX\n\n# Rozptyl\nEX2 = sum(x*x*p) # druhý obecný moment\nDX = EX2 - EX^2\nDX\n\n# Směrodatná odchylka\nsigma.X = sqrt(DX)\nsigma.X\n\n# Funkce pro výpočet základních číselných charakteristik\nsouhrn=function(x,p){\n EX = sum(x*p)\n EX2 = sum(x*x*p) \n DX = EX2-EX^2\n sigma.X = sqrt(DX)\n # zápis výsledků do tabulky\n tab = rbind(EX, DX, sigma.X)\n tab.popis = c(\"str. hodnota\",\"rozptyl\",\"smer. odchylka\")\n rownames(tab) = tab.popis\n return(tab)\n}\n\nsouhrn(x, p)\n\n# ** 1. d) ####\n# Určete pravděpodobnostní funkci a distribuční funkci náhodné veličiny Y, která je\n# definována jako denní příjem majitele servisu.\n\n\ny = 500*x\ny\n\npravd.f(y, p)\n\n# Distribuční funkce\ndist.f(y,p)\n\n# ** 1. e) ####\n# Určete střední hodnotu, směrodatnou odchylku a modus příjmu majitele servisu ze\n# zapůjčených automobilů během jednoho dne.\n\n\nsouhrn(y,p)\n\n# ** 1. f) ####\n# Určete pravděpodobnost, že příjem majitele servisu (náhodná veličina Y) z půjčování\n# automobilů převýší jeho výdaje.\n\n\n# zisk\nz=500*x-800\nz\n\n# příjem převýší výdaje, když je zisk kladný\nz > 0\n\np\nsum(p[z>0])\n\n# ** 1. g) ####\n# Určete střední hodnotu, směrodatnou odchylku a modus náhodné veličiny Z, která je\n# definována jako zisk majitele servisu ze zapůjčených automobilů během jednoho dne.\n\n\nsouhrn(z, p)\n\n# * Příklad č. 2 ####\n# Pro distribuční funkci náhodné veličiny X platí:\n# \n# $F(x)=\\begin{cases}\n# 0 & x \\leq -1 \\\\\n# 0.3 & -1 < x \\leq 0 \\\\\n# 0.7 & 0 < x \\leq 1 \\\\\n# 1 & -1 < x\n# \\end{cases}$\n# \n# ** 2. a) ####\n# Určete pravděpodobnostní funkci náhodné veličiny X, její střední hodnotu a směrodatnou\n# odchylku.\n\n\nF = c(0, 0.3, 0.7, 1)\nF\nx = c(-1,0,1)\nx\n\ndiff(F)\n\np = diff(F)\nx\np\n\npravd.f(x,p)\n\ndist.f(x,p)\n\nsouhrn(x,p)\n\n# ** 2. b) ####\n# Náhodná veličina Y = 1 − 3X, určete P(y), F(y), E(Y), D(Y).\n\n\ny = 1 - 3*x\npravd.f(y,p)\n\ndist.f(y,p) # Nesmyslný výstup - čím je to způsobeno?\ny\np\n\ny\nsort(y)\nidx_sorted = order(y) # funkce order vrátí indexy setřízeného pořadí\nidx_sorted\ny = y[idx_sorted]\np_y = p[idx_sorted]\np_y\n\ndist.f(y,p_y)\n\nsouhrn(y, p_y)\n\n# ** 2. c) ####\n# Náhodná veličina W = $3X^2$, určete P(w), F(w), E(W), D(W).\n\n\nw = 3*x*x\nw\n\npravd.f(w,p)\ndist.f(w,p)\n\nw\nw_uniq = unique(w)\nw_uniq\nw_sorted = sort(w_uniq)\nw_sorted\n\np_w = w_sorted*0 # inicializace pole o stejné velikosti\nfor(i in 1:length(w_sorted)){\n p_w[i] = sum(p[w == w_sorted[i]])\n}\np_w\n\npravd.f(w_sorted,p_w)\ndist.f(w_sorted,p_w)\nsouhrn(w_sorted,p_w)\n\n# * Příklad 3. ####\n# V dílně jsou dva stroje pracující nezávisle na sobě. Pravděpodobnost poruchy prvního\n# stroje\n# je 0,2, pravděpodobnost poruchy druhého stroje je 0,3. Náhodná veličina X je\n# definována jako\n# počet současně porouchaných strojů. Určete:\n# ** 3. a) ####\n# pravděpodobnostní funkci náhodné veličiny X,\n\n\nx = c(0, 1, 2)\nx\np1 = 0.2\np2 = 0.3\n\np = x*0\n# spočteme jednotlivé pravděpodobnosti počtu porouchaných strojů\np[1] = (1 - p1)*(1 - p2) # 0 porouchaných tedy oba v provozu\np[3] = p1*p2 # 2 tedy porouchané oba\np\n1 - sum(p)\np[2] = (1 - p1)*p2 + p1*(1 - p2) # právě jeden - buď první nebo druhý\np\n\nsum(p)\n\npravd.f(x,p)\n\n# ** 3. b) ####\n# distribuční funkci náhodné veličiny X,\n\n\ndist.f(x,p)\n\n# ** 3. c) ####\n# střední hodnotu a rozptyl náhodné veličiny X.\n\n\nsouhrn(x,p)\n\n\n\n", "meta": {"hexsha": "c003f32aec2a48ef841c7d35c00818af76022a29", "size": 8659, "ext": "r", "lang": "R", "max_stars_repo_path": "CV3/cv3.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": "CV3/cv3.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": "CV3/cv3.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": 26.5613496933, "max_line_length": 107, "alphanum_fraction": 0.6195865573, "num_tokens": 3684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.4492558036011677}}
{"text": "#' @title\n#' Nested reduced-rank regression with given ranks\n#'\n#' @description\n#' This function implements the blockwise coordinate descent algorithm\n#' to get the nested reduced-rank regression estimator with\n#' given rank values \\code{(r, rx, ry)}.\n#'\n#' @usage\n#' NRRR.est(Y, X, Ag0 = NULL, Bg0 = NULL,\n#' rini, r, rx, ry, jx, jy, p, d, n,\n#' maxiter = 100, conv = 1e-4,\n#' method = c(\"RRR\", \"RRS\")[1], lambda = 0)\n#'\n#'\n#' @param Y response matrix of dimension n-by-jy*d.\n#' @param X design matrix of dimension n-by-jx*p.\n#' @param Ag0 an initial estimator of matrix U. If \\code{Ag0 = NULL} then generate it\n#' by \\code{\\link{NRRR.ini}}. Default is NULL.\n#' @param Bg0 an initial estimator of matrix V. If \\code{Bg0 = NULL} then generate it\n#' by \\code{\\link{NRRR.ini}}. Default is NULL.\n#' @param rini,r rank of the local reduced-rank structure. \\code{rini} is used\n#' in \\code{\\link{NRRR.ini}} to get the initial\n#' estimators of U and V.\n#' @param rx number of latent predictors.\n#' @param ry number of latent responses.\n#' @param jx number of basis functions to expand the functional predictor.\n#' @param jy number of basis functions to expand the functional response.\n#' @param p number of predictors.\n#' @param d number of responses.\n#' @param n sample size.\n#' @param maxiter the maximum iteration number of the\n#' blockwise coordinate descent algorithm. Default is 100.\n#' @param conv the tolerance level used to control the convergence of the\n#' blockwise coordinate descent algorithm. Default is 1e-4.\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'} and\n#' a positive value should be provided.\n#' Default is 0.\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}{degrees of freedom of the model.}\n#' \\item{sse}{sum of squared errors.}\n#' \\item{ic}{a vector containing values of BIC, BICP, AIC, GCV.}\n# \\item{obj}{a vector contains all objective function (sse) values along iteration.}\n#' \\item{iter}{the number of iterations needed to converge.}\n#'\n#' @details\n#' The \\emph{nested reduced-rank regression (NRRR)} is proposed to solve\n#' a multivariate functional linear regression problem where both the response and\n#' predictor are multivariate and functional (i.e., \\eqn{Y(t)=(y_1(t),...,y_d(t))^T}\n#' and \\eqn{X(s)=(x_1(s),...,y_p(s))^T}). To control the complexity of the\n#' problem, NRRR imposes a nested reduced-rank structure on the regression\n#' surface \\eqn{C(s,t)}. Specifically, a global dimension reduction makes use of the\n#' correlation within the components of multivariate response and multivariate\n#' predictor. Matrices U (d-by-ry) and V (p-by-rx) provide weights to form ry latent\n#' functional responses and rx latent functional predictors, respectively.\n#' Dimension reduction is achieved\n#' once \\eqn{ry < d} or \\eqn{rx < p}. Then, a local dimension reduction is\n#' conducted by restricting the latent regression surface \\eqn{C^*(s,t)} to be of low-rank.\n#' After basis expansion and truncation, also by applying proper rearrangement to\n#' columns and rows of the resulting data matrices and coefficient matrices, we\n#' have the nested reduced-rank problem:\n#' \\deqn{ \\min_{C} || Y - XC ||_F^2, s.t., C = (I_{jx} \\otimes V) BA^T (I_{jy} \\otimes U)^T,}\n#' where \\eqn{BA^T} is a full-rank decomposition to control the local\n#' rank and \\eqn{jx, jy} are the number of basis functions. Beyond the functional\n#' setup, this structure can also be applied to multiple scenarios, including\n#' multivariate time series autoregression analysis and tensor-on-tensor regression.\n#' This problem is non-convex and has no explicit solution, thus we use a\n#' blockwise coordinate descent algorithm to find a local solution. The convergence\n#' is decided by the change in objective values between two neighboring iterations.\n#'\n#'\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#' @examples\n#' library(NRRR)\n#' simDat <- NRRR.sim(n = 100, ns = 200, nt = 200, r = 5, rx = 3, ry = 3,\n#' jx = 15, jy = 15, p = 10, d = 6, s2n = 1, rho_X = 0.5,\n#' rho_E = 0, Sigma = \"CorrAR\")\n#' fit_init <- with(simDat, NRRR.est(Y = Yest, X = Xest,\n#' Ag0 = NULL, Bg0 = NULL, rini = 5, r = 5,\n#' rx = 3, ry = 3, jx = 15, jy = 15,\n#' p = 10, d = 6, n = 100))\n#' fit_init$Ag\n#' @importFrom MASS ginv\n#' @export\nNRRR.est <- function(Y, X, Ag0 = NULL, Bg0 = NULL, rini, r, rx, ry, jx, jy, p, d, n,\n maxiter = 100, conv = 1e-4,\n method = c(\"RRR\", \"RRS\")[1], lambda = 0) {\n if (rini == 0) stop(\"rini cannot be 0\")\n if (r == 0) stop(\"r cannot be 0\")\n if(p < rx) stop(\"rx cannot be greater than p\")\n if(d < ry) stop(\"ry cannot be greater than d\")\n\n\n if (method == \"RRS\" & lambda != 0) { # RRS is reduced rank ridge regression.\n Y <- rbind(Y, matrix(nrow = p * jx, ncol = d * jy, 0.0))\n X <- rbind(X, sqrt(lambda) * diag(nrow = p * jx, ncol = p * jx))\n n <- n + p * jx\n }\n\n # require(rrpack)\n # compute initial values of U and V\n if (is.null(Ag0) | is.null(Bg0)) {\n ini <- NRRR.ini(Y, X, rini, rx, ry, jx, jy, p, d, n)\n Ag0 <- ini$Ag\n Bg0 <- ini$Bg\n }\n\n if (d == ry) {\n Yl0 <- Y\n } else {\n Yl0 <- Y %*% kronecker(diag(jy), Ag0)\n }\n if (p == rx) {\n Xl0 <- X\n } else {\n Xl0 <- X %*% kronecker(diag(jx), Bg0)\n }\n\n # Given Ag (U) and Bg (V), compute Al and Bl\n if (r > min(dim(Yl0)[2])) stop(\"r cannot be greater than jy*ry\")\n fitRR <- RRR(Yl0, Xl0, nrank = r)\n Bl0 <- fitRR$C_ls %*% fitRR$A\n Al0 <- fitRR$A\n\n\n obj <- vector() # collect all objective function (sse) values\n obj[1] <- Obj(Y, X, Ag0, Bg0, Al0, Bl0, jx, jy)$obj\n objnow <- obj[1] + 10\n iter <- 1\n while (iter < maxiter & abs(obj[iter] - objnow) > conv) { # use sse to control convergence.\n\n ### For updating Ag (U)###\n if (d == ry) {\n Ag1 <- diag(nrow = ry, ncol = ry) # an identity matrix\n Yl0 <- Y\n } else {\n Xg <- Xl0 %*% Bl0 %*% t(Al0)\n Yg0 <- matrix(nrow = d, ncol = ry, 0)\n for (j in 1:jy) {\n a1 <- d * (j - 1) + 1\n b1 <- d * j\n\n a2 <- ry * (j - 1) + 1\n b2 <- ry * j\n\n Yg0 <- Yg0 + t(Y[, a1:b1]) %*% (Xg[, a2:b2])\n }\n svdYg0 <- svd(Yg0)\n Ag1 <- svdYg0$u %*% t(svdYg0$v)\n Yl0 <- Y %*% kronecker(diag(jy), Ag1)\n }\n\n\n ### For updating Bg (V)###\n if (p == rx) {\n Bg1 <- diag(nrow = rx, ncol = rx)\n Xl0 <- X\n } else {\n yB <- as.vector(Yl0 %*% Al0)\n XB <- matrix(nrow = n * r, ncol = rx * p, 0)\n for (j in 1:jx) {\n a1 <- rx * (j - 1) + 1\n b1 <- rx * j\n\n a2 <- p * (j - 1) + 1\n b2 <- p * j\n\n XB <- XB + kronecker(matrix(t(Bl0)[, a1:b1], nrow = r, ncol = rx), X[, a2:b2])\n }\n Bg1 <- matrix(nrow = p, ncol = rx, byrow = FALSE, MASS::ginv(t(XB) %*% XB +\n 0.0000001 * diag(1, rx * p, rx * p)) %*% t(XB) %*% yB)\n\n Bg1 <- qr.Q(qr(Bg1))\n Xl0 <- X %*% kronecker(diag(jx), Bg1)\n }\n\n ### For updating Al (A) and Bl (B)###\n fitRR <- RRR(Yl0, Xl0, nrank = r)\n Bl1 <- fitRR$C_ls %*% fitRR$A\n Al1 <- fitRR$A\n\n iter <- iter + 1\n Objiter <- Obj(Y, X, Ag1, Bg1, Al1, Bl1, jx, jy)\n obj[iter] <- Objiter$obj\n objnow <- obj[iter - 1]\n C <- Objiter$C\n\n\n Al0 <- Al1\n Bl0 <- Bl1\n Ag0 <- Ag1\n Bg0 <- Bg1\n }\n\n # compute rank of X\n xr <- sum(svd(X)$d > 1e-2)\n # compute degrees of freedom of NRRR\n df <- ifelse(xr / jx > rx, rx * (xr / jx - rx), 0) + ry * (d - ry) + (jy * ry + jx * rx - r) * r\n # obtain sse\n sse <- ifelse(Objiter$sse < 0.1, 0, Objiter$sse)\n # compute information criterion\n BIC <- log(sse) + log(d * jy * n) / d / jy / n * df\n BICP <- log(sse) + 2 * log(d * jy * p * jx) / d / jy / n * df\n AIC <- log(sse) + 2 / d / jy / n * df\n GCV <- sse / d / jy / n / (1 - df / d / jy / n)^2\n\n if (method == \"RRS\") sse <- sse - lambda * sum(Objiter$C^2)\n\n # if (!quietly) {\n # cat(\"SSE = \", sse, \"DF = \", df, \"\\n\", sep = \"\")\n # }\n return(list(\n Ag = Ag1, Bg = Bg1, Al = as.matrix(Al1), Bl = as.matrix(Bl1), C = C, df = df,\n sse = sse, ic = c(BIC, BICP, AIC, GCV), obj = obj, iter = iter\n ))\n}\n", "meta": {"hexsha": "ceab42d955a8525800dff4d89d0db2c5c660757d", "size": 8733, "ext": "r", "lang": "R", "max_stars_repo_path": "R/NestRRR.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/NestRRR.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/NestRRR.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": 37.8051948052, "max_line_length": 98, "alphanum_fraction": 0.5771212642, "num_tokens": 3025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4491194134876732}}
{"text": "# Day 9: Smoke Basin\n\nget_day9_input_path <- function() {\n paste(getwd(), \"/2021/Day 9/Day9_input.txt\", sep = \"\")\n}\n\npart1 <- function() {\n readings <- readLines(get_day9_input_path())\n\n basin_rows <- length(readings)\n basin_cols <- nchar(readings[1])\n basin <- matrix(ncol = basin_cols)[-1, ]\n\n for (i in seq_len(length(readings))) {\n basin <- rbind(basin, strtoi(unlist(strsplit(readings[i], \"\"))))\n }\n\n total_risk_level <- 0\n\n for (r in seq_len(basin_rows)) {\n for (c in seq_len(basin_cols)) {\n total_risk_level <- total_risk_level +\n calc_risk_level(basin, r, c, basin_rows, basin_cols)\n }\n }\n\n print(total_risk_level)\n}\n\npart2 <- function() {\n readings <- readLines(get_day9_input_path())\n\n basin_rows <- length(readings)\n basin_cols <- nchar(readings[1])\n basin <- matrix(ncol = basin_cols)[-1, ]\n low_points <- matrix(ncol = 2)[-1, ]\n basin_sizes <- c()\n\n for (i in seq_len(length(readings))) {\n basin <- rbind(basin, strtoi(unlist(strsplit(readings[i], \"\"))))\n }\n\n for (r in seq_len(basin_rows)) {\n for (c in seq_len(basin_cols)) {\n if (calc_risk_level(basin, r, c, basin_rows, basin_cols) > 0) {\n low_points <- rbind(low_points, c(r, c))\n }\n }\n }\n\n for (i in seq_len(length(low_points) / 2)) {\n # Sprawl from low points to make basins\n ind_basin <- get_basin_from_low_point(\n basin,\n low_points[i, 1],\n low_points[i, 2],\n basin_rows,\n basin_cols)\n\n # Get size of individual basin\n ind_basin_size <- length(ind_basin) / 2\n basin_sizes <- append(basin_sizes, ind_basin_size)\n }\n\n basin_sizes <- sort(basin_sizes, decreasing = TRUE)\n\n # Multiply sizes of 3 largest basins\n print(prod(basin_sizes[1:3]))\n}\n\ncalc_risk_level <- function(basin, row, col, max_row, max_col) {\n point_val <- basin[row, col]\n risk_level <- 0\n adj_point_vals <- c()\n\n # Up Value\n if (row > 1) {\n adj_point_vals <- append(adj_point_vals, basin[row - 1, col])\n }\n\n # Down Value\n if (row < max_row) {\n adj_point_vals <- append(adj_point_vals, basin[row + 1, col])\n }\n\n # Left Value\n if (col > 1) {\n adj_point_vals <- append(adj_point_vals, basin[row, col - 1])\n }\n\n # Right Value\n if (col < max_col) {\n adj_point_vals <- append(adj_point_vals, basin[row, col + 1])\n }\n\n if (sum(adj_point_vals > point_val) == length(adj_point_vals)) {\n risk_level <- point_val + 1\n }\n\n risk_level\n}\n\nget_basin_from_low_point <- function(basin, row, col, max_row, max_col) {\n basin_points <- matrix(ncol = 2)[-1, ]\n new_points <- matrix(ncol = 2)[-1, ]\n\n basin_points <- rbind(basin_points, c(row, col))\n new_points <- rbind(new_points, c(row, col))\n\n while (length(new_points) > 0) {\n adj_points <- get_adj_points(basin,\n new_points[1, 1],\n new_points[1, 2],\n max_row, max_col)\n new_points <- new_points[-1, ]\n new_points <- rbind(new_points)\n\n for (i in seq_len(length(adj_points) / 2)) {\n adj_point_r <- adj_points[i, 1]\n adj_point_c <- adj_points[i, 2]\n point_val <- basin[adj_point_r, adj_point_c]\n if (point_val < 9) {\n match <- FALSE\n for (p in seq_len(length(basin_points) / 2)) {\n match <- (basin_points[p, 1] == adj_point_r &&\n basin_points[p, 2] == adj_point_c)\n if (match) break\n }\n\n if (!match) {\n basin_points <- rbind(basin_points,\n c(adj_point_r, adj_point_c))\n new_points <- rbind(new_points,\n c(adj_point_r, adj_point_c))\n }\n }\n }\n }\n basin_points\n}\n\nget_adj_points <- function(basin, row, col, max_row, max_col) {\n adj_points <- matrix(ncol = 2)[-1, ]\n\n # Up Value\n if (row > 1) {\n adj_points <- rbind(adj_points, c(row - 1, col))\n }\n\n # Down Value\n if (row < max_row) {\n adj_points <- rbind(adj_points, c(row + 1, col))\n }\n\n # Left Value\n if (col > 1) {\n adj_points <- rbind(adj_points, c(row, col - 1))\n }\n\n # Right Value\n if (col < max_col) {\n adj_points <- rbind(adj_points, c(row, col + 1))\n }\n\n adj_points\n}\n\npart1()\npart2()\n", "meta": {"hexsha": "ee4d7918e6bcc57c8d0a0f1165ed097cd582f261", "size": 4678, "ext": "r", "lang": "R", "max_stars_repo_path": "2021/Day 09/Day9_SmokeBasin.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 09/Day9_SmokeBasin.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 09/Day9_SmokeBasin.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": 27.5176470588, "max_line_length": 75, "alphanum_fraction": 0.5303548525, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4489965703150022}}
{"text": "subroutine collincheck(nadj,madj,npts,x,y,ntot,eps)\n\n# Collinearity check --- experimental. Runs through the adjacency\n# list to see if any of the putative triangles in the triangulation\n# that has so far been created are \"degenerate\", i.e. are actually\n# just three points lying on a straight line.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot)\ndimension nadj(-3:ntot,0:madj)\nlogical collin, changed\n\nnerror = -1\nchanged = .false.\nrepeat {\n do j = 1,npts {\n nj = nadj(j,0)\n do k = 1,nj {\n k1 = nadj(j,k)\n call succ(k2,j,k1,nadj,madj,ntot,nerror)\n if(nerror > 0) {\n call intpr(\"Error number =\",-1,nerror,1)\n call rexit(\"Error in succ, called from collincheck.\")\n }\n\n# Check whether triangle j, k1, k2 is really a triangle.\n call crossutil(j,k1,k2,x,y,ntot,eps,collin)\n\n# If collinear, remove the triangle from the mix.\n if(collin) {\n changed = .true.\n# First determine which of k1 and k2 is closer to j. It\n# *should* be k1, but y'never know in these chaotic\n# circumstances.\n sd1 = (x(k1) - x(j))**2 + (y(k1) - y(j))**2\n sd2 = (x(k2) - x(j))**2 + (y(k2) - y(j))**2\n if(sd1 < sd2) {\n kr = k2\n } else {\n kr = k1\n }\n# Delete kr (\"r\" for \"remove\") from the adjacency list of j and j\n# from the adjacency list of kr.\n call delet(j,kr,nadj,madj,ntot,nerror)\n if(nerror > 0) {\n call intpr(\"Error number =\",-1,nerror,1)\n call rexit(\"Error in collincheck.\")\n }\n break\n }\n }\n if(changed) break\n }\n}\nuntil(!changed)\nreturn\nend\n", "meta": {"hexsha": "49f0b0f34cf43645ae952172396babb211c3e685", "size": 1755, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/code.discarded/collincheck.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/code.discarded/collincheck.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/code.discarded/collincheck.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": 30.2586206897, "max_line_length": 68, "alphanum_fraction": 0.5487179487, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44867500468595584}}
{"text": "# 4. faza: Napredna analiza podatkov\n\nsource(\"lib/libraries.r\")\n\n################################################################################\n# RAZVRŠČANJE V SKUPINE - \n# Razvrščanje držav v skupine glede na to, kakšne rezultate dosegajo\n\n### Najprej k-means:\n\n# Tabela s podatki o državah:\n# | država | točke DH | točke SG | točke GS | točke SL | povprečen YB |\n\n# Najprej spremenimo kratice držav, da lahko združimo z zemljevidom\nprave.kratice <- REZULTATI.VREME %>% \n mutate(NSA = str_replace_all(REZULTATI.VREME$NSA, pattern = \"SLO\", replacement = \"SVN\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"GER\", replacement = \"DEU\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"CRO\", replacement = \"HRV\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"SUI\", replacement = \"CHE\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"NED\", replacement = \"NLD\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"BUL\", replacement = \"BGR\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"GRE\", replacement = \"GRC\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"MON\", replacement = \"MCO\"))\nprave.kratice <- prave.kratice %>% \n mutate(NSA = str_replace_all(prave.kratice$NSA, pattern = \"RSF\", replacement = \"RUS\"))\nprave.kratice\n\nDH.analiza <- prave.kratice %>% filter(Disciplina == \"DH\") %>% group_by(NSA) %>%\n summarise(tocke.DH = sum(tocke_30))\nSG.analiza <- prave.kratice %>% filter(Disciplina == \"SG\") %>% group_by(NSA) %>%\n summarise(tocke.SG = sum(tocke_30))\nGS.analiza <- prave.kratice %>% filter(Disciplina == \"GS\") %>% group_by(NSA) %>%\n summarise(tocke.GS = sum(tocke_30))\nSL.analiza <- prave.kratice %>% filter(Disciplina == \"SL\") %>% group_by(NSA) %>%\n summarise(tocke.SL = sum(tocke_30))\nYB.analiza <- prave.kratice %>% group_by(NSA) %>% summarise(YB.povprecen = mean(YB))\n\ndrzave <- left_join(prave.kratice, DH.analiza, by = \"NSA\")\ndrzave <- left_join(drzave, SG.analiza, by = \"NSA\")\ndrzave <- left_join(drzave, GS.analiza, by = \"NSA\")\ndrzave <- left_join(drzave, SL.analiza, by = \"NSA\")\ndrzave <- left_join(drzave, YB.analiza, by = \"NSA\")\n\ndrzave <- drzave %>% \n dplyr::select(YB.povprecen, NSA, tocke.DH, tocke.SG, tocke.GS, tocke.SL)\n\ndrzave$tocke.DH[is.na(drzave$tocke.DH)] <- 0\ndrzave$tocke.SG[is.na(drzave$tocke.SG)] <- 0\ndrzave$tocke.GS[is.na(drzave$tocke.GS)] <- 0\ndrzave$tocke.SL[is.na(drzave$tocke.SL)] <- 0\ndrzave <- unique(drzave)\n\n\n# Clustering s k-means\nset.seed(123)\n\nskupine <- drzave[,-2] %>%\n kmeans(centers = 5) %>%\n getElement(\"cluster\") %>%\n as.ordered()\nprint(skupine)\n\ntabela.skupine <- drzave %>% \n transform(NSA = as.factor(NSA)) %>% \n mutate(Skupine = as.numeric(skupine))\n\nzemljevid.za.skupine <-\n uvozi.zemljevid(\n \"http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/ne_50m_admin_0_countries.zip\",\n \"ne_50m_admin_0_countries\",\n mapa = \"zemljevidi\",\n pot.zemljevida = \"\",\n encoding = \"UTF-8\"\n ) %>%\n fortify() %>% filter(long < 170 & long > -170 & lat > 0 & lat < 85)\n\nzemljevid.po.skupinah <- ggplot() +\n aes(x = long, y = lat, group = group, fill = Skupine) +\n geom_polygon(data=tabela.skupine %>% right_join(zemljevid.za.skupine, \n by = c(\"NSA\" = \"ADM0_A3\"))) +\n xlab(\"\") +\n ylab(\"\") +\n ggtitle(\"Države s podobno strukturo smučarjev 2020/21\") +\n coord_fixed(ratio = 2) +\n guides(fill=guide_legend(title=\"Skupina\")) + \n theme(legend.title = element_text(color = \"black\", size = 11),\n legend.background = element_rect(colour =\"#006699\", fill = \"white\"), \n plot.title = element_text(color = \"#006699\", hjust = 0.5, size = 15))\nzemljevid.po.skupinah\n\n\n### Še hierarhično razvrščanje:\ndendrogram <- drzave[,-2] %>%\n dist() %>%\n hclust()\n\nplot(dendrogram,\n labels = drzave$NSA,\n ylab = \"višina\",\n main = NULL)\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 = tibble(\n k = as.ordered(od:do),\n visina = dendrogram$height[do:od]\n ) %>%\n mutate(\n dvisina = visina - lag(visina)\n ) %>%\n mutate(\n koleno = lead(dvisina) - dvisina > eps\n )\n k.visina\n}\n\n# iz tabele k.visina vrne seznam vrednosti k, pri katerih opazujemo koleno\nhc.kolena.k <- function(k.visina) {\n k.visina %>%\n filter(koleno) %>%\n dplyr::select(k) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\n# tabela s koleni za dendrogram\nr <- hc.kolena(dendrogram)\n\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 = \"#006699\", 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}\n\ndiagram.kolena(r)\n\n\n################################################################################\n# NAPOVEDNI MODEL\n# Napovemo uvrstitev, ki jo pričakujemo od smučarja glede na to, katere smuči uporablja, \n# v kateri disciplini tekmuje in glede na snežno podlago\n\n# spemenimo imenske spremenljivke v numerične\none_hot = function(pod, spr) {\n domena = pod %>%\n dplyr::select({{spr}}) %>%\n unlist() %>%\n unique()\n for (v in domena) {\n pod = pod %>%\n mutate(\n \"{{spr}}.{v}\" := ifelse({{spr}} == v, 1, 0)\n )\n }\n pod %>% dplyr::select(-{{spr}})\n}\n\n\nsmuci <- levels(REZULTATI.VREME$Ski)[-c(9)]\n\n# Podatki, na katerih bom delala napovedi:\npodatki <- REZULTATI.VREME %>% \n dplyr::select(Rank, Ski, Disciplina, sneg) %>% \n filter(Ski %in% smuci) %>%\n one_hot(Ski) %>% one_hot(Disciplina) %>% one_hot(sneg)\n\n\nset.seed(123)\n# linearna regresija, da napovemo uvrstitve tekmovalca glede na:\n# smuči (1. MODEL)\nlin.reg.smuci = lm(\n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Voelkl + Ski.Dynastar + Ski.Blizzard,\n data = podatki)\nprint(lin.reg.smuci)\n\n# smuči in disciplino (2.MODEL)\nlin.reg.smuci.disc = lm(\n Rank ~ Disciplina.DH + Disciplina.SG + Disciplina.GS + Disciplina.SL +\n Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol +\n Ski.Salomon + Ski.Stoeckli + Ski.Dynastar + Ski.Voelkl+ Ski.Blizzard,\n data = podatki)\nprint(lin.reg.smuci.disc)\n\n# smuči in snežno podlago (3. MODEL)\nlin.reg.smuci.sneg = lm(\n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Blizzard + Ski.Dynastar + Ski.Voelkl + sneg.HARD + \n `sneg.SPRING CONDITIONS` + sneg.COMPACT + sneg.SOFT + sneg.PACKED,\n data = podatki)\nprint(lin.reg.smuci.sneg)\n\n# Še model, ki vključuje tako smuči kot tudi disciplino in snežno podlago (4. MODEL):\nlin.reg.skupaj = lm(\n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Blizzard + Ski.Dynastar + Ski.Voelkl +\n Disciplina.DH + Disciplina.SG + Disciplina.GS + Disciplina.SL + sneg.HARD + \n `sneg.SPRING CONDITIONS` + sneg.COMPACT + sneg.SOFT + sneg.PACKED,\n data = podatki)\nprint(lin.reg.skupaj)\n\n# prečno preverjanje\nnapaka.cv <- function(podatki, formula, k) {\n set.seed(123)\n n <- nrow(podatki)\n # naključno premešamo primere\n r <- sample(1:n)\n # razrez na k intervalov\n razrez <- cut(seq_along(r), k, labels = FALSE)\n # razbijemo vektor na k seznamov na osnovi razreza intervalov\n razbitje = split(r, razrez)\n # zdaj imamo dane indekse za vsakega od k-tih delov\n pp.napovedi = rep(0, nrow(podatki))\n # prečno preverjanje\n for (i in 1:length(razbitje)) {\n train.data = podatki[-razbitje[[i]],] # učni podatki\n test.data = podatki[razbitje[[i]],] # testni podatki\n # naučimo model\n model = lm(data = train.data, formula = formula)\n # napovemo za testne podatke\n napovedi = predict(model, newdata = test.data)\n pp.napovedi[razbitje[[i]]] = napovedi\n }\n # izračunamo MSE\n napaka = mean((pp.napovedi - podatki$Rank) ^ 2)\n return(napaka)\n}\n\n# formule za napovedi\nformula.smuci <-\n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Voelkl + Ski.Dynastar + Ski.Blizzard\nformula.smuci.disc <- \n Rank ~ Disciplina.DH + Disciplina.SG + Disciplina.GS + Disciplina.SL +\n Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol +\n Ski.Salomon + Ski.Stoeckli + Ski.Dynastar + Ski.Voelkl+ Ski.Blizzard\nformula.smuci.sneg <- \n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Blizzard + Ski.Dynastar + Ski.Voelkl + sneg.HARD + \n `sneg.SPRING CONDITIONS` + sneg.COMPACT + sneg.SOFT + sneg.PACKED\nformula.skupaj <- \n Rank ~ Ski.Atomic + Ski.Fischer + Ski.Head + Ski.Kaestle + Ski.Nordica + Ski.Rossignol + \n Ski.Salomon + Ski.Stoeckli + Ski.Blizzard + Ski.Dynastar + Ski.Voelkl +\n Disciplina.DH + Disciplina.SG + Disciplina.GS + Disciplina.SL + sneg.HARD + \n `sneg.SPRING CONDITIONS` + sneg.COMPACT + sneg.SOFT + sneg.PACKED\n\nnapaka.smuci <- napaka.cv(podatki, formula.smuci, 10)\nnapaka.smuci.disc <- napaka.cv(podatki, formula.smuci.disc, 10)\nnapaka.smuci.sneg <- napaka.cv(podatki, formula.smuci.sneg, 10)\nnapaka.skupaj <- napaka.cv(podatki, formula.skupaj, 10)\nprint(c(napaka.smuci, napaka.smuci.disc, napaka.smuci.sneg, napaka.skupaj))\n# --> najboljši model je tisti s smučmi in disciplino (2. model)\n\n# Prikaz za 1. model:\nuvrstitev <- c(1:length(smuci)) * 0\nnapovedi.za.smuci <- tibble(smuci, uvrstitev)\n\nfor (i in 1:length(smuci)){\n vzorec = podatki[1,2:12]\n vzorec[1,] = c(rep(0,i-1), 1, rep(0, length(smuci)-i))\n napovedi.za.smuci[i,2] <- predict(lin.reg.smuci, newdata = vzorec)\n}\nnapovedi.za.smuci[2]\n\nbarve <- c(\"#FF0000\", \"#FF6633\",\"#00CCCC\", \"#FFFF00\", \"#FFF7A9\", \"#009966\", \n \"#330000\", \"#FF3300\", \"#000066\", \"#990000\", \"#CCCC00\")\n\ngraf.napovedi <-\n ggplot(napovedi.za.smuci) +\n aes(x = smuci, y = uvrstitev) +\n geom_bar(stat = \"identity\", aes(fill = smuci)) + \n scale_fill_manual(values = barve) +\n xlab(\"Smuči\") +\n ylab(\"Uvrstitev\") +\n ggtitle(\"Napovedane uvrstitve glede na smuči v sezoni 2020/21\") +\n theme(legend.position = \"none\",\n plot.title = element_text(color = \"#006699\", hjust = 0.5, size = 15),\n axis.text.x = element_text(angle = 25))\ngraf.napovedi\n\n# Primeri za v poročilo, delam jih na podlagi 2. modela, ker ima najmanjšo napako:\nvzorec.2 = podatki[1, 2:16]\n# Opazujmo smuči znamke Atomic, za katere smo ugotovili, da so najbolj vsestranske, \n# torej primerne z tekmovanje v vseh disciplinah:\nvzorec.2[1,] = c(rep(0,3), 1, rep(0, 7), 1, rep(0, 3))\npred.atomic.dh <- predict(lin.reg.smuci.disc, newdata = vzorec.2)\nvzorec.2[1,] = c(rep(0,3), 1, rep(0, 8), 1, rep(0, 2))\npred.atomic.sg <- predict(lin.reg.smuci.disc, newdata = vzorec.2)\nvzorec.2[1,] = c(rep(0,3), 1, rep(0, 9), 1, 0)\npred.atomic.gs <- predict(lin.reg.smuci.disc, newdata = vzorec.2)\nvzorec.2[1,] = c(rep(0,3), 1, rep(0, 10), 1)\npred.atomic.sl <- predict(lin.reg.smuci.disc, newdata = vzorec.2)\n\nUvrstitev <- c(pred.atomic.dh, pred.atomic.sg, pred.atomic.gs, pred.atomic.sl)\nDisciplina <- c(\"Smuk\", \"Superveleslalom\", \"Veleslalom\", \"Slalom\")\n# Tabela za v poročilo:\natomic <- t(tibble(Disciplina, Uvrstitev))\n\n", "meta": {"hexsha": "d5b6c16e9f7a296bfcd25595c2d84447c084f524", "size": 11910, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "EvaRudolf/APPR-2021-22", "max_stars_repo_head_hexsha": "ef93278887b6db89c923862b5a56c0dc29a67865", "max_stars_repo_licenses": ["MIT"], "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": "EvaRudolf/APPR-2021-22", "max_issues_repo_head_hexsha": "ef93278887b6db89c923862b5a56c0dc29a67865", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-03T12:31:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T11:19:45.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "EvaRudolf/APPR-2021-22", "max_forks_repo_head_hexsha": "ef93278887b6db89c923862b5a56c0dc29a67865", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5337423313, "max_line_length": 120, "alphanum_fraction": 0.6482787573, "num_tokens": 4386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4483538165470336}}
{"text": "# -*- encoding: utf-8 -*-\r\n\r\n# 目的: 实现基于网格的SVM近邻聚类算法(GCASK),同时进行数值模拟以及复杂度分析\r\n\r\n\r\n##########################################################\r\n# 设置工作路径\r\n##########################################################\r\nsetwd('E:/projects/grid_svm_knn/data')\r\n# setwd('D:/个人/坚果云同步/我的坚果云/论文/grid_svm_knn/data')\r\n###########################################################\r\n# 基于网格的SVM近邻聚类算法相关代码\r\n###########################################################\r\n\r\n# 对数据空间进行网格化,返回各个维度上网格化的边界\r\nGridding <- function(X,l_grid=0){\r\n # 得到X的属性个数\r\n p <- ncol(X)\r\n # 得到X样本点个数\r\n n <- nrow(X)\r\n # 计算得到各个属性维度的最大值和最小值,确定数据空间的范围\r\n X_range <- matrix(ncol=2,nrow=p)\r\n # X_range的第一列为每个维度上的最大值\r\n X_range[,1] <- apply(X,2,max)\r\n # X_range的第二列为每个维度上的最小值\r\n X_range[,2] <- apply(X,2,min)\r\n # 若X_range的第一列和第二列相同,说明该属性取值都相同,应该删除该属性\r\n # Index <- (X_range[,1] == X_range[,2])\r\n # X <- X[,!Index]\r\n # X_range <- X_range[!Index,]\r\n # p <- ncol(X)\r\n # 计算整个空间的体积\r\n V <- cumprod(X_range[,1]-X_range[,2])[p]\r\n # 计算小网格的边长\r\n if (l_grid == 0){\r\n l_grid <- (V/n) ** (1/p)\r\n }\r\n # 计算每个维度上网格的个数\r\n n_grid <- ceiling((X_range[,1]-X_range[,2]) / l_grid)\r\n # 用DividingLine来存放各个维度上网格的划分边界线\r\n DivdingLine <- matrix(ncol=p,nrow=max(n_grid)+1)\r\n for(i in 1:p){\r\n DivdingLine[1:(n_grid[i]+1),i] <- X_range[i,2] + ((0:n_grid[i]) * l_grid)\r\n }\r\n Lst <- list(DivdingLine=DivdingLine,n_grid=n_grid)\r\n return(Lst)\r\n}\r\n\r\n\r\n# 判断格子里有没有点\r\nbox_point <- function(X,border){\r\n Index <- 1:nrow(X)\r\n p <- ncol(X)\r\n for(i in 1:p){\r\n new_X <- X[Index,]\r\n new_X <- matrix(new_X,ncol=p)\r\n Index <- which( (new_X[,i]>=border[i,1]) & (new_X[,i]<=border[i,2]) )\r\n if(length(Index) == 0){\r\n return(1)\r\n }\r\n }\r\n return(0)\r\n}\r\n\r\n\r\n# 生成小格子边界的索引\r\nget_combinations <- function(n_grid,Index_matrix,Index = 1,row=1){\r\n for(i in 1:n_grid[Index]){\r\n if(Index == length(n_grid)){\r\n for(j in 1:n_grid[Index]){\r\n Index_matrix[which(is.na(Index_matrix[,Index]))[1],Index] <- j\r\n row <- row + 1\r\n }\r\n return(list(Index_matrix=Index_matrix, row=row))\r\n }else{\r\n Index_matrix[row:nrow(Index_matrix),Index] <- i\r\n Index <- Index + 1\r\n Lst <- get_combinations(n_grid,Index_matrix,Index,row)\r\n Index <- Index - 1\r\n row <- Lst$row\r\n Index_matrix <- Lst$Index_matrix\r\n }\r\n }\r\n return(Lst)\r\n}\r\n\r\n\r\n# 对稀疏区域进行插点\r\nget_nothing_point <- function(X,l_grid=0){\r\n # 得到网格边界\r\n Lst <- Gridding(X,l_grid)\r\n DivdingLine <- Lst$DivdingLine\r\n n_grid <- Lst$n_grid\r\n # 得到网格索引矩阵\r\n Index_matrix <- matrix(ncol=length(n_grid),nrow=cumprod(n_grid)[length(n_grid)])\r\n Lst <- get_combinations(n_grid,Index_matrix,Index = 1,row=1)\r\n Index_matrix <- Lst$Index_matrix\r\n # 生成一个插点矩阵\r\n point_matrix <- matrix(nrow=nrow(Index_matrix),ncol=1)\r\n # 生成小格子border,并进行判别\r\n border <- matrix(ncol=2,nrow=ncol(X))\r\n for(i in 1:nrow(Index_matrix)){\r\n for(j in 1:ncol(Index_matrix)){\r\n border[j,1] <- DivdingLine[Index_matrix[i,j],j]\r\n border[j,2] <- DivdingLine[Index_matrix[i,j]+1,j]\r\n }\r\n point_matrix[i] <- box_point(X,border)\r\n }\r\n Index_matrix <- cbind(Index_matrix,point_matrix)\r\n # 得到稀疏区域点的坐标\r\n Index_matrix <- Index_matrix[Index_matrix[,ncol(Index_matrix)]==1 ,]\r\n nothing_point <- matrix(ncol=ncol(X),nrow=nrow(Index_matrix))\r\n for(i in 1:nrow(Index_matrix)){\r\n for(j in 1:ncol(X)){\r\n nothing_point[i,j] <- (DivdingLine[Index_matrix[i,j],j] + DivdingLine[Index_matrix[i,j]+1,j]) / 2\r\n }\r\n }\r\n return(nothing_point)\r\n}\r\n\r\n# 生成有监督学习的数据\r\nget_newdata <- function(X,l_grid=0){\r\n nothing_point <- get_nothing_point(X,l_grid)\r\n label0 <- matrix(0,nrow=nrow(nothing_point),ncol=1)\r\n X1 <- cbind(nothing_point,label0)\r\n label1 <- matrix(1,nrow = nrow(X),ncol=1)\r\n X2 <- cbind(X,label1)\r\n newdata <- rbind(X1,X2)\r\n return(newdata)\r\n}\r\n\r\n\r\n# 找到最近的k个点\r\nnearest_k_point <- function(x,X,C_S,k){\r\n x <- matrix(rep(x,nrow(X)), byrow = TRUE, ncol = ncol(X))\r\n dis_matrix <- diag((x-X) %*% t(x-X))\r\n dis_matrix[C_S] <- max(dis_matrix)+1\r\n Index <- c()\r\n kk <- sum(!((1:nrow(X)) %in% C_S))\r\n k <- min(k,kk)\r\n if(k==0){return(Index)}\r\n for(i in 1:k){\r\n Index <- c(Index,which.min(dis_matrix))\r\n dis_matrix[Index[i]] <- max(dis_matrix)+1\r\n }\r\n return(Index) # Index中最后的那个就是最远的那个\r\n}\r\n\r\n\r\n# 判断最近的k个点中有几个要生成新类\r\nnew_class_point <- function(x,X,Index,model){\r\n x <- matrix(rep(x,length(Index)), byrow = TRUE, ncol = ncol(X))\r\n med <- as.data.frame((x + X[Index,])/2)\r\n colnames(med) <- colnames(X)\r\n pred <- predict(model,med)\r\n # 需要生成新类的点\r\n newclass_point <- Index[!(as.logical(as.numeric(pred)-1))]\r\n # 不需要生成新类的点\r\n oldclass_point <- Index[as.logical(as.numeric(pred)-1)]\r\n point <- list(newclass_point=newclass_point, oldclass_point=oldclass_point)\r\n return(point)\r\n}\r\n\r\n\r\nNewClass <- function(class_list,k,Index){\r\n # k表示当前有几个类\r\n class_list[[k]] <- Index\r\n return(class_list)\r\n}\r\n\r\n\r\n# 函数:合并到上一类\r\nCombindClass <- function(class_list,k,Index){\r\n # k表示当前类的个数\r\n class_list[[k]] <- c(class_list[[k]],Index)\r\n return(class_list)\r\n}\r\n\r\n\r\n# 融合形成新类\r\nCombind <- function(X,C,C_S,model,class_list,k,k_class=0,Index1=1){\r\n # 若是第一个点,先生成一个类\r\n if(k_class == 0){\r\n k_class <- k_class+1\r\n class_list <- list()\r\n class_list[k_class] <- C[Index1]\r\n C_S <- c(C_S,C[Index1])\r\n #print(X[Index1,])\r\n #points(X[Index1,1],X[Index1,2],col=k_class,pch=18)\r\n #pause()\r\n }\r\n \r\n # 有了类之后可以进行判别聚类了\r\n # 只要还有点没有分类就执行代码\r\n while(length(C_S) <= length(C)){\r\n #readline('请按回车')\r\n # 找到聚类点\r\n #if(exists('new_center')){\r\n # x <- new_center\r\n #}else{\r\n # x <- X[C[Index1],]\r\n #}\r\n x <- X[C[Index1],]\r\n # 找到最近的k个点\r\n Index <- nearest_k_point(x,X,C_S,k)\r\n if(is.null(Index)){return(class_list)}\r\n # 对是否每个k近邻点需要生成新类进行分析\r\n point <- new_class_point(x,X,Index,model)\r\n # 判断是不是所有的点都需要生成新类\r\n if(length(point$newclass_point) == length(Index)){ # 所有点都要生成新类\r\n # 找到最近的那个点\r\n Index2 <- Index[1]\r\n C_S <- c(C_S,C[Index2])\r\n # 生成新类\r\n k_class <- k_class + 1\r\n class_list <- NewClass(class_list,k_class,C[Index2])\r\n #points(X[Index2,1],X[Index2,2],pch=20,col=k_class)\r\n #pause()\r\n Index1 <- Index2\r\n }else{\r\n Index2 <- point$oldclass_point\r\n C_S <- c(C_S,C[Index2])\r\n # 合并类\r\n class_list <- CombindClass(class_list,k_class,C[Index2])\r\n #points(X[Index2,1],X[Index2,2],pch=20,col=k_class)\r\n #pause()\r\n #Index1 <- Index2[length(Index2)] # 选择最远的同类点作为下一个迭代点\r\n #this_class_points <- X[class_list[[length(class_list)]],]\r\n #new_center <- apply(this_class_points, 2, mean)\r\n Index1 <- Index2[1] # 选择最近的同类点作为下一个迭代点\r\n }\r\n }\r\n return(class_list)\r\n}\r\n\r\n\r\n# 噪声点识别\r\nget_noise_point<- function(dat,pred){\r\n index_1 <- sum(dat$g==0)\r\n noise_index <- dat$g == 1 & pred != dat$g\r\n noise_point <- dat[noise_index,]\r\n row.names(noise_point) <- as.numeric(row.names(noise_point)) - index_1\r\n not_noise_point_index <- dat$g == 1 & pred == dat$g\r\n not_noise_point <- dat[not_noise_point_index,]\r\n row.names(not_noise_point) <- as.numeric(row.names(not_noise_point)) - index_1\r\n res <- list(noise_point=noise_point, not_noise_point=not_noise_point)\r\n return(res)\r\n}\r\n\r\ngrid_svm_knn <- function(newdata, gamma ,cost, k, Index1){\r\n # 若是没有加载e1071则加载该包\r\n if(!('e1071' %in% (.packages()))){library(e1071)}\r\n mydata <- get_newdata(newdata,l_grid = 0)\r\n dat <- as.data.frame(mydata)\r\n colnames(dat)[ncol(dat)] <- 'g'\r\n dat$g<- as.factor(dat$g)\r\n gamma <- 50\r\n model <- svm(g~.,data = dat,type='C',kernel='radial',gamma=gamma,cost=cost)\r\n #plot(model,dat)\r\n pred <- predict(model,dat[,-ncol(dat)])\r\n X <- as.matrix(newdata[,1:2])\r\n res <- get_noise_point(dat,pred)\r\n X <- as.matrix(res$not_noise_point[,1:2])\r\n index_X <- as.numeric(row.names(res$not_noise_point))\r\n C <- 1:nrow(X)\r\n C_S <- c()\r\n class_list <- list()\r\n class_list <- Combind(X,C,C_S,model,class_list,k = k, Index1=Index1)\r\n noise_point <- as.numeric(row.names(res$noise_point))\r\n #clusters_result <- list(class_list = class_list, noise_point = noise_point)\r\n # 对结果进行整理\r\n pred <- rep(0, dim(newdata)[1])\r\n for(i in 1:length(class_list)){\r\n pred[index_X[class_list[[i]]]] <- i\r\n }\r\n return(pred)\r\n}\r\n\r\n#########################################################################################\r\n# 动态分位数Kmeans算法\r\n#########################################################################################\r\nRadius.KMeans <- function(x,p,q=0.5,t=1.5){\r\n lst <- FILTER(x,11,q,t)\r\n C <- lst$C\r\n R <- lst$R\r\n k <- COMBINE(C,R)\r\n km <- kmeans(x,k)\r\n plot(x,col=km$cluster,main = 'Radius.KMeans result')\r\n return(list(k = k,km = km))\r\n}\r\n\r\n# 中心筛选——对应2.3中的算法2\r\nFILTER <- function(x,p,q=0.5,t=1.5){\r\n C <- matrix(nrow = 1,ncol = dim(x)[2])\r\n R <- c()\r\n # 生成中心点集合C以及对应的半径集合R\r\n for(k in 2:p){\r\n # 进行Kmeans聚类\r\n km <- kmeans(x,k)\r\n for (i in 1:k) {\r\n # 返回本次聚类属于第i类的样本\r\n samples <- x[km$cluster==i,]\r\n # 计算样本到对应聚类中心的距离\r\n d <- dist(km$centers[i,],samples)\r\n # 得到当前类聚类中心对应的半径\r\n r <- as.numeric(quantile(d,q))\r\n R <- c(R,r)\r\n # 聚类中心\r\n C <- rbind(C,km$centers[i,])\r\n }\r\n }\r\n # 绘制图像\r\n #plot(C,pch=19,col=2,xlim = c(-30,30),ylim = c(-30,30),main = 'Sizeable radiuses(中心筛选前)')\r\n library(plotrix)\r\n for(i in 1:length(R)){\r\n draw.circle(C[i,1],C[i,2],R[i])\r\n }\r\n C <- C[-1,]\r\n COL <- c()\r\n for (i in 1:length(R)) {\r\n for (j in 1:length(R)) {\r\n # 计算Condition1\r\n d_i_j <- sqrt(sum((C[i,] - C[j,])^2))\r\n MIN_i_j <- min(R[i],R[j])\r\n MAX_i_j <- max(R[i],R[j])\r\n Condition1 <- (d_i_j + MIN_i_j < (t * MAX_i_j))\r\n if ((i!=j) && Condition1) {\r\n col <- c(i,j)[which.max(R[c(i,j)])]\r\n COL <- c(COL,col)\r\n }\r\n }\r\n }\r\n COL <- unique(COL)\r\n C <- C[-COL,]\r\n R <- R[-COL]\r\n # 绘制图像\r\n #plot(C,pch=19,col=2,xlim = c(-5,20),ylim = c(-5,20),main = 'Sizeable radiuses(中心筛选后)')\r\n library(plotrix)\r\n for(i in 1:length(R)){\r\n draw.circle(C[i,1],C[i,2],R[i])\r\n }\r\n return(list(C=C,R=R))\r\n}\r\n\r\n# 中心融合——对应2.3中的算法3\r\nCOMBINE <- function(C,R){\r\n L_C <- length(R)\r\n # 生成pointer矩阵\r\n pointer <- matrix(0,nrow = L_C,ncol = L_C)\r\n s <- c()\r\n c_s <- 1:L_C\r\n for(i in 1:L_C){\r\n for(j in 1:L_C){\r\n d_i_j <- sqrt(sum((C[i,1:2] - C[j,1:2])^2))\r\n Condition2 <- d_i_j<(R[i]+R[j])\r\n if((i!=j) & Condition2){\r\n pointer[i,j] <- 1\r\n pointer[j,i] <- 1\r\n }\r\n }\r\n }\r\n k <- 0\r\n while (length(c_s) != 0) {\r\n lst <- RECURSION(pointer,s,c_s,c_s[1])\r\n s <- lst$s\r\n c_s <- lst$c_s\r\n k <- k + 1\r\n }\r\n return(k)\r\n}\r\n\r\n# 递归函数,完成类的寻找工作——对应2.3中的算法4\r\nRECURSION <- function(pointer,s,c_s,ini_co){\r\n corrdin <- which(pointer[ini_co,] == 1)\r\n s <- c(s,ini_co)\r\n c_s <- c_s[which(c_s!=ini_co)]\r\n if(length(corrdin) != 0){\r\n for(i in 1:length(corrdin)){\r\n if(corrdin[i] %in% s){\r\n next\r\n }else{\r\n ini_co <- corrdin[i]\r\n lst <- RECURSION(pointer,s,c_s,ini_co)\r\n s <- lst$s\r\n c_s <- lst$c_s\r\n }\r\n }\r\n }\r\n return(list(s=s,c_s=c_s))\r\n}\r\n\r\n# 定义distance函数,计算类内所有点到聚类中心距离的排序\r\ndist <- function(centers,X){\r\n d <- sqrt(diag((X - centers) %*% t(X - centers)))\r\n return(d)\r\n}\r\n\r\n\r\n######################################################################################\r\n# 生成模拟数据\r\n#####################################################################################\r\n# 导入用到的包\r\nlibrary(MASS)\r\n# 多图绘制\r\npar(mfrow=c(2,2))\r\n# =============================================案例1:三圆环数据=========================================\r\nset.seed(123)\r\nn1 <- 500 # 内部圆的样本点数量\r\nn2 <- 500 # 中间圆环的样本点数量\r\nn3 <- 500 # 外部圆环的样本点数量\r\nX1 <- matrix(nrow = n1,ncol = 2)\r\nmu <- c(0,0)\r\nsigma <- matrix(c(1,0,0,1),nrow = 2,ncol = 2)\r\nfor(i in 1:n1){\r\n x <- mvrnorm(1,mu,sigma)\r\n while(TRUE){\r\n if((x[1]^2 + x[2]^2) >= 0 & (x[1]^2 + x[2]^2) <= 1){\r\n X1[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu,sigma)\r\n } \r\n }\r\n \r\n}\r\n\r\nX2 <- matrix(nrow = n2,ncol = 2)\r\nmu <- c(0,0)\r\nsigma <- matrix(c(9,0,0,9),nrow = 2,ncol = 2)\r\nfor(i in 1:n2){\r\n x <- mvrnorm(1,mu,sigma)\r\n while(TRUE){\r\n if((x[1]^2 + x[2]^2) >= 2 & (x[1]^2 + x[2]^2) <= 3){\r\n X2[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu,sigma)\r\n } \r\n }\r\n}\r\nX3 <- matrix(nrow = n3,ncol = 2)\r\nmu <- c(0,0)\r\nsigma <- matrix(c(36,0,0,36),nrow = 2,ncol = 2)\r\nfor(i in 1:n2){\r\n x <- mvrnorm(1,mu,sigma)\r\n while(TRUE){\r\n if((x[1]^2 + x[2]^2) >= 5 & (x[1]^2 + x[2]^2) <= 6){\r\n X3[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu,sigma)\r\n } \r\n }\r\n}\r\n# 合并数据\r\nX <- rbind(X1,X2,X3)\r\ng <- c(rep(1,n1),rep(2,n2),rep(3,n3))\r\n# 无标签绘图\r\nplot(X,pch=20,col='blue',main='DataSet1',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 有标签绘图\r\nplot(X,col=g,pch=20,main='圆环数据',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 保存数据\r\ndataset1 <- cbind(X,g)\r\ncolnames(dataset1) <- c('X1','X2','g')\r\nwrite.csv(dataset1, 'dataset1.csv', fileEncoding = 'utf-8', row.names = FALSE)\r\n# ============================================案例2:块状数据===============================================\r\nn <- 300\r\nmu1 <- c(0,0)\r\nmu2 <- c(0,-3)\r\nmu3 <- c(3,-3)\r\nmu4 <- c(3,3)\r\nmu5 <- c(-3,3)\r\nsigma <- matrix(c(0.1,0,0,0.1),nrow = 2,ncol = 2)\r\nX1 <- mvrnorm(n,mu1,sigma)\r\nX2 <- mvrnorm(n,mu2,sigma)\r\nX3 <- mvrnorm(n,mu3,sigma)\r\nX4 <- mvrnorm(n,mu4,sigma)\r\nX5 <- mvrnorm(n,mu5,sigma)\r\nX <- rbind(X1,X2,X3,X4,X5)\r\ng <- rep(1:5,each=n)\r\n# 无标签绘图\r\nplot(X,pch=20,col='blue',main='DataSet2',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 有标签绘图\r\nplot(X,col=g,pch=20,main='块状数据',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 保存数据\r\ndataset2 <- cbind(X,g)\r\ncolnames(dataset2) <- c('X1','X2','g')\r\nwrite.csv(dataset2, 'dataset2.csv', fileEncoding = 'utf-8', row.names = FALSE)\r\n# ======================================案例3:块状数据+噪声==================================================\r\nn <- 300\r\nmu1 <- c(0,0)\r\nmu2 <- c(0,-3)\r\nmu3 <- c(3,-2)\r\nmu4 <- c(2,2)\r\nmu5 <- c(-1.5,3)\r\nsigma <- matrix(c(0.1,0,0,0.1),nrow = 2,ncol = 2)\r\nX1 <- mvrnorm(n,mu1,sigma)\r\nX2 <- mvrnorm(n,mu2,sigma)\r\nX3 <- mvrnorm(n,mu3,sigma)\r\nX4 <- mvrnorm(n,mu4,sigma)\r\nX5 <- mvrnorm(n,mu5,sigma)\r\nX <- rbind(X1,X2,X3,X4,X5)\r\ng <- rep(1:5,each=n)\r\nn_noise <- 100\r\nX_noise <- matrix(ncol=2,nrow = n_noise)\r\nfor(i in 1:n_noise){\r\n min_dist <- 0\r\n while(min_dist < 0.5){\r\n noise_x<- runif(1,-4,4)\r\n noise_y <- runif(1,-4,4)\r\n noise_one <- matrix(rep(c(noise_x, noise_y), times=dim(X)[1]), ncol = 2,byrow = TRUE)\r\n min_dist <- min(dist(noise_one, X))\r\n }\r\n X_noise[i,] <- noise_one[1,]\r\n}\r\nX <- rbind(X,X_noise)\r\ng <- c(g,rep(6,n_noise))\r\n# 无标签绘图\r\nplot(X,pch=20,col='blue',main='DataSet3',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 有标签绘图\r\nplot(X,col=g,pch=20,main='带噪声的块状数据',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 保存数据\r\ndataset3 <- cbind(X,g)\r\ncolnames(dataset3) <- c('X1','X2','g')\r\nwrite.csv(dataset3, 'dataset3.csv', fileEncoding = 'utf-8', row.names = FALSE)\r\n# ==========================================案例4:圆弧数据+噪声==============================================\r\nset.seed(123)\r\nn1 <- 1000 # 上圆弧的样本点数量\r\nn2 <- 1000 # 下圆弧的样本点数量\r\nX1 <- matrix(nrow = n1,ncol = 2)\r\nmu <- c(-0.5,0)\r\nsigma <- matrix(c(1,0,0,1),nrow = 2,ncol = 2)\r\nfor(i in 1:n1){\r\n x <- mvrnorm(1,mu,sigma)\r\n while(TRUE){\r\n if(((x[1]+0.5)^2 + x[2]^2) >= 1 & ((x[1]+0.5)^2 + x[2]^2) <= 2 & x[2] > -0.5){\r\n X1[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu,sigma)\r\n } \r\n }\r\n}\r\nX2 <- matrix(nrow = n2,ncol = 2)\r\nmu <- c(0.5,0)\r\nsigma <- matrix(c(1,0,0,1),nrow = 2,ncol = 2)\r\nfor(i in 1:n1){\r\n x <- mvrnorm(1,mu,sigma)\r\n while(TRUE){\r\n if(((x[1]-0.5)^2 + x[2]^2) >= 1 & ((x[1]-0.5)^2 + x[2]^2) <= 2 & x[2] < 0.5){\r\n X2[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu,sigma)\r\n } \r\n }\r\n}\r\n# 合并数据\r\nX <- rbind(X1,X2)\r\ng <- c(rep(1,n1),rep(2,n2))\r\n# 噪声数据\r\nn_noise <- 100\r\nX_noise <- matrix(ncol=2,nrow = n_noise)\r\nfor(i in 1:n_noise){\r\n min_dist <- 0\r\n while(min_dist < 0.1){\r\n noise_x<- runif(1,-2,2)\r\n noise_y <- runif(1,-2,2)\r\n noise_one <- matrix(rep(c(noise_x, noise_y), times=dim(X)[1]), ncol = 2,byrow = TRUE)\r\n min_dist <- min(dist(noise_one, X))\r\n }\r\n X_noise[i,] <- noise_one[1,]\r\n}\r\nX <- rbind(X,X_noise)\r\ng <- c(g,rep(3,n_noise))\r\n# 无标签绘图\r\nplot(X,pch=20,col='blue',main='DataSet4',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 有标签绘图\r\nplot(X,col=g,pch=20,main='带噪声的弧形数据',xlab = expression(X[1]),ylab=expression(X[2]))\r\n# 保存数据\r\ndataset4 <- cbind(X,g)\r\ncolnames(dataset4) <- c('X1','X2','g')\r\nwrite.csv(dataset4, 'dataset4.csv', fileEncoding = 'utf-8', row.names = FALSE)\r\n\r\n\r\n# ==========================================案例3:混合数据+噪声==============================================\r\nset.seed(123)\r\nn1 <- 300 # 左边块的样本点数量\r\nn2 <- 200 # 右边块的样本点数量\r\nn3 <- 1000 # 圆弧的样本点数量\r\n# 生成左边的块\r\nX1 <- matrix(nrow = n1,ncol = 2)\r\nmu1 <- c(-2,2)\r\nsigma1 <- matrix(c(0.2,0,0,0.2),nrow = 2,ncol = 2)\r\nX1 <- mvrnorm(n1,mu1,sigma1)\r\n# 生成右边的块\r\nX2 <- matrix(nrow = n2,ncol = 2)\r\nmu2 <- c(2,2)\r\nsigma2 <- matrix(c(0.2,0,0,0.2),nrow = 2,ncol = 2)\r\nX2 <- mvrnorm(n2,mu2,sigma2)\r\n# 生成圆弧\r\nX3 <- matrix(nrow = n3,ncol = 2)\r\nmu3 <- c(0,0)\r\nsigma3 <- matrix(c(3,0,0,3),nrow = 2,ncol = 2)\r\nfor(i in 1:n3){\r\n x <- mvrnorm(1,mu3,sigma3)\r\n while(TRUE){\r\n if(((x[1])^2 + x[2]^2) >= 1 & ((x[1])^2 + x[2]^2) <= 1.5 & x[2] <= 0){\r\n X3[i,] <- x\r\n break()\r\n }else{\r\n x <- mvrnorm(1,mu3,sigma3)\r\n } \r\n }\r\n}\r\n# 添加噪声\r\nn_noise <- 40\r\nX_noise <- matrix(ncol=2,nrow = n_noise)\r\nfor(i in 1:n_noise){\r\n min_dist <- 0\r\n while(min_dist < 0.1){\r\n noise_x<- runif(1,-2,2)\r\n noise_y <- runif(1,-2,2)\r\n noise_one <- matrix(rep(c(noise_x, noise_y), times=dim(X)[1]), ncol = 2,byrow = TRUE)\r\n min_dist <- min(dist(noise_one, X))\r\n }\r\n X_noise[i,] <- noise_one[1,]\r\n}\r\n\r\n\r\n\r\nX <- rbind(X1,X2, X3,X_noise)\r\nplot(X,pch=20,col='blue',main='DataSet4',xlab = expression(X[1]),ylab=expression(X[2]))\r\n\r\n\r\n\r\n\r\n#################################################################################\r\n# 利用各种方法进行聚类\r\n#################################################################################\r\n# 绘制聚类结果图\r\nplot_clustering <- function(X, res, main){\r\n pch_set=c(1,2,3,5,7,8,9)\r\n plot(X[,1], X[,2],xlab = expression(X[1]),ylab=expression(X[2]),main=main, col='white')\r\n for(i in 1:length(res_grid_svm_knn)){\r\n if(res[i] == 0){\r\n points(x = X[i,1], y = X[i,2], col=res[i]+1, pch=15)\r\n }else{\r\n points(x = X[i,1], y = X[i,2], col=res[i]+1, pch=pch_set[res[i]])\r\n }\r\n }\r\n}\r\n\r\n# 加载一些包\r\nlibrary(fpc)\r\nlibrary(dbscan)\r\nlibrary(ellipse)\r\nX <- dataset1[,1:2]; g <- dataset1[,3]\r\n# X <- dataset2[,1:2]; g <- dataset2[,3]\r\n# X <- dataset3[,1:2]; g <- dataset3[,3]\r\n# X <- dataset4[,1:2]; g <- dataset4[,3]\r\n# grid_SVM_knn\r\nres_grid_svm_knn <- grid_svm_knn(X, gamma=10 ,cost=10, k=18, Index1=1213) # dataset1\r\n#res_grid_svm_knn <- grid_svm_knn(X, gamma=5 ,cost=0.36, k=18, Index1=1)\r\nres_grid_svm_knn <- grid_svm_knn(X, gamma=20,cost=0.01, k=18, Index1=1213)\r\nres_grid_svm_knn <- grid_svm_knn(X, gamma=10, cost=0.02265, k=25, Index1=1213)\r\nres_grid_svm_knn <- grid_svm_knn(X, gamma=10, cost=0.023, k=18, Index1=1213)\r\n# 绘制聚类结果\r\nplot_clustering(X, res_grid_svm_knn, 'DataSet1')\r\n# dbscan\r\nkNNdistplot(X,k = 20) # 找最优eps\r\nres_db <- dbscan(X,eps=0.2,minPts=8)\r\nres_db <- res_db$cluster\r\nplot_clustering(X, res_db, 'DataSet4聚类效果图')\r\n# DP-Kmeans\r\nres_DP_Kmeans <- Radius.KMeans(X,1213,q=0.5,t=1.2)\r\nres_DP_Kmeans <- res_DP_Kmeans$km$cluster\r\nplot_clustering(X, res_DP_Kmeans,'DataSet4聚类效果图')\r\n# 汇总上面的结果并保存\r\nres1 <- cbind(res_grid_svm_knn, res_db, res_DP_Kmeans)\r\nwrite.csv(res1, 'res1.csv', row.names = FALSE, fileEncoding = 'utf-8')\r\n\r\nres2 <- cbind(res_grid_svm_knn, res_db, res_DP_Kmeans)\r\nwrite.csv(res2, 'res2.csv', row.names = FALSE, fileEncoding = 'utf-8')\r\n\r\nres3 <- cbind(res_grid_svm_knn, res_db, res_DP_Kmeans)\r\nwrite.csv(res3, 'res3.csv', row.names = FALSE, fileEncoding = 'utf-8')\r\n\r\nres4 <- cbind(res_grid_svm_knn, res_db, res_DP_Kmeans)\r\nwrite.csv(res4, 'res4.csv', row.names = FALSE, fileEncoding = 'utf-8')\r\n# birch用python处理\r\n\r\n\r\n# 解除多图绘制\r\npar(mfrow=c(1,1))\r\n###############################################################################\r\n# 聚类效果评估\r\n###############################################################################\r\nlibrary(NMI)\r\nNMI(res_db$cluster, g)\r\n\r\n\r\n\r\n\r\n\r\n###############################################################################\r\n# 对算法的时间复杂度进行分析\r\n###############################################################################\r\nlibrary(MASS)\r\ncreate_data <- function(n){\r\n n <- n/2\r\n mu1 <- c(0,2)\r\n mu2 <- c(0,-2)\r\n sigma <- matrix(c(0.1,0,0,0.1),nrow = 2,ncol = 2)\r\n X1 <- mvrnorm(n,mu1,sigma)\r\n X2 <- mvrnorm(n,mu2,sigma)\r\n X <- rbind(X1,X2)\r\n return(X)\r\n}\r\nX <- create_data(500)\r\n# 无标签绘图\r\nplot(X,pch=20,col='blue',xlab = expression(X[1]),ylab=expression(X[2]))\r\nres_grid_svm_knn <- grid_svm_knn(X, gamma=1,cost=1, k=5, Index1=1213)\r\n\r\n# 随n增大的时间消耗情况\r\nn_set <- (1:20)*50\r\ntime_set <- matrix(nrow = length(n_set), ncol = 1)\r\nfor(i in 1:length(n_set)){\r\n print(i)\r\n n <- n_set[i]\r\n X <- create_data(n)\r\n t1 <- proc.time()\r\n res_grid_svm_knn <- grid_svm_knn(X, gamma=1,cost=1, k=5, Index1=1213)\r\n t2 <- proc.time()\r\n t <- t2 - t1\r\n time_set[i] <- t[3][[1]]\r\n}\r\nplot(x = n_set, y = time_set, type = 'b', main='the influence of n to running time', ylab = 'Time', xlab='n')\r\n\r\n# 随k增大的时间消耗情况\r\ntime_set <- matrix(nrow = length(k_set), ncol = 10)\r\nfor(j in 1:10){\r\n k_set <- 5:30\r\n for(i in 1:length(k_set)){\r\n print(paste0('正在处理 行',i,' 列',j))\r\n k <- k_set[i]\r\n X <- create_data(1000)\r\n t1 <- proc.time()\r\n res_grid_svm_knn <- grid_svm_knn(X, gamma=1,cost=1, k=k, Index1=1213)\r\n t2 <- proc.time()\r\n t <- t2 - t1\r\n time_set[i,j] <- t[3][[1]]\r\n }\r\n}\r\ntime_set_mean <- apply(time_set, 1, mean)\r\nplot(x = k_set, y = time_set_mean, type = 'b', main='the influence of k to running time', ylab = 'Time', xlab='k')\r\n\r\n\r\nk_set <- 1:30\r\ntime_set1 <- matrix(nrow = length(k_set), ncol = 1)\r\nfor(i in 1:length(k_set)){\r\n print(paste0('正在处理 行',i))\r\n k <- k_set[i]\r\n set.seed(1213)\r\n X <- create_data(2000)\r\n t1 <- proc.time()\r\n res_grid_svm_knn <- grid_svm_knn(X, gamma=1,cost=1, k=k, Index1=1213)\r\n t2 <- proc.time()\r\n t <- t2 - t1\r\n time_set1[i] <- t[3][[1]]\r\n}\r\nplot(x = k_set, y = time_set1, type = 'b', main='the influence of k to running time', ylab = 'Time', xlab='k')\r\n\r\n\r\n# 随gamma增大的时间消耗情况\r\ngamma_set <- 10**(-6:6)\r\ntime_set <- matrix(nrow = length(gamma_set), ncol = 1)\r\nfor(i in 1:length(gamma_set )){\r\n print(i)\r\n gamma <- gamma_set[i]\r\n X <- create_data(1000)\r\n t1 <- proc.time()\r\n res_grid_svm_knn <- grid_svm_knn(X, gamma=gamma,cost=1, k=20, Index1=1213)\r\n t2 <- proc.time()\r\n t <- t2 - t1\r\n time_set[i] <- t[3][[1]]\r\n}\r\nplot(x = gamma_set, y = time_set, type = 'b', main='gamma对算法运行时间的影响', ylab = '消耗时间', xlab='gamma')\r\n\r\n\r\n# 随cost增大的时间消耗情况\r\ncost_set <- 10**(-4:4)\r\ntime_set <- matrix(nrow = length(cost_set), ncol = 1)\r\nfor(i in 1:length(cost_set )){\r\n print(i)\r\n cost <- cost_set[i]\r\n X <- create_data(3000)\r\n t1 <- proc.time()\r\n res_grid_svm_knn <- grid_svm_knn(X, gamma=1,cost=cost, k=20, Index1=1213)\r\n t2 <- proc.time()\r\n t <- t2 - t1\r\n time_set[i] <- t[3][[1]]\r\n}\r\nplot(x = cost_set, y = time_set, type = 'b', main='cost对算法运行时间的影响', ylab = '消耗时间', xlab='cost')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "16d1ed50cddac92797db600fdd340428df124a2f", "size": 24643, "ext": "r", "lang": "R", "max_stars_repo_path": "RGBASK.r", "max_stars_repo_name": "Auzzer/RGBASK", "max_stars_repo_head_hexsha": "762b828fec3e4ef09d29167398df7c5b8e28e211", "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": "RGBASK.r", "max_issues_repo_name": "Auzzer/RGBASK", "max_issues_repo_head_hexsha": "762b828fec3e4ef09d29167398df7c5b8e28e211", "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": "RGBASK.r", "max_forks_repo_name": "Auzzer/RGBASK", "max_forks_repo_head_hexsha": "762b828fec3e4ef09d29167398df7c5b8e28e211", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9428918591, "max_line_length": 115, "alphanum_fraction": 0.5098811021, "num_tokens": 8965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44793890167311246}}
{"text": "library (gsubfn) \nsetwd('C:/Users/midingoy/Documents/crop2mlcatalog/SQ_Energy_Balance/src/r')\nsource('Netradiation.r')\nsource('Netradiationequivalentevaporation.r')\nsource('Priestlytaylor.r')\nsource('Conductance.r')\nsource('Diffusionlimitedevaporation.r')\nsource('Penman.r')\nsource('Ptsoil.r')\nsource('Soilevaporation.r')\nsource('Evapotranspiration.r')\nsource('Soilheatflux.r')\nsource('Potentialtranspiration.r')\nsource('Cropheatflux.r')\nsource('Canopytemperature.r')\n\nmodel_energybalance <- 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 lambdaV = 2.454,\n hslope = 0.584,\n psychrometricConstant = 0.66,\n Alpha = 1.5,\n vonKarman = 0.42,\n heightWeatherMeasurements = 2.0,\n zm = 0.13,\n d = 0.67,\n zh = 0.013,\n plantHeight = 0.0,\n wind = 124000.0,\n deficitOnTopLayers = 5341.0,\n soilDiffusionConstant = 4.2,\n VPDair = 2.19,\n rhoDensityAir = 1.225,\n specificHeatCapacityAir = 0.00101,\n tau = 0.9983,\n tauAlpha = 0.3,\n isWindVpDefined = 1){\n #'- Name: EnergyBalance -Version: 001, -Time step: 1\n #'- Description:\n #' * Title: EnergyBalance\n #' * Author: Pierre MARTRE\n #' * Reference: Modelling energy balance in the wheat crop model SiriusQuality2: Evapotranspiration and canopy and soil temperature calculations\n #' * Institution: INRA/LEPSE\n #' * ExtendedDescription: see documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * ShortDescription: This component calculates the canopy temperature and energy balance\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 #' * 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: hslope\n #' ** description : the slope of saturated vapor pressure temperature curve at a given temperature \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.584\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : hPa °C-1\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: psychrometricConstant\n #' ** description : psychrometric constant\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.66\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\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: vonKarman\n #' ** description : von Karman constant\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0.42\n #' ** unit : dimensionless\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' * name: heightWeatherMeasurements\n #' ** description : reference height of wind and humidity measurements\n #' ** parametercategory : soil\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10\n #' ** default : 2\n #' ** unit : m\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: zm\n #' ** description : roughness length governing momentum transfer, FAO\n #' ** parametercategory : constant\n #' ** inputtype : parameter\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0.13\n #' ** unit : m\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: d\n #' ** description : corresponding to 2/3. This is multiplied to the crop heigth for calculating the zero plane displacement height, FAO\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.67\n #' ** min : 0\n #' ** max : 1\n #' ** unit : dimensionless\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547rl\n #' * name: zh\n #' ** description : roughness length governing transfer of heat and vapour, FAO\n #' ** parametercategory : constant\n #' ** inputtype : parameter\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0.013\n #' ** unit : m\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: plantHeight\n #' ** description : plant Height\n #' ** datatype : DOUBLE\n #' ** default : 0\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : mm\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' * name: wind\n #' ** description : wind\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 124000\n #' ** min : 0\n #' ** max : 1000000\n #' ** unit : m/d\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\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 #' * name: VPDair\n #' ** description : vapour pressure density\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 2.19\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: rhoDensityAir\n #' ** description : Density of air\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 1.225\n #' ** unit : \n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : parameter\n #' * name: specificHeatCapacityAir\n #' ** description : Specific heat capacity of dry air\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.00101\n #' ** min : 0\n #' ** max : 1\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 #' * name: isWindVpDefined\n #' ** description : if wind and vapour pressure are defined\n #' ** parametercategory : constant\n #' ** datatype : INT\n #' ** default : 1\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: 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 #' * 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 #' * name: evapoTranspirationPriestlyTaylor\n #' ** description : evapoTranspiration of Priestly Taylor \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 #' * 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 #' * 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 #' * name: conductance\n #' ** description : the boundary layer conductance\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : m/d\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: evapoTranspirationPenman\n #' ** description : evapoTranspiration of Penman Monteith\n #' ** variablecategory : rate\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 #' * name: soilEvaporation\n #' ** description : soil 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 #' * name: evapoTranspiration\n #' ** description : evapoTranspiration\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : mm\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: potentialTranspiration\n #' ** description : potential Transpiration \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 #' * 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 #' * name: cropHeatFlux\n #' ** description : crop 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 #' * name: minCanopyTemperature\n #' ** description : minimal Canopy Temperature \n #' ** datatype : DOUBLE\n #' ** variablecategory : state\n #' ** min : -30\n #' ** max : 45\n #' ** unit : degC\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' * name: maxCanopyTemperature\n #' ** description : maximal Canopy Temperature \n #' ** datatype : DOUBLE\n #' ** variablecategory : state\n #' ** min : -30\n #' ** max : 45\n #' ** unit : degC\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n list[netRadiation, netOutGoingLongWaveRadiation] <- model_netradiation(minTair, maxTair, albedoCoefficient, stefanBoltzman, elevation, solarRadiation, vaporPressure, extraSolarRadiation)\n conductance <- model_conductance(vonKarman, heightWeatherMeasurements, zm, zh, d, plantHeight, wind)\n diffusionLimitedEvaporation <- model_diffusionlimitedevaporation(deficitOnTopLayers, soilDiffusionConstant)\n netRadiationEquivalentEvaporation <- model_netradiationequivalentevaporation(lambdaV, netRadiation)\n evapoTranspirationPriestlyTaylor <- model_priestlytaylor(netRadiationEquivalentEvaporation, hslope, psychrometricConstant, Alpha)\n energyLimitedEvaporation <- model_ptsoil(evapoTranspirationPriestlyTaylor, Alpha, tau, tauAlpha)\n evapoTranspirationPenman <- model_penman(evapoTranspirationPriestlyTaylor, hslope, VPDair, psychrometricConstant, Alpha, lambdaV, rhoDensityAir, specificHeatCapacityAir, conductance)\n soilEvaporation <- model_soilevaporation(diffusionLimitedEvaporation, energyLimitedEvaporation)\n evapoTranspiration <- model_evapotranspiration(isWindVpDefined, evapoTranspirationPriestlyTaylor, evapoTranspirationPenman)\n soilHeatFlux <- model_soilheatflux(netRadiationEquivalentEvaporation, tau, soilEvaporation)\n potentialTranspiration <- model_potentialtranspiration(evapoTranspiration, tau)\n cropHeatFlux <- model_cropheatflux(netRadiationEquivalentEvaporation, soilHeatFlux, potentialTranspiration)\n list[minCanopyTemperature, maxCanopyTemperature] <- model_canopytemperature(minTair, maxTair, cropHeatFlux, conductance, lambdaV, rhoDensityAir, specificHeatCapacityAir)\n return (list (\"netRadiation\" = netRadiation,\"netOutGoingLongWaveRadiation\" = netOutGoingLongWaveRadiation,\"netRadiationEquivalentEvaporation\" = netRadiationEquivalentEvaporation,\"evapoTranspirationPriestlyTaylor\" = evapoTranspirationPriestlyTaylor,\"diffusionLimitedEvaporation\" = diffusionLimitedEvaporation,\"energyLimitedEvaporation\" = energyLimitedEvaporation,\"conductance\" = conductance,\"evapoTranspirationPenman\" = evapoTranspirationPenman,\"soilEvaporation\" = soilEvaporation,\"evapoTranspiration\" = evapoTranspiration,\"potentialTranspiration\" = potentialTranspiration,\"soilHeatFlux\" = soilHeatFlux,\"cropHeatFlux\" = cropHeatFlux,\"minCanopyTemperature\" = minCanopyTemperature,\"maxCanopyTemperature\" = maxCanopyTemperature))\n}", "meta": {"hexsha": "8da8b7d6f02c99322fb56779ae52c768d8b02d73", "size": 26861, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Energy_Balance/EnergyBalanceComponent.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/EnergyBalanceComponent.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/EnergyBalanceComponent.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": 58.9057017544, "max_line_length": 729, "alphanum_fraction": 0.3968951268, "num_tokens": 5637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.4475874731697747}}
{"text": "## Funciones\n\n# La creación de funciones es la principal utilidad de un lenguaje programado,\n# aún en un lenguaje orientado a la estadística como R. Anteriormente nos\n# ocupamos de distintos tipos de objeto que podemos encontrar en R. En la pre-\n# sente unidad nos dedicaremos a la comprensión de la estructura y funcionamien-\n# to de las funciones, así como a la creación y corrección de las mismas.\n\n## ¿Para qué hacer funciones?\n\n# El primer motivo que encontramos para escribir funciones es la practicidad.\n# Esto es cierto en situaciones en las que se debe realizar un procedimiento\n# que requiere la ejecución de comandos en un orden específico, o volver a eje-\n# cutar una serie de comandos que nos quedó muy atrás en el historial y sabemos\n# que los vamos a tener que utilizar nuevamente. En casos como estos, puede\n# ahorrarnos tiempo y esfuerzo escribir una función que contenga estos pasos y\n# que podamos utilizar una y otra vez. Un ejemplo claro de esto es la función\n# 'sort', que ejecuta las instrucciones necesarias para ordenar un vector.\n\nx <- sample(1:15) # Si generamos un vector muestreando los valores de 1 a 15\nsort (x) # la ejecución de 'sort' nos devuelve este vector ordenado.\n\n# Dentro de esta función están las instrucciones necesarias para realizar la\n# tarea, y que se ejecutarán sin necesidad de hacerlo paso a paso.\n\nsort\n\n# Más adelante volveremos sobre la estructura de las funciones, su anatomía,\n# para entender qué exactamente es cada uno de sus componentes.\n\n# El segundo motivo, que se desprende del anterior, es la generalización.\n# Muchas veces vamos a generar una función para atender a un caso particular,\n# a un determinado set de datos o situación. Sin embargo, en la medida en que\n# las funciones que escribimos nos resulten útiles, es importante poder pasar\n# de su aplicabilidad a valores fijos a utilizar variables que podamos modificar\n# en cada caso. Veamos un ejemplo, en la creación de una función que nos permita\n# calcular el área de un triángulo.\n\n# El problema planteado es el área de un triángulo que presenta 3 cm de base y\n# 4 de altura. La forma más sencilla de estimar la misma es, directamente,\n\n4 * 3 / 2\n\n# Sin embargo, si necesitamos hallar el área de varios triángulos, podemos crear\n# la función 'area', utilizando base y altura como variables.\n\narea <- function(a, b) {\n a * b / 2\n}\n\narea (4, 3) # Podemos usarla con las medidas de nuestro triángulo\narea (12, 10) # o de cualquier otro.\n\n# En este caso, es muy sencillo entender que se pasó del caso particular de un\n# par de valores de base y altura a una función que corre para cualquier par de\n# valores. En este sentido, la abstracción es similar a lo que uno ve en las\n# matemáticas, en el sentido de pasar de valores particulares a símbolos que\n# pueden ser sustituidos en una ecuación por valores conocidos, logrando poder\n# aplicar la función a cualquier situación similar.\n\n# Otro ejemplo más ilustrativo puede ser el siguiente: teniendo un vector `x` de\n# 15 elementos, podemos calcular su promedio de la siguiente manera:\n\nx <- rpois(15, 4)\np <- sum(x) / 15\np\n\n# Este código sólo sirve para `x` u otro vector con 15 elementos. Si queremos\n# adaptar este código para calcular el promedio de cualquier vector, indepen-\n# dientemente de su longitud, vamos a tener que sustituir este valor por la\n# longitud de un vector genérico, empleando `length(x)`.\n\np <- sum(x) / length(x)\n\n# En este caso, aún sin crear una función, hemos ganado en abstracción, ya que\n# salimos del caso concreto en el que `x` tiene 15 elementos y ahora podemos\n# utilizar esta línea de código para hacerlo para cualquier vector `x` posible.\n# Pero aún dependemos de esta línea de comando, que podemos haber olvidado o\n# puede haber quedado muy atrás en el historial y volver a encontrarla para\n# ejecutarla puede ser un derroche de tiempo y esfuerzo. Sin mencionar que el\n# vector tiene necesariamente que llamarse `x` para que funcione. En este caso\n# puede ser más sencillo crear una función que haga la operación deseada.\n\nf <- function(v) {\n p <- sum(v) / length(v)\n p\n}\n\nf(rpois(19, 23)) # Y sabemos que devuelve un resultado para cualquier vector\n\n# Si bien puede parecer un derroche crear una función para una operación tan\n# sencilla. Esto es cierto, pero también debe tenerse en cuenta que se pueden agregar nuevas\n# capacidades y detalles a la función, consideremos la situación en que nuestro vector \n# presenta NAs:\n\nx <- rpois(20, 10)\nx[c(3, 6, 7)] <- NA\nf(x)\n\n# En tal caso, deberemos agregar un comando para descartar dichos valores en la\n# propia función, por ejemplo creando un objeto 'v' dentro de la misma que sea\n# nuestro vector sin los NAs.\n\nf <- function(v) {\n v <- v[!is.na(v)]\n p <- sum(v) / length(v)\n p\n}\n\nf(x)\n\n# Como último detalle, no es necesario que las funciones representen una\n# abstracción o generalización de una operación a partir de un caso concreto.\n# Es posible crear funciones sin argumentos, cosas tan simples como:\n\ng <- function() print(\"Hola mundo\")\ng()\n\n# En la próxima lección exploraremos los componentes que hacen a las funciones,\n# en una suerte de lección de anatomía de las mismas.\n", "meta": {"hexsha": "52043f78720d3d177950f40c2128bff0f5206462", "size": 5149, "ext": "r", "lang": "R", "max_stars_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.1-para-que-escribir-funciones.r", "max_stars_repo_name": "jcombari/Data-products-Course-Project", "max_stars_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.1-para-que-escribir-funciones.r", "max_issues_repo_name": "jcombari/Data-products-Course-Project", "max_issues_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.1-para-que-escribir-funciones.r", "max_forks_repo_name": "jcombari/Data-products-Course-Project", "max_forks_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5537190083, "max_line_length": 92, "alphanum_fraction": 0.7582054768, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.4473183113001273}}
{"text": "#' Calibrate a single station metabolism model\n#' @param oxy Dissolved oxygen time series (g/L)\n#' @param temp Water temperature time series (degrees); one per DO observation\n#' @param light Light, (lux or W/m^2); one per DO observation\n#' @param pressure Air pressure (hPa); single value or one per DO observation\n#' @param depth Water depth, in meters\n#' @param dt Time interval of observations (minutes)\n#' @param nsamples The number of posterior samples to return\n#' @param prior Priors for the function chosenl, see 'details'\n#' @param ... Additional arguments to pass to the rstan\n#' \n#' @details Implements a one-station stream metaoblism model; much code from Fuß et al 2017. \n#' \n#' This model requires that the observations consist of a single 24-hour period. Start time\n#' may be arbitrary, as long as an entire 24-hours is covered. No checking is done for this, \n#' it is up to the user to ensure this is correct.\n#' \n#' For a prior, you may specify a named list, with each item a vector of parameters to use for\n#' the prior. Currently, the following parameters are supported:\n#' * lp1: the log of the inverse of the slope of the photosynthesis-irradiance curve; default \n#' \t\t`c(0, 9)`.\n#' * lp2: the log of the saturation term of the photosynthesis-irradiance curve; default \n#' \t\t`c(0, 9)`.\n#' * k: gas transfer velocity, default c(0, 10)\n#' * gpp: daily gross primary productivity, default c(0, 10)\n#' * er: daily in-situ ecosystem respiration, default c(0, 10) (note first item must be <= 0)\n#' \n#' Priors all use a half normal distribution. \n#' @references Fuß, T. et al. (2017). Land use controls stream ecosystem metabolism by shifting\n#' \t\t dissolved organic matter and nutrient regimes. *Freshw Biol* **62**:582–599. \n#' @return A fitted rstan model\n#' @export\nonestation <- function(oxy, temp, light, pressure, depth, dt, \n\tnsamples = 1000, prior = list(), ...) {\n\n\t# basic input validation\n\tif(length(oxy) != length(temp) | length(oxy) != length(light))\n\t\tstop(\"oxy, light, and temp must have the same length\")\n\tif(length(pressure) == 1)\n\t\tpressure = rep(pressure, length(oxy))\n\tif(length(oxy) != length(pressure))\n\t\tstop(\"length(pressure) must be 1 or equal to length(oxy)\")\n\n\tif(! \"lp1\" %in% prior)\n\t\tprior$lp1 <- c(0,9)\n\tif(! \"lp2\" %in% prior)\n\t\tprior$lp2 <- c(0,9)\n\tif(! \"k\" %in% prior)\n\t\tprior$k = c(0, 10)\n\tif(! \"gpp\" %in% prior)\n\t\tprior$gpp = c(0, 10)\n\tif(! \"er\" %in% prior)\n\t\tprior$er = c(0, 10)\n\n\tdata = list(\n\t\tnDO = length(oxy), \n\t\tDO = oxy,\n\t\ttemp = temp,\n\t\tlight = light,\n\t\tpressure = pressure,\n\t\tdepth = depth,\n\t\tdelta_t = dt,\n\t\tlp1_pr = prior$lp1,\n\t\tlp2_pr = prior$lp2,\n\t\tk_pr = prior$k,\n\t\tgpp_pr = prior$gpp,\n\t \ter_pr = prior$er)\n\n\tfile = system.file(\"stan/onestation.stan\", package=\"NSmetabolism\")\n\tmodcode = rstan::stanc_builder(file = file)\n\tmod = rstan::stan_model(stanc_ret = modcode)\n\tcalib = rstan::sampling(mod, data = data, iter = nsamples, ...)\n\treturn(calib)\n}\n\n", "meta": {"hexsha": "3fa152c390e3465af7cb13b6a5f7a145fdfe8ea3", "size": 2914, "ext": "r", "lang": "R", "max_stars_repo_path": "R/calibration.r", "max_stars_repo_name": "mtalluto/NSmetabolism", "max_stars_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/calibration.r", "max_issues_repo_name": "mtalluto/NSmetabolism", "max_issues_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/calibration.r", "max_forks_repo_name": "mtalluto/NSmetabolism", "max_forks_repo_head_hexsha": "1b179726cd1968f9562236799a82104ed5957d81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3421052632, "max_line_length": 95, "alphanum_fraction": 0.6839396019, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.44607942502076336}}
{"text": "probitKDH<-function(minimal_data,num_cat,num_cont, returned_iters = 500, burn = 25, prior_var = 10)\r\n{\r\n\tintvar = groupvar = one_way_var = two_way_var = cont_var = prior_var\r\n\t\r\n #numper of iterations the sampler will have to run\r\n iters=burn+returned_iters\r\n #create lm formula to fit frequentist model (and the model matrix)\r\n \r\n \r\n minimal_data[ ,2] = as.factor(minimal_data[ ,2])\r\n \r\n \r\n namer=paste0(names(minimal_data)[3:(3+num_cat-1)],sep=\"+\",collapse = \"\")\r\n namer=substr(namer,1,nchar(namer)-1)\r\n formulaa=paste(names(minimal_data)[1],'~',names(minimal_data)[2],\"+ (\",namer,\")^2\")\r\n #handle continuous\r\n if(num_cont>0)\r\n {\r\n cont_addition=paste0(names(minimal_data)[(3+num_cat):length(names(minimal_data))],sep=\"+\",collapse = \"\")\r\n cont_addition=substr(cont_addition,1,nchar(cont_addition)-1)\r\n formulaa=paste(formulaa,'+',cont_addition)\r\n }\r\n if(num_cat+num_cont<1)\r\n {\r\n formulaa=paste0(names(minimal_data)[1],'~',names(minimal_data)[2])\r\n }\r\n frequentist_model=glm(formula(formulaa),family=binomial(link=\"logit\"),data=minimal_data)\r\n \r\n \r\n\r\n \r\n #extract the parameter estimates for the hospitals / subunits, hard code first to zero to take into account reference level\r\n ests=c(0,coefficients(frequentist_model)[which(substr(names(coefficients(frequentist_model)),1,6)==names(minimal_data)[2])])\r\n \r\n\r\n \r\n #same for covariance\r\n covv=vcov(frequentist_model)[1:(length(ests)),1:(length(ests))]\r\n covv[1,]=0\r\n covv[,1]=0\r\n \r\n #reparameterize as described in D-G paper\r\n xform_mat=diag(1,length(ests))-replicate(length(ests),table(minimal_data[,2]))/sum(table(minimal_data[,2]))\r\n new_ests=c(ests%*%xform_mat)\r\n new_cov_mat=t(xform_mat)%*%covv%*%xform_mat\r\n z_frequentist=new_ests/sqrt(diag(new_cov_mat))\r\n \r\n #bayesian model, first extract model matrix\r\n xx=model.matrix(frequentist_model)\r\n yy=as.numeric(as.character(eval(parse(text=paste0(\"minimal_data$\",fun=names(minimal_data)[1])))))\r\n num_group_coef=length(table(minimal_data[,2]))-1\r\n \r\n num_2way=dim(xx)[2]-dim(model.matrix(glm(gsub(\"^2\",'',formulaa,fixed=TRUE),family=binomial(link=\"logit\"),data=minimal_data)))[2]\r\n num_1way=dim(xx)[2]-(1+num_group_coef+num_2way+num_cont)\r\n n=length(yy)\r\n p=dim(xx)[2]\r\n \r\n #create limits for the gibbs sampler truncated normals\r\n lower=rep(-Inf,n)*(-(yy-1))\r\n lower[is.nan(lower)]<-0\r\n upper=rep(Inf,n)*yy\r\n upper[is.nan(upper)]<-0\r\n \r\n #initialize storage and get initial values\r\n mcmc_betas=matrix(0,iters,p)\r\n mcmc_betas[1,]=coefficients(frequentist_model)\r\n colnames(mcmc_betas)=names(coefficients(frequentist_model))\r\n mcmc_latent=truncnorm::rtruncnorm(n,lower,upper,xx%*%mcmc_betas[1,])\r\n\r\n #priors, specified by macro\r\n priormean=rep(0,p)\r\n priorcov=c(rep(intvar,1),rep(groupvar,num_group_coef),rep(one_way_var,num_1way),rep(two_way_var,num_2way))\r\n if(num_cont>0)\r\n {\r\n priorcov=c(priorcov,rep(cont_var,num_cont))\r\n }\r\n \r\n \r\n mcmc_betas = probitFit(yy, xx, priorcov,\r\n\titers = returned_iters + burn)[-(1:burn), ]\r\n \r\n \r\n \r\n # #pre calculate some stuff from data to make regression faster\r\n # XpX=crossprod(xx)\r\n # IR=backsolve(chol(XpX/1+diag(1/priorcov)),diag(p))\r\n # sigmasq=1\r\n \r\n # #MCMC: probit gibbs\r\n # for(i in 2:iters)\r\n # {\r\n # #first perform regression on latent normals\r\n # Xpy=crossprod(xx, as.matrix(mcmc_latent))\r\n # btilde=crossprod(t(IR))%*%(Xpy/sigmasq+diag(1/priorcov)%*%priormean)\r\n # mcmc_betas[i,] = t(replicate(1,as.vector(btilde))) + rnorm(p)%*%t(IR)\r\n # #then conditional on the regression coefficients, generate truncated normals\r\n # mcmc_latent=truncnorm::rtruncnorm(n,lower,upper,xx%*%mcmc_betas[i,])\r\n # }\r\n # #delete burn in section\r\n # mcmc_betas=mcmc_betas[(burn+1):iters,]\r\n #now reparameterize for d-g paper, but using the bayesian estimate of the covariance of the coefficients\r\n \r\n #estimate of covariance between the subunits, last row is all zero for effect coded category\r\n covv=cov(mcmc_betas)[1:(length(ests)),1:(length(ests))]\r\n covv[1,]=0\r\n covv[,1]=0\r\n \r\n #calculate new xform and covariance matrix to reparameterize\r\n xform_mat=diag(1,length(ests))-replicate(length(ests),table(minimal_data[,2]))/sum(table(minimal_data[,2]))\r\n new_cov_mat=t(xform_mat)%*%covv%*%xform_mat\r\n\r\n #extract the coefficients for the subunits\r\n tempp=(mcmc_betas[,1:length(ests)])\r\n #code first to zero for our dummy coded category\r\n tempp[,1]=0\r\n #uncertainty bands for our z scores plus a point estimate at the median\r\n est_matrix=tempp%*%xform_mat\r\n z_mat=est_matrix%*%diag(sqrt(1/(diag(new_cov_mat))))\r\n bayesian_z_ests=cbind(group_label=names(table(minimal_data[,2])),z_score=apply(z_mat, 2, quantile, probs = c(.5), na.rm = TRUE))\r\n colnames(est_matrix)=paste0(\"group_\",names(table(minimal_data[,2])))\r\n \r\n #create data to return\r\n returner=list(\r\n column_names=names(minimal_data)[1],\r\n mcmc_betas=mcmc_betas,\r\n z_matrix=z_mat,\r\n frequentist_model=frequentist_model,\r\n z_frequentist=z_frequentist,\r\n minimal_dataset=minimal_data,\r\n regression_formula=formulaa,\r\n bayesian_z_ests=bayesian_z_ests,\r\n group_labels=names(table(minimal_data[,2])),\r\n bayesian_ests=est_matrix,\r\n model_matrix = xx,\r\n yy = yy,\r\n priorcov = priorcov,\r\n Z= as.numeric(bayesian_z_ests[ ,2]),\r\n xform_mat = xform_mat\r\n )\r\n return(returner)\r\n}", "meta": {"hexsha": "ff76e2e98217f572bb4b5fdbe461f08ad2e777c2", "size": 5313, "ext": "r", "lang": "R", "max_stars_repo_path": "R/probitKDH.r", "max_stars_repo_name": "dhelkey/dghrank", "max_stars_repo_head_hexsha": "8af4df19623594294272a2d90fd6b7e9593bc9c1", "max_stars_repo_licenses": ["MIT"], "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/probitKDH.r", "max_issues_repo_name": "dhelkey/dghrank", "max_issues_repo_head_hexsha": "8af4df19623594294272a2d90fd6b7e9593bc9c1", "max_issues_repo_licenses": ["MIT"], "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/probitKDH.r", "max_forks_repo_name": "dhelkey/dghrank", "max_forks_repo_head_hexsha": "8af4df19623594294272a2d90fd6b7e9593bc9c1", "max_forks_repo_licenses": ["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.6808510638, "max_line_length": 132, "alphanum_fraction": 0.7012987013, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4458655229700413}}
{"text": "h1Proportion <- function (pv, method = \"storey\", lambda = 0.5)\n{\n method = match.arg(method)\n pi1 = 1 - mean(pv > lambda, na.rm = TRUE)/(1 - lambda)\n if (pi1 < 0) {\n warning(paste(\"estimated pi1 =\", round(pi1, digits = 4),\n \"set to 0.0\"))\n pi1 = 0\n }\n if (pi1 > 1) {\n warning(paste(\"estimated pi1 =\", round(pi1, digits = 4),\n \"set to 1.0\"))\n pi1 = 1\n }\n return(pi1)\n}\n", "meta": {"hexsha": "b990e43dbeed9f50dff63f4ec285d6e53205f12e", "size": 431, "ext": "r", "lang": "R", "max_stars_repo_path": "R/h1Proportion.r", "max_stars_repo_name": "YunaBlum/WISP", "max_stars_repo_head_hexsha": "8a6bdd162ce26f9b729da8e3da7b3788fda84a9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-08T08:35:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T14:27:57.000Z", "max_issues_repo_path": "R/h1Proportion.r", "max_issues_repo_name": "YunaBlum/WISP", "max_issues_repo_head_hexsha": "8a6bdd162ce26f9b729da8e3da7b3788fda84a9b", "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/h1Proportion.r", "max_forks_repo_name": "YunaBlum/WISP", "max_forks_repo_head_hexsha": "8a6bdd162ce26f9b729da8e3da7b3788fda84a9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3529411765, "max_line_length": 64, "alphanum_fraction": 0.4965197216, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.44585586457068127}}
{"text": "### fimd5.R\n### R code from Van Buuren, S. (2012). \n###\t\tFlexible Imputation of Missing Data. \n###\t\tCRC/Chapman & Hall, Boca Raton, FL.\n### (c) 2012 Stef van Buuren, www.multiple-imputation.com\n### Version 1, 21mar2012\n### Version 2, 4nov2015 tested with mice 2.23\n### Tested with Mac OS X 10.7.3, R2.14-2, mice 2.12\n\nif (packageVersion(\"mice\")<'2.12') stop(\"This code requires mice 2.12.\")\n\nlibrary(\"mice\")\nlibrary(\"lattice\")\nlibrary(\"gamlss\")\nlibrary(\"AGD\")\n\n### set Trellis layout parameters\nlhset <- trellis.par.get(\"layout.heights\")\nlhset$top.padding <- 0\nlhset$bottom.padding <- 0\ntrellis.par.set(\"layout.heights\", lhset)\nlwset <- trellis.par.get(\"layout.widths\")\nlwset$left.padding <- 0\nlwset$right.padding <- 0\ntrellis.par.set(\"layout.widths\", lwset)\n\n\n### Section 5.3.2 Predictors\n\nimp <- mice(nhanes, print=FALSE)\nimp$predictorMatrix\nimp <- mice(cbind(nhanes, chl2=2*nhanes$chl), print=FALSE)\nimp$loggedEvents\n\n\n### Section 5.4.1 Ratio of two variables\n\nimp1 <- mice(boys)\nlong <- complete(imp1, \"long\", inc=TRUE)\nlong$whr <- with(long, wgt/(hgt/100))\n# imp2 <- long2mids(long)\n\n### Just anothor varianble (JAV)\nboys$whr <- boys$wgt/(boys$hgt/100)\nimp.jav <- mice(boys, m=1, seed=32093, maxit=10)\nimp.jav$loggedEvents\n\n### Passive imputation\nini <- mice(boys, m=1, maxit=0)\nmeth <- ini$meth\nmeth[\"whr\"] <- \"~I(wgt/(hgt/100))\"\nmeth[\"bmi\"] <- \"~I(wgt/(hgt/100)^2)\"\npred <- ini$pred\npred[c(\"wgt\",\"hgt\",\"bmi\"),\"whr\"] <- 0\npred[c(\"wgt\",\"hgt\",\"whr\"),\"bmi\"] <- 0\npred\nimp.pas <- mice(boys, m=1, meth=meth, pred=pred, seed=32093, maxit=10)\n\n### passive imputation 2 \npred[c(\"wgt\",\"hgt\",\"hc\",\"reg\"),\"bmi\"] <- 0\npred[c(\"gen\",\"phb\",\"tv\"),c(\"hgt\",\"wgt\",\"hc\")] <- 0\npred[,\"whr\"] <- 0\nimp.pas2 <- mice(boys, m=1, meth=meth, pred=pred, seed=32093, maxit=10)\n\n### Figure 5.1\nc1 <- cbind(model=\"JAV\",complete(imp.jav))\nc2 <- cbind(model=\"passive\",complete(imp.pas))\nc3 <- cbind(model=\"passive 2\",complete(imp.pas2))\ncd <- rbind(c1,c2, c3)\ntrellis.par.set(mice.theme())\ntp51 <- xyplot(whr~hgt|model,data=cd,layout=c(3,1),\n groups=rep(is.na(imp.jav$data$whr),3), pch=c(1,20), cex=c(0.4,1),\n xlab=\"Height (cm)\", ylab=\"Weight/Height (kg/m)\")\nprint(tp51)\n\n### Section 5.4.3 Interaction terms\nrm(boys)\nexpr <- expression((wgt-40)*(hc-50))\nboys$wgt.hc <- with(boys, eval(expr))\nini <- mice(boys, max=0)\nmeth <- ini$meth\nmeth[\"wgt.hc\"] <- paste(\"~I(\",expr,\")\",sep=\"\")\nmeth[\"bmi\"] <- \"\"\npred <- ini$pred\npred[c(\"wgt\",\"hc\"),\"wgt.hc\"] <- 0\nimp.int <- mice(boys, m=1, maxit=10, meth=meth, pred=pred, seed=62587)\n\n### Figure 5.2\nmiss <- is.na(imp.int$data$wgt.hc)\ntp52a <- xyplot(imp.int, wgt~wgt.hc, na.groups = miss,\n cex=c(0.8,1.2), pch=c(1,20),\n ylab=\"Weight (kg)\", xlab=\"Interaction\")\ntp52b <- xyplot(imp.int, hc~wgt.hc, na.groups = miss,\n cex=c(0.8,1.2), pch=c(1,20),\n ylab=\"Head circumference (cm)\", xlab=\"Interaction\")\nprint(tp52a)\nprint(tp52b)\n\n### Section 5.4.4 Conditional imputation\n\nini <- mice(airquality[,1:2],maxit=0)\npost <- ini$post\npost[\"Ozone\"] <- \"imp[[j]][,i] <- squeeze(imp[[j]][,i],c(1,200))\"\n### Note: ifdo() not yet implemented\n### so for the moment use old form\n## post[\"Ozone\"] <- \"ifdo(c(Ozone<1, Ozone>200), c(1, 200))\"\nimp <- mice(airquality[,1:2],method=\"norm.nob\",m=1,maxit=1,seed=1,post=post)\n\n### Figure 5.3\n\nlwd <- 1.5\npar(mfrow=c(1,2))\nbreaks <- seq(-20, 200, 10)\nnudge <- 1\nx <- matrix(c(breaks-nudge, breaks+nudge), ncol=2)\nobs <- airquality[,\"Ozone\"]\nmis <- imp$imp$Ozone[,1]\nfobs <- c(hist(obs, breaks, plot=FALSE)$counts, 0)\nfmis <- c(hist(mis, breaks, plot=FALSE)$counts, 0)\ny <- matrix(c(fobs, fmis), ncol=2)\nmatplot(x, y, type=\"s\",\n col=c(mdc(4),mdc(5)), lwd=2, lty=1,\n xlim = c(0, 170), ylim = c(0,40), yaxs = \"i\",\n xlab=\"Ozone (ppb)\",\n ylab=\"Frequency\")\nbox()\n\ntp <- xyplot(imp, Ozone~Solar.R, na.groups=ici(imp),\n ylab=\"Ozone (ppb)\", xlab=\"Solar Radiation (lang)\",\n cex = 0.75, lex=lwd,\n ylim = c(-20, 180), xlim = c(0,350))\nprint(tp, newpage = FALSE, position = c(0.48,0.08,1,0.92))\n\n\n\n### Post-processing on the boys data\n\npost <- mice(boys, m=1, maxit=0)$post\npost[\"gen\"] <- \"imp[[j]][p$data$age[!r[,j]]<8,i] <- levels(boys$gen)[1]\"\npost[\"phb\"] <- \"imp[[j]][p$data$age[!r[,j]]<8,i] <- levels(boys$phb)[1]\"\npost[\"tv\"] <- \"imp[[j]][p$data$age[!r[,j]]<8,i] <- 1\"\nfree <- mice(boys, m=1, seed=85444, print=FALSE)\nrestricted <- mice(boys, m=1, post=post, seed=85444, print=FALSE)\n\n### The following code using ifdo does not yet work\n### Use the form given above\n## post <- mice(boys, m=1, maxit=0)$post\n## post[\"gen\"] <- \"ifdo(age<8, levels(gen)[1])\"\n## post[\"phb\"] <- \"ifdo(age<8, levels(phb)[1])\"\n## post[\"tv\"] <- \"ifdo(age<8, 1)\"\n## free <- mice(boys, m=1, seed=85444)\n## restricted <- mice(boys, m=1, post=post, seed=85444)\n\n\n### Figure 5.4\n\nimp3 <- rbind(free, restricted) # ignore warning\nmodel <- rep(c(\"Free\",\"Restricted\"),each=nrow(boys))\ntp54 <- xyplot(imp3, gen~age|model, pch=c(3,1), cex=c(3,1.5),\n ylab=\"Genital development\", xlab=\"Age (years)\")\nprint(tp54)\n\n### Section 5.4.5 Compositional data\n\nset.seed(43112)\nn <- 400\nY1 <- sample(1:10, size=n, replace=TRUE)\nY2 <- sample(1:20, size=n, replace=TRUE)\nY3 <- 10 + 2 * Y1 + 0.6 * Y2 + sample(-10:10, size=n, replace=TRUE)\nY <- data.frame(Y1, Y2, Y3)\nY[1:100, 1:2] <- NA\nmd.pattern(Y)\n\nY123 <- Y1+Y2+Y3\nY12 <- Y123-Y[,3]\nP1 <- Y[,1]/Y12\ndata <- data.frame(Y, Y123, Y12, P1)\n\nini <- mice(data, maxit=0, m=10, print=FALSE, seed=21772)\nmeth <- ini$meth\nmeth[\"Y1\"] <- \"~I(P1*Y12)\"\nmeth[\"Y2\"] <- \"~I((1-P1)*Y12)\"\nmeth[\"Y12\"] <- \"~I(Y123-Y3)\"\npred <- ini$pred\npred[\"P1\",] <- 0\npred[c(\"P1\"),c(\"Y12\",\"Y3\")] <- 1\nimp1 <- mice(data, meth=meth, pred=pred, m=10, print=FALSE)\n\nround(summary(pool(with(imp1, lm(Y3~Y1+Y2))))[,1:2],2)\n\n### improved solution for Figure 5.5b\nini <- mice(data, maxit=0, m=10, print=FALSE, seed=21772)\nmeth <- ini$meth\nmeth[\"Y1\"] <- \"~I(P1*Y12)\"\nmeth[\"Y2\"] <- \"~I((1-P1)*Y12)\"\nmeth[\"Y12\"] <- \"~I(Y123-Y3)\"\npred <- ini$pred\npred[\"P1\",] <- 0\npred[c(\"P1\"),c(\"Y12\",\"Y3\")] <- 1\nimp1 <- mice(data, meth=meth, pred=pred, m=1, print=FALSE)\npred[\"P1\",\"Y3\"] <- 0\nimp2 <- mice(data, meth=meth, pred=pred, m=1, print=FALSE)\n\n### Figure 5.5\nimp <- rbind(imp1, imp2) # ignore warning\nmodel <- rep(c(\"Y12 and Y3\",\"Y12 only\"),each=n)\ntp55 <- xyplot(imp, P1~Y12|model, pch=c(1,19), xlab=\"Y1 + Y2\")\nprint(tp55)\n\n### Section 5.5.1 Visit sequence\n\n### Continue from the imp.int object calculated in section 5.4.3 \nimp.int$vis\nvis <- c(2,3,5,10,6:9)\nrm(boys) # refresh boys data\nexpr <- expression((wgt-40)*(hc-50))\nboys$wgt.hc <- with(boys, eval(expr))\nimp.int2 <- mice(boys, m=1, max=1, vis=vis, meth=imp.int$meth, pred=imp.int$pred, seed=23390)\n\n### monotone sequence\nimp.int2 <- mice(boys, m=1, max=1, vis=\"monotone\", meth=imp.int$meth, pred=imp.int$pred, seed=23390)\n\n### Section 5.5.2 Convergence\n\n### Figure 5.6 Default color version\n\nimp <- mice(nhanes, seed=62006, maxit=20, print=FALSE)\ntp56 <- plot(imp)\nprint(tp56)\n\n### Figure 5.6 Book version\n\ntp56b <- plot(imp, col=mdc(5), lty=1:5)\nprint(tp56b)\n\n### Example of pathological convergence\nrm(boys)\nini <- mice(boys,max=0,print=FALSE)\nmeth <- ini$meth\nmeth[\"bmi\"] <- \"~I(wgt/(hgt/100)^2)\"\nimp.bmi1 <- mice(boys, meth=meth, maxit=20, seed=60109)\n\n### Figure 5.7\n### Does not reproduce exactly, but the message is the same\ntp57 <- plot(imp.bmi1,c(\"hgt\",\"wgt\",\"bmi\"), col=mdc(5), lty=1:5)\nprint(tp57)\n\n### Breaking cyclic imputations for hgt and wgt\npred <- ini$pred\npred[c(\"hgt\",\"wgt\"),\"bmi\"] <- 0\nimp.bmi2 <- mice(boys, meth=meth, pred=pred, maxit=20, seed=60109)\n\n### Figure 5.8\n### Does not reproduce exactly, but the message is the same\ntp58 <- plot(imp.bmi2,c(\"hgt\",\"wgt\",\"bmi\"), col=mdc(5), lty=1:5)\nprint(tp58)\n\n### Section 5.6.2 Diagnostic graphs\n\nset.seed(24417)\n### create 50% missing data in wgt\nboys$wgt[sample(1:nrow(boys),nrow(boys)/2)] <- NA\nmeth <- c(\"\",\"pmm\",\"pmm\",\"\",\"pmm\",\"polr\",\"polr\",\"pmm\",\"polyreg\")\nimp <- mice(boys, m=1, meth=meth, seed=53882, print=FALSE)\n\n### Simple scatterplot wgt-age (not given in book)\ntp58b <- xyplot(imp, wgt~age|.imp)\nprint(tp58b)\n\n### Fit separate regression models for wgt\n### for observed (n=372) and imputed (n=376) data\ncd <- complete(imp)[,-4]\nisobs <- !is.na(boys$wgt)\ncdobs <- cd[isobs,]\ncdmis <- cd[!isobs,]\nobs <- gamlss(wgt~age+hgt+hc+gen+phb+tv+reg, data=cdobs)\nmis <- gamlss(wgt~age+hgt+hc+gen+phb+tv+reg, data=cdmis)\n\n### Figure 5.9 worm plot\nwp.twin(obs, mis, xvar=NULL, xvar.column=2, n.inter=9, col1=mdc(4), col2=mdc(5), ylim=0.9, cex=1, pch=1)\n\n### Figure 5.10\nimp <- mice(nhanes, seed=29981)\ntp510 <- stripplot(imp, pch=c(1,20))\nprint(tp510)\n\n### Figure 5.11\ntp511 <- densityplot(imp)\nprint(tp511)\n\n### Calculate propensity scores\nfit <- with(imp, glm(ici(imp)~age+bmi+hyp+chl,family=binomial))\nps <- rep(rowMeans(sapply(fit$analyses, fitted.values)),imp$m)\n\n### Figure 5.12\ntp512 <- xyplot(imp, bmi~ps|.imp, pch=c(1,19), \n xlab=\"Probability that record is incomplete\", \n ylab=\"BMI\")\nprint(tp512)\n\n\n", "meta": {"hexsha": "d5f5fc4ccb4b7cf795af3e6a099b2b073dc2f362", "size": 8919, "ext": "r", "lang": "R", "max_stars_repo_path": "packrat/lib/x86_64-pc-linux-gnu/3.2.5/mice/doc/fimd5.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/fimd5.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/fimd5.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": 29.5331125828, "max_line_length": 104, "alphanum_fraction": 0.6274245992, "num_tokens": 3492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.4458558524507835}}
{"text": "#' Fit a mixture of factor analyzers with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param num_factors Number of factors in the factor analyzers.\n#' @param num_components Integer specifying the number of components.\n#' @param epsilon For the EM algorithm, stop when the relative difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned.\n#' @export\nfit.factor.mixture <- function(x, num_factors, num_components, epsilon = 1e-6, maxsteps = 1000, verbose = F)\n{\n nvar <- ncol(x)\n nparam <- num_components * nvar + nvar + num_components * (num_factors * nvar - num_factors * (num_factors - 1) / 2) + num_components - 1\n if (nparam >= nrow(x)) {\n warning(\"More parameters than samples, consider lowering the number of factors or components\")\n return(NULL)\n }\n \n result <- list()\n result$type <- \"mfa\"\n result$mfa_res <- NULL\n if (verbose) {\n try(result$mfa_res <- EMMIXmfa::mfa(x, num_components, num_factors, tol=epsilon,\n itmax=maxsteps, sigma_type = \"unique\", D_type = \"unique\",\n nrandom=5, nkmeans=5, conv_measure=\"ratio\"), silent=F)\n } else {\n output <- capture.output(capture.output(result$mfa_res <- EMMIXmfa::mfa(x, num_components, num_factors, tol=epsilon,\n itmax=maxsteps, sigma_type = \"unique\", D_type = \"unique\",\n nrandom=5, nkmeans=5, conv_measure=\"ratio\"), type=\"message\"), type=\"output\")\n }\n if (class(result$mfa_res)[1] != \"emmix\" || class(result$mfa_res)[2] != \"mfa\") {\n warning(\"Failed to fit MFA\")\n return(NULL)\n }\n if (sum(class(result$mfa_res) == c(\"emmix\", \"mfa\")) != 2) {\n warning(\"Factor mixture fitting failed\")\n return(NULL)\n }\n \n result$num_components <- num_components\n result$num_factors <- num_factors\n result$weights <- result$mfa_res$pivec\n result$factor_loadings <- result$mfa_res$B\n result$factor_means <- result$mfa_res$mu\n result$covariances <- result$mfa_res$D\n result$log_likelihood <- result$mfa_res$logL\n result$BtBpD <- list()\n for (i in 1:num_components) {\n result$BtBpD[[i]] <- result$mfa_res$B[,,i] %*% t(result$mfa_res$B[,,i]) + result$mfa_res$D[,,i]\n }\n result$AIC <- 2 * nparam - 2 * result$log_likelihood\n result$BIC <- log(nrow(x)) * nparam - 2 * result$log_likelihood\n \n # Make covariance matrices symmetric (numerical issue?)\n # if (result$num_factors > 1) {\n # for (i in 1:result$num_components) {\n # for (j in 1:(result$num_factors-1)) {\n # for (k in (j+1):result$num_factors) {\n # cov <- mean(result$factor_covariances[i,j,k], result$factor_covariances[i,j,k])\n # result$factor_covariances[i,j,k] <- cov\n # result$factor_covariances[i,k,j] <- cov\n # }\n # }\n # }\n # }\n \n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Fit a transformed mixture of factor analyzers with a specific number of components.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param num_factors Number of factors in the factor analyzers.\n#' @param num_components Integer specifying the number of components.\n#' @param bounds Dx2 matrix specifying the lower and upper bound for each variable.\n#' @param epsilon For the EM algorithm, stop when the relative difference in log likelihood is less than this epsilon.\n#' @param maxsteps Maximum number of steps to take in the EM algorithm. When the maximum number is reached, the current fit will be returned.\n#' @export\nfit.transformed.factor.mixture <- function(x, num_factors, num_components, bounds, epsilon = 1e-6, maxsteps = 1000, verbose = F)\n{\n result <- list()\n result$type <- \"mfa.transformed\"\n result$transform.bounds <- bounds\n transformed <- mvd.transform_to_unbounded(x, bounds)\n result$mfa <- fit.factor.mixture(transformed, num_factors, num_components, epsilon = epsilon, maxsteps = maxsteps, verbose = verbose)\n return(structure(result, class = \"mvd.density\"))\n}\n\n#' Calculate AIC of a mixture of factor analyzers across a range of number of components and factors.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param factors Vector specifying the number of factors to test\n#' @param components Vector specifying the number of components to test\n#' @param optimal.only If TRUE, directly return only the GMM with optimal number of components; otherwise return a structure with fits for all tested number of components/factors.\n#' @param epsilon See fit.factor.mixture\n#' @param maxsteps See fit.factor.mixture\n#' @param verbose Display the fitting progress.\n#' @export\nfactor.mixture.AIC <- function(x, factors = 1:5, components = 1:5, optimal.only = F, epsilon = 1e-6, maxsteps = 1000, verbose = F) {\n result <- list()\n result$factors <- factors\n result$components <- components\n result$AIC <- matrix(NA, length(factors), length(components))\n result$fits <- list()\n for (i in 1:length(factors)) {\n result$fits[[i]] <- list()\n \n for (j in 1:length(components)) {\n if (verbose) {\n cat(\"Fitting factors =\", factors[i], \" components =\", components[j], \"\\n\")\n }\n \n if (factors[i] < ncol(x)) {\n fit <- fit.factor.mixture(x, factors[i], components[j], epsilon = epsilon, maxsteps = maxsteps, verbose=verbose)\n result$fits[[i]][[j]] <- fit\n if(!is.null(fit)) {\n result$AIC[i,j] <- fit$AIC\n }\n } else {\n result$fits[[i]][[j]] <- NULL\n }\n }\n }\n if (optimal.only) {\n ixs <- which(result$AIC == min(result$AIC, na.rm=T), arr.ind = T)\n return(result$fits[[ixs[1]]][[ixs[2]]])\n } else {\n return(result)\n }\n}\n\n\n#' Calculate AIC of a transformed mixture of factor analyzers across a range of number of components and factors.\n#'\n#' description\n#' @param x Matrix or vector of samples. For matrices, rows are samples and columns are variables.\n#' @param factors Vector specifying the number of factors to test\n#' @param components Vector specifying the number of components to test\n#' @param optimal.only If TRUE, directly return only the GMM with optimal number of components; otherwise return a structure with fits for all tested number of components/factors.\n#' @param epsilon See fit.factor.mixture\n#' @param maxsteps See fit.factor.mixture\n#' @param verbose Display the fitting progress.\n#' @export\ntransformed.factor.mixture.AIC <- function(x, bounds, factors = 1:5, components = 1:5, optimal.only = F, epsilon = 1e-6, maxsteps = 1000, verbose = F) {\n result <- list()\n result$factors <- factors\n result$components <- components\n result$AIC <- matrix(NA, length(factors), length(components))\n result$fits <- list()\n for (i in 1:length(factors)) {\n result$fits[[i]] <- list()\n \n for (j in 1:length(components)) {\n if (verbose) {\n cat(\"Fitting factors =\", factors[i], \" components =\", components[j], \"\\n\")\n }\n \n if (factors[i] < ncol(x)) {\n fit <- fit.transformed.factor.mixture(x, factors[i], components[j], bounds, epsilon = epsilon, maxsteps = maxsteps, verbose=verbose)\n result$fits[[i]][[j]] <- fit\n if(!is.null(fit)) {\n result$AIC[i,j] <- fit$mfa$AIC\n }\n } else {\n result$fits[[i]][[j]] <- NULL\n }\n }\n }\n if (optimal.only) {\n ixs <- which(result$AIC == min(result$AIC, na.rm=T), arr.ind = T)\n return(result$fits[[ixs[1]]][[ixs[2]]])\n } else {\n return(result)\n }\n}\n\n\n#' Evaluate a mixture of factor analyzers\n#'\n#' description\n#' @param fit An mvd.density object obtained from fit.factor.mixture\n#' @param x Matrix or vector of samples at which to evaluate the mixture of factor analyzers. For matrices, rows are samples and columns are variables.\n#' @param log Return log probability density\n#' @export\nevaluate.factor.mixture <- function(fit, x, log = F) {\n p <- rep(NA, nrow(x))\n for (i in 1:nrow(x)) {\n compp <- rep(NA, fit$num_components)\n for (j in 1:fit$num_components) {\n compp[j] <- mvtnorm::dmvnorm(x[i,], fit$factor_means[,j], fit$BtBpD[[j]], log=log)\n }\n if (log) {\n p[i] <- .logsum(compp + log(fit$weights))\n } else {\n p[i] <- sum(compp * fit$weights)\n }\n }\n return(p)\n}\n", "meta": {"hexsha": "3af437a63bb157f9a3c350eb079459af92926b46", "size": 8577, "ext": "r", "lang": "R", "max_stars_repo_path": "R/factor.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/factor.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/factor.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": 42.4603960396, "max_line_length": 179, "alphanum_fraction": 0.6545412149, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.44573604265087063}}
{"text": "#' mmHg2mb\n#'\n#' Conversion mmHg2mb to millibar [hPa].\n#'\n#' @param numeric mmHg millimeter of mercures.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords mmHg2mb\n#' \n#' @export\n#'\n#'\n#'\n#'\n\nmmHg2mb<-function(mmHg)\n{\n return (mmHg * 1.33322);\n}", "meta": {"hexsha": "bf88a22a2a2cb1e914e7d0b7575a809bbbd5114d", "size": 330, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mmHg2hPa.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/mmHg2mb.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/mmHg2mb.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.7142857143, "max_line_length": 101, "alphanum_fraction": 0.6484848485, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.44519328090239885}}
{"text": "#' kmh2knots\n#'\n#' Conversion from kilometer per hour to knot per second.\n#'\n#' @param numeric kmh Speed in kilometer per hour.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords kmh2knots \n#' \n#' @export\n#'\n#'\n#'\n#'\n\nkmh2knots<-function(kmh)\n{\n return(kmh * 0.539957);\n}", "meta": {"hexsha": "45b0fe8b4a6d84896ee43a31fdab708b3ece77e5", "size": 355, "ext": "r", "lang": "R", "max_stars_repo_path": "R/kmh2knots.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/kmh2knots.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/kmh2knots.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9047619048, "max_line_length": 101, "alphanum_fraction": 0.6647887324, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44502202043029054}}
{"text": "########################### BayesKin ###########################\n## Bayesian estimates of rigid body kinematics\n## Andy Pohl\n## UofC - Faculty of Kinesiology\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: April 2021\n################################################################\n\n##################### RunMdl_TripleLink.r ###################\n## Performs analysis comparing Bayesian to Least squares approaches for\n## 3 link kinematic chains.\n################################################################\nrm(list = ls())\n\nWORKING_DIR = \"\" # Replace with the location of the BayesKin/src directory on the local PC.\nSAVE_MDL = TRUE # assume save\n\nINIT_TYPE = 'ls_est' # either 'true_vals', 'ls_est', 'random\n\nsetwd(WORKING_DIR)\n\nsource('library.r') # Retrieve function library\nset.seed(1) # Set seed for reproducibility\n\n## 1) Specify parameters\nn.links = 3 # Number of links.\nseg.length = c(0.45, 0.35, 0.25) # Length of segment specified in m. NB: Pataky pg 2.\nr_true = c(0.07, 0.03) # Origin location in m.\ntheta_true = c(-55, -110, -10) # Rotation angle in deg. NB: specified to avoid 0/360 issue\n# and mirroring solutions.\nsigma_true = 1.5/1000 # Measurement noise in m. NB Noise specified as 1.5mm\n# midpoint of range explored by Pataky et al.\ntrue_vals = c(r_true = r_true, theta_true = theta_true, sigma_true = sigma_true)\n\n\n# Generate posture\nlinks = list(gen_link(seg.length = seg.length[1],\n plate.center = 0.7*seg.length[1]),\n gen_link(seg.length = seg.length[2],\n plate.center = 0.5*seg.length[2]),\n gen_link(seg.length = seg.length[3],\n plate.center = 0.5*seg.length[3]))\nposture = gen_posture(links, r = r_true, theta = theta_true)\n\n\nnits = 1000 # number of iterations.\nseeds = 1:nits\ni = 1\nwhile (length(list.files('./TripleLink_Mdl/Bayes_p3/')) < nits){\n files = list.files(path = paste0(\"./TripleLink_Mdl/Bayes_p5/\"))\n processed_seeds = as.numeric(gsub(\"(.+?)(\\\\_.*)\", \"\\\\1\", files))\n #set seed\n seed = seeds[i]\n\n if(!(seed %in% processed_seeds)){\n set.seed(seed)\n print(sprintf(\"Iteration %.0f of %.0f - seed = %.0f\",length(list.files('./TripleLink_Mdl/Bayes_p5/')), nits, seed))\n # gen obs\n y = gen_obs(posture, sigma_true)\n\n #Compute LS solution.\n LS_result = LS_soln(y, links,\n inits = c(r_true, theta_true, sigma_true),\n init_type = 'true_vals')\n\n print(\"LS Solution Complete\")\n r_mdl_file_name = paste0('./TripleLink_Mdl/LS/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, 'LSModel')\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(LS_result, file = r_mdl_file_name)\n #\n # Compute Bayes_P1\n Bayes_p1_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p1.jags',\n init_type = INIT_TYPE,\n true_vals = true_vals,\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n print(\"Bayes P1 Solution Complete\")\n mdl_type = 'BayesModel_p1'\n r_mdl_file_name = paste0('./TripleLink_Mdl/Bayes_p1/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, mdl_type)\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(Bayes_p1_result, file = r_mdl_file_name)\n\n # Compute Bayes_P2\n Bayes_p2_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p2.jags',\n init_type = INIT_TYPE,\n true_vals = true_vals,\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n\n print(\"Bayes P2 Solution Complete\")\n mdl_type = 'BayesModel_p2'\n r_mdl_file_name = paste0('./TripleLink_Mdl/Bayes_p2/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, mdl_type)\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(Bayes_p2_result, file = r_mdl_file_name)\n\n # Compute Bayes_P3\n Bayes_p3_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p3.jags',\n init_type = INIT_TYPE,\n true_vals = true_vals,\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n\n print(\"Bayes P3 Solution Complete\")\n mdl_type = 'BayesModel_p3'\n r_mdl_file_name = paste0('./TripleLink_Mdl/Bayes_p3/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, mdl_type)\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(Bayes_p3_result, file = r_mdl_file_name)\n\n # Comppute Bayes P4\n Bayes_p4_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p4.jags',\n init_type = INIT_TYPE,\n true_vals = true_vals,\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n\n mdl_type = 'BayesModel_p4'\n r_mdl_file_name = paste0('./TripleLink_Mdl/Bayes_p4/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, mdl_type)\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(Bayes_p4_result, file = r_mdl_file_name)\n\n # Comppute Bayes P5\n Bayes_p5_result = Bayes_soln(y=y,\n links = links,\n mdlfile = './BayesModel_p5.jags',\n init_type = INIT_TYPE,\n true_vals = true_vals,\n ls_est = c(LS_result$r.hat, LS_result$theta.hat, LS_result$sigma.hat))\n\n mdl_type = 'BayesModel_p5'\n r_mdl_file_name = paste0('./TripleLink_Mdl/Bayes_p5/', as.character(as.numeric(seed)))\n r_mdl_file_name = paste0(r_mdl_file_name, '_')\n r_mdl_file_name = paste0(r_mdl_file_name, mdl_type)\n r_mdl_file_name = paste0(r_mdl_file_name, '.rda')\n print(sprintf(\"Saving file %s\", r_mdl_file_name))\n saveRDS(Bayes_p5_result, file = r_mdl_file_name)\n }\n i = i+1\n print('#######################################################################')\n}\n", "meta": {"hexsha": "464fef5fcfda8c42a508ff6ce3cf58895c0fe940", "size": 7481, "ext": "r", "lang": "R", "max_stars_repo_path": "src/RunMdl_TripleLink.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RunMdl_TripleLink.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RunMdl_TripleLink.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1790123457, "max_line_length": 125, "alphanum_fraction": 0.5484560888, "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4446521424627061}}
{"text": "#' Estimating the generalised joint exceedance (GJE) environmental contours\n#'\n#' @description\n#' This function estimates the generalised joint exceedance (GJE) environmental contours, as proposed in Jonathan et al. (2014), for a\n#' given sample data set or a fitted joint distribution of class \\code{ht} or \\code{wln}.\n#' \n#' @param object either a fitted joint distribution of class \\code{wln} or \\code{ht}, or an existing sample data\n#' set containing \\code{hs} and \\code{tp} as columns. See details.\n#' \n#' @param output_rp the required return periods (in years) for the estimated contours.\n#' \n#' @param type the type of joint exceedance definition. The default value is 2. See details.\n#' \n#' @param npy the (optional) number of data points per year. This argument is only needed if the input\n#' \\code{object} is a sample data set.\n#' \n#' @param n_point the number of points to output around each contour. The default value is 100.\n#' \n#' @details\n#' The joint exceedance contour is a collection of points corresponding to a constant joint exceedance proability.\n#' The definition is one-sided or two-sided depending on the input argument \\code{type}:\n#' \n#' \\itemize{\n#' \n#' \\item If \\code{type = 1}, the \\eqn{T}-year contour passes through any point \\eqn{(hs, tp)} such that the \n#' joint exceedance probability \\eqn{P(Hs > hs & Tp > tp)} is one in \\eqn{T} years.\n#' \n#' \\item If \\code{type = 2}, the \\eqn{T}-year contour passes through an anchor point \\eqn{(hs0, tp0)}\n#' where \\eqn{hs0} is the (\\eqn{T/2})-year wave heights, and \\eqn{tp0} is the conditional median of the\n#' wave period given the wave height is \\eqn{hs0}. The joint exceedance probability is defined as\n#' \\eqn{P(Hs > hs & Tp > tp)} for all \\eqn{tp > tp0} and \\eqn{P(Hs > hs & Tp < tp)} for all \\eqn{tp < tp0}.\n#' \n#' }\n#' \n#' The function can be applied to an existing sample set, which can be generated by function \\code{\\link{sample_jdistr}}\n#' or otherwise by importing a CSV file using function \\code{\\link[data.table]{fread}}. The input sample data\n#' object must contain \\code{hs} and \\code{tp} as columns. The user must also specify the number of points per year\n#' \\code{npy} and a valid \\code{output_rp}, i.e. the maximum \\code{output_rp} must be shorter than the total\n#' duration of the data set.\n#' \n#' Alternatively this function can be applied to a fitted joint distribution object\n#' generated by function \\code{\\link{fit_ht}} or \\code{\\link{fit_wln}}. When applied to a\n#' \\code{wln} or \\code{ht} object, the contour estimation makes use of the importance\n#' sampling technique proposed in Huseby et. al. (2014) to improve the efficiency of the function.\n#' \n#' \n#' @return\n#' A set of estimated GJE contours with the specified return periods in the format\n#' of a \\code{data.table} with \\code{rp}, \\code{hs}, and \\code{tp} as columns.\n#'\n#' @examples\n#' # Estimating type-1 GJE contours based on a fitted model\n#' data(ww3_pk)\n#' wln = fit_wln(data = ww3_pk, npy = nrow(ww3_pk)/10)\n#' ec_wln = estimate_gje(object = wln, output_rp = c(10,100,1000,10000), type = 1)\n#' plot_ec(ec = ec_wln, raw_data = ww3_pk)\n#' \n#' # Estimating type-2 GJE contours based on a sample data set\n#' data(ww3_ts)\n#' ec_data = estimate_gje(object = ww3_ts, output_rp = c(.5, 1, 2), type = 2, npy = ww3_ts[, .N/10])\n#' plot_ec(ec = ec_data, raw_data = ww3_ts)\n#' \n#' @references\n#' Jonathan, P., Ewans, K., Flynn, J., 2014. On the estimation of ocean engineering design contours.\n#' ASME J. Offshore Mech. Arct. Eng. 136:041101.\n#' \n#' Huseby, A., Vanem, E., Natvig, B., 2014. A new Monte Carlo method for environmental contour estimation.\n#' Conference Proceedings. DOI:10.1201/b17399-286.\n#' \n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}, \\code{\\link{sample_jdistr}}, \\code{\\link{plot_ec}}\n#' \n#' @export\nestimate_gje = function(\n object, output_rp, type = 2, npy = NULL, n_point = 100){\n \n if(\"wln\" %in% class(object)){\n \n res = .estimate_gje_from_wln(wln = object, output_rp = output_rp, type = type, n_point = n_point)\n \n if(!is.null(npy)){\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\n }\n \n }else if(\"ht\" %in% class(object)){\n \n res = .estimate_gje_from_ht(ht = object, output_rp = output_rp, type = type, n_point = n_point)\n \n if(!is.null(npy)){\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\n }\n \n }else if(\"data.table\" %in% class(object)){\n \n if(is.null(npy)){\n stop(\"Argument npy must be provided for estimating contours from sample data.\")\n }else{\n invalid_rp = output_rp[output_rp>object[, .N/npy]]\n if(length(invalid_rp)==length(output_rp)){\n stop(\"All output_rp values are invalid as they require extrapolation. Consider fitting a joint distribution first.\")\n }else if(length(invalid_rp)>=1 & length(invalid_rp)=hs1, .N], .(hs1)]\n calc[, p_tp_upper:=1-n_jex/n_hs_tail]\n calc[, p_tp_lower:=n_jex/n_hs_tail]\n calc[, tp_upper:=sample_data[hs>=hs1, quantile(tp, p_tp_upper)], .(hs1)]\n calc[, tp_lower:=sample_data[hs>=hs1, quantile(tp, p_tp_lower)], .(hs1)]\n out = rbind(calc[.N:2, .(hs=hs1, tp=tp_upper)], calc[, .(hs=hs1, tp=tp_lower)])\n }else{\n # browser()\n calc = data.table(hs1 = seq(ap_hs, min(sample_data$hs), length.out = n_point))\n calc[, tp:=sample_data[hs>=hs1, sort(tp, decreasing = T)[n_jex]], .(hs1)]\n out = calc[, .(hs=hs1, tp)] \n }\n return(out)\n}\n\n\n.estimate_gje_from_wln = function(wln, output_rp, type, n_point){\n \n res_list=list()\n for(this_rp in output_rp){\n this_sample_data = .sample_wln_is(wln, target_rp=this_rp)\n this_out = .estimate_gje_from_data(\n sample_data = this_sample_data, n_jex = .target_rp_ub,\n ap_hs = this_sample_data[, sort(hs, decreasing = T)[type*.target_rp_ub]],\n type = type, n_point = n_point)\n res_list[[as.character(this_rp)]] = cbind(rp=this_rp, this_out)\n }\n res = rbindlist(res_list)\n return(res)\n}\n\n.estimate_gje_from_ht = function(ht, output_rp, type, n_point){\n \n res_list=list()\n for(this_rp in output_rp){\n this_sample_data = .sample_ht_is(ht, target_rp=this_rp)\n this_out = .estimate_gje_from_data(\n sample_data = this_sample_data, n_jex = .target_rp_ub,\n ap_hs = this_sample_data[, sort(hs, decreasing = T)[type*.target_rp_ub]],\n type = type, n_point = n_point)\n res_list[[as.character(this_rp)]] = cbind(rp=this_rp, this_out)\n }\n res = rbindlist(res_list)\n}\n", "meta": {"hexsha": "54368adb36cdcf95db600e4f048d49d2707dae1b", "size": 7563, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/estimate_gje.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_gje.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_gje.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": 43.4655172414, "max_line_length": 134, "alphanum_fraction": 0.6814756049, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.44393548099487945}}
{"text": "\n### R과 함께 배우는 네트워크 분석 ###\n\n## 01. 핵심 패키지 설치 \n\n# 패키지 설치\ninstall.packages(\"igraph\") \ninstall.packages(\"network\") \ninstall.packages(\"sna\")\ninstall.packages(\"visNetwork\")\ninstall.packages(\"threejs\")\ninstall.packages(\"ndtv\")\n\ninstall.packages(\"RColorBrewer\") \ninstall.packages(\"png\")\ninstall.packages(\"networkD3\")\ninstall.packages(\"animation\")\ninstall.packages(\"maps\")\ninstall.packages(\"geosphere\")\n\nlibrary(RColorBrewer)\n\n### 02. 색 알아보기\nplot(x=1:10, y=rep(5,10), pch=19, cex=5, col=\"dark red\")\npoints(x=1:10, y=rep(6, 10), pch=19, cex=5, col=\"#557799\")\npoints(x=1:10, y=rep(4, 10), pch=19, cex=5, col=rgb(.25, .5, .3))\n\n## 전체 색 - 657가지의 colors \nlength(colors())\n\n## 'green'의 이름을 가진 것 알아보기\ngrep('green', colors(), value=T)\n\n\n## rgb 컬러는 기본적으로 0-1사이의 값이다. \n## 0-255 사이의 값으로 보고 싶다면 다음과 같이 할 수 있다.\nrgb(10, 100, 100, maxColorValue = 255)\ncol1 = rgb(10, 100, 100, maxColorValue = 255)\nplot(x=1:10, y=rep(5,10), pch=19, cex=5, col=col1)\n\n\n### 투명도 - Transparency /ˌtranˈsperənsē/ -\n### 우리는 alpha를 이용하여 투명도 설정이 가능하다.\nplot(x=1:5, y=rep(5,5), pch=19, cex=10, \n col=rgb(.25, .5, .3, alpha=0.5), xlim=c(0,6)) \n\n### - Palettes -\n### 때로는 대조되는 여러가지 색상이 필요하다.\n### R은 우리를 위해 함수를 만들어 놓았다.\n\npal1 <- heat.colors(5, alpha=1) # 반투명\npal2 <- rainbow(5, alpha=.5) # 투명\n\nplot(x=1:10, y=1:10, pch=19, cex=10, col=pal1)\npar(new=TRUE) # 첫번째 plot를 지우지 않고, 두번째 플롯을 더한다.\nplot(x=10:1, y=1:10, pch=19, cex=10, col=pal2)\n\n\n### - colorRampPalette() -\n### 그래디언트를 발생시키기 위해 우리는 위의 함수를 사용한다. \n### 이 함수를 이용하여 우리가 필요로 하는 수의 색을 발생시킬 수 있다.\npalf <- colorRampPalette(c(\"gray70\", \"dark red\"))\nis(palf)\npalf(10)\nplot(x=10:1, y=1:10, pch=19, cex=10, col=palf(10)) # 10가지 색 \n\n### - colorRampPalette() - \n### 우리는 여기에 투명도를 alpha를 이용하여 추가 가능하다.\npalf <- colorRampPalette(c(rgb(1,1,1, 0.2), rgb(0.8, 0, 0, 0.7)), alpha=TRUE)\nplot(x=10:1, y=1:10, pch=19, cex=10, col=palf(10)) # 10가지 색 \n\n### - ~~ ColorBrewer -----\n### 우리는 준비되어 있는 색상 R palettes 가 있다.\n### 이 함수는 중요한 함수 하나 있다. 'brewer.pal'\n### 우리는 이를 이용하여 색의 확인이 가능하다. \n### display.brewer.pal(8, \"Set3\")\nlibrary(RColorBrewer)\n\ndisplay.brewer.all()\nbrewer.pal.info # 색상 정보 확인\nbrewer.pal.info[\"Blues\", ]\n\ndisplay.brewer.pal(8, \"Set3\") # Set3의 색상 보기\ndisplay.brewer.pal(8, \"Spectral\")\ndisplay.brewer.pal(8, \"Blues\")\n\n### 03. RColorBrewer를 이용한 plot 그리기\n\npar(mfrow=c(1,2)) # plot two figures - 1 row, 2 columns\npal3 <- brewer.pal(10, \"Set3\") # Set3의 10가지 색 지정.\nplot(x=10:1, y=10:1, pch=19, cex=6, col=pal3) # 원 크기 6 지정.\nplot(x=10:1, y=10:1, pch=19, cex=6, col=rev(pal3)) # backwards-색 거꾸로\n\ndev.off() # 지정된 그래픽 구성을 없애기 위해서는 graphic device를 끈다.\ndetach(\"package:RColorBrewer\") # search() 경로로부터 이용가능한 R개체 없애기\n\n?detach\n\n### 04. 네트워크 데이터를 igraph로 읽기\n### 데이터 다운로드 (http://bit.ly/polnet2018)\nrm(list=ls())\n\n### 작업 디렉터리 지정\nsetwd(\"D:/polnet2018\") \ngetwd()\n\nlibrary(igraph)\n\n# 데이터 읽기\nnodes <- read.csv(\"./Data files/Dataset1-Media-Example-NODES.csv\", header=T, as.is=T)\nlinks <- read.csv(\"./Data files/Dataset1-Media-Example-EDGES.csv\", header=T, as.is=T)\n\n## 데이터 확인\nhead(nodes); head(links)\ndim(nodes); dim(links)\n\n## -- graph_from_data_frame(d=links, vertices=nodes, directed=T)\n## 데이터를 igraph 객체로 변환\n## graph_from_data_frame() 함수는 d와 vertices 컬럼을 갖는다. \n## 소스와 대상은 node IDs를 포함한다. \n## 'vertices'는 Node IDs 컬럼으로 시작해야 한다. \n## \n\nnet <- graph_from_data_frame(d=links, vertices=nodes, directed=T) \n\nclass(net)\nnet \n\n?E # 그래프의 Edges\n?V # 그래프의 Vertices \nE(net)\nV(net)\nE(net)$type # hyperlink/mention\nV(net)$media # 미디어 회사명 \n\nE(net)[type==\"mention\"]\nV(net)[media==\"BBC\"]\n\nas_edgelist(net, names=T) # edge의 리스트를 확인\nas_adjacency_matrix(net, attr=\"weight\")\n\n# Or data frames describing nodes and edges:\nas_data_frame(net, what=\"edges\")\nas_data_frame(net, what=\"vertices\")\n?as_data_frame\n\n# 그래프를 그리기 위한 첫번째 시도\nplot(net) # not pretty!\n\n# Removing loops from the graph:\nnet <- simplify(net, remove.multiple = F, remove.loops = T) \n\n# 화살표 크기를 줄이고, Lables 를 제거하는 것\nplot(net, edge.arrow.size=.4,vertex.label=NA)\n\n### 05. 2번째 데이터 셋 : matrix\n### 데이터 읽기\nnodes2 <- read.csv(\"./Data files/Dataset2-Media-User-Example-NODES.csv\", header=T, as.is=T)\nlinks2 <- read.csv(\"./Data files/Dataset2-Media-User-Example-EDGES.csv\", header=T, row.names=1)\n\nhead(links2, 100)\n\n\nnet2 <- graph_from_incidence_matrix(links2)\n\ntable(V(net2)$type)\n\nplot(net2,vertex.label=NA)\n\n\nclass(net2)\nnet2 \n\n### 06. igraph를 이용한 분석 및 시각화\nplot(net, edge.arrow.size=.4)\n\n\n\n### 03. RColorBrewer를 이용한 plot 그리기\n### 04. 네트워크 데이터를 igraph로 읽기 \n### 05. 2번째 데이터 셋 : matrix\n### 06. igraph를 이용한 분석 및 시각화 \nplot(net, edge.arrow.size=.4, edge.curved=.3) # 곡선 커브 및 방향\nplot(net, edge.arrow.size=.2, edge.curved=0,\n vertex.color=\"orange\", vertex.frame.color=\"#555555\",\n vertex.label=V(net)$media, vertex.label.color=\"black\",\n vertex.label.cex=.7) \n\n# Generate colors based on media type:\ncolrs <- c(\"gray50\", \"tomato\", \"gold\")\nV(net)$color <- colrs[V(net)$media.type]\n\n\n# Compute node degrees (#links) and use that to set node size:\ndeg <- degree(net, mode=\"all\")\nV(net)$size <- deg*3\n# Alternatively, we can set node size based on audience size:\nV(net)$size <- V(net)$audience.size*0.7\n\n\n# The labels are currently node IDs.\n# Setting them to NA will render no labels:\nV(net)$label.color <- \"black\"\nV(net)$label <- NA\n\n# Set edge width based on weight:\nE(net)$width <- E(net)$weight/6\n\n#change arrow size and edge color:\nE(net)$arrow.size <- .2\nE(net)$edge.color <- \"gray80\"\n\n# We can even set the network layout:\ngraph_attr(net, \"layout\") <- layout_with_lgl\nplot(net) \n\n# 그래프의 edge=color을 구하기 \nplot(net, edge.color=\"orange\", vertex.color=\"gray50\") \nplot(net) \nlegend(x=-1.1, y=-1.1, c(\"Newspaper\",\"Television\", \"Online News\"), pch=21,\n col=\"#777777\", pt.bg=colrs, pt.cex=2.5, bty=\"n\", ncol=1)\n\n\n\n# Sometimes, especially with semantic networks, we may be interested in \n# plotting only the labels of the nodes:\n\nplot(net, vertex.shape=\"none\", vertex.label=V(net)$media, \n vertex.label.font=2, vertex.label.color=\"gray40\",\n vertex.label.cex=.7, edge.color=\"gray85\")\n\n\n# Let's color the edges of the graph based on their source node color.\n# We'll get the starting node for each edge with \"ends()\".\nedge.start <- ends(net, es=E(net), names=F)[,1]\nedge.col <- V(net)$color[edge.start]\n\nplot(net, edge.color=edge.col, edge.curved=.1)\n\n# Let's generate a slightly larger 100-node graph using \n# a preferential attachment model (Barabasi-Albert).\n\nnet.bg <- sample_pa(100, 1.2) \nV(net.bg)$size <- 8\nV(net.bg)$frame.color <- \"white\"\nV(net.bg)$color <- \"orange\"\nV(net.bg)$label <- \"\" \nE(net.bg)$arrow.mode <- 0\nplot(net.bg)\n\n\n\n\n## Ref\n## https://bookdown.org/rdpeng/exdata/plotting-and-color-in-r.html \n## Exploratory Data Analysis with R\n## RColorBrewer : http://ftp.auckland.ac.nz/software/CRAN/doc/packages/RColorBrewer.pdf", "meta": {"hexsha": "d5eb62bdd17236ae725dccbc811f723d6befd62e", "size": 6682, "ext": "r", "lang": "R", "max_stars_repo_path": "01_R_Class/Bonus/polnet2018/test.r", "max_stars_repo_name": "LDJWJ/SBA01_BigData", "max_stars_repo_head_hexsha": "e851974017ca55b612af9f97f9a13d65ff4a55f9", "max_stars_repo_licenses": ["CC-BY-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": "01_R_Class/Bonus/polnet2018/test.r", "max_issues_repo_name": "LDJWJ/SBA01_BigData", "max_issues_repo_head_hexsha": "e851974017ca55b612af9f97f9a13d65ff4a55f9", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_R_Class/Bonus/polnet2018/test.r", "max_forks_repo_name": "LDJWJ/SBA01_BigData", "max_forks_repo_head_hexsha": "e851974017ca55b612af9f97f9a13d65ff4a55f9", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 95, "alphanum_fraction": 0.6667165519, "num_tokens": 2674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.4424337446776617}}
{"text": "## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n## Functions for the Soay sheep coat colour IBM\n## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nlibrary(arm) ## invlogit\n\n## Population statistics from annual sheep data\nsdNt <- 127.1302\nmidNt <- 431.7917\nscaleN <- function(N) return((N-midNt)/sdNt)\n\n## Mean age and capture weight of mothers of age 0 individuals (from\n## Soay demographic data)\nmean.ageMum <- 4.06147\nmean.capWgtMum <- 3.082146\n\ninitState <- function (m.par, init.pop.size = 500, init.G = NULL, maxA = 15) {\n ## Initialise individual state array for the population.\n\n ## Follows strategy in supplementary material to Rees et al. 2014,\n ## which is to initialise the population with a random selection\n ## of new recruits from a normal distribution based on mean parent\n ## size.\n\n ## If an initial genotype is specified then the new individuals\n ## are assigned to that genotype, with an equal number of\n ## offspring of each sex. Otherwise, offspring are equally\n ## distributed between sexes and genotypes.\n\n ## Args:\n ## m.par: Demographic model parameters.\n ## init.pop.size: Initial size of the population.\n ## init.G: Initial genotype of population.\n ## maxA: Maximum age.\n\n ## Returns:\n ## Individual state array containing the size of each individual\n ## in the population, structured by age, sex and coat colour\n ## genotype.\n\n ## Population structure - age, sex, genotype\n Aset <- as.character(seq.int(0, maxA))\n Gset <- c(\"GG\",\"GT\",\"TT\")\n Sset <- c(\"F\",\"M\")\n\n ## Initialise state array\n z <- mk.flist(list(S=Sset, A=Aset, G=Gset))\n\n ## Assume equal numbers of offspring of each sex, distributed\n ## equally amongst genotypes, unless an initial genotype is\n ## specified.\n n <- ifelse(is.null(init.G), init.pop.size/6, init.pop.size/2)\n\n ## Get proportion of twins in the new population based on twinning\n ## rate for an average adult female\n p.twin <- invlogit(m.par[\"t.a1.F.(Intercept)\"] + m.par[\"t.a1.F.capWgt\"]*mean.capWgtMum\n + m.par[\"t.a1.F.poly(ageY, 2, raw = TRUE)1\"]*mean.ageMum\n + m.par[\"t.a1.F.poly(ageY, 2, raw = TRUE)2\"]*mean.ageMum^2)\n ## Proportion of twins is number of twin lambs over total number of lambs\n ## From twinning rate, 0.5*num.twin = p.twin(0.5*num.twin + num.sing))\n ## Substitute num.sing = num.tot - num.twin and rearrange to get num.twin/num.tot:\n prop.twin <- 2*p.twin/(1+p.twin)\n\n ## Get the sizes of the new individuals in each class, based on\n ## mean maternal state\n for (G in Gset) {\n if (!is.null(init.G) && init.G != G) next\n for (S in Sset) {\n mu <- m.par[\"sz.off.(Intercept)\"] +\n m.par[\"sz.off.capWgtMum\"]*mean.capWgtMum +\n m.par[\"sz.off.ageMum\"]*mean.ageMum +\n m.par[\"sz.off.sexM\"]*as.numeric(S==\"M\")\n\n z[[S, \"0\", G]] <- c(rnorm(n*prop.twin\n , mean = mu + m.par[\"sz.off.isTwnMat\"]\n , sd = m.par[\"sz.off.sigma\"]),\n rnorm(n*(1-prop.twin)\n , mean = mu\n , sd = m.par[\"sz.off.sigma\"]))\n\n }\n }\n return(z)\n}\n\ndoSim <- function (model.params, init.pop.size = 500, sim.length = 200, init.G = NULL, init.state = NULL, maxA = 15) {\n ## Run simulation for the Soay coat colour genotype IBM.\n\n ## This could be generalised to require that client passes in the\n ## functions required to set up the state array for the system and\n ## to iterate the array between time steps.\n\n ## Args:\n ## model.params: Demographic model parameters.\n ## init.pop.size: Initial size of the population.\n ## sim.length: Maximum number of time-steps in simulation.\n ## init.G: Initial genotype.\n ## init.state: Initial state array. If not specified then an\n ## initial population state array is generated.\n ## maxA: Maximum age of individuals.\n\n ## Returns:\n ## Time series data consisting of population state array for each time step.\n\n ## Check the dimensions of model.params to determine whether\n ## to run simulation as averaged or variable environment.\n tEnv <- numeric(0)\n mPar <- model.params\n if (!is.null(dim(mPar))) {\n ## Sample environment parameters from the set available\n tEnv <- sample(1:(dim(mPar)[2]), sim.length+1, replace=TRUE)\n mPar <- model.params[,tEnv[1]]\n }\n\n ## Get initial population state\n if (is.null(init.state)) {\n z <- initState (mPar, init.pop.size, init.G, maxA)\n } else {\n z <- init.state\n }\n\n ## Population structure - age, sex, genotype\n Aset <- dimnames(z)$A\n Gset <- dimnames(z)$G\n Sset <- dimnames(z)$S\n\n numAset <- as.numeric(Aset)\n names(numAset) <- Aset\n numGset <- seq.int(-1,1)\n names(numGset) <- Gset\n\n ## Storage for simulated population at each timestep\n zt <- list(sim.length)\n\n for (i in seq_len(sim.length)) {\n if(length(tEnv)>0) {\n ## Select model parameters for this step\n mPar <- model.params[,tEnv[i+1]]\n }\n\n ## Get the current population density (standardized according\n ## to the mean and standard deviation observed in the St Kilda\n ## population)\n Nt <- scaleN(length(unlist(z)))\n\n ## Calculate male paternity probabilities for each genotype\n pGm <- calcMalePaternity(z, Nt, mPar)\n\n ## Apply life history events\n z1 <- mk.flist(list(S=Sset, A=Aset, G=Gset))\n z1.rec <- mk.flist(list(S=Sset, G=Gset))\n for (G in Gset) {\n numG <- switch(G, GG=-1, GT=0, TT=+1)\n for (A in Aset) {\n numA <- numAset[A]\n for (S in Sset) {\n z.sub <- z[[S, A, G]]\n if (!is.null(z.sub) & length(z.sub) > 0) {\n\n ## survival\n pS <- p.surv(z.sub, numG, S, numA, Nt, mPar)\n surv <- rbinom(n=length(z.sub), prob=pS, size=1)\n z.sub <- z.sub[which(surv == 1)]\n\n if (length(z.sub) == 0) next\n\n ## growth\n if (numA < maxA) {\n z1[[S, as.character(numA+1), G]] <- r.grow(z.sub, numG, S,\n numA, Nt, mPar)\n }\n\n ## reproduction\n if (S == \"F\" && !is.na(pGm)) {\n pB <- p.repr(z.sub, numG, numA, Nt, mPar)\n repr <- rbinom(n=length(z.sub), prob=pB, size=1)\n z.repr <- z.sub[which(repr == 1)]\n\n ## Twin or not?\n pT <- p.twin(z.repr, numG, numA, Nt, mPar)\n twin <- rbinom(n=length(z.repr), prob=pT, size=1)\n\n for (t.off in seq.int(0,1)) {\n\n z_ <- z.repr[which(twin == t.off)]\n n.off <- ifelse(t.off == 1, 2*length(z_), length(z_))\n\n ## Offspring sex\n o.sex <- rbinom(n=n.off, prob=0.5, size=1)\n o.sex <- paste(c(\"F\",\"M\")[match(o.sex, c(0,1))])\n\n ## Offspring genotype\n ## pGm is paternity probability for male genotypes\n pOffgen <- p.offgenotype(Gset, G, pGm)\n ## Assign (numeric) genotypes to\n ## offspring; not taking account of\n ## paternity of twins for now. (Pemberton\n ## et al. 1999 recorded 26% of twins with\n ## known paternity having same sire.)\n o.gen <- rmultinom(n=n.off, prob=pOffgen, size=1)\n o.gen <- t(o.gen)%*%numGset\n\n ## Offspring survival\n ## Need to do for each offspring sex (M/F) and twin (0/1) status\n for (s.off in Sset) {\n ## Index into maternal set for this sex\n ## This should sort out the parents appropriately for twin offspring\n i.subset <- which(o.sex == s.off)\n i.par <- ifelse(t.off == 1, ceiling(i.subset/2), i.subset)\n pRec <- p.offsurv(z_[i.par], A=numA, Nt=Nt, mPar=mPar,\n S.off=s.off, T.off=t.off)\n recr <- rep(NA, n.off)\n recr[i.subset] <- rbinom(n=length(i.subset), prob=pRec, size=1)\n\n ## Recruit size\n if (sum(recr,na.rm=TRUE)>0) {\n z1.rec <- rep(NA, n.off)\n i.recr <- which(recr == 1)\n i.par <- ifelse(t.off == 1, ceiling(i.recr/2), i.recr)\n z1.rec[i.recr] <- r.offsize(z_[i.par], numG, numA, Nt,\n mPar, S.o=s.off, T.off=t.off)\n ## Store result for each genotype from the survivors\n for (numG.off in unique(o.gen[which(recr==1)])) {\n G.off <- Gset[numG.off+2]\n z1[[s.off, \"0\", G.off]] <- c(z1[[s.off, \"0\", G.off]],\n z1.rec[which(recr == 1 &\n o.gen == numG.off)])\n }\n }\n }\n }\n }\n }\n }\n }\n }\n ## Store population for this timestep\n zt[[i]] <- z1\n if(length(unlist(z1)) == 0) {\n break\n }\n z <- z1\n }\n return(zt)\n}\n\ncalcMalePaternity <- function(z, Nt, model.params) {\n ## Calculate male paternity probabilities for each genotype.\n\n ## Calculates male paternity probabilities for each genotype based\n ## on the expected number of offspring for males of each genotype\n ## in the population.\n\n ## Args:\n ## z: Population state vector\n ## Nt: Population density\n ## model.params: Vital rate model parameters\n\n ## Returns:\n ## Vector indicating the probability of paternity for males of\n ## each genotype, or NA if the expected number of offspring for\n ## all genotypes is zero.\n\n Gset <- dimnames(z)$G\n Aset <- dimnames(z)$A\n num.off <- mk.flist(list(G=Gset))\n for (G in Gset) {\n num.off[[G]] <- 0\n numG <- switch(G, GG=-1, GT=0, TT=+1)\n for (A in Aset) {\n z.sub <- z[[\"M\", A, G]]\n if (!is.null(z.sub) & length(z.sub) > 0) {\n numA <- as.numeric(A)\n ## n.mrepro gives mean num offspring for each individual\n lambda <- n.mrepro(z.sub, numG, numA, Nt, model.params)\n ## rpois gets random pick from Poisson distribution with the given mean\n num.off[[G]] <- sum(sapply(lambda, function(x) rpois(1,x))) + num.off[[G]]\n }\n }\n }\n ## obtain mating probs\n nTot <- sum(unlist(num.off))\n if (nTot > 0) {\n pGm <- sapply(num.off, function(x) x/nTot)\n } else {\n pGm <- NA\n }\n return(pGm)\n}\n\nsummariseSimRun <- function (simRun) {\n simLen <- length(simRun)\n ntT <- ntF <- ntM <- ntGG <- ntGT <- ntTT <- numeric(simLen)\n ## compute quantities\n for (tt in 1:simLen) {\n nt1 <- simRun[[tt]]\n ntT [tt] <- length(unlist(nt1[ ,, ]))\n ntF [tt] <- length(unlist(nt1[\"F\",, ]))\n ntM [tt] <- length(unlist(nt1[\"M\",, ]))\n ntGG[tt] <- length(unlist(nt1[ ,,\"GG\"]))\n ntGT[tt] <- length(unlist(nt1[ ,,\"GT\"]))\n ntTT[tt] <- length(unlist(nt1[ ,,\"TT\"]))\n }\n return( list(ntT=ntT, ntF=ntF, ntM=ntM, ntGG=ntGG, ntGT=ntGT, ntTT=ntTT) )\n}\n\n\n## Adapted from IPM code\nr.grow.list <- mk.flist(list(S=c(\"F\",\"M\"), A=c(0,+1)))\n\nr.grow.list[[\"F\",\"0\"]] <- function(x, Nt, mPar) {\n mu <- mPar[\"g.a0.F.(Intercept)\"]+mPar[\"g.a0.F.capWgt\"]*x+mPar[\"g.a0.F.Nt\"]*Nt\n sg <- mPar[\"g.a0.F.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.grow.list[[\"F\",\"1\"]] <- function(x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.F.(Intercept)\"] +\n mPar[\"g.a1.F.capWgt\"]*x +\n mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A +\n mPar[\"g.a1.F.Nt\"]*Nt +\n mPar[\"g.a1.F.ageY:Nt\"]*Nt*A +\n mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2\n sg <- mPar[\"g.a1.F.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.grow.list[[\"M\",\"0\"]] <- function(x, Nt, mPar) {\n mu <- mPar[\"g.a0.M.(Intercept)\"]+\n mPar[\"g.a0.M.capWgt\"]*x+\n mPar[\"g.a0.M.Nt\"]*Nt+\n mPar[\"g.a0.M.obsY\"]*mPar[\"obsY\"]\n sg <- mPar[\"g.a0.M.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.grow.list[[\"M\",\"1\"]] <- function(x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.M.(Intercept)\"] +\n mPar[\"g.a1.M.capWgt\"]*x\n sg <- mPar[\"g.a1.M.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\n\nr.grow <- function(x, G, S, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(S) != 1 | length(A) != 1)\n stop(\"growth function not vectorised for S(ex) and (A)ge\")\n ## assign the required function\n if (S==\"F\") {\n if (A == 0) {\n f <- r.grow.list[[\"F\", \"0\"]]\n } else if (A >= 1) {\n f <- r.grow.list[[\"F\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else if (S==\"M\") {\n if (A == 0) {\n f <- r.grow.list[[\"M\", \"0\"]]\n } else if (A >= 1) {\n f <- r.grow.list[[\"M\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else stop(\"invalid (S)ex\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## Adapted from IPM code\nr.offsize.list <- mk.flist(list(S.off=c(\"F\",\"M\"), T.off=c(\"0\",\"1\")))\n\nr.offsize.list[[\"F\",\"0\"]] <- function(x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.offsize.list[[\"M\",\"0\"]] <- function(x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.offsize.list[[\"F\",\"1\"]] <- function(x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\nr.offsize.list[[\"M\",\"1\"]] <- function(x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(rnorm(length(x),mu,sg))\n}\n\nr.offsize <- function(x, G, A, Nt, mPar, S.off, T.off)\n{\n ## expect S and A to have length=1\n if (length(S.off) != 1 | length(T.off) != 1)\n stop(\"offspring size function not vectorised for offspring S(ex), female (A)ge and (T)win status\")\n ## assign the required function\n if (all(A >= 0)) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- r.offsize.list[[\"F\",\"0\"]]\n } else if (T.off == 1) {\n f <- r.offsize.list[[\"F\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- r.offsize.list[[\"M\",\"0\"]]\n } else if (T.off == 1) {\n f <- r.offsize.list[[\"M\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n", "meta": {"hexsha": "21b5a19b387f3677fd0e994c9712c4745d75043c", "size": 17416, "ext": "r", "lang": "R", "max_stars_repo_path": "code_r/ibm_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/ibm_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/ibm_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": 40.1290322581, "max_line_length": 118, "alphanum_fraction": 0.481511254, "num_tokens": 4824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4414820244696}}
{"text": "#####################################################################################################\n# Function for FDR corrected hypergeometric enrichment test\n#####################################################################################################\nset.based.enrichment.test=function(steps, pool, select, DB, nthread=1) {\n \n \n ## convert the database and the select and pollt to sorted integer lists\n list_of_all_genes<-unique(c(unlist(DB),pool))\n\n \n select <- intersect ( select, pool) \n \n ############\n \n DB_names <- names(DB)\n number_of_DB_categories <- length(DB) # Number of DB categories\n size_pool <- length(pool)\n size_select <- length(select)\n \n # init empty data frame with the row-size of DB (number of DB categories) to store the result\n result_df1 <- data.frame(\n DB_names=DB_names,\n DB_in_select = as.integer(NA),\n DB_in_pool = as.integer(NA),\n Genes_in_DB = as.integer(NA),\n P_val = as.double(NA),\n R_obs = as.integer(NA)\n )\n \n \n # for every DB entity in the DB list\n for (i in 1:number_of_DB_categories)\n {\n # create a vector of genes connected to the i-th DB category\n current_DB_category=DB[[i]]\n # hypergometric test\n result_df1$DB_in_select[i]=length(intersect(select,current_DB_category)) \t#q: number of common genes between a DBterm and select\n result_df1$DB_in_pool[i]=length(intersect(pool,current_DB_category))\t#m: number of common genes between DBterm and BackGround\n result_df1$Genes_in_DB[i]=length(current_DB_category)\t\t\t\n \n }\n \n \n # compute the p values (raw p values witout any corrections )\n #\n # n: number of non-pool genes among DB\n # k: number of genes in select\n # phyper(q, m, n, k, lower.tail = TRUE, log.p = FALSE)\n result_df1$P_val=1-phyper(result_df1$DB_in_select-1, result_df1$DB_in_pool, size_pool-result_df1$DB_in_pool, size_select) \n \n \n P_val_round=round(result_df1$P_val, digits=15) ## can change the digits, this is important for the precision of '0' is R\n result_df1$R_obs=rank(P_val_round, na.last = TRUE,ties.method =\"max\")\n \n \n result_df1$P_adj_Bonf=p.adjust(result_df1$P_val, method=\"bonferroni\")\n result_df1$P_adj_BH=p.adjust(result_df1$P_val, method=\"BH\")\n \n ################################################\n ############# simualtion\n ######\n \n if(length(select)==0 )\n {\n result_df1$R_exp=NaN\n result_df1$FDR=NaN\n \n return(result_df1)\n }\n \n \n names(DB) <- NULL \n \n \n\n if( nthread==1)\n {\n \n # simple call op C++ part of the code\n \n simulation_result_tbl = tryCatch(\n enrichment_test_simulation(\n DB, \n list_of_all_genes , \n pool, \n length(select), \n steps, \n 0) \n , error = print) # RCPP calling\n }else if(nthread>1 && round(nthread)==nthread)\n {\n \n # paralel call of C++ \n \n vv<-floor(steps / nthread)\n cc<-steps %% nthread\n steps_per_thread <- c( rep(vv , nthread-cc),rep(vv+1 , cc))\n seeds_per_thread <- sample( 2^15,nthread)\n stopifnot(sum( steps_per_thread)==steps)\n rm(cc,vv)\n \n library(parallel)\n cl <- makeCluster(spec=nthread, type = \"PSOCK\",outfile= \"log1.txt\")\n \n current_env <- environment()\n clusterExport(cl,\"DB\", envir = current_env)\n clusterExport(cl,\"list_of_all_genes\", envir = current_env)\n clusterExport(cl,\"pool\", envir = current_env)\n clusterExport(cl,\"select\", envir = current_env)\n # clusterExport(cl,\"enrichment_test_simulation\") #, envir = current_env\n clusterExport(cl,\"seeds_per_thread\", envir = current_env)\n clusterExport(cl,\"steps_per_thread\", envir = current_env)\n \n clusterEvalQ(cl, library(MulEA))\n \n # Sys.sleep(10)\n \n # muleaPkgDir <- find.package(\"MulEA\")\n # cppSourceFile <- paste(muleaPkgDir,\"/srcCpp/set-based-enrichment-test.cpp\", sep = \"\")\n # clusterExport(cl,\"cppSourceFile\", envir = current_env)\n \n # clusterEvalQ(cl, library(Rcpp))\n \n # clusterEvalQ(cl, Sys.setenv(\"PKG_CXXFLAGS\"=\"-std=c++11\"))\n # sourceCpp(code='\n # #include \n # \n # // [[Rcpp::export]]\n # int fibonacci(const int x) {\n # if (x == 0) return(0);\n # if (x == 1) return(1);\n # return (fibonacci(x - 1)) + fibonacci(x - 2);\n # }'\n # )\n \n # clusterEvalQ(cl, sourceCpp(cppSourceFile))\n # clusterEvalQ(cl, Rcpp::sourceCpp(cppSourceFile))\n \n result_of_paralel <- clusterApplyLB(cl=cl,1:nthread, function(idx){\n simulation_result_tbl <- tryCatch(\n enrichment_test_simulation(\n DB, \n list_of_all_genes , \n pool, \n length(select), \n steps_per_thread[[idx]], \n seeds_per_thread[[idx]]) \n , error = print) # RCPP hívás\n \n return(simulation_result_tbl)\n })\n \n stopCluster(cl)\n simulation_result_tbl<-do.call(rbind, result_of_paralel) \n \n }else{\n stop(\"nthred parameter must be a positive integer number\")\n }\n \n \n \n names(simulation_result_tbl)<-c(\"DB_in_pool\",\"intersect.size\",\"multiplicity\") # set the column names\n simulation_result_tbl$p <- 1-phyper(simulation_result_tbl$intersect.size-1, simulation_result_tbl$DB_in_pool, length(pool)-simulation_result_tbl$DB_in_pool, length(select))\n \n # test consitency\n stopifnot(steps*length(DB)==sum(simulation_result_tbl$multiplicity)) # ez nem fontos, de igy kell legyen\n if(! all(is.finite(simulation_result_tbl$p)) ) {stop(\"ERROR_002\")} # TODO handle somehow the exception \n \n \n # from the manual of phyper(q, m, n, k)\n # \n # simulation_result_tbl$intersect.size-1 ~ q vector of quantiles representing the number of white balls drawn without replacement from an urn which contains both black and white balls.\n #\n # simulation_result_tbl$DB_in_pool ~ m the number of white balls in the urn.\n # length(pool)-simulation_result_tbl$DB_in_pool ~ n \tthe number of black balls in the urn.\n # length(select) ~ k the number of balls drawn from the urn, hence must be in 0,1,…, m+n.\n \n \n \n #############################\n # group by the equal p-values and summarise the multiplicities \n \n simulation_result_tbl<-simulation_result_tbl[,c(\"multiplicity\",\"p\")]\n simulation_result_tbl$p<-round(simulation_result_tbl$p, digits=15)\n simulation_result_tbl<-simulation_result_tbl[order(simulation_result_tbl$p),]\n \n list11<- split(simulation_result_tbl,simulation_result_tbl$p)\n \n for( i in seq(list11))\n {\n if(nrow( list11[[i]])>1)\n {\n list11[[i]]<-data.frame(multiplicity=sum(list11[[i]]$multiplicity),p=list11[[i]]$p[1])\n }\n }\n simulation_result_tbl<-do.call(rbind, list11)\n rownames(simulation_result_tbl)<-NULL\n rm(list11)\n \n ##############################################\n \n ##########\n \n # some preparation to help the binary search\n if(simulation_result_tbl$p[1]!=0)\n {\n simulation_result_tbl<-rbind(data.frame(multiplicity=0,p=0),simulation_result_tbl)\n }\n if(simulation_result_tbl$p[nrow(simulation_result_tbl)]!=1)\n {\n simulation_result_tbl<-rbind(simulation_result_tbl,data.frame(multiplicity=0,p=1))\n }\n \n simulation_result_tbl$cum_sum_multiplicity<-cumsum(simulation_result_tbl$multiplicity)\n \n \n \n R_exp=integer(number_of_DB_categories) # init an empty vector. I will store here the result\n \n NN<-simulation_result_tbl$cum_sum_multiplicity[nrow(simulation_result_tbl)] # this id the greatest/last in cumsum.multiplicity\n for (i in 1:number_of_DB_categories) {\n if(P_val_round[i]>=1)\n {\n R_exp[i]= NN # it makes things much faster \n }else{\n target<-P_val_round[i]\n \n # binary search\n a1 <- 1\n a2 <- nrow(simulation_result_tbl) #-cnt.of.ones\n while(a1+1 < a2) \n {\t\n \n a3<-floor((a1+a2)/2)\n current <- simulation_result_tbl$p[a3]\n if( current <= target)\n {\n a1<-a3\n }\n else\n {\n a2<-a3\t\n }\n }\n # at the end of the binary search the \n # simulation_result_tbl$cum_sum_multiplicity[[a1]] is the count of p where p<=target\n # and a2=a1+1\n #\t\t \t\tR_exp[l]<-a2\n R_exp[i]<-simulation_result_tbl$cum_sum_multiplicity[[a1]]\n }\n }\n result_df1$R_exp=R_exp/steps\n result_df1$FDR=result_df1$R_exp/result_df1$R_obs\n \n \n return(result_df1)\n}\n", "meta": {"hexsha": "030d68ab547849fa4582ace967932c1e06559675", "size": 8288, "ext": "r", "lang": "R", "max_stars_repo_path": "R/set-based-enrichment-test.r", "max_stars_repo_name": "olbeimarton/MulEA", "max_stars_repo_head_hexsha": "f9288d49b5c15ff76b65cc4e35e5293f314f4b64", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-09-26T13:14:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T09:28:56.000Z", "max_issues_repo_path": "R/set-based-enrichment-test.r", "max_issues_repo_name": "olbeimarton/MulEA", "max_issues_repo_head_hexsha": "f9288d49b5c15ff76b65cc4e35e5293f314f4b64", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2021-03-14T14:11:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T20:06:19.000Z", "max_forks_repo_path": "R/set-based-enrichment-test.r", "max_forks_repo_name": "olbeimarton/MulEA", "max_forks_repo_head_hexsha": "f9288d49b5c15ff76b65cc4e35e5293f314f4b64", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-01-16T09:04:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T14:18:26.000Z", "avg_line_length": 32.1240310078, "max_line_length": 188, "alphanum_fraction": 0.6298262548, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4414820244695999}}
{"text": "#' Generic density function for HMM's emission probability\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data\n#' @param j hidden state index\n#' @param model current model as defined in hmmspec.gen(..)\n#' @return the emssion density of hidden state j\n#' @details see example code for usage\n#' @export\ngeneric.density = function( x, j, model, NegInf=-1000 ) {\n require(corpcor)\n p = NCOL(x)\n Ttot = NROW(x)\n D = model$D\n M = model$M\n if ( length(model$mtype) != p )\n stop(\"no. of columns does not equal length of mtype.\")\n\n # 1 = discrete\n ix1 = which(model$mtype == 1)\n if ( length(ix1) == 1 ) { \n # prob.v is a vector of length D, the number of multinomial outcomes\n prob.v = model$parms.emission$M1$prob.l[[j]]\n # x is coded so that it just take a simple table look-up to get the emission probability\n if ( model$Log ) {\n logb1 = log(prob.v[x]) # table look up\n } else {\n logb1 = prob.v[x] # table look up \n }\n } else if ( length(ix1) > 1 ) {\n # prob.m is a matrix max(D) x p\n prob.m = model$parms.emission$M1$prob.l[[j]]\n bb = matrix(0, nrow=Ttot, ncol=length(ix1))\n for ( i in 1:length(ix1) ) {\n if ( model$Log ) {\n bb[,i] = log(prob.m[x[, ix1[i]], i]) # <-- make sure usage matches definition\n } else {\n bb[,i] = prob.m[x[, ix1[i]], i] # <-- make sure usage matches definition\n }\n }\n if ( model$Log ) {\n logb1 = apply(bb, 1, sum)\n } else {\n logb1 = apply(bb, 1, prod)\n }\n } else {\n if ( model$Log ) {\n logb1 = rep(0, Ttot)\n } else {\n logb1 = rep(1, Ttot)\n }\n }\n\n # 2 = normal/multivariate\n ix2 = which(model$mtype == 2)\n if ( length(ix2) >= 1 ) {\n # for multivariate normal, M2$mu is a list of vector where the ith element\n # of the list is a vector for state i, and each element of the vector\n # is the mu for a gaussian density;\n # M2$sigma is a list of matrices where the ith element is the cov matrix for\n # state i.\n mu.v = model$parms.emission$M2$mu.l[[j]]\n sigma.m = model$parms.emission$M2$sigma.l[[j]]\n #cat(\"In generic.density, i see sigma :\", as.vector(sigma.m), \"\\n\")\n #ev = eigen(sigma.m)$values\n #cat(\"In generic.density, i see eigenvalues :\", ev, \"\\n\")\n if ( model$Log == FALSE & model$Intv == TRUE ) {\n logb2 = pmvnorm.intv(x[,ix2, drop=FALSE], mean=mu.v, sigma=sigma.m)\n } else {\n # Note that Dmvnorm will return a log value if log is set to TRUE.\n logb2 = Dmvnorm(x[,ix2, drop=FALSE], mean=mu.v, sigma=sigma.m, log=model$Log)\n }\n } else {\n if ( model$Log ) {\n logb2 = rep(0, Ttot)\n } else {\n logb2 = rep(1, Ttot)\n }\n }\n\n # 5 = gaussian mixture\n ix5 = which(model$mtype == 5)\n #cat(\"ix5\", ix5, \"\\n\")\n if ( length(ix5) >= 1 ) {\n # M5$mu is a list of lists where each element of the lists is a list, and\n # each element of this sublist is a vector corresponding to the mu for each\n # component of the mixture gaussian density; likewise, M5$sigma is a list\n # of lists, each list corresponds to a state, and each element of the sublist\n # corresponds to the cov matrix of a mixture component;\n # M5$c.l is a list of vectors, each element is the state i's mixture proportion\n # NOTATION : x.ll = list of list x.l = list\n mu.l = model$parms.emission$M5$mu.ll[[j]]\n sigma.l = model$parms.emission$M5$sigma.ll[[j]]\n c.v = model$parms.emission$M5$c.l[[j]]\n Ttot = NROW(x)\n # check for consistency\n #if ( length(c.v) != M ) {\n # cat(\"c.v length, M :\", length(c.v), M, \"\\n\")\n # stop(\"length mismatch in mixture parameters.\")\n #}\n # logbb : each row is a log probability of observing one observation (a row in x[,])\n # conditioned on mu and sigma of the hidden state\n logbb = matrix(NA, nrow=Ttot, ncol=M)\n for ( m in 1:M ) {\n tmp = x[, ix5, drop=FALSE]\n mu.v = mu.l[[m]]\n sigma.m = sigma.l[[m]]\n logbb[,m] = log(c.v[m]) + Dmvnorm(tmp, mean=mu.v, sigma=sigma.m, log=TRUE)\n }\n sum.p = rep(NA, Ttot)\n # since the columns of logbb are the gaussian mixture components, we need to sum them.\n for ( tt in 1:Ttot) {\n sum.p[tt] = Elnsum.vec(logbb[tt,]) # in the non-log version: sum.pr = rowSums(bb)\n }\n \n if ( model$Log == TRUE ) {\n logb5 = sum.p \n } else {\n logb5 = exp(sum.p)\n }\n } else {\n if ( model$Log ) {\n logb5 = rep(0, Ttot)\n } else {\n logb5 = rep(1, Ttot)\n }\n }\n\n # 3 = gamma\n ix3 = which(model$mtype == 3)\n if ( length(ix3) >= 1 ) {\n shape.v = model$parms.emission$M3$shape.l[[j]]\n scale.v = model$parms.emission$M3$scale.l[[j]]\n bb = matrix(NA, ncol=length(ix3), nrow=Ttot)\n for ( i in 1:length(ix3) ) {\n tmp = dgamma(x[,ix3[i]], shape=shape.v[i], scale=scale.v[i]) \n #iz = which(tmp < 1e-323)\n #tmp[iz] = 1e-323\n #cat(\"counting small values in dgamma:\", length(iz), \"\\n\")\n if ( model$Log ) {\n bb[,i] = log(tmp)\n } else {\n bb[,i] = tmp\n }\n }\n if ( model$Log ) {\n logb3 = apply(bb, 1, sum)\n } else {\n logb3 = apply(bb, 1, prod)\n }\n } else {\n if ( model$Log ) {\n logb3 = rep(0, Ttot)\n } else {\n logb3 = rep(1, Ttot)\n }\n }\n\n # 4 = beta\n ix4 = which(model$mtype == 4)\n if ( length(ix4) >= 1 ) {\n shape1.v = model$parms.emission$M4$shape1.l[[j]]\n shape2.v = model$parms.emission$M4$shape2.l[[j]]\n bb = matrix(NA, ncol=length(ix4), nrow=Ttot)\n for ( i in 1:length(ix4) ) {\n tmp = dbeta(x[,ix4[i]], shape1=shape1.v[i], shape2=shape2.v[i])\n #iz = which(tmp < 1e-323)\n #tmp[iz] = 1e-323\n #cat(\"counting small values in dgamma:\", length(iz), \"\\n\")\n if ( model$Log ) {\n bb[,i] = log(tmp)\n } else {\n bb[,i] = tmp\n }\n }\n if ( model$Log ) {\n logb4 = apply(bb, 1, sum)\n } else {\n logb4 = apply(bb, 1, prod)\n }\n } else {\n if ( model$Log ) {\n logb4 = rep(0, Ttot)\n } else {\n logb4 = rep(1, Ttot)\n }\n }\n if ( model$Log ) {\n b = logb1 + logb2 + logb3 + logb4 + logb5\n # NOTE : b may have -Inf, which can't be passed into C, so need to make them very small\n b[which(b < NegInf)] = NegInf\n } else {\n b = logb1 * logb2 * logb3 * logb4 * logb5\n } \n return(b)\n}\n\n#' Multivariable normal distribution at a point, calculate probability for a small interval around a point\n#'\n#' @param x numeric matrix\n#' @param mean mean vector of the multivariate normal \n#' @param sigma covariance matrix\n#' @param eps small numeric neighborhood around x\n#' @return vector of proabilities, length equal the number of rows in x\n#' @details used in generic.density\n#' @export\npmvnorm.intv = function (x, mean, sigma, eps=0.1) {\n require(mvtnorm)\n ll = x - eps/2\n uu = x + eps/2\n pp = double(NROW(x))\n for ( i in 1:NROW(x)) {\n pp[i] = pmvnorm(lower=ll[i,], upper=uu[i,], mean=mean, sigma=sigma) \n }\n return(pp)\n}\n\n#' Multivariable normal density for a hidden state evaluated at x\n#'\n#' @param x numeric matrix\n#' @param model HMM model\n#' @param j hidden state index\n#' @param Log boolean whether log is used, default to FALSE\n#' @return vector of proabilities, length equal the number of rows in x\n#' @details used in generic.density\n#' @export\ndmvnorm.hext = function (x, j, model, Log=FALSE) {\n mu.v = model$parms.emission$M2$mu.l[[j]]\n sigma.m = model$parms.emission$M2$sigma.l[[j]]\n ans = Dmvnorm(x, mean=mu.v, sigma=sigma.m, log=Log)\n #ans[is.na(ans)] <- 1 # not sure what this is for?\n return(ans)\n}\n\n#' Multivariable normal density, similar to the similar named function in mvtnorm\n#'\n#' @param x numeric matrix\n#' @param mean mean vector\n#' @param sigma covariance matrix\n#' @param log boolean whether log is used, default to FALSE\n#' @param num.cutoff numeric cutoff value\n#' @return vector of proabilities, length equal the number of rows in x\n#' @details use ginv from MASS to compute inverse matrix\n#' @export\nDmvnorm = function (x, mean, sigma, log=TRUE, num.cutoff=1e-100) {\n require(MASS) # MASS is needed because of ginv\n if (is.vector(x)) {\n x <- matrix(x, ncol = length(x))\n }\n #if (missing(mean)) {\n # mean <- rep(0, length = NCOL(x))\n #}\n #if (missing(sigma)) {\n # sigma <- diag(NCOL(x))\n #}\n #if (NCOL(x) != NCOL(sigma)) {\n # stop(\"x and sigma have non-conforming size\")\n #}\n #if (!isSymmetric(sigma, tol = sqrt(.Machine$double.eps))) {\n # assign(\"SIGMA\", sigma, envir = .GlobalEnv)\n # stop(\"sigma must be a symmetric matrix\")\n #}\n #if (length(mean) != NROW(sigma)) {\n # stop(\"mean and sigma have non-conforming size\")\n #}\n # Use this function from MASS, instead of the default solve() \n inv.sigma = ginv(sigma) \n \n distval = mahalanobis(x, center=mean, cov=inv.sigma, inverted=TRUE)\n ev = eigen(sigma, symmetric = TRUE, only.values = TRUE)$values\n logdet = sum(log(ev))\n \n logretval = -(NCOL(x) * log(2 * pi) + logdet + distval)/2\n ix = which(logretval > 0) # because exp(logretval) would be > 1\n #if ( length(ix) > 0 ) {\n # cat(\"NCOL(x):\", NCOL(x), \" \")\n # cat(\"logdet:\", logdet, \" \")\n # cat(\"distval[ix]:\", distval[ix], \"\\n\")\n #}\n \n if (log == TRUE) { \n return(logretval)\n } else { \n # put a floor on the probability value\n tmp = exp(logretval)\n ix = which( tmp < num.cutoff )\n if ( length(ix) > 0 ) {\n tmp[ix] = num.cutoff\n } \n return(tmp)\n }\n}\n\n#' Beta emission density for hidden state j in an HMM\n#'\n#' @param x numeric vector\n#' @param j hidden state index\n#' @param model HMM model\n#' @return vector of proabilities, length equal the number of rows in x\n#' @export\ndbeta.hext = function(x, j, model) {\n b = dbeta(x, shape1=model$parms.emission$shape1[j],\n shape2=model$parms.emission$shape2[j])\n b[is.na(b)] = 1\n return(b)\n}\n\n#' Multivariate beta emission density for hidden state j in an HMM\n#'\n#' @param x numeric matrix of size T x p, where T is number of obs, p the dimension of x\n#' @param j hidden state index\n#' @param model HMM model\n#' @return vector of proabilities, length equal the number of rows in x\n#' @export\ndmvbeta.hext = function(x, j, model) {\n p = NCOL(x)\n n = NROW(x)\n Shape1 = model$parms.emission$shape1[[j]]\n Shape2 = model$parms.emission$shape2[[j]]\n # shape and scale should be vector of length p\n if ( length(Shape1) != p | length(Shape2) != p )\n stop(\"shape1 or shape2 are of the wrong length!\")\n b = matrix(NA, nrow=n, ncol=p)\n for ( i in 1:p ) {\n b[,i] = dbeta(x[,i], shape1=Shape1[i], shape2=Shape2[i])\n }\n ans = apply(b, 1, prod)\n return(ans)\n}\n\n#' Univariate gamma emission density for hidden state j in an HMM\n#'\n#' @param x numeric vector\n#' @param j hidden state index\n#' @param model HMM model\n#' @return vector of proabilities, length equal the number of rows in x\n#' @export\ndgamma.hext = function(x, j, model) {\n b = dgamma(x, shape=model$parms.emission$shape[j],\n scale=model$parms.emission$scale[j])\n b[is.na(b)] = 1\n return(b)\n}\n\n#' Multivariate gamma emission density for hidden state j in an HMM\n#'\n#' @param x numeric matrix of size T x p, where T is number of obs, p the dimension of x\n#' @param j hidden state index\n#' @param model HMM model\n#' @return vector of proabilities, length equal the number of rows in x\n#' @export\ndmvgamma.hext = function(x, j, model) {\n p = NCOL(x)\n n = NROW(x)\n Shape = model$parms.emission$shape[[j]]\n Scale = model$parms.emission$scale[[j]]\n # shape and scale should be vector of length p\n if ( length(Shape) != p | length(Scale) != p )\n stop(\"shape or scale are of the wrong length!\")\n b = matrix(NA, nrow=n, ncol=p)\n for ( i in 1:p ) {\n b[,i] = dgamma(x[,i], shape=Shape[i], scale=Scale[i])\n }\n ans = apply(b, 1, prod)\n return(ans)\n}\n\n#' Weighted covariance matrices, similar to cov.wt in hsmm\n#'\n#' @param x numeric matrix of size T x p, where T is number of obs, p the dimension of x\n#' @param wt vector of weights for each obs\n#' @param cor boolean whether correlation matrix to be returned\n#' @param center centers to be used when computing covariances\n#' @param method either \"unbiased\" or \"ML\n#' @return list with components cov, center, n.obs, wt, cor\n#' @export\ncov.wt.hext = function (x, wt = rep(1/nrow(x), nrow(x)), cor = FALSE, center = TRUE, method = c(\"unbiased\", \"ML\")) {\n if (is.data.frame(x)) \n x <- as.matrix(x)\n else if (!is.matrix(x)) \n stop(\"'x' must be a matrix or a data frame\")\n if (!all(is.finite(x))) \n stop(\"'x' must contain finite values only\")\n n <- nrow(x)\n if (with.wt <- !missing(wt)) {\n if (length(wt) != n) \n stop(\"length of 'wt' must equal the number of rows in 'x'\")\n s = sum(wt)\n if (any(wt < 0) || s == 0) \n stop(\"weights must be non-negative and not all zero\")\n wt <- wt/s\n \n }\n if (is.logical(center)) {\n center <- if (center) \n colSums(wt * x)\n else 0\n }\n else {\n if (length(center) != ncol(x)) \n stop(\"length of 'center' must equal the number of columns in 'x'\")\n }\n x <- sqrt(wt) * sweep(x, 2, center, check.margin = FALSE)\n denom = 1 - sum(wt^2)\n if ( denom < 1e-300 ) {\n stop(\"1 - sum(wt^2) is very close to zero!\\n\")\n }\n cov <- switch(match.arg(method), unbiased=crossprod(x)/denom, ML = crossprod(x))\n y <- list(cov = cov, center = center, n.obs = n)\n if (with.wt) \n y$wt <- wt\n if (cor) {\n Is <- 1/sqrt(diag(cov))\n R <- cov\n R[] <- Is * cov * rep(Is, each = nrow(cov))\n y$cor <- R\n }\n y\n}\n\n", "meta": {"hexsha": "8a328211141bd96ad17ae3309182d231f26d2147", "size": 13952, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Density_fun.r", "max_stars_repo_name": "htso/Hext", "max_stars_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/Density_fun.r", "max_issues_repo_name": "htso/Hext", "max_issues_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/Density_fun.r", "max_forks_repo_name": "htso/Hext", "max_forks_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_forks_repo_licenses": ["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.219047619, "max_line_length": 116, "alphanum_fraction": 0.5799885321, "num_tokens": 4359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4413744167538253}}
{"text": "model_refreezing <- function (tavg = 0.0,\n Tmf = 0.0,\n SWrf = 0.0){\n #'- Name: Refreezing -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: snowfall accumulation calculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: It simulates the depth of snow cover and recalculate weather data\n #'- inputs:\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 #' * name: Tmf\n #' ** description : threshold temperature for snow melting \n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: SWrf\n #' ** description : degree-day temperature index for refreezing\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 #'- outputs:\n #' * name: Mrf\n #' ** description : liquid water in the snow cover in the process of refreezing\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n Mrf <- 0.0\n if (tavg < Tmf)\n {\n Mrf <- SWrf * (Tmf - tavg)\n }\n return (list('Mrf' = Mrf))\n}", "meta": {"hexsha": "2c03640c0b5ea97421110b2c62dec23bcfa4e9ed", "size": 2616, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Refreezing.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/Refreezing.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/Refreezing.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": 45.8947368421, "max_line_length": 108, "alphanum_fraction": 0.3275993884, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.44120472560593404}}
{"text": "/*\n * File: oarith.r\n * Contents: arithmetic operators + - * / % ^. Auxiliary routines\n * iipow, ripow.\n *\n * The arithmetic operators all follow a canonical conversion\n * protocol encapsulated in the macro ArithOp.\n */\n\n#ifdef DataParallel\nint list_add(dptr x, dptr y, dptr z);\n#endif\t\t\t\t\t/* DataParallel */\n\n#begdef ArithOp(icon_op, func_name, c_int_op, c_real_op, c_list_op)\n\n operator{1} icon_op func_name(x, y)\n declare {\n#ifdef LargeInts\n tended struct descrip lx, ly;\n#endif\t\t\t\t\t/* LargeInts */\n\t C_integer irslt;\n }\n#ifdef DataParallel\n if is:list(x) then {\n abstract {\n return type(x) ++ type(y)\n\t }\n\t inline { c_list_op(&x, &y, &result); return result; }\n }\n else\n#endif\t\t\t\t\t/* DataParallel */\n arith_case (x, y) of {\n C_integer: {\n abstract {\n return integer\n }\n inline {\n int over_flow = 0;\n c_int_op(x,y);\n }\n }\n integer: { /* large integers only */\n abstract {\n return integer\n }\n inline {\n big_ ## c_int_op(x,y);\n }\n }\n C_double: {\n abstract {\n return real\n }\n inline {\n c_real_op(x, y);\n }\n }\n }\nend\n\n#enddef\n\n/*\n * x / y\n */\n\n#begdef big_Divide(x,y)\n{\n if ( ( Type ( y ) == T_Integer ) && ( IntVal ( y ) == 0 ) )\n runerr(201); /* Divide fix */\n\n if (bigdiv(&x,&y,&result) == RunError) /* alcbignum failed */\n runerr(0);\n return result;\n}\n#enddef\n#begdef Divide(x,y)\n{\n if (y == 0)\n runerr(201); /* divide fix */\n\n irslt = div3(x,y, &over_flow);\n if (over_flow) {\n#ifdef LargeInts\n MakeInt(x,&lx);\n MakeInt(y,&ly);\n if (bigdiv(&lx,&ly,&result) == RunError) /* alcbignum failed */\n\t runerr(0);\n return result;\n#else /* LargeInts */\n runerr(203);\n#endif /* LargeInts */\n }\n else return C_integer irslt;\n}\n#enddef\n#begdef RealDivide(x,y)\n{\n double z;\n\n if (y == 0.0)\n runerr(204);\n\n z = x / y;\n return C_double z;\n}\n#enddef\n\n\nArithOp( / , divide , Divide , RealDivide, list_add /* bogus */)\n\n/*\n * x - y\n */\n\n#begdef big_Sub(x,y)\n{\n if (bigsub(&x,&y,&result) == RunError) /* alcbignum failed */\n runerr(0);\n return result;\n}\n#enddef\n\n#begdef Sub(x,y)\n irslt = sub(x,y, &over_flow);\n if (over_flow) {\n#ifdef LargeInts\n MakeInt(x,&lx);\n MakeInt(y,&ly);\n if (bigsub(&lx,&ly,&result) == RunError) /* alcbignum failed */\n runerr(0);\n return result;\n#else\t\t\t\t\t/* LargeInts */\n runerr(203);\n#endif\t\t\t\t\t/* LargeInts */\n }\n else return C_integer irslt;\n#enddef\n\n#define RealSub(x,y) return C_double (x - y);\n\nArithOp( - , minus , Sub , RealSub, list_add /* bogus */)\n\n\n/*\n * x % y\n */\n\n#define Abs(x) ((x) > 0 ? (x) : -(x))\n\n#begdef big_IntMod(x,y)\n{\n if ( ( Type ( y ) == T_Integer ) && ( IntVal ( y ) == 0 ) ) {\n irunerr(202,0);\n errorfail;\n }\n if (bigmod(&x,&y,&result) == RunError)\n runerr(0);\n return result;\n}\n#enddef\n\n#begdef IntMod(x,y)\n{\n irslt = mod3(x,y, &over_flow);\n if (over_flow) {\n irunerr(202,y);\n errorfail;\n }\n return C_integer irslt;\n}\n#enddef\n\n#begdef RealMod(x,y)\n{\n double d;\n\n if (y == 0.0)\n runerr(204);\n\n d = fmod(x, y);\n /* d must have the same sign as x */\n if (x < 0.0) {\n if (d > 0.0) {\n d -= Abs(y);\n }\n }\n else if (d < 0.0) {\n d += Abs(y);\n }\n return C_double d;\n}\n#enddef\n\nArithOp( % , mod , IntMod , RealMod, list_add /* bogus */ )\n\n/*\n * x * y\n */\n\n#begdef big_Mpy(x,y)\n{\n if (bigmul(&x,&y,&result) == RunError)\n runerr(0);\n return result;\n}\n#enddef\n\n#begdef Mpy(x,y)\n irslt = mul(x,y,&over_flow);\n if (over_flow) {\n#ifdef LargeInts\n MakeInt(x,&lx);\n MakeInt(y,&ly);\n if (bigmul(&lx,&ly,&result) == RunError) /* alcbignum failed */\n runerr(0);\n return result;\n#else\t\t\t\t\t/* LargeInts */\n runerr(203);\n#endif\t\t\t\t\t/* LargeInts */\n }\n else return C_integer irslt;\n#enddef\n\n\n#define RealMpy(x,y) return C_double ((long double)x * (long double)y);\n\nArithOp( * , mult , Mpy , RealMpy, list_add /* bogus */ )\n\f\n\n\"-x - negate x.\"\n\noperator{1} - neg(x)\n if cnv:(exact)C_integer(x) then {\n abstract {\n return integer\n }\n inline {\n\t C_integer i;\n\t int over_flow = 0;\n\n\t i = neg(x, &over_flow);\n\t if (over_flow) {\n#ifdef LargeInts\n\t struct descrip tmp;\n\t MakeInt(x,&tmp);\n\t if (bigneg(&tmp, &result) == RunError) /* alcbignum failed */\n\t runerr(0);\n return result;\n#else\t\t\t\t\t/* LargeInts */\n\t irunerr(203,x);\n errorfail;\n#endif\t\t\t\t\t/* LargeInts */\n }\n return C_integer i;\n }\n }\n#ifdef LargeInts\n else if cnv:(exact) integer(x) then {\n abstract {\n return integer\n }\n inline {\n\t if (bigneg(&x, &result) == RunError) /* alcbignum failed */\n\t runerr(0);\n\t return result;\n }\n }\n#endif\t\t\t\t\t/* LargeInts */\n else {\n if !cnv:C_double(x) then\n runerr(102, x)\n abstract {\n return real\n }\n inline {\n double drslt;\n\t drslt = -x;\n return C_double drslt;\n }\n }\nend\n\f\n\n\"+x - convert x to a number.\"\n/*\n * Operational definition: generate runerr if x is not numeric.\n */\noperator{1} + number(x)\n if cnv:(exact)C_integer(x) then {\n abstract {\n return integer\n }\n inline {\n return C_integer x;\n }\n }\n#ifdef LargeInts\n else if cnv:(exact) integer(x) then {\n abstract {\n return integer\n }\n inline {\n return x;\n }\n }\n#endif\t\t\t\t\t/* LargeInts */\n else if cnv:C_double(x) then {\n abstract {\n return real\n }\n inline {\n return C_double x;\n }\n }\n else\n runerr(102, x)\nend\n\n/*\n * x + y\n */\n\n#begdef big_Add(x,y)\n{\n if (bigadd(&x,&y,&result) == RunError)\n runerr(0);\n return result;\n}\n#enddef\n\n#begdef Add(x,y)\n irslt = add(x,y, &over_flow);\n if (over_flow) {\n#ifdef LargeInts\n MakeInt(x,&lx);\n MakeInt(y,&ly);\n if (bigadd(&lx, &ly, &result) == RunError) /* alcbignum failed */\n\t runerr(0);\n return result;\n#else\t\t\t\t\t/* LargeInts */\n runerr(203);\n#endif\t\t\t\t\t/* LargeInts */\n }\n else return C_integer irslt;\n#enddef\n\n#define RealAdd(x,y) return C_double (x + y);\n\nArithOp( + , plus , Add , RealAdd, list_add )\n\f\n#ifdef DataParallel\n\nint list_add(dptr x, dptr y, dptr z)\n{\n tended struct b_list *lp1;\n word size1, size2;\n word i, j, slot;\n\n if (is:list(*x) && is:list(*y)) {\n size1 = BlkLoc(*x)->List.size;\n size2 = BlkLoc(*y)->List.size;\n if (size1 != size2) return RunError;\n#ifdef Arrays \n if ( BlkType(BlkD(*x,List)->listhead)==T_Realarray){\n\t double *a, *c;\n\n\t if ( BlkType(BlkD(*y,List)->listhead)==T_Realarray){ /*the two are real arrays*/\n\t double *b;\n\t if (cprealarray(x, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t /* points to the three arrays data and copy! */\n\t a = ((struct b_realarray *) BlkLoc(*x)->List.listhead )->a;\n\t b = ((struct b_realarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead)->a;\n\t \n\t for(i=0; ilisthead)==T_Intarray){ /*first arrays is real, second is int*/\n\t word *b;\n\n\t if (cprealarray(x, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t \n\t a = ((struct b_realarray *) BlkLoc(*x)->List.listhead )->a;\n\t b = ((struct b_intarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead)->a;\n\t /* a is real, b is int, hopefully the c compiler knows how to do it*/\n\t for(i=0; iList.listhead;\n\t apc = (struct b_realarray *) BlkLoc(*z)->List.listhead;\n\t \n\t for (ep = BlkD(*y,List)->listhead; BlkType(ep) == T_Lelem;\n\t ep = Blk(ep,Lelem)->listnext){\n\t for (i = 0; i < Blk(ep,Lelem)->nused; i++) {\n\t\t j = ep->Lelem.first + i;\n\t\t if (j >= ep->Lelem.nslots)\n\t\t j -= ep->Lelem.nslots;\n\t\t \n\t\t if (!cnv:C_double(ep->Lelem.lslots[j], f)) \n\t\t return RunError;\n\t\t \n\t\t apc->a[k] = apa->a[k] + f;\n\t\t k++;\n\t\t }\n\t }\n\t }\n\t }\n else if ( BlkType(BlkD(*x,List)->listhead)==T_Intarray){\n\t word *a;\n\t \n\t if ( BlkType(BlkD(*y,List)->listhead)==T_Realarray){ /*first arrays is int, second is real*/\n\t double *b, *c;\n\t if (cprealarray(y, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t /* points to the three arrays data and copy! */\n\t a = ((struct b_intarray *) BlkLoc(*x)->List.listhead )->a;\n\t b = ((struct b_realarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead)->a;\n\t \n\t for(i=0; ilisthead)==T_Intarray){ /*the two are int arrays*/\n\t word *b, *c;\n\n\t if (cpintarray(x, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t \n\t a = ((struct b_intarray *) BlkLoc(*x)->List.listhead )->a;\n\t b = ((struct b_intarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_intarray *) BlkLoc(*z)->List.listhead)->a;\n\t /* a is real, b is int, hopefully the c compiler knows how to do it*/\n\t for(i=0; iList.listhead;\n\t apc = (struct b_intarray *) BlkLoc(*z)->List.listhead;\n\t \n\t for (ep = BlkD(*y,List)->listhead; BlkType(ep) == T_Lelem;\n\t ep = Blk(ep,Lelem)->listnext){\n\t for (i = 0; i < Blk(ep,Lelem)->nused; i++) {\n\t\t j = ep->Lelem.first + i;\n\t\t if (j >= ep->Lelem.nslots)\n\t\t j -= ep->Lelem.nslots;\n\t\t \n\t\t /* default : The resutling array is of type int */\n\t\t if (Type(ep->Lelem.lslots[j]) == T_Integer ){\n\t\t if (!cnv:C_integer(ep->Lelem.lslots[j], d))\n\t\t\treturn RunError;\n\t\t apc->a[k] = apa->a[k] + d;\n\t\t k++;\n\t\t }\n\t\t else{ \n\t\t /* we might be able to continue with real, copy the elements to \n\t\t * a new realarray and continue\n\t\t */\n\t\t tended struct b_realarray *apc2;\n\t\t double f;\n\t\t word ii;\n\t\t if (cpint2realarray(x, z, (word) 1, size1 + 1) == RunError)\n\t\t\treturn RunError;\n\t\t \n\t\t apc2 = (struct b_realarray *) BlkLoc(*z)->List.listhead;\n\t\t for (ii=0; iia[ii] = apc->a[ii];\n\t\t \n\t\t /* where we stoped in the last list lelem*/\n\t\t ii=i;\n\t\t /* no need to start over since elements were copied already*/\n\t\t for (/*ep = BlkD(*y,List)->listhead*/;\n\t\t\tBlkType(ep) == T_Lelem; ep = Blk(ep,Lelem)->listnext){\n\t\t\tfor (i = ii; i < Blk(ep,Lelem)->nused; i++) {\n\t\t\t j = ep->Lelem.first + i;\n\t\t\t if (j >= ep->Lelem.nslots)\n\t\t\t j -= ep->Lelem.nslots;\n\t\t\t if (!cnv:C_double(ep->Lelem.lslots[j], f))\n\t\t\t return RunError;\n\t\t\t apc2->a[k] = apa->a[k] + f;\n\t\t\t k++;\n\t\t\t }\n\t\t\tii=0;\n\t\t\t}\n\t\t return Succeeded;\n\t\t }\n\t\t } /*for i=0 */\n\t } /* for ep = */\n\t }\n\t }\n else if ( BlkType(BlkD(*y,List)->listhead)==T_Realarray){\n\t tended union block *ep;\n\t tended struct b_realarray *apa, *apc;\n\t word k=0;\n\t double f;\n\t \n\t if (cprealarray(y, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t \n\t apa = (struct b_realarray *) BlkLoc(*y)->List.listhead;\n\t apc = (struct b_realarray *) BlkLoc(*z)->List.listhead;\n\t \n\t for (ep = BlkD(*x,List)->listhead; BlkType(ep) == T_Lelem;\n\t ep = Blk(ep,Lelem)->listnext){\n\t for (i = 0; i < Blk(ep,Lelem)->nused; i++) {\n\t j = ep->Lelem.first + i;\n\t if (j >= ep->Lelem.nslots)\n\t\t j -= ep->Lelem.nslots;\n\t \n\t if (!cnv:C_double(ep->Lelem.lslots[j], f)) \n\t\t return RunError;\n\t \n\t apc->a[k] = apa->a[k] + f;\n\t k++;\n\t }\n\t }\n\t }\n else if ( BlkType(BlkD(*y,List)->listhead)==T_Intarray){\n\t tended union block *ep;\n\t tended struct b_intarray *apa, *apc;\n\t word k=0, d;\n\n\t if (cpintarray(y, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t \n\t apa = (struct b_intarray *) BlkLoc(*y)->List.listhead;\n\t apc = (struct b_intarray *) BlkLoc(*z)->List.listhead;\n\t \n\t for (ep = BlkD(*x,List)->listhead; BlkType(ep) == T_Lelem;\n\t ep = Blk(ep,Lelem)->listnext){\n\t for (i = 0; i < Blk(ep,Lelem)->nused; i++) {\n\t j = ep->Lelem.first + i;\n\t if (j >= ep->Lelem.nslots)\n\t\t j -= ep->Lelem.nslots;\n\t \n\t /* default : The resutling array is of type int */\n\t if (Type(ep->Lelem.lslots[j]) == T_Integer ){\n\t\t if (!cnv:C_integer(ep->Lelem.lslots[j], d))\n\t\t return RunError;\n\t\t apc->a[k] = apa->a[k] + d;\n\t\t k++;\n\t\t }\n\t else{ \n\t\t /* we might be able to continue with real, copy the elements to \n\t\t * a new realarray and continue\n\t\t */\n\t\t tended struct b_realarray *apc2;\n\t\t double f;\n\t\t word ii;\n\t\t if (cpint2realarray(y, z, (word) 1, size1 + 1) == RunError)\n\t\t return RunError;\n\t\t \n\t\t apc2 = (struct b_realarray *) BlkLoc(*z)->List.listhead;\n\t\t for (ii=0; iia[ii] = apc->a[ii];\n\t\t /* where we stoped in the last list lelem*/\n\t\t ii=i;\n\t\t /* no need to start over since elements were copied already*/\n\t\t for (/*ep = BlkD(*x,List)->listhead*/;\n\t\t BlkType(ep) == T_Lelem; ep = Blk(ep,Lelem)->listnext){\n\t\t for (i = ii; i < Blk(ep,Lelem)->nused; i++) {\n\t\t\tj = ep->Lelem.first + i;\n\t\t\tif (j >= ep->Lelem.nslots)\n\t\t\t j -= ep->Lelem.nslots;\n\t\t\tif (!cnv:C_double(ep->Lelem.lslots[j], f))\n\t\t\t return RunError;\n\t\t\tapc2->a[k] = apa->a[k] + f;\n\t\t\tk++;\n\t\t\t\n\t\t\t}\n\t\t\tii=0;\n\t\t }\n\t\t return Succeeded;\n\t\t \n\t\t }\n\t } /*for i=0*/\n\t } /* for ep */\n\t }\n else{ /* the two lists are of type List */\n#endif\t\t\t\t\t/* Arrays */\n\t struct descrip *slotptr;\n\t tended struct b_lelem *bp1;\n\t if (cplist(x, z, (word)1, size1 + 1) == RunError)\n\t return RunError;\n\t /* add in values from y */\n\n\t lp1 = (struct b_list *) BlkLoc(*y);\n\t bp1 = (struct b_lelem *) lp1->listhead;\n\t i = 1;\n\t slot = 0;\n\t while (size2 > 0) {\n\t j = bp1->first + i - 1;\n\t if (j >= bp1->nslots)\n\t j -= bp1->nslots;\n\t slotptr = BlkLoc(*z)->List.listhead->Lelem.lslots + slot++;\n\t list_add(slotptr, bp1->lslots+j, slotptr);\n\t if (++i > bp1->nused) {\n\t i = 1;\n\t bp1 = (struct b_lelem *) bp1->listnext;\n\t }\n\t size2--;\n\t }\n#ifdef Arrays\n\t }\n#endif\n }\n else if (is:list(*x)) {\n /* x a list, y a scalar */\n#ifdef Arrays\n if ( BlkType(BlkD(*x,List)->listhead)==T_Realarray){\n\t double *a, *c, f;\n\t size1 = BlkLoc(*x)->List.size;\n\t \n\t if (cprealarray(x, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t if (!cnv:C_double(*y, f)) \n\t return RunError;\n\t \n\t a = ((struct b_realarray *) BlkLoc(*x)->List.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead )->a;\n\n\t for(i=0; ilisthead)==T_Intarray){\n\t word *a, d;\n\t double f;\n\t size1 = BlkLoc(*x)->List.size;\n\t if ( Type ( *y ) == T_Integer ){\n\t word *c;\n\t if (!cnv:C_integer(*y, d)) \n\t return RunError;\n\t if (cpintarray(x, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t a = ((struct b_intarray *) BlkLoc(*x)->List.listhead )->a;\n\t c = ((struct b_intarray *) BlkLoc(*z)->List.listhead )->a;\n\t for(i=0; iList.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead )->a;\n\t for(i=0; iList.size;\n\t if (cplist(x, z, (word)1, size1 + 1) == RunError)\n\t return RunError;\n\t for (i=0; iList.listhead->Lelem.lslots + i;\n\t list_add(slotptr, y, slotptr);\n\t }\n#ifdef Arrays\t \n }\n#endif\t\t\t\t\t/* Arrays */\n }\n else if (is:list(*y)) {\n /* y a list, x a scalar */\n#ifdef Arrays \n if ( BlkType(BlkD(*y,List)->listhead)==T_Realarray){\n\t double *a, *c, f;\n\t size1 = BlkLoc(*y)->List.size;\n\t \n\t if (cprealarray(y, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t if (!cnv:C_double(*x, f)) \n\t return RunError;\n\t \n\t a = ((struct b_realarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead )->a;\n\n\t for(i=0; ilisthead)==T_Intarray){\n\t word *a, d;\n\t double f;\n\t size1 = BlkLoc(*y)->List.size;\n\t if ( Type ( *x ) == T_Integer ){\n\t word *c;\n\t if (!cnv:C_integer(*x, d)) \n\t return RunError;\n\t if (cpintarray(y, z, (word) 1, size1 + 1) == RunError)\n\t return RunError;\n\t a = ((struct b_intarray *) BlkLoc(*y)->List.listhead )->a;\n\t c = ((struct b_intarray *) BlkLoc(*z)->List.listhead )->a;\n\t for(i=0; iList.listhead )->a;\n\t c = ((struct b_realarray *) BlkLoc(*z)->List.listhead )->a;\n\t for(i=0; iList.size;\n\t if (cplist(y, z, (word)1, size1 + 1) == RunError)\n\t return RunError;\n\t for (i=0; iList.listhead->Lelem.lslots + i;\n\t list_add(slotptr, x, slotptr);\n\t }\n#ifdef Arrays\n\t }\n#endif\t\t\t\t\t/* Arrays */\t \n }\n else {\n C_integer tmp, tmp2, irslt;\n double tmp3, tmp4;\n#ifdef LargeInts\n tended struct descrip lx, ly;\n#endif\t\t\t\t\t/* LargeInts */\n \n /* x, y must be numeric */\n if (cnv:(exact)C_integer(*x, tmp) && cnv:(exact)C_integer(*y, tmp2)) {\n irslt = add(tmp,tmp2);\n\t if (over_flow) {\n#ifdef LargeInts\n MakeInt(x,&lx);\n MakeInt(y,&ly);\n if (bigadd(&lx, &ly, z) == RunError) /* alcbignum failed */\n return RunError;\n#endif\t\t\t\t\t/* LargeInts */\n\t }\n\t else MakeInt(irslt, z);\n }\n else if (cnv:C_double(*x, tmp3) && cnv:C_double(*y, tmp4)) {\n }\n else return RunError;\n }\n return Succeeded;\n}\n#endif\t\t\t\t\t/* DataParallel */\n\n\f\n\n\n\"x ^ y - raise x to the y power.\"\n\noperator{1} ^ powr(x, y)\n if cnv:(exact)C_integer(y) then {\n if cnv:(exact)integer(x) then {\n\t abstract {\n\t return integer\n\t }\n\t inline {\n#ifdef LargeInts\n\t tended struct descrip ly;\n\t MakeInt ( y, &ly );\n\t if (bigpow(&x, &ly, &result) == RunError) /* alcbignum failed */\n\t runerr(0);\n\t return result;\n#else\n\t int over_flow;\n\t C_integer r = iipow(IntVal(x), y, &over_flow);\n\t if (over_flow)\n\t runerr(203);\n\t return C_integer r;\n#endif\n\t }\n\t }\n else {\n\t if !cnv:C_double(x) then\n\t runerr(102, x)\n\t abstract {\n\t return real\n\t }\n\t inline {\n\t if (ripow( x, y, &result) == RunError)\n\t runerr(0);\n\t return result;\n\t }\n\t }\n }\n#ifdef LargeInts\n else if cnv:(exact)integer(y) then {\n if cnv:(exact)integer(x) then {\n\t abstract {\n\t return integer\n\t }\n\t inline {\n\t if (bigpow(&x, &y, &result) == RunError) /* alcbignum failed */\n\t runerr(0);\n\t return result;\n\t }\n\t }\n else {\n\t if !cnv:C_double(x) then\n\t runerr(102, x)\n\t abstract {\n\t return real\n\t }\n\t inline {\n\t if ( bigpowri ( x, &y, &result ) == RunError )\n\t runerr(0);\n\t return result;\n\t }\n\t }\n }\n#endif\t\t\t\t\t/* LargeInts */\n else {\n if !cnv:C_double(x) then\n\t runerr(102, x)\n if !cnv:C_double(y) then\n\t runerr(102, y)\n abstract {\n\t return real\n\t }\n inline {\n\t if (x == 0.0 && y < 0.0)\n\t runerr(204);\n\t if (x < 0.0)\n\t runerr(206);\n\t return C_double pow(x,y);\n\t }\n }\nend\n\n#if COMPILER || !(defined LargeInts)\n/*\n * iipow - raise an integer to an integral power. \n */\nC_integer iipow(C_integer n1, C_integer n2, int *over_flowp)\n {\n C_integer result;\n\n /* Handle some special cases first */\n *over_flowp = 0;\n switch ( n1 ) {\n case 1:\n\t return 1;\n case -1:\n\t /* Result depends on whether n2 is even or odd */\n\t return ( n2 & 01 ) ? -1 : 1;\n case 0:\n\t if ( n2 <= 0 )\n\t *over_flowp = 1;\n\t return 0;\n default:\n\t if (n2 < 0)\n\t return 0;\n }\n\n result = 1L;\n for ( ; ; ) {\n if (n2 & 01L)\n\t {\n\t result = mul(result, n1, over_flowp);\n\t if (*over_flowp)\n\t return 0;\n\t }\n\n if ( ( n2 >>= 1 ) == 0 ) break;\n n1 = mul(n1, n1, over_flowp);\n if (*over_flowp)\n\t return 0;\n }\n *over_flowp = 0;\n return result;\n }\n#endif\t\t\t\t\t/* COMPILER || !(defined LargeInts) */\n\n\n/*\n * ripow - raise a real number to an integral power.\n */\nint ripow(r, n, drslt)\ndouble r;\nC_integer n;\ndptr drslt;\n {\n double retval;\n CURTSTATE();\n\n if (r == 0.0 && n <= 0) \n ReturnErrNum(204, RunError);\n if (n < 0) {\n /*\n * r ^ n = ( 1/r ) * ( ( 1/r ) ^ ( -1 - n ) )\n *\n * (-1) - n never overflows, even when n == MinLong.\n */\n n = (-1) - n;\n r = 1.0 / r;\n retval = r;\n }\n else \t\n retval = 1.0;\n\n /* multiply retval by r ^ n */\n while (n > 0) {\n if (n & 01L)\n\t retval *= r;\n r *= r;\n n >>= 1;\n }\n#ifdef DescriptorDouble\n drslt->vword.realval = retval;\n#else\t\t\t\t\t/* DescriptorDouble */\n Protect(BlkLoc(*drslt) = (union block *)alcreal(retval), return RunError);\n#endif\t\t\t\t\t/* DescriptorDouble */\n drslt->dword = D_Real;\n return Succeeded;\n }\n", "meta": {"hexsha": "3ea06677153dd068850e11af43eb782065bcee39", "size": 22739, "ext": "r", "lang": "R", "max_stars_repo_path": "src/runtime/oarith.r", "max_stars_repo_name": "akhand1111/unicon", "max_stars_repo_head_hexsha": "096ebf0692eea58792b36b3cbe3da35842f85b4a", "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": "src/runtime/oarith.r", "max_issues_repo_name": "akhand1111/unicon", "max_issues_repo_head_hexsha": "096ebf0692eea58792b36b3cbe3da35842f85b4a", "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": "src/runtime/oarith.r", "max_forks_repo_name": "akhand1111/unicon", "max_forks_repo_head_hexsha": "096ebf0692eea58792b36b3cbe3da35842f85b4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0879237288, "max_line_length": 98, "alphanum_fraction": 0.5206033687, "num_tokens": 7429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4409083286315335}}
{"text": "# Function for generating NOEC distributions for each species\r\n# --- EXAMPLE OF A SPECIAL CASE FOR SILVER\r\n# \r\n# Yields a matrix with dimensions number of species * number of iterations in the simulation\r\n# \r\n# Arguments: - DP : matrix of data points\r\n# - UFt : matrix of uncertainty factors for the exposure time\r\n# - UFdd : matrix of uncertainty factors for the dose-descriptor\r\n# - SIM : number of iterations in the simulation\r\n# - CV.DP : coefficient of variation for the interlaboratory variation\r\n# - CV.UF : coefficient of variation for the use of non-substance-specific\r\n# uncertainty factors \r\n# \r\n# Date of last modification: 03.07.2019\r\n# \r\n# Associated publication: Systematic consideration of parameter uncertainty and variability in\r\n# probabilistic species sensitivity distributions\r\n# \r\n# Authors: Henning Wigger, Delphine Kawecki, Bernd Nowack and Véronique Adam\r\n# \r\n# Institute: Empa, Swiss Federal Laboratories for Materials Science and Technology,\r\n# Technology and Society Laboratory, Lerchenfeldstrasse 5, 9014 St. Gallen, Switzerland\r\n# \r\n# submitted to Integrated Environmental Assessment and Management in July 2019\r\n\r\n# -------------------------------------------------------------------------------------------------\r\n\r\n\r\n\r\ndo.pSSD.Ag <- function(DP,\r\n UFt,\r\n UFdd,\r\n SIM,\r\n CV.DP,\r\n CV.UF){\r\n \r\n # test if there is no data available for one species\r\n if(any(apply(DP,2,function(x) length(which(!is.na(x)))) == 0)){\r\n warning(\"No data is available for one or more species, it/they won't contribute to the PSSD calculation.\")\r\n # find which species has no data\r\n ind.sp.rem <- which(apply(DP,2,function(x) length(which(!is.na(x)))) == 0)\r\n # remove those columns\r\n DP <- DP[,-ind.sp.rem]\r\n UFt <- UFt[,-ind.sp.rem]\r\n UFdd <- UFdd[,-ind.sp.rem]\r\n }\r\n \r\n # Create the step distributions (or triangular or trapezoidal) for each species\r\n # Create an empty matrix in which step distributions will be compiled\r\n NOEC_comb <- matrix(NA, ncol(DP), SIM,\r\n dimnames = list(colnames(DP), NULL))\r\n \r\n # Fill in the matrix. If there is only one data point, NOEC stays the same. If there are\r\n # 2 endpoints, a uniform distribution is produced. If there are more than 2 endpoints, a step\r\n # distribution is produced. One line is for one species.\r\n require(trapezoid)\r\n require(mc2d)\r\n \r\n # store the corrected endpoints\r\n corr.endpoints <- DP/(UFdd*UFt)\r\n sort.endpoints <- apply(corr.endpoints,2, sort)\r\n \r\n for (sp in colnames(DP)){\r\n \r\n # store the indices of the minimal and maximal data point\r\n ind.min <- which.min(corr.endpoints[,sp])\r\n ind.max <- which.max(corr.endpoints[,sp])\r\n \r\n # calculate the theoretical minimum and maximum of the distribution we are looking for\r\n if (UFt[ind.min, sp] == 10){\r\n sp.min <- corr.endpoints[ind.min,sp]*(1-(sqrt((CV.DP/2.45)^2 + (CV.UF/2.45)^2)))/100\r\n } else {\r\n sp.min <- corr.endpoints[ind.min,sp]*(1-(sqrt((CV.DP/2.45)^2 + (CV.UF/2.45)^2 + (CV.UF/2.45)^2)*2.45))\r\n }\r\n if (UFt[ind.max, sp] == 10){\r\n sp.max <- corr.endpoints[ind.max,sp]*(1+(sqrt((CV.DP/2.45)^2) + (CV.UF/2.45)^2))/1\r\n } else {\r\n sp.max <- corr.endpoints[ind.max,sp]*(1+(sqrt((CV.DP/2.45)^2 + (CV.UF/2.45)^2 + (CV.UF/2.45)^2)*2.45))\r\n }\r\n \r\n # For species with one unique data point, NOEC stays the same:\r\n if(length(unique(sort.endpoints[[sp]])) == 1){\r\n NOEC_comb[sp,] <- rtrunc(\"rtriang\", min = sp.min, \r\n mode = sort.endpoints[[sp]][1],\r\n max = sp.max,\r\n n = SIM, linf = 0)\r\n \r\n \r\n # For species with two endpoints:\r\n } else if(length(sort.endpoints[[sp]]) == 2){\r\n # Create a trapezoidal distribution including both endpoints\r\n NOEC_comb[sp,] <- rtrunc(\"rtrapezoid\", SIM,\r\n mode1 = sort.endpoints[[sp]][1],\r\n mode2 = sort.endpoints[[sp]][2],\r\n min = sp.min, max = sp.max,\r\n linf = 0)\r\n \r\n \r\n # For species with three endpoints or more:\r\n } else {\r\n \r\n \r\n # Sample from this step distribution for each species\r\n NOEC_comb[sp,] <- rmore(values = sort.endpoints[[sp]], max = sp.max, min = sp.min, N = SIM, linf = 0)\r\n \r\n } \r\n }\r\n # return the whole matrix\r\n return(NOEC_comb)\r\n \r\n}\r\n\r\n", "meta": {"hexsha": "f50a50f0a0cf2d17284edd11a96a04a1b1f4aada", "size": 4666, "ext": "r", "lang": "R", "max_stars_repo_path": "do.pssd.ag.r", "max_stars_repo_name": "empa-tsl/PSSDplus", "max_stars_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_stars_repo_licenses": ["AAL"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T13:09:08.000Z", "max_issues_repo_path": "do.pssd.ag.r", "max_issues_repo_name": "empa-tsl/PSSDplus", "max_issues_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_issues_repo_licenses": ["AAL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "do.pssd.ag.r", "max_forks_repo_name": "empa-tsl/PSSDplus", "max_forks_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_forks_repo_licenses": ["AAL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-11T03:49:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T03:49:49.000Z", "avg_line_length": 41.2920353982, "max_line_length": 111, "alphanum_fraction": 0.5668666952, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.44065892433089626}}
{"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# Collection of Utilities to Biuld and Analyze Multiple Factor Model\n# Copyright (C) 2012 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# Count Consecutive Changes\n#' @export \n###############################################################################\nconsecutive.changes <- function\n(\n\tdata, \t\t# data series\n\tpositive=T\t# count positive consecutive changes\n) \n{ \n\tif(positive) dir = diff(data) > 0 else dir = diff(data) < 0\n\t\t\t\t\t\n\ttemp = cumsum(iif(dir, 1, 0))\n\ttemp - ifna.prev(iif(dir, NA, coredata(temp)))\n}\n\n###############################################################################\n# Create plot of factors average correlations and returns\n###############################################################################\n# http://stackoverflow.com/questions/4310727/what-is-rs-multidimensional-equivalent-of-rbind-and-cbind\n# apply(temp, 3, rbind)\n# http://r.789695.n4.nabble.com/Collapse-an-array-td850008.html\n#' @export \nfactor.avgcor <- function(data, next.month.ret, name) { \n\tload.packages('abind')\n\t# create matrix\n\ttemp = abind(data, along = 3)\n\t\ttemp = abind(next.month.ret, temp, along = 3)\n\t\tdimnames(temp)[[3]][1] = 'Ret'\n\t\n\t# plot\n\ttemp = t(compute.avgcor(temp, 'spearman')[,-1])\n\t\ttemp[] = plota.format(100 * temp, 0, '', '%')\n\t\tplot.table(temp, smain=paste(name,'Correlation',sep=' \\n '))\n}\n\t\t\t\n###############################################################################\n# Compute average correlations\n#' @export \n###############################################################################\ncompute.avgcor <- function\n(\n\tdata, \t\t# matrix with data: [rows,cols,factors]\n\tmethod = c('pearson', 'kendall', 'spearman')\n)\n{\n\tnr = dim(data)[1]\n\tnc = dim(data)[3]\n\tcorm = matrix(NA,nc,nc)\n\t\tcolnames(corm) = rownames(corm) = dimnames(data)[[3]]\n\t\t\n\tfor( i in 1:(nc-1) ) {\n\t\tfor( j in (i+1):nc ) {\n\t\t\tcorm[i,j] = mean( as.double( sapply(1:nr, function(t) \n\t\t\t\ttry(cor(data[t,,i], data[t,,j], use = 'complete.obs', method[1]),TRUE)\t\t\t\n\t\t\t\t)), na.rm=T)\n\t\t}\n\t}\n\treturn(corm)\n}\t\n\n###############################################################################\n# Compute Market Cap weighted mean\n#' @export \n###############################################################################\ncap.weighted.mean <- function\n(\n\tdata, \t# factor\n\tcapitalization\t# market capitalization\n) \n{\n\tcapitalization = capitalization * (!is.na(data))\n\tweight = capitalization / rowSums(capitalization,na.rm=T)\t\n\trowSums(data * weight,na.rm=T)\t\n}\t\n\n###############################################################################\n# Compute factor mean for each sector\n#' @export \n###############################################################################\nsector.mean <- function\n(\n\tdata, \t# factor\n\tsectors\t# sectors\n) \n{ \n\tout = data * NA\n\tfor(sector in levels(sectors)) {\n\t\tindex = (sector == sectors)\n\t\tout[,index] = ifna(apply(data[,index, drop=F], 1, mean, na.rm=T),NA)\n\t}\n\treturn(out)\n}\t\n\t\n\n###############################################################################\n# Create quantiles\n# http://en.wikipedia.org/wiki/Quantile\n# rank each month stocks according to E/P factor\n# create quantiles, and record their performance next month\n#' @export \n###############################################################################\ncompute.quantiles <- function\n(\n\tdata, \t\t\t# factor\n\tnext.month.ret, # future returns\n\tsmain='', \t\t# title for plot\n\tn.quantiles=5, \t# number of quantiles\n\tplot=T\t\t\t# flag to create plot\n) \n{ \n\tn = ncol(data)\n\tnperiods = nrow(data)\n\t\n\tdata = coredata(ifna(data,NA))\n\tnext.month.ret = coredata(ifna(next.month.ret,NA))\n\t\n\ttemp = matrix(NA, nperiods, n.quantiles)\n\thist.factor.quantiles = hist.ret.quantiles = temp\n\t\n\ttemp = matrix(NA, nperiods, n)\n\tquantiles = weights = ranking = temp\n\t\n\t#index = which(rowSums(!is.na(data * next.month.ret)) > n/2)\n\t#index = which(rowSums(!is.na(data)) > n/2)\n\tindex = which(rowSums(!is.na(data)) >= n.quantiles)\n\tfor(t in index) {\n\t\tfactor = data[t,]\n\t\tret = next.month.ret[t,]\n\t\t\n\t\tranking[t,] = rank(factor, na.last = 'keep','first')\n\t\tt.ranking = ceiling(n.quantiles * ranking[t,] / count(factor))\n\t\n\t\tquantiles[t,] = t.ranking\n\t\tweights[t,] = 1/tapply(rep(1,n), t.ranking, sum)[t.ranking]\n\t\t\t\n\t\thist.factor.quantiles[t,] = tapply(factor, t.ranking, mean)\n\t\thist.ret.quantiles[t,] = tapply(ret, t.ranking, mean)\n\t}\n\t\n\t# create plot\n\tif(plot) {\n\t\tpar(mar=c(4,4,2,1)) \t \t \t\n\t\ttemp = 100*apply(hist.ret.quantiles,2,mean,na.rm=T)\n \t\tbarplot(temp, names.arg=paste(1:n.quantiles), ylab='%', \n \t\t\tmain=paste(smain, ', spread =',round(temp[n.quantiles]-temp[1],2), '%'))\n \t}\n \t\t\n \treturn(list(quantiles=quantiles, weights=weights, ranking=ranking, \n \t\thist.factor.quantiles = hist.factor.quantiles, hist.ret.quantiles = hist.ret.quantiles))\n}\n\n\n###############################################################################\n# Create Average factor\n#' @export \n###############################################################################\nadd.avg.factor <- function\n(\n\tdata\t# factors\n) \n{ \n\t# compute the overall factor\n\ttemp = abind(data, along = 3)\n\tdata$AVG = data[[1]]\n\tdata$AVG[] = ifna(apply(temp, c(1,2), mean, na.rm=T),NA)\n\treturn(data)\t\n}\n\n\t\n###############################################################################\n# Convert factor to Z scores, normalize using market capitalization average\n#' @export \n###############################################################################\nnormalize.mkval <- function\n(\n\tdata,\t# factors\n\tMKVAL\t# capitalization\n) \n{ \n\t# normalize (convert to z scores) cross sectionaly all factors\n\tfor(i in names(data)) {\n\t\t#data[[i]] = (data[[i]] - apply(data[[i]], 1, mean, na.rm=T)) / apply(data[[i]], 1, sd, na.rm=T)\n\t\tdata[[i]] = (data[[i]] - cap.weighted.mean(data[[i]], MKVAL)) / \n\t\t\t\t\t\t\tapply(data[[i]], 1, sd, na.rm=T)\n\t}\n\treturn(data)\t\n}\n\t\n\n###############################################################################\n# Convert factor to Z scores, only keep the ranks\n#' @export \n###############################################################################\nnormal.transform <- function(data) \n{\t\n\trk=rank(data, na.last='keep', ties.method = 'first')\n\tn = count(data)\n\tx = qnorm((1:n) / (n+1))\n\treturn(x[rk])\n}\n\n#' @export\nnormalize.normal <- function\n(\n\tdata\t# factors\n)\n{ \n\t# normalize (convert to z scores) cross sectionaly all factors\n\tfor(i in names(data)) {\n\t\tdata[[i]][] = t(apply(data[[i]], 1, normal.transform))\n\t}\n\treturn(data)\t\n}\n\t\n\n###############################################################################\n# Plot Quantiles\n#' @export \n###############################################################################\nplot.quantiles <- function\n(\n\tdata, \t\t\t# factors\n\tnext.month.ret, # future one month returns\n\tsmain=''\t\t# title\n) \n{ \n\tlayout(matrix(1:(2*ceiling(len(data)/2)), nc=2))\n\tsapply(1:len(data), function(i)\n\t\tcompute.quantiles(data[[i]], next.month.ret, paste(names(data)[i],smain))\n\t)\t\n}\n\n###############################################################################\n# Plot Backtest Quantiles and spread (Q5-Q1)\n#' @export \n###############################################################################\nplot.bt.quantiles <- function\n(\n\tfactors,\t\t# factors\n\tnext.month.ret, # future one month returns\n\tsmain='',\t\t# title\n\tdata\t\t \t# data \n) \n{ \n\tout = compute.quantiles(factors, next.month.ret, plot=F)\t\n\t\t\n\tprices = data$prices\n\t\tprices = bt.apply.matrix(prices, function(x) ifna.prev(x))\n\t\t\n\t# find month ends\n\tmonth.ends = endpoints(prices, 'months')\n\n\t# create strategies that invest in each qutile\n\tmodels = list()\n\t\n\tfor(i in 1:5) {\n\t\tdata$weight[] = NA\n\t\t\tdata$weight[month.ends,] = iif(out$quantiles == i, out$weights, 0)\n\t\t\tcapital = 100000\n\t\t\tdata$weight[] = (capital / prices) * (data$weight)\t\n\t\tmodels[[paste('Q',i,sep='')]] = bt.run(data, type='share', capital=capital)\n\t}\n\t\n\t# spread\n\tdata$weight[] = NA\n\t\tdata$weight[month.ends,] = iif(out$quantiles == 5, out$weights, \n\t\t\t\t\t\t\t\t\tiif(out$quantiles == 1, -out$weights, 0))\n\t\tcapital = 100000\n\t\tdata$weight[] = (capital / prices) * (data$weight)\n\tmodels$Q5_Q1 = bt.run(data, type='share', capital=capital)\n\t\n\t#*****************************************************************\n\t# Create Report\n\t#****************************************************************** \t\n\tplotbt(models, plotX = T, log = 'y', LeftMargin = 3, main=smain)\t \t\n\t\tmtext('Cumulative Performance', side = 2, line = 1)\n}\n\t\t\n\t\t\n\n###############################################################################\n# Plot Factors details\n#' @export \n###############################################################################\nplot.factors <- function\n(\n\tdata, \t\t\t# factors\n\tname, \t\t\t# name of factor group\n\tnext.month.ret\t# future one month returns\n)\n{ \n\tx = as.vector(t(data))\n\ty = as.vector(t(next.month.ret))\n\t\tx = ifna(x,NA)\n\t\ty = ifna(y,NA)\n\t\tindex = !is.na(x) & !is.na(y)\n\t\tx = x[index]\n\t\ty = y[index]\t\n\t\t\t \t\n\tcor.p = round(100*cor(x, y, use = 'complete.obs', method = 'pearson'),1)\n\tcor.s = round(100*cor(x, y, use = 'complete.obs', method = 'spearman'),1)\n\t\t\t\n\t# Plot\n\tlayout(1:2)\n\tplot(x, pch=20)\n\t\t\n\tpar(mar=c(4,4,2,1)) \t \t \t\n\tplot(x, y, pch=20, xlab=name, ylab='Next Month Return')\n\t\tabline(lm(y ~ x), col='blue', lwd=2)\n\t\tplota.legend(paste('Pearson =',cor.p,',Spearman =', cor.s))\n}\t\t \t\t\n\t\t \t\t\n\t", "meta": {"hexsha": "c8db35188e6367c1370791d9b40e6a6b09535d58", "size": 10267, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/factor.model.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/factor.model.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/factor.model.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": 30.4658753709, "max_line_length": 102, "alphanum_fraction": 0.5062822636, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4404024735544792}}
{"text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC ## LASSO Regression model \n# MAGIC Lasso stands for Least Absolute Shrinkage and Selection Operator. It makes use of L1 regularization technique in the objective function. \n# MAGIC \n# MAGIC Lasso regression is a parsimonious model that performs L1 regularization. The L1 regularization adds a penalty equivalent to the absolute magnitude of regression coefficients and tries to minimize them\n# MAGIC \n# MAGIC Lasso regression can perform in-built variable selection as well as parameter shrinkage. While using ridge regression one may end up getting all the variables but with Shrinked Paramaters.\n\n# COMMAND ----------\n\n# MAGIC %md\n\n# COMMAND ----------\n\n# MAGIC %sh \n# MAGIC install.packages(\"lme4\")\n\n# COMMAND ----------\n\nlibrary(lme4)\nlibrary(tidyverse)\nlibrary(pscl)\nlibrary(parameters)\nlibrary(gt)\nlibrary(gsubfn)\nlibrary(proto)\nlibrary(sqldf)\nlibrary(RSQLite)\nlibrary(glmnet)\nlibrary(usethis)\nlibrary(devtools)\nlibrary(visdat)\nlibrary(skimr)\nlibrary(caret)\nlibrary(DataExplorer)\n\n# COMMAND ----------\n\n# MAGIC %sh ls /dbfs/FileStore/tables/\n\n# COMMAND ----------\n\ndata<-read.csv(\"/dbfs/FileStore/tables/all_vars_for_zeroinf_analysis.csv\")\n\n# COMMAND ----------\n\nhead(data, 10)\n\n# COMMAND ----------\n\ndim(data)\n\n# COMMAND ----------\n\nglimpse(data)\n\n# COMMAND ----------\n\nsummary(data)\n\n# COMMAND ----------\n\nstr(data)\n\n# COMMAND ----------\n\ncolnames(data)\n\n# COMMAND ----------\n\ncolnames(data) <- c( \"county\", \"confirmed_cases\" , \"confirmed_deaths\" ,\n \"state\" ,\"length_of_lockdown\" ,\"cases\" ,\"deaths\",\"POP_ESTIMATE_2018\" , \"total_state_pop\",\t'Active_Physicians_per_100000_Population_2018_AAMC',\t'Total_Active_Patient_Care_Physicians_per_100000_Population_2018_AAMC',\t'Active_Primary_Care_Physicians_per_100000_Population_2018_AAMC',\t'Active_Patient_Care_Primary_Care_Physicians_per_100000_Population_2018_AAMC',\t'Active_General_Surgeons_per_100000_Population_2018_AAMC',\t'Active_Patient_Care_General_Surgeons_per_100000_Population_2018_AAMC',\t'Percentage_of_Active_Physicians_Who_Are_Female_2018_AAMC',\t'Percentage_of_Active_Physicians_Who_Are_Intertiol_Medical_Graduates_IMGs-2018_AAMC',\t'Percentage_of_Active_Physicians_Who_Are_Age_60_or_Older_2018_AAMC',\t'MD_and_DO_Student_Enrollment_per_100000_Population_AY_2018_2019_AAMC',\t'Student_Enrollment_at_Public_MD_and_DO_Schools_per_100000_Population_AY_2018_2019_AAMC',\t'Percentage_Change_in_Student_Enrollment_at_MD_and_DO_Schools_2008_2018_AAMC',\t'Percentage_of_MD_Students_Matriculating_In_State_AY_2018_2019_AAMC',\t'Total_Residents_Fellows_in_ACGME_Programs_per_100000_Population_as_of_December_31_2018_AAMC',\t'Total_Residents_Fellows_in_Primary_Care_ACGME_Programs_per_100000_Population_as_of_Dec_31_2018_AAMC',\t'Percentage_of_Residents_in_ACGME_Programs_Who_Are_IMGs_as_of_December_31_2018_AAMC',\t'Ratio_of_Residents_and_Fellows_GME_to_Medical_Students_UME-AY_2017_2018_AAMC',\t'Percent_Change_in_Residents_and_Fellows_in_ACGME_Accredited_Programs_2008_2018_AAMC',\t'Percentage_of_Physicians_Retained_in_State_from_Undergraduate_Medical_Education_UME-2018_AAMC',\t'All_Specialties_AAMC',\t'State_Local_Government_hospital_beds_per_1000_people_2019',\t'Non_profit_hospital_beds_per_1000_people_2019',\t'For_profit_hospital_beds_per_1000_people_2019',\t'Total_hospital_beds_per_1000_people_2019',\t'Total_nurse_practitioners_2019',\t'Total_physician_assistants_2019',\t'Total_Hospitals_2019',\t'Total_Primary_Care_Physicians_2019',\t'Surgery_specialists_2019',\t'Emergency_Medicine_specialists_2019',\t'Total_Specialist_Physicians_2019',\t'ICU_Beds',\t'pop_fraction',\t'Length_of_Life_rank',\t'Quality_of_Life_rank',\t'Health_Behaviors_rank',\t'Clinical_Care_rank',\t'Social-Economic_Factors_rank',\t'Physical_Environment_rank',\t'Adult_smoking_percentage',\t'Adult_obesity_percentage',\t'Excessive_drinking_percentage',\t'Population_per_sq_mile',\t'House_per_sq_mile',\t'Share_of_Tests_with_Positive_COVID_19_Results', 'Number_of_Tests_with_Results_per_1000_Population'\n)\n\n# COMMAND ----------\n\nview(data)\n\n# COMMAND ----------\n\nselect(data, county, confirmed_cases)\n\n# COMMAND ----------\n\ndata %>%\n group_by(county) %>%\n summarise(count = n())\n\n# COMMAND ----------\n\nvis_miss(data)\nvis_dat(data)\n\n# COMMAND ----------\n\nskim(data)\n\n# COMMAND ----------\n\n#DataExplorer::create_report(data)\n\n# COMMAND ----------\n\n#colnames(data)\n\n# COMMAND ----------\n\ndata %>% \nselect(county,length_of_lockdown, confirmed_cases,confirmed_deaths,POP_ESTIMATE_2018, POP_ESTIMATE_2018,ICU_Beds, Adult_obesity_percentage, Quality_of_Life_rank, Excessive_drinking_percentage, Population_per_sq_mile,\n Clinical_Care_rank, Adult_smoking_percentage,Total_Specialist_Physicians_2019,Physical_Environment_rank, Number_of_Tests_with_Results_per_1000_Population) -> final_data\n\n# COMMAND ----------\n\ndisplay(final_data)\n\n# COMMAND ----------\n\n#Creating dependent and independent variables. \nfinal_data %>% \nselect(confirmed_deaths, ICU_Beds, Adult_obesity_percentage, Quality_of_Life_rank, Excessive_drinking_percentage, Population_per_sq_mile, Clinical_Care_rank, Adult_smoking_percentage, Total_Specialist_Physicians_2019, Physical_Environment_rank, Number_of_Tests_with_Results_per_1000_Population) -> X_variables\n\n\nfinal_data %>% \nselect(confirmed_deaths) -> y_target\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Linear Regression\n\n# COMMAND ----------\n\nset.seed(100) \n\nindex = sample(1:nrow(final_data), 0.7*nrow(final_data)) \n\ntrain = final_data[index,] # Create the training data \ntest = final_data[-index,] # Create the test data\n\ndim(train)\n\n\n\n# COMMAND ----------\n\ntrain\n\n# COMMAND ----------\n\ndim(test)\n\n# COMMAND ----------\n\nlr = lm(confirmed_deaths ~ ICU_Beds + Adult_obesity_percentage + Quality_of_Life_rank + Excessive_drinking_percentage + Population_per_sq_mile + Clinical_Care_rank + Adult_smoking_percentage+ Total_Specialist_Physicians_2019 + Physical_Environment_rank + Number_of_Tests_with_Results_per_1000_Population, data = train)\nsummary(lr)\n\n# COMMAND ----------\n\n#Step 1 - create the evaluation metrics function\n\neval_metrics = function(model, df, predictions, target){\n resids = df[,target] - predictions\n resids2 = resids**2\n N = length(predictions)\n r2 = as.character(round(summary(model)$r.squared, 2))\n adj_r2 = as.character(round(summary(model)$adj.r.squared, 2))\n print(adj_r2) #Adjusted R-squared\n print(as.character(round(sqrt(sum(resids2)/N), 2))) #RMSE\n}\n\n# Step 2 - predicting and evaluating the model on train data\npredictions = predict(lr, newdata = train)\neval_metrics(lr, train, predictions, target = 'confirmed_deaths')\n\n# Step 3 - predicting and evaluating the model on test data\npredictions = predict(lr, newdata = test)\neval_metrics(lr, test, predictions, target = 'confirmed_deaths')\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC The above output shows that RMSE, one of the two evaluation metrics, is 80.82 for train data and 84.69 for test data. On the other hand, R-squared value is around 25 percent for both train and test data, which indicates bad performance.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ### Regularization\n\n# COMMAND ----------\n\n\ncols_reg = c('county', 'confirmed_deaths', 'ICU_Beds', 'Adult_obesity_percentage', 'Quality_of_Life_rank', 'Excessive_drinking_percentage', 'Population_per_sq_mile', 'Clinical_Care_rank', 'Adult_smoking_percentage', 'Total_Specialist_Physicians_2019', 'Physical_Environment_rank', 'Number_of_Tests_with_Results_per_1000_Population')\n\ndummies <- dummyVars(confirmed_deaths ~ ., data = final_data[,cols_reg])\n\ntrain_dummies = predict(dummies, newdata = train[,cols_reg])\n\ntest_dummies = predict(dummies, newdata = test[,cols_reg])\n\nprint(dim(train_dummies)); print(dim(test_dummies))\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ## Ridge Regression\n# MAGIC \n# MAGIC Ridge regression is an extension of linear regression where the loss function is modified to minimize the complexity of the model. \n# MAGIC \n# MAGIC This modification is done by adding a penalty parameter that is equivalent to the square of the magnitude of the coefficients.\n\n# COMMAND ----------\n\nx = as.matrix(train_dummies)\ny_train = train$confirmed_deaths\n\nx_test = as.matrix(test_dummies)\ny_test = test$confirmed_deaths\n\nlambdas <- 10^seq(2, -3, by = -.1)\nridge_reg = glmnet(x, y_train, nlambda = 25, alpha = 0, family = 'gaussian', lambda = lambdas)\n\nsummary(ridge_reg)\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\ncv_ridge <- cv.glmnet(x, y_train, alpha = 0, lambda = lambdas)\noptimal_lambda <- cv_ridge$lambda.min\noptimal_lambda\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC The optimal lambda value comes out to be 7.943282 and will be used to build the ridge regression model\n\n# COMMAND ----------\n\n# Compute R^2 from true and predicted values\neval_results <- function(true, predicted, df) {\n SSE <- sum((predicted - true)^2)\n SST <- sum((true - mean(true))^2)\n R_square <- 1 - SSE / SST\n RMSE = sqrt(SSE/nrow(df))\n\n \n # Model performance metrics\ndata.frame(\n RMSE = RMSE,\n Rsquare = R_square\n)\n \n}\n\n# Prediction and evaluation on train data\npredictions_train <- predict(ridge_reg, s = optimal_lambda, newx = x)\neval_results(y_train, predictions_train, train)\n\n\n# COMMAND ----------\n\n\n# Prediction and evaluation on test data\npredictions_test <- predict(ridge_reg, s = optimal_lambda, newx = x_test)\neval_results(y_test, predictions_test, test)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC 80.82 for train data and 84.69 for test data.\n# MAGIC \n# MAGIC The above output shows that the RMSE and R-squared values for the ridge regression model on the training data are 80.89787 and 25 percent, respectively. For the test data, the results for these metrics are 84 and 7 percent, respectively. There is an improvement in the performance compared with linear regression model.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC ### Lasso Regression model \n# MAGIC \n# MAGIC Lasso regression, or the Least Absolute Shrinkage and Selection Operator, is also a modification of linear regression. \n# MAGIC \n# MAGIC In lasso, the loss function is modified to minimize the complexity of the model by limiting the sum of the absolute values of the model coefficients (also called the l1-norm).\n# MAGIC \n# MAGIC The loss function for lasso regression can be expressed as below:\n# MAGIC \n# MAGIC Loss function = OLS + alpha * summation (absolute values of the magnitude of the coefficients)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC The first step to build a lasso model is to find the optimal lambda value using the code below.\n\n# COMMAND ----------\n\nlambdas <- 10^seq(2, -3, by = -.1)\n\n# Setting alpha = 1 implements lasso regression\nlasso_reg <- cv.glmnet(x, y_train, alpha = 1, lambda = lambdas, standardize = TRUE, nfolds = 5)\n\n# Best \nlambda_best <- lasso_reg$lambda.min \nlambda_best\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Once we have the optimal lambda value, we train the lasso model in the first line of code below.\n\n# COMMAND ----------\n\nlasso_model <- glmnet(x, y_train, alpha = 1, lambda = lambda_best, standardize = TRUE)\n\npredictions_train <- predict(lasso_model, s = lambda_best, newx = x)\neval_results(y_train, predictions_train, train)\n\n\n\n# COMMAND ----------\n\npredictions_test <- predict(lasso_model, s = lambda_best, newx = x_test)\neval_results(y_test, predictions_test, test)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ## Elastic Net Regression model \n# MAGIC \n# MAGIC Elastic net regression combines the properties of ridge and lasso regression. \n# MAGIC \n# MAGIC It works by penalizing the model using both the 1l2-norm1 and the 1l1-norm1. \n# MAGIC \n# MAGIC The model can be easily built using the caret package, which automatically selects the optimal value of parameters alpha and lambda.\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC - The first line of code creates the training control object train_cont which specifies how the repeated cross validation will take place. \n# MAGIC \n# MAGIC - The second line builds the elastic regression model in which a range of possible alpha and lambda values are tested and their optimum value is selected. The argument tuneLength specifies that 10 different combinations of values for alpha and lambda are to be tested.\n\n# COMMAND ----------\n\n# Set training control\ntrain_cont <- trainControl(method = \"repeatedcv\",\n number = 10,\n repeats = 5,\n search = \"random\",\n verboseIter = TRUE)\n\n# Train the model\nelastic_reg <- train(confirmed_deaths ~ .,\n data = train,\n method = \"glmnet\",\n preProcess = c(\"center\", \"scale\"),\n tuneLength = 10,\n trControl = train_cont)\n\n\n# Best tuning parameter\nelastic_reg$bestTune\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC Once we have trained the model, we use it to generate the predictions and print the evaluation results for both the training and test datasets\n\n# COMMAND ----------\n\n# Make predictions on training set\npredictions_train <- predict(elastic_reg, x)\n\neval_results(y_train, predictions_train, train) \n\n\n\n# COMMAND ----------\n\n\n\n# COMMAND ----------\n\n# Make predictions on test set\npredictions_test <- predict(elastic_reg, x_test)\neval_results(y_test, predictions_test, test)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC The above output shows that the RMSE and R-squared values for the elastic net regression model on the training data are and percent, respectively. \n# MAGIC \n# MAGIC The results for these metrics on the test data are and 86 , respectively.\n# MAGIC \n# MAGIC Conclusion\n# MAGIC \n# MAGIC The performance of the models is summarized below:\n# MAGIC \n# MAGIC - Linear Regression Model: Test set RMSE of and R-square of percent.\n# MAGIC \n# MAGIC - Ridge Regression Model: Test set RMSE of and R-square of percent.\n# MAGIC \n# MAGIC - Lasso Regression Model: Test set RMSE of and R-square of percent.\n# MAGIC \n# MAGIC - ElasticNet Regression Model: Test set RMSE of and R-square of percent.\n\n# COMMAND ----------\n\nY1 <- as.matrix(y_target)\nis.matrix(Y1)\nX1 <- as.matrix(X_variables)\nis.matrix(X_variables)\nCV = cv.glmnet(x=X1, y=Y1, family= \"gaussian\",standardize=FALSE, type.measure = \"mae\", alpha = 0)\n\n# COMMAND ----------\n\nplot(CV)\n\n# COMMAND ----------\n\nfit = (glmnet(x=X1, y=Y1, family= \"gaussian\", alpha=0,standardize=FALSE, lambda=CV$lambda.1se))\n\n\n# COMMAND ----------\n\nfit$beta[,1]\nridge <- as.matrix(fit$beta)\n\n# COMMAND ----------\n\n\nwrite.table(ridge,\"/databricks/driver/ridge.txt\", sep=\"\\t\")\n\n# COMMAND ----------\n\nplot(fit, label = TRUE)\nplot(fit)\nprint(fit)\n\nwrite.table\n\n# COMMAND ----------\n\n\n", "meta": {"hexsha": "639f40f667e8e0c223b2d682b24cfd56973ac1dc", "size": 14708, "ext": "r", "lang": "R", "max_stars_repo_path": "Regression_Lasso Regression.r", "max_stars_repo_name": "garbamoussa/LASSO-Regression-model", "max_stars_repo_head_hexsha": "d2129a0770fe7695ce919c00bf6354e321e97a56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-02T14:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T14:41:28.000Z", "max_issues_repo_path": "Codes/Regression_Lasso Regression.r", "max_issues_repo_name": "garbamoussa/data-teams-unite-personal-team", "max_issues_repo_head_hexsha": "7e201f95ac89b64ea2e53ee5c0076a522913aaed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Codes/Regression_Lasso Regression.r", "max_forks_repo_name": "garbamoussa/data-teams-unite-personal-team", "max_forks_repo_head_hexsha": "7e201f95ac89b64ea2e53ee5c0076a522913aaed", "max_forks_repo_licenses": ["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.5398230088, "max_line_length": 2446, "alphanum_fraction": 0.7349061735, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.43944382019252876}}
{"text": "model_tempmax <- function (Sdepth_cm = 0.0,\n prof = 0.0,\n tmax = 0.0,\n tminseuil = 0.0,\n tmaxseuil = 0.0){\n #'- Name: TempMax -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Maximum temperature recalculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: recalculation of maximum temperature\n #'- inputs:\n #' * name: Sdepth_cm\n #' ** description : snow depth\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : cm\n #' ** uri : \n #' * name: prof\n #' ** description : snow cover threshold for snow insulation \n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 1000\n #' ** unit : cm\n #' ** uri : \n #' * name: tmax\n #' ** description : current maximum air 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 #' * name: tminseuil\n #' ** description : minimum temperature when snow cover is higher than prof\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: tmaxseuil\n #' ** description : maximum temperature when snow cover is higher than prof\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : degC\n #' ** uri : \n #'- outputs:\n #' * name: tmaxrec\n #' ** description : recalculated maximum temperature\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n tmaxrec <- tmax\n if (Sdepth_cm > prof)\n {\n if (tmax < tminseuil)\n {\n tmaxrec <- tminseuil\n }\n else\n {\n if (tmax > tmaxseuil)\n {\n tmaxrec <- tmaxseuil\n }\n }\n }\n else\n {\n if (Sdepth_cm > 0.0)\n {\n if (tmax <= 0.0)\n {\n tmaxrec <- tmaxseuil - ((1 - (Sdepth_cm / prof)) * -tmax)\n }\n else\n {\n tmaxrec <- 0.0\n }\n }\n }\n return (list('tmaxrec' = tmaxrec))\n}", "meta": {"hexsha": "7e76f03f0040764b57c60ce89e6177ef7d44729a", "size": 4144, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Tempmax.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/Tempmax.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/Tempmax.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": 40.2330097087, "max_line_length": 104, "alphanum_fraction": 0.3076737452, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4393966375592549}}
{"text": "# 4. faza: Analiza podatkov\n\n# združevanje v skupine\n\nlibrary(tmap)\n\nzivlj_doba_razv <- data.frame(filter(zivlj_doba, SPOL=='m'))\nzivlj_doba_razv <- zivlj_doba_razv[-c(3)]\nprorac_razv <- filter(zdravstvo, LETO == '2016')\nprorac_razv <- prorac_razv[c(1,3)]\npostelje_razv <- filter(zdravstvo, LETO == '2016')\npostelje_razv <- postelje_razv[c(1,4)]\ntabela_razvrscanje1 <- inner_join(zivlj_doba_razv, prorac_razv, by=\"DRZAVA\")\ntabela_razvrscanje2 <- inner_join(tabela_razvrscanje1, postelje_razv, by=\"DRZAVA\")\nrownames(tabela_razvrscanje2) = tabela_razvrscanje2$DRZAVA\ntabela_razvrscanje <- tabela_razvrscanje2[-c(1)]\n\nset.seed(1000)\nclustri_zdr <- kmeans(scale(tabela_razvrscanje), 4, nstart=100)\ntabela1 <- data.frame(DRZAVA = tabela_razvrscanje2$DRZAVA, ZIVLJENJSKA_DOBA = tabela_razvrscanje2$ZIVLJENJSKA_DOBA,\n PRORACUN = tabela_razvrscanje2$PRORACUN, POSTELJE = tabela_razvrscanje2$POSTELJE, \n SKUPINA = factor(clustri_zdr$cluster, ordered = TRUE))\nskupaj3 <- left_join(drzave, tabela1, by=\"DRZAVA\")\nzemljevid_cluster_zdr <- ggplot() + geom_polygon(data=left_join(zemljevid_evrope, skupaj3, by=c(\"NAME\"=\"DRZAVA\")), \n aes(x=long, y=lat, group=group, fill=SKUPINA)) +\n geom_line() + \n theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(),\n axis.ticks.y=element_blank()) +\n scale_fill_manual(values = c('yellow', 'orange', 'orangered', 'red3'),\n labels = c('1', '2', '3', '4'), na.value=\"grey\") +\n labs(x = \" \") +\n labs(y = \" \") +\n ggtitle(\"Razvrstitev držav v skupine glede na zdravstveno stanje\")\n\n#print(zemljevid_cluster_zdr)\n\n\ntabela_razvitost <- data.frame(filter(razvitost, LETO == '2016'))\ntabela_razvitost$BREZPOSELNI <- -(tabela_razvitost$BREZPOSELNI)\nrownames(tabela_razvitost) = tabela_razvitost$DRZAVA\ntabela_razvitost <- na.omit(tabela_razvitost)[-c(2)]\ntabela_razvitost1 <- tabela_razvitost[-c(1)]\n\nset.seed(1000)\nclustri_razv <- kmeans(scale(tabela_razvitost1), 4, nstart=100)\ntabela2 <- data.frame(DRZAVA = tabela_razvitost$DRZAVA, BDP = tabela_razvitost$BDP, \n DOHODEK = tabela_razvitost$DOHODEK, BREZPOSELNI = tabela_razvitost$BREZPOSELNI,\n SKUPINA = factor(clustri_razv$cluster, ordered = TRUE))\nskupaj4 <- left_join(drzave, tabela2, by=\"DRZAVA\")\nzemljevid_cluster_razv <- ggplot() + geom_polygon(data=left_join(zemljevid_evrope, skupaj4, by=c(\"NAME\"=\"DRZAVA\")), \n aes(x=long, y=lat, group=group, fill=SKUPINA)) +\n geom_line() + \n theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.text.y=element_blank(),\n axis.ticks.y=element_blank()) +\n scale_fill_manual(values = c('yellow', 'orange', 'orangered', 'red3'),\n labels = c('1', '2', '3', '4'), na.value=\"grey\") +\n labs(x = \" \") +\n labs(y = \" \") +\n ggtitle(\"Razvrstitev držav v skupine glede na gospodarsko razvitost\")\n\n#print(zemljevid_cluster_razv)\n\n# regresija življenjske dobe\n\nzivlj_doba_evropa <- group_by(zivlj_doba_regresija, LETO) %>% summarise(POVPRECJE=mean(ZIVLJ_DOBA))\n\nprileganje <- lm(data = zivlj_doba_evropa, POVPRECJE ~ LETO)\n\nnapoved <- data.frame(LETO=seq(2019, 2025, 1)) %>% mutate(POVPRECJE=predict(prileganje, data.frame(LETO=seq(2019, 2025, 1))))\n\ngraf_regresija <- ggplot(zivlj_doba_evropa, aes(x=LETO, y=POVPRECJE)) +\n geom_smooth(method=lm, fullrange = TRUE, color = 'blue') +\n geom_point(data=napoved, aes(x=LETO, y=POVPRECJE), color='red', size=2) +\n geom_point() +\n labs(title='Napoved življenjske dobe za države Evropske unije', y=\"ŽIVLJENJSKA DOBA\")\n\n#print(graf_regresija)\n", "meta": {"hexsha": "017542a96e59bbbe2ba4f928d59e03bbb5b2919f", "size": 3677, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "evarozman/APPR-2018-19", "max_stars_repo_head_hexsha": "fbf53acc824d0e2f789f5608d2dfc18287b6d0ef", "max_stars_repo_licenses": ["MIT"], "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": "evarozman/APPR-2018-19", "max_issues_repo_head_hexsha": "fbf53acc824d0e2f789f5608d2dfc18287b6d0ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-12-08T23:35:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T09:05:43.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "evarozman/APPR-2018-19", "max_forks_repo_head_hexsha": "fbf53acc824d0e2f789f5608d2dfc18287b6d0ef", "max_forks_repo_licenses": ["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.141025641, "max_line_length": 125, "alphanum_fraction": 0.691868371, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.43910890945060715}}
{"text": "## anova between cell types for DMP analysis\n## sets double negative as baseline\n## bumphunter for regional analysis\n## use Zhou et al hg38 probe annotation to align with other omics data.\n\nanovaModel<-function(row, celltype, age,sex){\n\tmodel<-lm(row ~ celltype + age + sex)\n\tnull<-lm(row ~ age + sex)\n\ttmp<-summary(model)$coefficients\n\tregCoeffs<-c(t(tmp[c(\"celltypeNeuN +ve\", \"celltypeSox10 +ve\", \"celltypeIRF8 +ve\"), c(1,4)]), anova(model,null)[2,6])\n\treturn(regCoeffs)\n}\n\nlibrary(ChIPseeker)\nlibrary(Gviz)\nlibrary(TxDb.Hsapiens.UCSC.hg38.knownGene)\nlibrary(doParallel)\nlibrary(data.table)\n\n\n### test cell comp differences\nsource(\"rmdConfig.mrc\")\nsetwd(dataDir)\nload(normData)\n\n## remove rs probes\ncelltypenormbeta<-celltypenormbeta[grep(\"rs\", rownames(celltypenormbeta), invert = TRUE),]\n\n\n## calc cell type means including Total\ncellMeans<-NULL\nfor(each in sort(unique(pheno$Cell.type))){\n\tcellMeans<-cbind(cellMeans, apply(celltypenormbeta[,which(pheno$Cell.type == each)], 1, mean))\n}\ncolnames(cellMeans)<-sort(unique(pheno$Cell.type))\n\n## calc cell type SDs including Total\ncellSDs<-NULL\nfor(each in sort(unique(pheno$Cell.type))){\n\tcellSDs<-cbind(cellSDs, apply(celltypenormbeta[,which(pheno$Cell.type == each)], 1, sd))\n}\ncolnames(cellSDs)<-sort(unique(pheno$Cell.type))\n\n\n## filter to just cell fractions\npheno<-pheno[pheno$Cell.type %in% c(\"Double -ve\",\"NeuN +ve\",\"Sox10 +ve\", \"IRF8 +ve\"),]\ncelltypenormbeta<-celltypenormbeta[,pheno$Basename]\npheno$Cell.type<-factor(pheno$Cell.type)\n\n## anova for cell type differences at individual positions\nctOut<-apply(celltypenormbeta, 1, anovaModel, pheno$Cell.type, pheno$Age, pheno$Sex)\nctOut<-t(ctOut)\ncolnames(ctOut)<-c(\"NeuN:Coeff\", \"NeuN:P\", \"Sox10:Coeff\", \"Sox10:P\", \"IRF8:Coeff\", \"IRF8:P\", \"ANOVA:P\")\n\nannoObj <- minfi::getAnnotationObject(\"IlluminaHumanMethylationEPICanno.ilm10b4.hg19\")\nall <- minfi:::.availableAnnotation(annoObj)$defaults\nnewfData <- do.call(cbind, lapply(all, function(wh) {\n minfi:::.annoGet(wh, envir = annoObj@data)\n}))\n\nnewfData<-newfData[rownames(celltypenormbeta),]\n\n## filter out sites with missing location info\nctOut<-ctOut[!is.na(newfData$pos),]\ncelltypenormbeta<-celltypenormbeta[rownames(ctOut),]\nnewfData <- newfData[rownames(ctOut), ] \n\n## looking at ucsc the middle of start,end gives the C position\nprobeAnno<-fread(\"../References/EPICArray/EPIC.anno.GRCh38.tsv\", sep = \"\\t\", header = TRUE)\nprobeAnno<-probeAnno[match(rownames(celltypenormbeta), probeAnno$probeID),]\nprobeAnno<-as.data.frame(probeAnno)\n\nctOut<-cbind(ctOut, probeAnno[,c(\"chrm\",\"start\", \"end\", \"GeneNames\", \"GeneClasses\", \"TranscriptIDs\")])\nctOut<-ctOut[which(ctOut$chrm != \"*\"),]\nsave(ctOut, file=\"Analysis/CellType/ANOVABrainCellTypes.rdata\")\n\nlength(which(ctOut[,7] < 9e-8))\nlength(which(ctOut[,2] < 9e-8))\nlength(which(ctOut[,4] < 9e-8))\nlength(which(ctOut[,6] < 9e-8))\n\npdf(\"Analysis/CellType/QQplot.pdf\")\npar(mfrow = c(2,2))\nqq(ctOut[,7], main = \"Any\")\nqq(ctOut[,2], main = \"NeuNvsDoubleNeg\")\nqq(ctOut[,4], main = \"Sox10vsDoubleNeg\")\nqq(ctOut[,6], main = \"IRF8vsDoubleNeg\")\ndev.off()\n\nindex<-which(ctOut[,7] < 9e-8)\n\n## look at direction of effect\npdf(\"Analysis/CellType/HistDMPsMeanDifferences.pdf\", width = 12, height = 4)\npar(mfrow = c(1,3))\nhist(ctOut[which(ctOut[,2] < 9e-8),1], xlab = \"Mean Difference\", main = \"NeuNvsDoubleNegative\", ylab = \"nDMPs\")\nsignTab<-table(sign(ctOut[which(ctOut[,2] < 9e-8),1]))\nsignTest<-binom.test(signTab[1], sum(signTab))\ntext(x = par(\"usr\")[2],y = par(\"usr\")[4], pos = 2, offset = -1, paste(signif(signTab[2]/sum(signTab)*100,3), \"% DMPs hypermethylated.\\nP =\", signif(signTest$p.value, 3)), xpd= TRUE)\nhist(ctOut[which(ctOut[,4] < 9e-8),3], xlab = \"Mean Difference\", main = \"Sox10vsDoubleNegative\", ylab = \"nDMPs\")\nsignTab<-table(sign(ctOut[which(ctOut[,4] < 9e-8),3]))\nsignTest<-binom.test(signTab[1], sum(signTab))\ntext(x = par(\"usr\")[2],y = par(\"usr\")[4], pos = 2, offset = -1, paste(signif(signTab[2]/sum(signTab)*100,3), \"% DMPs hypermethylated.\\nP =\", signif(signTest$p.value, 3)), xpd= TRUE)\nhist(ctOut[which(ctOut[,6] < 9e-8),5], xlab = \"Mean Difference\", main = \"IRF8vsDoubleNegative\", ylab = \"nDMPs\")\nsignTab<-table(sign(ctOut[which(ctOut[,6] < 9e-8),5]))\nsignTest<-binom.test(signTab[1], sum(signTab))\ntext(x = par(\"usr\")[2],y = par(\"usr\")[4], pos = 2, offset = -1, paste(signif(signTab[2]/sum(signTab)*100,3), \"% DMPs hypermethylated.\\nP =\", signif(signTest$p.value, 3)), xpd= TRUE)\ndev.off()\n\nlibrary(VennDiagram)\nlibrary(minfi)\n \n# Chart\nvenn.diagram(\n x = list(rownames(ctOut)[which(ctOut[,2] < 9e-8)], rownames(ctOut)[which(ctOut[,4] < 9e-8)], rownames(ctOut)[which(ctOut[,6] < 9e-8)]),\n category.names = c(\"NeuNvsDoubleNeg\" , \"Sox10vsDoubleNeg\" , \"IRF8vsDoubleNeg\"),\n filename = 'Analysis/CellType/VennDiagramCelltypeDMPs.png',\n output=TRUE\n)\n\n## for probes that are DMPs in two cell types, same direction and magnitude?\n\nNeun.ES<-cut(ctOut[,1], seq(-1,1,0.05))\nSox10.ES<-cut(ctOut[,3], seq(-1,1,0.05))\nIrf8.ES<-cut(ctOut[,5], seq(-1,1,0.05))\n\npdf(\"Analysis/CellType/HeatmapSharedDMPsBetweenCellTypes.pdf\")\nindex<-which(ctOut[,2] < 9e-8 & ctOut[,4] < 9e-8)\nheatmap(table(Neun.ES[index], Sox10.ES[index]), Rowv = NA, Colv = NA, xlab = \"NeuN+ve vs Double-ve\", ylab = \"Sox10+ve vs Double-ve\")\nindex<-which(ctOut[,2] < 9e-8 & ctOut[,6] < 9e-8)\nheatmap(table(Neun.ES[index], Irf8.ES[index]), Rowv = NA, Colv = NA, xlab = \"NeuN+ve vs Double-ve\", ylab = \"Irf8+ve vs Double-ve\")\nindex<-which(ctOut[,4] < 9e-8 & ctOut[,6] < 9e-8)\nheatmap(table(Sox10.ES[index], Irf8.ES[index]), Rowv = NA, Colv = NA, xlab = \"Sox10+ve vs Double-ve\", ylab = \"Irf8+ve vs Double-ve\")\ndev.off()\n\n\n\n## how many loci?\ndat<-data.frame(\"ids\" = rownames(ctOut), \"pval\" = ctOut[,\"NeuN:P\"], \"chr\" = newfData$chr, \"pos\" = newfData$pos)\nclump.neun<-clump(dat, thres1 = 9e-28, thres2 = 9e-28)\n\n## how many genes?\n\n\n\n## bumphunter to call regions\n\n## filter samples with missing Age\ncelltypenormbeta<-celltypenormbeta[,!is.na(pheno$Age)]\npheno<-pheno[!is.na(pheno$Age),]\n## sort\nctOut<-ctOut[order(ctOut$chrm, ctOut$start),]\ncelltypenormbeta<-celltypenormbeta[rownames(ctOut),]\n\n\ncl<-clusterMaker(ctOut$chrm, ctOut$start, maxGap = 500)\n\n## use probes in clusters with > 1 probe to determine background genes for pathway analysis\ntab<-table(cl)\ntab<-tab[which(tab > 1)]\nbackgroundDMRs<-GRanges(seqnames = ctOut$chrm[which(cl %in% names(tab))], strand = \"*\", ranges = IRanges(start = ctOut$start[which(cl %in% names(tab))], end = ctOut$end[which(cl %in% names(tab))]))\nsave(backgroundDMRs, file = \"Analysis/CellType/BackgroundDMRProbes.rdata\")\n#segs <- getSegments(ctOut[,1], cl, cutoff=0.05, assumeSorted = FALSE)\n#tabs<-regionFinder(ctOut[,1],newfData$chr, newfData$pos, cl, cutoff = 0.05)\nnCor<-detectCores()\nregisterDoParallel(cores = nCor)\n\ndesignMat<-model.matrix(formula( ~ pheno$Cell.type + pheno$Age + pheno$Sex))\n## need to run twice to compare Neun+ to all others and then Sox10+ to all others\ntab.neun<-bumphunter(celltypenormbeta, designMat, ctOut$chrm, as.numeric(ctOut$start), cl, coef = 3, cutoff = 0.1, nullMethod=\"bootstrap\")\ntab.irf8<-bumphunter(celltypenormbeta, designMat, ctOut$chrm, ctOut$start, cl, coef = 2,cutoff = 0.1, nullMethod=\"bootstrap\")\ntab.sox10<-bumphunter(celltypenormbeta, designMat, ctOut$chrm, ctOut$start, cl, coef = 4,cutoff = 0.1, nullMethod=\"bootstrap\")\nsave(tab.neun, tab.sox10, tab.irf8,file=\"Analysis/CellType/BumpHunterBrainCellTypes.rdata\")\n\n## as bootstrapping takes too long/never seems to finish even with a handful of iterations look at overlap of significant DMPs in these regions\n\ndmps<-GRanges(seqnames = ctOut$chrm, strand = \"*\", ranges = IRanges(start = ctOut$start, end = ctOut$end))\nmcols(dmps)<-ctOut[,1:7]\nneun.regions<-GRanges(seqnames = tab.neun$table$chr, strand = \"*\", ranges = IRanges(start = tab.neun$table$start, end = tab.neun$table$end))\nmcols(neun.regions)<-tab.neun$table[,-c(1:3)]\nsox10.regions<-GRanges(seqnames = tab.sox10$table$chr, strand = \"*\", ranges = IRanges(start = tab.sox10$table$start, end = tab.sox10$table$end))\nmcols(sox10.regions)<-tab.sox10$table[,-c(1:3)]\nirf8.regions<-GRanges(seqnames = tab.irf8$table$chr, strand = \"*\", ranges = IRanges(start = tab.irf8$table$start, end = tab.irf8$table$end))\nmcols(irf8.regions)<-tab.irf8$table[,-c(1:3)]\n\n## filter to regions with at least 2 sites\nneun.regions<-neun.regions[neun.regions$L > 1]\nsox10.regions<-sox10.regions[sox10.regions$L > 1]\nirf8.regions<-irf8.regions[irf8.regions$L > 1]\n\n## calculate proportion of probes in bump from cluster\nsummary(neun.regions$L/neun.regions$clusterL)\nsummary(sox10.regions$L/sox10.regions$clusterL)\nsummary(irf8.regions$L/irf8.regions$clusterL)\n\n## for each region count significant DMPs\ninterDmpsNeun<-findOverlaps(dmps, neun.regions)\nnDMPs<-table(subjectHits(interDmpsNeun)[which(mcols(dmps)[queryHits(interDmpsNeun), \"NeuN:P\"] < 9e-8)])\nneun.regions$nDMPs<-as.numeric(nDMPs[match(1:length(neun.regions), names(nDMPs))])\nneun.regions$nDMPs[is.na(neun.regions$nDMPs)]<-0\n\ninterDmpsSox10<-findOverlaps(dmps, sox10.regions)\nnDMPs<-table(subjectHits(interDmpsSox10)[which(mcols(dmps)[queryHits(interDmpsSox10), \"Sox10:P\"] < 9e-8)])\nsox10.regions$nDMPs<-as.numeric(nDMPs[match(1:length(sox10.regions), names(nDMPs))])\nsox10.regions$nDMPs[is.na(sox10.regions$nDMPs)]<-0\n\ninterDmpsIrf8<-findOverlaps(dmps, irf8.regions)\nnDMPs<-table(subjectHits(interDmpsIrf8)[which(mcols(dmps)[queryHits(interDmpsIrf8), \"IRF8:P\"] < 9e-8)])\nirf8.regions$nDMPs<-as.numeric(nDMPs[match(1:length(irf8.regions), names(nDMPs))])\nirf8.regions$nDMPs[is.na(irf8.regions$nDMPs)]<-0\n\n\nsummary(neun.regions$nDMPs)\nsummary(neun.regions$nDMPs/neun.regions$L)\nlength(which(neun.regions$nDMPs/neun.regions$L == 1))\nsummary(sox10.regions$nDMPs)\nsummary(sox10.regions$nDMPs/sox10.regions$L)\nlength(which(sox10.regions$nDMPs/sox10.regions$L == 1))\nsummary(irf8.regions$nDMPs)\nsummary(irf8.regions$nDMPs/irf8.regions$L)\nlength(which(irf8.regions$nDMPs/irf8.regions$L == 1))\n\n## summarise size of bumps\nsummary(width(neun.regions))\nsummary(width(sox10.regions))\nsummary(width(irf8.regions))\nsummary(width(neun.regions[which(neun.regions$nDMPs > 0),]))\nsummary(width(sox10.regions[which(sox10.regions$nDMPs > 0),]))\nsummary(width(irf8.regions[which(irf8.regions$nDMPs > 0),]))\nsummary(width(neun.regions[which(neun.regions$nDMPs/neun.regions$L == 1),]))\nsummary(width(sox10.regions[which(sox10.regions$nDMPs/sox10.regions$L == 1),]))\nsummary(width(irf8.regions[which(irf8.regions$nDMPs/irf8.regions$L == 1),]))\n\n## identify regions specific to each cell type\nneun.specific<-neun.regions[unique(subjectHits(findOverlaps(setdiff(neun.regions, reduce(c(sox10.regions, irf8.regions))), neun.regions))),]\nsox10.specific<-sox10.regions[unique(subjectHits(findOverlaps(setdiff(sox10.regions,reduce(c(neun.regions, irf8.regions))), sox10.regions))),]\nirf8.specific<-irf8.regions[unique(subjectHits(findOverlaps(setdiff(irf8.regions,reduce(c(neun.regions, sox10.regions))), irf8.regions))),]\n\n## noticed some specific regions are consecuative\nneun.conseq<-unique(c(neun.specific[queryHits(findOverlaps(neun.specific, sox10.specific)),], neun.specific[queryHits(findOverlaps(neun.specific, irf8.specific)),]))\nsox10.conseq<-unique(c(sox10.specific[subjectHits(findOverlaps(neun.specific, sox10.specific)),],sox10.specific[subjectHits(findOverlaps(irf8.specific, sox10.specific)),]))\nirf8.conseq<-unique(c(irf8.specific[subjectHits(findOverlaps(neun.specific, irf8.specific)),],irf8.specific[subjectHits(findOverlaps(sox10.specific, irf8.specific)),]))\n\n\n## how many DMPs are not located within \n\nsingleProbeCl<-names(table(cl))[which(table(cl) == 1)]\ntable(unique(cl[which(ctOut[,2] < 9e-8)]) %in% singleProbeCl)\ntable(unique(cl[which(ctOut[,4] < 9e-8)]) %in% singleProbeCl)\ntable(unique(cl[which(ctOut[,6] < 9e-8)]) %in% singleProbeCl)\n\n\n## annotate with genes\ntxdb <- TxDb.Hsapiens.UCSC.hg38.knownGene\nneunRegionAnno <- annotatePeak(neun.regions, tssRegion=c(-3000, 3000), TxDb=txdb)\nsox10RegionAnno <- annotatePeak(sox10.regions, tssRegion=c(-3000, 3000), TxDb=txdb)\nirf8RegionAnno <- annotatePeak(irf8.regions, tssRegion=c(-3000, 3000), TxDb=txdb)\nsave(neunRegionAnno, sox10RegionAnno, irf8RegionAnno, file = \"Analysis/CellType/AnnotatedBumps.rdata\")\n\n\n## plot examples select those with the most DMPs\nplotCols<-c(\"darkgreen\", \"darkblue\", \"darkmagenta\", \"deeppink\", \"darkgray\") ## assumes celltypes are ordered alphabetically\n\naxTrack <- GenomeAxisTrack()\n\npdf(\"Analysis/CellType/NeuNSpecificDMRs.pdf\", width = 8, height = 8)\nfor(i in order(neun.specific$nDMPs, decreasing = TRUE)[1:10]){\n\tstart <- as.numeric(start(neun.specific)[i])\n\tend <- as.numeric(end(neun.specific)[i])\n\tchr <- as.character(seqnames(neun.specific)[i])\n\t\n\t## add in window around region\n\twindowSize<-end-start\n\tstart<-start-windowSize\n\tend<-end+windowSize\n\tprobesInCluster<-rownames(newfData)[which(newfData$chr == chr & newfData$pos <= end+1000000 & newfData$pos >= start-1000000)] ### add in extra sites so that plot starts and finishes outside of plotting region\n\n\tidxTrack <- IdeogramTrack(genome=\"hg19\", chromosome=chr)\n\trefGenes <- UcscTrack(genome=\"hg19\", chromosome=chr, table=\"ncbiRefSeq\", track = 'NCBI RefSeq',from=start, to=end, trackType=\"GeneRegionTrack\", rstarts=\"exonStarts\", rends=\"exonEnds\", gene=\"name\",\n\t\t\t\t\t\t\tsymbol=\"name2\", transcript=\"name\", strand=\"strand\", fill=\"#8282d2\",\n\t\t\t\t\t\t\t name=\"NCBI RefSeq\", transcriptAnnotation=\"symbol\", collapseTranscripts = \"longest\")\n\tcpgIslands <- UcscTrack(genome=\"hg19\", chromosome=chr, track=\"cpgIslandExt\", from=start, to=end,trackType=\"AnnotationTrack\", start=\"chromStart\", end=\"chromEnd\", id=\"name\",shape=\"box\", fill=\"#006400\", name=\"CpG Islands\")\n\n\tcellMeans.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), cellMeans[probesInCluster, ])\n\tdTrack1<-DataTrack(range = cellMeans.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"DNAm Mean\", col = plotCols[1:4], type = \"smooth\", groups = c(\"Double -ve\", \"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(0,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tcoeffs.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), ctOut[probesInCluster, c(\"IRF8:Coeff\", \"NeuN:Coeff\", \"Sox10:Coeff\")])\n\tpvals.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), \"IRF8:log10P\" = -log10(ctOut[probesInCluster, c(\"IRF8:P\")]),\"NeuN:log10P\" = -log10(ctOut[probesInCluster, c(\"NeuN:P\")]), \"Sox10:log10P\" = -log10(ctOut[probesInCluster, c(\"Sox10:P\")]))\n\tdTrack2<-DataTrack(range = coeffs.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"Reg. Coeffs\", col = plotCols[c(2:4)], type = \"smooth\", groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(-1,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tdTrack3<-DataTrack(range = pvals.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"-logP\", ylim = c(0, max(mcols(pvals.granges)[,1])), groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), baseline = 0, col.baseline = \"gray\", lwd.baseline = 1, col = plotCols[c(2:4)])\n\tht <- HighlightTrack(trackList=list(axTrack, refGenes,cpgIslands, dTrack1,dTrack2, dTrack3), start=as.numeric(start(neun.specific)[i]), end = as.numeric(end(neun.specific)[i]),chromosome=chr)\n\n\t## set plot to just inside\n\tplotTracks(list(idxTrack, ht), from=start, to=end, showTitle=TRUE)\n}\ndev.off()\n\npdf(\"Analysis/CellType/Sox10DMRs.pdf\", width = 8, height = 8)\nfor(i in order(sox10.regions$nDMPs, decreasing = TRUE)[1:10]){\n\tstart <- tab.sox10$table$start[i]\n\tend <- tab.sox10$table$end[i]\n\tchr <- tab.sox10$table$chr[i]\n\n\t## add in window around region\n\twindowSize<-end-start\n\tstart<-start-windowSize\n\tend<-end+windowSize\n\n\tidxTrack <- IdeogramTrack(genome=\"hg19\", chromosome=chr)\n\trefGenes <- UcscTrack(genome=\"hg19\", chromosome=chr, table=\"ncbiRefSeq\", track = 'NCBI RefSeq',from=start, to=end, trackType=\"GeneRegionTrack\", rstarts=\"exonStarts\", rends=\"exonEnds\", gene=\"name\",\n\t\t\t\t\t\t\tsymbol=\"name2\", transcript=\"name\", strand=\"strand\", fill=\"#8282d2\",\n\t\t\t\t\t\t\t name=\"NCBI RefSeq\", transcriptAnnotation=\"symbol\", collapseTranscripts = \"longest\")\n\tcpgIslands <- UcscTrack(genome=\"hg19\", chromosome=chr, track=\"cpgIslandExt\", from=start, to=end,trackType=\"AnnotationTrack\", start=\"chromStart\", end=\"chromEnd\", id=\"name\",shape=\"box\", fill=\"#006400\", name=\"CpG Islands\")\n\n\tprobesInCluster<-rownames(newfData)[which(newfData$chr == chr & newfData$pos <= end & newfData$pos >= start)]\n\n\tcellMeans.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), cellMeans[probesInCluster, ])\n\tdTrack1<-DataTrack(range = cellMeans.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"DNAm Mean\", col = plotCols[1:4], type = \"smooth\", groups = c(\"Double -ve\", \"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(0,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tcoeffs.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), ctOut[probesInCluster, c(\"IRF8:Coeff\", \"NeuN:Coeff\", \"Sox10:Coeff\")])\n\tpvals.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), \"IRF8:log10P\" = -log10(ctOut[probesInCluster, c(\"IRF8:P\")]),\"NeuN:log10P\" = -log10(ctOut[probesInCluster, c(\"NeuN:P\")]), \"Sox10:log10P\" = -log10(ctOut[probesInCluster, c(\"Sox10:P\")]))\n\tdTrack2<-DataTrack(range = coeffs.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"Reg. Coeffs\", col = plotCols[c(2:4)], type = \"smooth\", groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(-1,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tdTrack3<-DataTrack(range = pvals.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"-logP\", ylim = c(0, max(mcols(pvals.granges)[,1])), groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), baseline = 0, col.baseline = \"gray\", lwd.baseline = 1, col = plotCols[c(2:4)])\n\tht <- HighlightTrack(trackList=list(axTrack, refGenes,cpgIslands, dTrack1,dTrack2, dTrack3), start=tab.sox10$table$start[i], end = tab.sox10$table$end[i],chromosome=chr)\n\n\t## set plot to just inside\n\tplotTracks(list(idxTrack, ht), from=start, to=end, showTitle=TRUE)\n}\ndev.off()\n\n\npdf(\"Analysis/CellType/IRF8DMRs.pdf\", width = 8, height = 8)\nfor(i in order(irf8.regions$nDMPs, decreasing = TRUE)[1:10]){\n\tstart <- tab.irf8$table$start[i]\n\tend <- tab.irf8$table$end[i]\n\tchr <- tab.irf8$table$chr[i]\n\n\t## add in window around region\n\twindowSize<-end-start\n\tstart<-start-windowSize\n\tend<-end+windowSize\n\n\tidxTrack <- IdeogramTrack(genome=\"hg19\", chromosome=chr)\n\trefGenes <- UcscTrack(genome=\"hg19\", chromosome=chr, table=\"ncbiRefSeq\", track = 'NCBI RefSeq',from=start, to=end, trackType=\"GeneRegionTrack\", rstarts=\"exonStarts\", rends=\"exonEnds\", gene=\"name\",\n\t\t\t\t\t\t\tsymbol=\"name2\", transcript=\"name\", strand=\"strand\", fill=\"#8282d2\",\n\t\t\t\t\t\t\t name=\"NCBI RefSeq\", transcriptAnnotation=\"symbol\", collapseTranscripts = \"longest\")\n\tcpgIslands <- UcscTrack(genome=\"hg19\", chromosome=chr, track=\"cpgIslandExt\", from=start, to=end,trackType=\"AnnotationTrack\", start=\"chromStart\", end=\"chromEnd\", id=\"name\",shape=\"box\", fill=\"#006400\", name=\"CpG Islands\")\n\n\tprobesInCluster<-rownames(newfData)[which(newfData$chr == chr & newfData$pos <= end & newfData$pos >= start)]\n\n\tcellMeans.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), cellMeans[probesInCluster, ])\n\tdTrack1<-DataTrack(range = cellMeans.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"DNAm Mean\", col = plotCols[1:4], type = \"smooth\", groups = c(\"Double -ve\", \"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(0,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tcoeffs.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), ctOut[probesInCluster, c(\"IRF8:Coeff\", \"NeuN:Coeff\", \"Sox10:Coeff\")])\n\tpvals.granges<-GRanges(seqnames = newfData[probesInCluster, \"chr\"], strand = \"*\", ranges = IRanges(start = newfData[probesInCluster, \"pos\"], end = newfData[probesInCluster, \"pos\"]), \"IRF8:log10P\" = -log10(ctOut[probesInCluster, c(\"IRF8:P\")]),\"NeuN:log10P\" = -log10(ctOut[probesInCluster, c(\"NeuN:P\")]), \"Sox10:log10P\" = -log10(ctOut[probesInCluster, c(\"Sox10:P\")]))\n\tdTrack2<-DataTrack(range = coeffs.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"Reg. Coeffs\", col = plotCols[c(2:4)], type = \"smooth\", groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), lwd = 2, baseline = seq(-1,1,0.2), col.baseline = \"gray\", lwd.baseline = 1)\n\tdTrack3<-DataTrack(range = pvals.granges, genome = \"hg19\", type = \"p\", chromosome=chr, name = \"-logP\", ylim = c(0, max(mcols(pvals.granges)[,1])), groups = c(\"IRF8+ve\", \"NeuN+ve\", \"Sox10+ve\"), baseline = 0, col.baseline = \"gray\", lwd.baseline = 1, col = plotCols[c(2:4)])\n\tht <- HighlightTrack(trackList=list(axTrack, refGenes,cpgIslands, dTrack1,dTrack2, dTrack3), start=tab.irf8$table$start[i], end = tab.irf8$table$end[i],chromosome=chr)\n\n\t## set plot to just inside\n\tplotTracks(list(idxTrack, ht), from=start, to=end, showTitle=TRUE)\n}\ndev.off()\n\n", "meta": {"hexsha": "702015164e64b5da28b2a66ff2b5d1342cc72cbe", "size": 21650, "ext": "r", "lang": "R", "max_stars_repo_path": "DNAm/EWAS/testCellTypeDiffs.r", "max_stars_repo_name": "ejh243/BrainFANS", "max_stars_repo_head_hexsha": "903b30516ec395e0543d217c492eeac541515197", "max_stars_repo_licenses": ["Artistic-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": "DNAm/EWAS/testCellTypeDiffs.r", "max_issues_repo_name": "ejh243/BrainFANS", "max_issues_repo_head_hexsha": "903b30516ec395e0543d217c492eeac541515197", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2022-02-16T09:35:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:06:32.000Z", "max_forks_repo_path": "DNAm/EWAS/testCellTypeDiffs.r", "max_forks_repo_name": "ejh243/BrainFANS", "max_forks_repo_head_hexsha": "903b30516ec395e0543d217c492eeac541515197", "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": 59.972299169, "max_line_length": 367, "alphanum_fraction": 0.7133949192, "num_tokens": 7531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4384589795928402}}
{"text": "######### internal functions #########\n\n##' @title tss\n##'\n##' @param x count matrix (each OTU in one row)\n##' @description Calculate the relative abundances by dividing the total abundance (Total Sum Sacling)\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\ntss <- function(x){ apply(x, 2, function(x) x/sum(x)) }\n\n\n##' @title css\n##'\n##' @param m matrix of data (variables in columns, measurements in rows)\n##' @param p quantile used for normalization (default: 0.5)\n##' @description Function to perform cumulative sum scaling (CSS)\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\ncss <- function(m, p=0.5){\n m[m==0] <- NA\n ## find the quantile in each sample\n quant <- apply(m,1,function(x) quantile(x, p=p, na.rm = TRUE))\n ## calculate normalization factor\n f <- rowSums(m*sweep(m, 1, quant, '<='),na.rm = TRUE)\n nf <- f/exp(mean(log(f)))\n dat.css <- sweep(m,1,nf, '/')\n return(list(\"normCounts\" = dat.css, \"normFactors\"=nf))\n}\n\n##' @title infer\n##'\n##' @param Y response\n##' @param X predictors\n##' @param method blasso or lm\n##' @param intercept whether to include the intercept\n##' @param seed seed\n##' @param alpha the alpha parameter for elastic net (1:lasso [default], 0:ridge)\n##' @param lambda.init user provides initial lambda values\n##' @param lambda.choice 1: use lambda.1se for LASSO, 2: use lambda.min for LASSO, a number between (0, 1): this will select a lambda according to (1-lambda.choice)*lambda.min + lambda.choice*lambda.1se\n##' @param nfolds number of folds for glmnet cross-validation\n##' @import glmnet\n##' @description Infer parameters with blasso\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\ninfer <- function(Y, X, method='glmnet', intercept=FALSE, seed=0, alpha=1, nfolds=5,\n lambda.init=NULL, lambda.choice=1){\n lambda.lower <- 1e-9\n lambda.upper <- 1\n set.seed(seed)\n if(method=='lm'){\n return(as.numeric(coef(lm(Y~X+0))))\n }\n if(method=='glmnet'){\n penalty <- c(0,rep(1, ncol(X)-1))\n maxmin <- median(Y) + 5 * IQR(Y) %*% c(1,-1)\n idx <- Y <= maxmin[1] & Y >= maxmin[2]\n if(is.null(lambda.init)){\n ## select a lambda range first\n lambda.init <- rev(exp(seq(log(lambda.lower), log(lambda.upper), length.out = 50)))\n fit <- cv.glmnet(X[idx,], Y[idx], intercept=intercept, lambda=lambda.init, nfolds=nfolds,\n penalty.factor=penalty, alpha=alpha)\n lambda <- rev(exp(seq(\n max(log(fit$lambda.min/10), log(lambda.lower)),\n min(log(fit$lambda.min*10), log(lambda.upper)),\n length.out = 50)))\n }else{\n ## adjust lambda by up to 50%\n lambda <- rev(exp(seq(\n max(log(lambda.init/2), log(lambda.lower)), ## bounded by the min lambda\n min(log(lambda.init*1.5), log(lambda.upper)), ## bounded by the max lambda\n length.out = 20)))\n }\n\n fit <- cv.glmnet(X[idx,], Y[idx], intercept=intercept, lambda=lambda, nfolds=nfolds,\n penalty.factor=penalty, alpha=alpha)\n if(lambda.choice == 1){\n s = fit$lambda.1se\n }else if(lambda.choice == 2){\n s = fit$lambda.min\n }else{\n s = (1-lambda.choice)*fit$lambda.min + lambda.choice*fit$lambda.1se\n }\n coefs <- coef(fit, s=s)[-1]\n e <- as.numeric((Y-(X %*% coefs)[,1]))\n rm(.Random.seed, envir=.GlobalEnv)\n return(c(coefs, e, s))\n }\n}\n\n\n# ##' @title boot_stat\n# ##'\n# ##' @param data data in the format of cbind(Y, X)\n# ##' @param indices indices for bootstrapping\n# ##' @description bootstrapping the inference process\n# ##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\n# bs <- function(data, indices) {\n# X_s <- data[indices, -1] # allows boot to select sample\n# Y_s <- data[indices, 1]\n# fit <- infer(Y_s, X_s)\n# return(fit[1:ncol(X_s)])\n# }\n\n# ##' @title func.E.boot\n# ##'\n# ##' @param dat.tss relative abundances matrix (each OTU in one row)\n# ##' @param sample.filter filter out samples contain outliers in Y\n# ##' @param m estimated biomass values\n# ##' @param ncpu number of CPUs (default: 4)\n# ##' @importFrom boot boot\n# ##' @importFrom doParallel registerDoParallel\n# ##' @import foreach\n# ##' @description bootstrapped E-step\n# ##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\n# func.E.boot <- function(dat.tss, m, sample.filter, ncpu=4, ...){\n# registerDoParallel(ncpu)\n# p <- nrow(dat.tss)\n# res <- foreach(i=1:p, .combine=rbind) %do% {\n# message(paste0(\"Bootstrapping for species \", i))\n# fil <- dat.tss[i,]!=0 & !sample.filter[i,]\n# X <- t(rbind(1/m, dat.tss[-i,])[,fil])\n# Y <- dat.tss[i, fil]\n# theta <- rep(0, p+1)\n# stab <- rep(1, p)\n# theta[i+1] <- -1 ## -beta_{ii}/beta_{ii}\n# tmp <- boot(data=cbind(Y,X), statistic=bs, R=100)\n# theta[-(i+1)] <- apply(tmp$t, 2, median)\n# stab[-(i)] <- (colSums(tmp$t!=0)/tmp$R)[-1]\n# c(theta, stab)\n# }\n# list(a=res[,1], b=postProcess(res[,1:p+1]), stab=res[,(p+2):ncol(res)])\n# }\n\n# ##' @title func.E.stab\n# ##'\n# ##' @param dat.tss relative abundances matrix (each OTU in one row)\n# ##' @param sample.filter filter out samples contain outliers in Y\n# ##' @param m estimated biomass values\n# ##' @param ncpu number of CPUs (default: 4)\n# ##' @param perc percentage of samples to take for each iteration\n# ##' @param niter number of iterations to run\n# ##' @param ... additional parameters for beemStatic:::infer\n# ##' @importFrom doParallel registerDoParallel\n# ##' @import foreach\n# ##' @description E-step with subsampling to estimate stability\n# ##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\n# func.E.stab <- function(dat.tss, m, sample.filter, ncpu=4, perc=0.6, niter=100, ...){\n# registerDoParallel(ncpu)\n# p <- nrow(dat.tss)\n# res <- foreach(i=1:p, .combine=rbind) %do% {\n# message(paste0(\"Resampling for species \", i))\n# fil <- dat.tss[i,]!=0 & !sample.filter[i,]\n# X <- t(rbind(1/m, dat.tss[-i,])[,fil])\n# Y <- dat.tss[i, fil]\n# theta <- rep(0, p+1)\n# stab <- rep(1, p)\n# theta[i+1] <- -1 ## -beta_{ii}/beta_{ii}\n# tmp <- (sapply(1:niter, function(x) sub_stat(data=cbind(Y,X), perc) ))\n# theta[-(i+1)] <- apply(tmp, 1, median)\n# stab[-(i)] <- (rowSums(tmp!=0)/niter)[-1]\n# c(theta, stab)\n# }\n# list(a=res[,1], b=postProcess(res[,1:p+1]), stab=res[,(p+2):ncol(res)])\n# }\n\n# ##' @title sub_stat\n# ##'\n# ##' @param data data in the format of cbind(Y, X)\n# ##' @param perc percentage of samples to take for each iteration\n# ##' @param ... additional parameters for beemStatic:::infer\n# ##' @description Resampling for the inference process\n# ##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\n# sub_stat <- function(data, perc, ...) {\n# n <- nrow(data)\n# indices <- sample(1:n, n*perc)\n# X_s <- data[indices, -1]\n# Y_s <- data[indices, 1]\n# fit <- infer(Y_s, X_s)\n# return(fit[1:ncol(X_s)])\n# }\n\n##' @title norm\n##'\n##' @param a estimated growth rate values (scaled by self-interaction)\n##' @param b estimated interaction matrix (scaled by self-interaction)\n##' @param c estimated external perturbation effect matrix (scaled by self-interaction) (default: NULL)\n##' @param s external perturbation presence vector in one sample\n##' @param x relative abundances in one sample\n##' @description estimate biomass with linear regression\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nnorm <- function(a, b, c = NULL, s = NULL, x){\n if (!is.null(c) || !is.null(s)) {\n perturbation.eff <- c %*% s\n res <- -(a + perturbation.eff) / (b %*% x)\n } else {\n res <- -a / (b %*% x)\n }\n res <- res[x!=0]\n if(all(res < 0)){\n m <- abs(max(res))\n } else{\n m <- median(res[res>0])\n }\n if (!is.null(c) || !is.null(s)) {\n err <- (m * (b %*% x) + a + perturbation.eff)[,1]/a\n } else {\n err <- (m * (b %*% x) + a)[,1]/a\n }\n err[x==0] <- 0\n c(m, err)\n\n}\n\n##' @title entropy\n##'\n##' @param v a vector input (treated as binary, i.e. zero/non-zero)\n##' @description Compute the entropy of a binary vector\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nentropy <- function(v){\n p <- sum(v == 0)/length(v)\n ifelse(p==0 || p==1, 0, -(p*log2(p) + (1-p)*log2(1-p)) )\n}\n\n##' @title func.E\n##'\n##'\n##' @param dat.tss relative abundances matrix (each OTU in one row)\n##' @param external.perturbation external perturbation presence matrix *1/m (each perturbation in one row, each sample in one column) (Default: NULL)\n##' @param sample.filter filter out samples contain outliers in Y\n##' @param lambda.inits initial lambda values\n##' @param m estimated biomass values (1 X no. of samples) matrix\n##' @param ncpu number of CPUs (default: 4)\n##' @param center center data or not\n##' @param ... additional parameters for `beemStatic::infer`\n##' @importFrom doParallel registerDoParallel\n##' @import foreach\n##' @description E-part of BEEM, estimate model parameters with inferred m\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nfunc.E <- function(dat.tss, external.perturbation = NULL, m, sample.filter, lambda.inits=NULL, ncpu=4, center=FALSE, ...){\n ## infer parameter for each OTU\n registerDoParallel(ncpu)\n p <- nrow(dat.tss)\n if (!is.null(external.perturbation)) {\n k <- nrow(external.perturbation) #Number of external perturbations\n }\n res <- foreach(i=1:p, .combine=rbind) %dopar% {\n fil <- dat.tss[i,]!=0 & !sample.filter[i,]\n X <- t(rbind(1/m, dat.tss[-i,])[,fil])\n Y <- dat.tss[i, fil]\n if(center){\n Y <- Y-mean(Y)\n X <- X-rowMeans(X)\n }\n theta <- rep(0, p+1)\n theta[i+1] <- -1 ## -beta_{ii}/beta_{ii}\n if (!is.null(external.perturbation)) {\n perturbation.coefficients <- rep(0, k) #Creating a vector to store perturbation coefficients\n external.perturbation.filtered <- external.perturbation[,fil] #Filtering out the external perturbations corresponding to samples which were filtered out\n X <- cbind(X, t(external.perturbation.filtered))\n }\n\n tmp <- infer(Y,X, lambda.init=lambda.inits[i], ...)\n\n if (!is.null(external.perturbation)) {\n theta[-(i+1)] <- tmp[1:p]\n perturbation.coefficient <- tmp[seq(p+1,p+k)]\n e <- rep(NA, ncol(dat.tss))\n e[fil] <- tmp[(p+k+1):(length(tmp)-1)]\n lambda <- tmp[length(tmp)]\n c(theta, perturbation.coefficient, e, lambda)\n } else {\n theta[-(i+1)] <- tmp[1:p]\n e <- rep(NA, ncol(dat.tss))\n e[fil] <- tmp[(p+1):(length(tmp)-1)]\n lambda <- tmp[length(tmp)]\n c(theta, e, lambda)\n }\n }\n\n ## check if there is not enough information\n uncertain <- foreach(i=1:p, .combine=rbind) %dopar% {\n fil <- dat.tss[i,]!=0\n X <- dat.tss[, fil]\n apply(X, 1, entropy)\n ## abs(rowSums(X!=0)/ncol(X) - 0.5) ## non-zero entries\n }\n if (!is.null(external.perturbation)) {\n list(a=res[,1], b=postProcess_species(res[,1:p+1]),\n perturbation.coefficients = postProcess_perturbation(matrix(res[,seq(p+2,p+k+1)], ncol = k), res[,1]),\n e=res[,(p+k+2):(ncol(res)-1)],\n uncertain=uncertain, lambdas=res[,ncol(res)])\n } else {\n list(a=res[,1], b=postProcess_species(res[,1:p+1]), e=res[,(p+2):(ncol(res)-1)],\n uncertain=uncertain, lambdas=res[,ncol(res)])\n }\n}\n\n\n##' @title func.M\n##'\n##' @param dat.tss relative abundance matrix (each OTU in one row)\n##' @param a estimated growth rate values (scaled by self-interaction)\n##' @param b estimated interaction matrix (scaled by self-interaction)\n##' @param c estimated external perturbation effect matrix (scaled by self-interaction)\n##' @param perturbation.presence estimated external perturbation presence (not to be multiplied by 1/m) (each perturbation in one row, each sample in one column)\n##' @param ncpu number of CPUs (default: 4)\n##' @importFrom doParallel registerDoParallel\n##' @import foreach\n##' @description M-part of BEEM, estimate biomass with inferred model parameters\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nfunc.M <- function(dat.tss, a, b, c = NULL, perturbation.presence=NULL, ncpu=4){\n registerDoParallel(ncpu)\n foreach(i=1:ncol(dat.tss), .combine=rbind) %dopar%{\n x <- dat.tss[,i]\n if (!is.null(c) || !is.null(perturbation.presence)) {\n s <- perturbation.presence[,i]\n norm(a, b, c = c, s = s, x)\n } else {\n norm(a, b, c = NULL, s = NULL, x)\n }\n }\n}\n\n##' @title preProcess\n##'\n##' @param dat OTU count/relative abundance matrix (each OTU in one row)\n##' @param dev dev * IQR from median will be filtered out (default: 0, nothing to remove)\n##' @description pre-process data\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\npreProcess <- function(dat, dev=0){\n ## filter out species abundances that are too low\n detection_limit <- 1e-4\n dat <- tss(dat)\n dat[dat threshold)\n}\n\n######### Exported functions #########\n\n##' @title beem2param\n##'\n##' @param beem a BEEM object\n##' @description extract parameter estimates from a BEEM object\n##' @export\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nbeem2param <- function(beem){\n p <- ncol(beem$err.m) #Number of species\n num.perturb <- (nrow(beem$trace.p) - p - p*p)/p\n tmp <- beem$trace.p[, ncol(beem$trace.p)]\n a.est <- tmp[1:p]\n b.est <- matrix(tmp[-c(1:p)], p, p)\n if (num.perturb == 0) {\n return (list(a.est=a.est, b.est=b.est))\n } else {\n c.est <- matrix(tmp[(nrow(beem$trace.p) - (num.perturb*p - 1)):nrow(beem$trace.p)],\n ncol = num.perturb)\n return (list(a.est=a.est, b.est=b.est, c.est=c.est))\n }\n}\n\n##' @title beem2biomass\n##'\n##' @param beem a BEEM object\n##' @description extract biomass estimates from a BEEM object\n##' @export\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nbeem2biomass <- function(beem){\n niter <- ncol(beem$trace.m)\n return (beem$trace.m[,niter])\n}\n\n\n##' @title func.EM\n##'\n##' @param dat OTU count/relative abundance matrix (each OTU in one row)\n##' @param external.perturbation external perturbation presence matrix (each perturbation in one row, each sample in one column) (Default: NULL)\n##' @param ncpu number of CPUs (default: 4)\n##' @param scaling a scaling factor to keep the median of all biomass constant (default: 1000)\n##' @param dev deviation of the error (for one sample) from the model to be excluded (default: Inf - all the samples will be considered)\n##' @param m.init initial biomass values (default: use CSS normalization)\n##' @param max.iter maximal number of iterations (default 30)\n##' @param warm.iter number of iterations to run before removing any samples and stop adjusting lambda (default: run until convergence and start to remove samples)\n##' @param lambda.choice 1: use lambda.1se for LASSO, 2: use lambda.min for LASSO, a number between (0, 1): this will select a lambda according to (1-lambda.choice)*lambda.min + lambda.choice*lambda.1se\n##' @param resample number of iterations to resample the data to compute stability of the interaction parameters (default: 0 - no resampling)\n##' @param alpha the alpha parameter for the Elastic Net model (1-LASSO [default], 0-RIDGE)\n##' @param refresh.iter refresh the removed samples every X iterations (default: 1)\n##' @param epsilon convergence threshold (in relative difference): uqn of the relative error in biomass changes (default 1e-3)\n##' @param verbose print out messages\n##' @param debug output debugging information (default FALSE)\n##' @description Iteratively estimating scaled parameters and biomass\n##' @export\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nfunc.EM <- function(dat, external.perturbation = NULL, ncpu=4, scaling=1000, dev=Inf, m.init=NULL,\n max.iter=30, warm.iter=NULL, lambda.choice=1, resample=0,\n alpha=1, refresh.iter=1, epsilon=1e-3,\n debug=FALSE, verbose=TRUE){\n\n ## pre-processing\n dat.init <- preProcess(dat, dev=0)\n dat.tss <- dat.init$tss\n spNames <- rownames(dat)\n\n ## ensure valid samples\n temp <- colSums(dat.tss, na.rm = TRUE) == 0\n if(any(temp)){\n stop(paste0('Sample ', which(temp), ' has zero total abudance...'))\n }\n\n ## initialization\n sample.filter.iter <- dat.init$sample.filter\n tmp <- css(t(dat.tss))$normFactors\n if(is.null(m.init)) {\n m.iter <- scaling * tmp/median(tmp)\n }else{\n m.iter <- scaling * m.init/median(m.init)\n }\n trace.m <- matrix(m.iter)\n trace.p <- apply(expand.grid(spNames, spNames), 1, function(x) paste0(x[2], '->', x[1]))\n trace.p <- c(paste0(NA, '->',spNames), trace.p)\n if (!is.null(external.perturbation)) {\n external.perturbation.Names <- rownames(external.perturbation)\n trace.p.external.perturbation <- apply(expand.grid(spNames, external.perturbation.Names), 1, function(x) paste0(x[2], '->', x[1]))\n trace.p <- append(trace.p, trace.p.external.perturbation)\n }\n trace.p <- data.frame(name=trace.p)\n trace.lambda <- data.frame(spNames)\n lambda.inits <- NULL\n ## flags\n remove_non_eq <- FALSE\n removeIter <- 0\n\n ## constants\n m1 <- matrix(rep(1,nrow(sample.filter.iter)))\n ## EM\n for(iter in 1:max.iter){\n if(verbose) message(paste0(\"############# Run for iteration \", iter,\": #############\"))\n if(verbose) message(\"E-step: estimating scaled parameters...\")\n if(iter>=2) lambda.inits <- lambdas\n if(is.null(external.perturbation)){\n ext.pert <- NULL\n }else{\n ext.pert <- 1/m.iter * external.perturbation\n }\n tmp.p <- func.E(dat.tss, external.perturbation = ext.pert,\n m.iter, sample.filter.iter, ncpu=ncpu, method='glmnet',\n lambda.inits=lambda.inits, alpha=alpha)\n err.p <- tmp.p$e\n lambdas <- tmp.p$lambdas\n uncertain <- tmp.p$uncertain\n if(debug){\n print(rowSums(tmp.p$b!=0))\n plot(1-rowMeans(err.p^2, na.rm = TRUE)/apply(dat.tss[,], 1, function(x) var(x[x!=0], na.rm=TRUE) ))\n ##abline(h=0.5)\n }\n\n if(verbose) message(\"M-step: estimating biomass...\")\n if (!is.null(external.perturbation)) {\n tmp.m <- func.M(dat.tss, tmp.p$a, tmp.p$b, c = tmp.p$perturbation.coefficients, perturbation.presence = external.perturbation, ncpu)\n } else {\n tmp.m <- func.M(dat.tss, tmp.p$a, tmp.p$b, c = NULL, perturbation.presence = NULL, ncpu)\n }\n m.iter <- tmp.m[,1]\n err.m <- tmp.m[,-1]\n\n if(remove_non_eq){\n ## clear up removed samples every X iterations\n if (iter %% refresh.iter == 0 ) {\n sample.filter.iter <- dat.init$sample.filter\n }\n bad.samples <- detectBadSamples(apply(err.p^2, 2, median, na.rm = TRUE), dev)\n sample.filter.iter <- (m1 %*% bad.samples)>0 | sample.filter.iter\n if(verbose) message(paste0(\"Number of samples removed (detected to be non-static): \",\n sum(colSums(sample.filter.iter)>0)))\n removeIter <- removeIter + 1\n }\n m.fil <- colSums(sample.filter.iter)==0\n m.iter <- m.iter*scaling/median(m.iter[m.fil], na.rm=TRUE)\n trace.m <- cbind(trace.m, m.iter)\n if (!is.null(external.perturbation)) {\n trace.p <- cbind(trace.p, formatOutput(tmp.p$a, tmp.p$b, c = tmp.p$perturbation.coefficients,\n spNames, pnames = external.perturbation.Names)$value)\n } else {\n trace.p <- cbind(trace.p, formatOutput(tmp.p$a, tmp.p$b, c = NULL, spNames, pnames = NULL)$value)\n }\n\n trace.lambda <- cbind(trace.lambda, lambdas)\n summary.m <- apply(trace.m[m.fil, ], 1, function(x) median(rev(x)[1:min(5,length(x))]))\n #criterion <- quantile(abs((trace.m[m.fil, iter+1] - summary.m)/summary.m), 1) warm.iter && !remove_non_eq){\n if(verbose) message(\"Start to detect and remove bad samples...\")\n remove_non_eq <- TRUE\n }\n if (iter > 5 && !remove_non_eq && criterion && is.finite(dev)) {\n if(verbose) message(\"Converged and start to detect and remove bad samples...\")\n remove_non_eq <- TRUE\n }\n if (((removeIter > 5 && remove_non_eq) || is.infinite(dev)) && criterion) {\n if(verbose) message(\"Converged!\")\n break\n }\n }\n res.resample <- NULL\n\n if(resample!=0){\n if(verbose) message(\"Estimating stability...\")\n ##res.resample <- func.E.stab(dat.tss, m.iter, sample.filter.iter, ncpu=ncpu, alpha=alpha)\n if (!is.null(external.perturbation)) {\n res.resample <- resample.EM(dat[, m.fil], external.perturbation = external.perturbation[, m.fil], m=m.iter[m.fil],\n perc=0.6, res.iter=resample,\n ncpu=ncpu, scaling=scaling, dev=dev, refresh.iter=refresh.iter, alpha=alpha,\n max.iter=20, warm.iter=0, resample=0, debug=FALSE, verbose=FALSE)\n } else {\n res.resample <- resample.EM(dat[, m.fil], external.perturbation = NULL, m=m.iter[m.fil],\n perc=0.6, res.iter=resample,\n ncpu=ncpu, scaling=scaling, dev=dev, refresh.iter=refresh.iter, alpha=alpha,\n max.iter=20, warm.iter=0, resample=0, debug=FALSE, verbose=FALSE)\n }\n res.resample$a.summary <- apply(res.resample$res.a, 1, median)\n res.resample$b.summary <- matrix(apply(res.resample$res.b, 1, function(x) median(x)), nrow(dat))\n res.resample$b.stab <- matrix(rowSums(res.resample$res.b != 0)/ncol(res.resample$res.a), nrow(dat))\n if (!is.null(external.perturbation)) {\n res.resample$c.summary <- apply(res.resample$res.c, 1, function(x) median(x))\n res.resample$c.stab <- matrix(rowSums(res.resample$res.c != 0)/ncol(res.resample$res.a), nrow(dat))\n }\n }\n list(trace.m=trace.m, trace.p=trace.p, err.m=err.m, err.p=err.p,\n b.uncertain = uncertain, trace.lambda=trace.lambda,\n resample=res.resample,\n dev=dev,\n sample2rm = which(!m.fil))\n}\n\n##' @title resample.EM\n##'\n##' @param data data in the format of cbind(Y, X)\n##' @param external.perturbation external perturbation presence matrix (each perturbation in one row, each sample in one column) (Default: NULL)\n##' @param m biomass initialization\n##' @param perc percentage of samples to take for each iteration\n##' @param res.iter number of resample iteration\n##' @param ... additional parameters for beemStatic::func.EM\n##' @description Resampling for the inference process\n##' @export\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\nresample.EM <- function(data, external.perturbation = NULL, m, perc, res.iter, ...) {\n n <- ncol(data)\n p <- nrow(data)\n res_p <- data.frame(matrix(NA, p*(p+1), res.iter))\n res_m <- data.frame(matrix(NA, n, res.iter))\n\n for(i in 1:res.iter){\n message(paste0(\"#### Resample iteration: \", i, \" #####\"))\n indices <- sort(sample(1:n, n*perc))\n if (!is.null(external.perturbation)) {\n num.perturb <- nrow(external.perturbation)\n tmp <- func.EM(data[, indices], external.perturbation = external.perturbation[, indices], m.init=m[indices], ...)\n } else {\n tmp <- func.EM(data[, indices], external.perturbation = NULL, m.init=m[indices], ...)\n }\n res_p[,i] <- tmp$trace.p[, ncol(tmp$trace.p)]\n res_m[indices,i] <- tmp$trace.m[, ncol(tmp$trace.m)]\n }\n if (!is.null(external.perturbation)) {\n list(res.a = res_p[1:p,], res.b = res_p[(p+1):(nrow(res_p)-num.perturb*p),], res.c = res_p[(nrow(res_p)-num.perturb*p + 1):nrow(res_p),], res.m = res_m)\n } else {\n list(res.a = res_p[1:p,], res.b = res_p[-c(1:p),], res.m = res_m)\n }\n\n list(res.a = res_p[1:p,], res.b = res_p[-c(1:p),])\n}\n\n\n##' @title predict_beem\n##'\n##' @param dat.new OTU count/relative abundance matrix (each OTU in one row)\n##' @param beem output of the EM algorithm\n##' @param dev deviation of the error (for one sample) from the model to be excluded\n##' @param ncpu number of CPUs (default: 4)\n##' @param pert.new external perturbation presence matrix (each perturbation in one row, each sample in one column) (Default: NULL)\n##' @importFrom doParallel registerDoParallel\n##' @description Use a trained BEEM-static model to predict biomass, deviation from steady states and violation of model assumption\n##' @export\n##' @author Chenhao Li, Gerald Tan, Niranjan Nagarajan\npredict_beem <- function(dat.new, beem, dev, ncpu=4, pert.new = NULL){\n ### currently not ready for an S3method yet\n param <- beem2param(beem)\n dat.new.tss <- tss(dat.new)\n if (!is.null(pert.new)){\n tmp.m <- func.M(dat.new.tss, param$a.est, param$b.est, c = param$c.est, perturbation.presence = pert.new, ncpu = 1)\n } else {\n tmp.m <- func.M(dat.new.tss, param$a.est, param$b.est, ncpu=ncpu)\n }\n m.pred <- tmp.m[,1]\n err.m.pred <- tmp.m[,-1]\n\n registerDoParallel(ncpu)\n p <- nrow(dat.new.tss)\n e <- foreach(i=1:p, .combine=rbind) %dopar% {\n X <- t(rbind(1/m.pred, dat.new.tss[-i,]))\n Y <- dat.new.tss[i, ]\n coefs <- c(param$a.est[i], param$b.est[i,-i])\n if(!is.null(param$c.est)){\n pert <- t(pert.new)\n coefs_pert <- param$c.est[i,]\n as.numeric(Y - (X %*% coefs)[,1] - (1/m.pred) * ((pert %*% coefs_pert)[,1]) )\n }else{\n as.numeric((Y - (X %*% coefs)[,1] ) )\n }\n }\n isBad <- detectBadSamples(apply(e^2, 2, median, na.rm = TRUE), dev)\n return(list(biomass.pred=m.pred, dev.from.eq=t(err.m.pred), isBad=isBad))\n}\n", "meta": {"hexsha": "e16fd7a45f7af23066c5a8ebdd768db5d44adb5b", "size": 28016, "ext": "r", "lang": "R", "max_stars_repo_path": "R/em_functions.r", "max_stars_repo_name": "CSB5/BEEM-static", "max_stars_repo_head_hexsha": "83d97e2c1ca8bf9226f291100f75d6298a179688", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2018-11-22T13:37:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:45:11.000Z", "max_issues_repo_path": "R/em_functions.r", "max_issues_repo_name": "CSB5/BEEM-static", "max_issues_repo_head_hexsha": "83d97e2c1ca8bf9226f291100f75d6298a179688", "max_issues_repo_licenses": ["MIT"], "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/em_functions.r", "max_forks_repo_name": "CSB5/BEEM-static", "max_forks_repo_head_hexsha": "83d97e2c1ca8bf9226f291100f75d6298a179688", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-02-18T06:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-18T06:50:07.000Z", "avg_line_length": 40.8396501458, "max_line_length": 202, "alphanum_fraction": 0.634673044, "num_tokens": 8399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583124210895, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4382968729748297}}
{"text": "softmax <- function (x) {\n m <- max(x)\n exps <- exp(x - m)\n s <- sum(exps)\n return(exps / s)\n}\nscore <- function(input) {\n if ((input[3]) > (3.1500000000000004)) {\n var0 <- -1.1986122886681099\n } else {\n if ((input[2]) > (3.35)) {\n var0 <- -0.8986122886681098\n } else {\n var0 <- -0.9136122886681098\n }\n }\n if ((input[3]) > (3.1500000000000004)) {\n if ((input[3]) > (4.450000000000001)) {\n var1 <- -0.09503010837903424\n } else {\n var1 <- -0.09563272415214283\n }\n } else {\n if ((input[2]) > (3.35)) {\n var1 <- 0.16640323607832397\n } else {\n var1 <- 0.15374604217339707\n }\n }\n if ((input[3]) > (1.8)) {\n if ((input[4]) > (1.6500000000000001)) {\n var2 <- -1.2055899476674514\n } else {\n var2 <- -0.9500445227622534\n }\n } else {\n var2 <- -1.2182214705715104\n }\n if ((input[4]) > (0.45000000000000007)) {\n if ((input[4]) > (1.6500000000000001)) {\n var3 <- -0.08146437273923739\n } else {\n var3 <- 0.14244886188108738\n }\n } else {\n if ((input[3]) > (1.4500000000000002)) {\n var3 <- -0.0950888159264695\n } else {\n var3 <- -0.09438233722389686\n }\n }\n if ((input[4]) > (1.6500000000000001)) {\n if ((input[3]) > (5.3500000000000005)) {\n var4 <- -0.8824095771015287\n } else {\n var4 <- -0.9121126703829481\n }\n } else {\n if ((input[3]) > (4.450000000000001)) {\n var4 <- -1.1277829563828181\n } else {\n var4 <- -1.1794405099157212\n }\n }\n if ((input[3]) > (4.750000000000001)) {\n if ((input[3]) > (5.150000000000001)) {\n var5 <- 0.16625543464258166\n } else {\n var5 <- 0.09608601737074281\n }\n } else {\n if ((input[1]) > (4.950000000000001)) {\n var5 <- -0.09644547407948921\n } else {\n var5 <- -0.08181864271444342\n }\n }\n return(softmax(c((var0) + (var1), (var2) + (var3), (var4) + (var5))))\n}\n", "meta": {"hexsha": "916101d2d30d86d9d3c9c19d9f7ca4f168f93baa", "size": 2185, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/classification/lightgbm.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/classification/lightgbm.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/classification/lightgbm.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": 27.3125, "max_line_length": 73, "alphanum_fraction": 0.4553775744, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.43809520500666815}}
{"text": "# Filename: \tcode.r\n# Project: \t/Users/shume/Developer/stat/IntroductoryStatistics/01\n# Author: \tshumez \n# Created: \t2019-05-25 14:06:7\n# Modified: \t2019-05-25 14:21:43\n# -----\n# Copyright (c) 2019 shumez\n\n# 01\n\nrequire(ggplot2)\ninstall.packages(\"dplyr\")\nrequire(dplyr)\nlibrary(dplyr)\ninstall.packages(\"tidyr\")\nlibrary(tidyr)\n\ndir = '~/Developer/stat/IntroductoryStatistics/01'\nsetwd(dir)\ndir_fig = file.path(dir, 'fig')\n\n# Collaborative Exercise\n\ndat = c(5, 5.5, 6, 6, 6, 6.5, 6.5, 6.5, 6.5, 7, 7, 8, 8, 9)\ndf = data.frame(SleepingTime=dat)\nView(df)\n\np <- ggplot(df, aes(SleepingTime))\np <- p + geom_dotplot(binwidth = .5, dotsize=1)#, method = \"histodot\")\np %+% geom_histogram(binwidth = .5)\np <- p + labs(x='Sleeping Time')\nggsave(file.path(dir_fig,'0102.png'), width = 3, height = 3)\n\n\n# 01.01.\n\n\n# 01.02. \nCollege = c('De Anza College', 'Foothill College')\nFullTime = c(9200, 4059)\nPartTime = c(13296, 10124)\ndf = data.frame(College=College, 'FullTime'=FullTime, 'PartTime'=PartTime)\nView(df)\n\ndat <- gather(df, 'category', 'number', -College)\ndat$category[which(dat$category=='FullTime')] <- 'Full-time'\ndat$category[which(dat$category=='PartTime')] <- 'Part-time'\ndat$College <- as.character(dat$College)\ndat$College[which(dat$College=='De Anza College')] <- 'De Anza'\ndat$College[which(dat$College=='Foothill College')] <- 'Foothill'\nView(dat)\nggplot(dat, aes(College, number, fill=category)) + geom_col()\nggsave(file.path(dir_fig, '0106.png'), width = 3, height = 3)\n\n\n# 01.02.03. Variation in Data\ncans = c(15.8, 16.1, 15.2, 14.8, 15.8, 15.9, 16.0, 15.5)\nsd(cans)\n\n# 01.03. Frequency, Frequency Tables, and Levels of Measurement\n\n# 01.03.03. Frequency\n\nStudentWorkHours = data.frame(DataValue=c(2, 3, 4, 5, 6, 7), Frequency=c(3, 5, 3, 6, 2, 1))\nStudentWorkHours$RelativeFrequency = StudentWorkHours$Frequency/sum(StudentWorkHours$Frequency)\nStudentWorkHours$CumulativeRelativeFrequency = rep(0, length(StudentWorkHours$RelativeFrequency))\nfor (i in 1:length(StudentWorkHours$RelativeFrequency)) {\n if(i == 1){\n StudentWorkHours$CumulativeRelativeFrequency[1] = StudentWorkHours$RelativeFrequency[1]\n }else{\n StudentWorkHours$CumulativeRelativeFrequency[i] = StudentWorkHours$RelativeFrequency[i] + StudentWorkHours$CumulativeRelativeFrequency[i-1]\n }\n}\nView(StudentWorkHours)\n\nSoccerPlayerHeight = data.frame(height=c('59.95–61.95', '61.95–63.95', '63.95–65.95', '65.95–67.95', '67.95–69.95', '69.95–71.95', '71.95–73.95', '73.95–75.95'), \n height_from = c(59.95, 61.95, 63.95, 65.95, 67.95, 69.95, 71.95, 73.95),\n height_to = c(61.95, 63.95, 65.95, 67.95, 69.95, 71.95, 73.95, 75.95),\n frequency=c(5, 3, 15, 40, 17, 12, 7, 1))\nSoccerPlayerHeight$RelativeFrequency = SoccerPlayerHeight$frequency / sum(SoccerPlayerHeight$frequency)\nView(SoccerPlayerHeight)\n", "meta": {"hexsha": "bc6b7bcd72da45b7ae29c1236d7ca61cfb473e7a", "size": 2896, "ext": "r", "lang": "R", "max_stars_repo_path": "IntroductoryStatistics/01/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": "IntroductoryStatistics/01/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": "IntroductoryStatistics/01/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": 35.3170731707, "max_line_length": 162, "alphanum_fraction": 0.6812845304, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6688802537704064, "lm_q1q2_score": 0.4380461525545998}}
{"text": "#' Calculate Information Value for character or factor columns\n#'\n#' This function calculates information value for character or factor columns of data frame. \n#'\n#' @param df data frame with at least two columns (predictor x and outcome y)\n#' @param x column (character or factor) for which Information Value should be calculated\n#' @param y column (integer) with binary outcome. y has to be a column in df data frame. It is suggested that y is factor with two levels \"bad\" and \"good\" If there are no levels good/bad than the following assumptions are applied - if y is integer, than 0=good and 1=bad. If y is factor than level 2 is assumed to mean bad and 1 good.\n#' @param verbose Prints additional details when TRUE. Useful mainly for debugging.\n#' @export\n#' @examples\n#' iv.str(german_data,\"purpose\",\"gb\")\n#' iv.str(german_data,\"savings\",\"gb\")\n\niv.str <- function(df,x,y,verbose=FALSE) {\n if (!(class(df)==\"data.frame\")) {\n stop(\"Parameter df has to be a data frame.\")\n } \n if (!(is.character(df[, x]) || is.factor(df[, x]))) {\n stop(paste(\"Input is not a character or factor! Variable:\", x))\n } \n if (!(is.numeric(df[, y]) || is.factor(df[, y]))) {\n stop(\"Outcome is not a number nor factor!\")\n } \n if (length(unique(df[, y])) != 2) {\n if(verbose) paste(cat(unique(df[,y])),\"\\n\")\n stop(\"Not a binary outcome\")\n }\n if (!(all(sort(unique(df[, y])) == c(0,1))) && is.numeric(df[,y])) {\n stop(\"Numeric outcome has to be encoded as 0 (good) and 1 (bad). \\n\")\n }\n if (is.factor(df[,y]) && all(levels(df[,y])[order(levels(df[,y]))]==c(\"bad\",\"good\"))) {\n if (verbose) cat(\"Assuming good = level 'good' and bad = level 'bad' \\n\")\n total_1 <- sum(df[,y]==\"bad\")\n } else if (is.factor(df[,y])) {\n if (verbose) cat(\"Factor: Assuming bad = level 2 and good = level 1 \\n\")\n total_1 <- sum(as.integer(df[, y])-1)\n\n } else {\n if (verbose) cat(\"Numeric: Assuming bad = 1 and good = 0 \\n\")\n total_1 <-sum(df[, y])\n\n }\n\n outcome_0 <- outcome_1 <- NULL # This is needed to avoid NOTES about not visible binding from R CMD check\n \n total_0 <- nrow(df) - total_1 \n iv_data <- data.frame(unclass(table(df[, x],df[, y])))\n \n if (all(names(iv_data)==c(\"bad\",\"good\"))) {\n iv_data <- iv_data[,c(2,1)]\n }\n\n\n names(iv_data) <- c(\"outcome_0\",\"outcome_1\")\n iv_data <- within(iv_data, {\n class <- row.names(iv_data)\n variable <- x\n pct_0 <- outcome_0 / total_0\n pct_1 <- outcome_1 / total_1\n odds <- pct_0 / pct_1\n woe <- log(odds)\n miv <- (pct_0 - pct_1) * woe \n })\n\n if(is.factor(df[,x])) {\n iv_data$class <- factor(iv_data$class,levels=levels(df[,x]))\n } \n \n iv_data <- iv_data[c(\"variable\",\"class\",\"outcome_0\",\"outcome_1\",\"pct_0\",\"pct_1\",\"odds\",\"woe\",\"miv\")]\n\n if(any(iv_data$outcome_0 == 0) | any(iv_data$outcome_1 == 0)) {\n warning(\"Some group for outcome 0 has zero count. This will result in -Inf or Inf WOE. Replacing - ODDS=1, WoE=0, MIV=0. \\n The bin is either too small or suspiciously predictive. \\n You should fix this before running any model. It does not make any sense to keep WoE = 0 for such bin.\")\n iv_data$woe <- ifelse(is.infinite(iv_data$woe),0,iv_data$woe)\n iv_data$miv <- ifelse(is.infinite(iv_data$miv),0,iv_data$miv)\n iv_data$odds <-ifelse(is.infinite(iv_data$odds),1,iv_data$odds)\n }\n \n rownames(iv_data) <- NULL\n cat (paste(\"Information Value\",round(sum(iv_data$miv),2),\"\\n\"))\n iv_data\n}\n\n", "meta": {"hexsha": "f950a9692e808b8ab643b153bfc04e3399f968fe", "size": 3511, "ext": "r", "lang": "R", "max_stars_repo_path": "Classification & Clustering/others/iv.str.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/iv.str.r", "max_issues_repo_name": "kkc-krish/DataScienceR", "max_issues_repo_head_hexsha": "b51837e5be357a3e25daf46ed6bba67dbca2be10", "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/iv.str.r", "max_forks_repo_name": "kkc-krish/DataScienceR", "max_forks_repo_head_hexsha": "b51837e5be357a3e25daf46ed6bba67dbca2be10", "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": 42.3012048193, "max_line_length": 334, "alphanum_fraction": 0.6217601823, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4373973342840862}}
{"text": "#Analyses for Tutorial 06: Ancestral State Estimation in R\n #Parts of this tutorial are based on that of L. Revell: http://www.phytools.org/eqg2015/asr.html\n\nlibrary(phytools)\nlibrary(geiger)\n\n######Discrete Anc. State Estimation\n## Read data & tree\ntree<-read.tree(\"TutorialData/anole.gp.tre\",tree.names=T)\ngroup<-read.csv('TutorialData/anole.gp.csv', row.names=1, header=TRUE,colClasses=c('factor'))\ngp<-as.factor(t(group)); names(gp)<-row.names(group)\n\n#Plot \nplotTree(tree,type=\"fan\",fsize=0.8)\ncols<-setNames(palette()[1:length(unique(gp))],sort(unique(gp)))\ntiplabels(pie=model.matrix(~gp-1),piecol=cols,cex=0.3)\nadd.simmap.legend(colors=cols,prompt=FALSE,x=0.9*par()$usr[1],\n y=-max(nodeHeights(tree)),fsize=0.8)\n\n### A:Parsimony estimation\n #programming NOTE: 'MPR' in APE requires unrooted tree, outgroup specification & integer states\n#gp.int<-as.numeric(gp); names(gp.int)<-names(gp) \n#anc.mp<-MPR(gp.int,unroot(tree), outgroup = \"Anolis_occultus\") \n\n#Plot\n#anc.mp.mat<-(model.matrix(~as.factor(anc.mp[,1])-1) +model.matrix(~as.factor(anc.mp[,2])-1)) /2 #matrix of states for plotting nodes\n#plotTree(tree, type=\"fan\",fsize=0.8,ftype=\"i\")\n#cols<-setNames(palette()[1:length(unique(gp.int))],sort(unique(gp.int)))\n#tiplabels(pie=model.matrix(~as.factor(gp.int)-1),piecol=cols,cex=0.3)\n# NOTE: barks on nodelabels\n#nodelabels(node=1:tree$Nnode+Ntip(tree),\n# pie=anc.mp.mat,piecol=cols,cex=0.3)\n#add.simmap.legend(colors=cols,prompt=FALSE,x=0.9*par()$usr[1],\n# y=-max(nodeHeights(tree)),fsize=0.8)\n\n### B: ML estimation\nanc.ML<-ace(gp,tree,model=\"ER\",type=\"discrete\")\n round(anc.ML$lik.anc[1:10,],3) #show result: \n#PLOT \nplotTree(tree,type=\"fan\",fsize=0.8,ftype=\"i\")\ncols<-setNames(palette()[1:length(unique(gp))],sort(unique(gp)))\nnodelabels(node=1:tree$Nnode+Ntip(tree),\n pie=anc.ML$lik.anc,piecol=cols,cex=0.3)\ntiplabels(pie=model.matrix(~gp-1),piecol=cols,cex=0.3)\nadd.simmap.legend(colors=cols,prompt=FALSE,x=0.9*par()$usr[1],\n y=-max(nodeHeights(tree)),fsize=0.8)\n\n\n#MCMC Stochastic Character Mapping (SIMMAP) based on Huelsenbeck et al. 2003\n# simulate single stochastic character map using empirical Bayes method\ntree.smp1<-make.simmap(tree,gp,model=\"ER\")\nplot(tree.smp1,cols,type=\"fan\",fsize=0.8,ftype=\"i\") #one run. Not overly useful. \n\n#Must do many times\ntree.smp<-make.simmap(tree,gp,model=\"ER\",nsim=100)\nanc.smp<-summary(tree.smp,plot=FALSE)\nplot(anc.smp, type=\"fan\", fsize=0.8,ftype=\"i\")\n\nrm(list = ls())\n\n######Continuous Anc. State Estimation\n#Data from Mahler et al. 2010. Evolution\ntree<-read.tree(\"TutorialData/anole.svl.tre\",tree.names=T)\nsvl<-read.csv('TutorialData/anole.svl.csv', row.names=1, header=TRUE)\nsvl<-as.matrix(svl)[,1] #change to vector\nanc.cont.ML<-fastAnc(tree,svl,vars=TRUE,CI=TRUE)\n #anc.cont.ML #output: estimate and 95% CI\nanc.cont.ML$ace #ancestral estimates\nplot(tree)\nnodelabels()\n\n\n#PLOT as color map\ntree.col<-contMap(tree,svl,plot=FALSE) #runs Anc. St. Est. on branches of tree\nplot(tree.col,type=\"fan\",legend=0.7*max(nodeHeights(tree)),\n fsize=c(0.7,0.9))\n\n#using 'ace' function in APE\nanc.cont.ML2<-ace(x=svl,phy=tree, type=\"continuous\", method=\"ML\")\nanc.cont.ML2$ace #with APE\nanc.cont.ML$ace #with phytools: the same estimates\n\nanc.cont.gls<-ace(x=svl,phy=tree, corStruct = corBrownian(1, tree), method=\"GLS\") #same as ML (see Schluter et al. 1997)\nanc.cont.gls$ace #GLS: SCP. the same\n\nrm(list = ls())\n######################## Simulation with known nodes\ntree<-pbtree(n=100,scale=1)\n## simulate data with a trend\nx<-fastBM(tree,internal=TRUE,mu=3)\nphenogram(tree,x,ftype=\"off\")\n\n#estimate with no prior \na<-x[as.character(1:tree$Nnode+Ntip(tree))]\nx<-x[tree$tip.label]\n## let's see how bad we do if we ignore the trend\nplot(a,fastAnc(tree,x),xlab=\"true values\",\n ylab=\"estimated states under BM\")\nlines(range(c(x,a)),range(c(x,a)),lty=\"dashed\",col=\"red\")\ntitle(\"estimated without prior information\")\n\n## incorporate prior knowledge\npm<-setNames(c(1000,rep(0,tree$Nnode)),\n c(\"sig2\",1:tree$Nnode+length(tree$tip.label)))\n## the root & two randomly chosen nodes\nnn<-as.character(c(length(tree$tip.label)+1,\n sample(2:tree$Nnode+length(tree$tip.label),2)))\npm[nn]<-a[as.character(nn)]\n## prior variance\npv<-setNames(c(1000^2,rep(1000,length(pm)-1)),names(pm))\npv[as.character(nn)]<-1e-100\n## run MCMC\nmcmc<-anc.Bayes(tree,x,ngen=100000,\n control=list(pr.mean=pm,pr.var=pv,\n a=pm[as.character(length(tree$tip.label)+1)],\n y=pm[as.character(2:tree$Nnode+length(tree$tip.label))]))\n\nanc.est<-colMeans(mcmc$mcmc[201:1001,as.character(1:tree$Nnode+length(tree$tip.label))])\n\nplot(a,anc.est,xlab=\"true values\",\n ylab=\"estimated states using informative prior\")\nlines(range(c(x,a)),range(c(x,a)),lty=\"dashed\",col=\"red\")\ntitle(\"estimated using informative prior\")\n", "meta": {"hexsha": "150c4fd48b0f7847bca4c065d061055efc325527", "size": 4921, "ext": "r", "lang": "R", "max_stars_repo_path": "practicals/TutorialData/AncStateEstimation.r", "max_stars_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_stars_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practicals/TutorialData/AncStateEstimation.r", "max_issues_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_issues_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practicals/TutorialData/AncStateEstimation.r", "max_forks_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_forks_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_forks_repo_licenses": ["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.685483871, "max_line_length": 133, "alphanum_fraction": 0.6856330014, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4372963847551408}}
{"text": "#author: Thomas Coleman\n# Difference in Differences Regressions - Error Analysis and Graphs for data from Snow 1855\n\n# See \"Causality in the Time of Cholera\" working paper at https://papers.ssrn.com/abstract=3262234 \n# and my John Snow project website, http://www.hilerun.org/econ/papers/snow\n\n# This code is licensed under the BSD 2-Clause License, https://opensource.org/licenses/BSD-2-Clause\n\n# This collect together some simple functions that produce a standard format graph, and are 'source'd \n# into various notebooks\n\n# **preperrdata** Before graphing, to prepare the data\n\n# * Takes in *fittedmodel* - a regression that has been already run. From this it extracts the necessary \n# parameters. Also *single*, a string which for \"single\" says that there is a single treatment effect. \n# * Calculates the 1849 and 1854 predicted counts and rates\n# * Calculates *approximate* 95% error bars around the predicted rates, based on whether the fitted model \n# is Poisson or Negative Binomial\n# * Produces an adjusted 1854 predicted rate, adjusting for the 1854 time effect and treatment effect, so \n# that it is comparable to the 1849 predicted rate (for purposes of plotting with error bars)\n\n# This function changes global data (the x1849 & x1854 dataframes) using the \"<<-\" instead of \"<-\" \n# assignment. This is poor programming style but I could not find another easy way of doing what I wanted. \n\n# **plot2_worker** Plots actual vs predicted, with error bars around the predicted\n\n# * Actually does the plotting, given all the data as input arguments (sequence no. for sub-districts; \n# the actual mean or rate; predicted; the 2.5% and 97.5% points; title)\n# * btw, the hack for plotting error bars is from \n# https://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars\n\n# **plot2_worker** Is a cover function which unpacks the actual versus predicted mean from the appropriate dataframe\n\n# **plot3** Plots actual 1849, 1854 (adjusted for time & treatment effects), predicted, with error bars\n\n# **plotcomp** Plots actual 1849 versus 1854, with error bars around actual 1849\n\n# **ploterrbars** is NOT a function you should use - I use it to print out .pdf versions of the graphs I want to use\n\n\n\n\npreperrdata <- function(fittedmodel,single = \"single\") { # This is not a good way to do this because I am \n\t # changing globals from within the function (using <<- \n\t # instead of <-)\n# Function to prepare the data (error bars) for graphing\n# The 2.5% and 97.5% confidence bands are calculated assuming either Poisson or Negative Binomial\n# The rates are calculated by generating the counts up and down from the \"expected\" (from the fitted model)\n\n\texpected <- exp(predict(fittedmodel)) # expected values\n\ttheta <- fittedmodel$theta\n\tx1849$predcount <<- expected[1:28]\n\tx1854$predcount <<- expected[29:56]\n\tx1849$predrate <<- 10000 * expected[1:28] / x1849$pop1851\n\tx1854$predrate <<- 10000 * expected[29:56] / x1854$pop1851\n\txfamily <- family(fittedmodel)$family\n\tif (xfamily == \"poisson\") { # Get 95% confidence bands depending on model used (Poiss vs Neg Binom)\n\t\tx1849$limdn <<- 10000 * qpois(.025,lambda=x1849$predcount) / x1849$pop1851\n\t\tx1849$limup <<- 10000 * qpois(.975,lambda=x1849$predcount) / x1849$pop1851\n\t} else {\n\t\tx1849$limdn <<- 10000 * qnbinom(.025,size=theta,mu=x1849$predcount) / x1849$pop1851\n\t\tx1849$limup <<- 10000 * qnbinom(.975,size=theta,mu=x1849$predcount) / x1849$pop1851\n\t\tx1854$limdn <<- 10000 * qnbinom(.025,size=theta,mu=x1854$predcount) / x1849$pop1851\n\t\tx1854$limup <<- 10000 * qnbinom(.975,size=theta,mu=x1854$predcount) / x1849$pop1851\n\t\tx1849$limdnact <<- 10000 * qnbinom(.025,size=theta,mu=x1849$deaths) / x1849$pop1851\n\t\tx1849$limupact <<- 10000 * qnbinom(.975,size=theta,mu=x1849$deaths) / x1849$pop1851\n\t}\n\n\n\t# Now adjust the 1854 predicted counts (and rates) for the time and treatment fixed effects -\n\t# effectively netting out the 1854 effect and making it 1849-equivalent\n\txyr1854 <- (coef(fittedmodel)[\"year1854\"])\n\tx3 <- exp(-xyr1854)\n\t# Adjust for the year effect only - this should make 1849 & 1854 comparable net of time effect\n\tx1854$rateadjyr <<- 10000 * (x1854$deaths*x3) / x1854$pop1851\n\t# Adjust the 1854 actual for the estimated Treatment Effect and the estimate Year Effect\n\tif (single == \"single\") { # model with single treatment effect\n\t\txdegless <- (coef(fittedmodel)[\"supplierSouthwarkVauxhall_Lambeth:year1854\"])\n\t\txdegmore <- xdegless # Make both treatment effects the same\n\t\tx3 <- x3 * exp(-(x1854$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\tx3 <- x3 * exp(-(x1854$lambethdegree == \"more_Lambeth\")*xdegmore)\n\t} else if (single == \"two\") { # model with two treatment effects \t\t\n\t\txdegless <- coef(fittedmodel)[\"lambethdegreeless_Lambeth:year1854\"]\n\t\txdegmore <- coef(fittedmodel)[\"lambethdegreemore_Lambeth:year1854\"]\n\t\tx3 <- x3 * exp(-(x1854$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\tx3 <- x3 * exp(-(x1854$lambethdegree == \"more_Lambeth\")*xdegmore)\n\t} else { # model with continuous treatment (population proportions)\n\t\txlambethperc54 <- coef(fittedmodel)[\"lambethperc54\"]\n\t\tx3 <- x3 * exp(-(x1854$lambethperc54 * xlambethperc54))\n\t}\n\n\t# Adjust for year & treatment effect - so that we can compare the actuals against each other \n\tx1854$rateadj <<- 10000 * (x1854$deaths*x3) / x1854$pop1851\n\n\treturn(xfamily)\n}\n\n\n# \"Worker\" function to plot mean, predicted, and error bars\nplot2_worker <- function(yseq, xmean,xlimdn,xpred,xlimup,title) { \n\txplot <- plot(xmean, yseq,\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), col=\"red\",\n\t main=title,xlab=\"Mortality rate actual (red filled) vs predicted (empty circle)\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xpred, yseq, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), \n\t pch=1)\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, yseq, xlimup, yseq, length=0.05, angle=90, code=3,lty=3)\n\txplot\n}\n# \"Cover\" function that takes in the dataframe and unpacks\nplot2 <- function(confidata,xsupplier,title) { \n\txmean <- subset(confidata,supplier==xsupplier)[,\"rate\"]\n\txlimdn <- subset(confidata,supplier==xsupplier)[,\"limdn\"]\n\txlimup <- subset(confidata,supplier==xsupplier)[,\"limup\"]\n\txpred <- subset(confidata,supplier==xsupplier)[,\"predrate\"]\n\tyseq <- subset(confidata,supplier==xsupplier)[,\"seq\"]\n#\txtitle <- paste(xsupplier,title)\n\txplot <- plot2_worker(yseq,xmean,xlimdn,xpred,xlimup,title)\n}\n\nplot3 <- function(confidata1849,confidata1854,xsupplier,title) { \n\txmean <- subset(confidata1849,supplier==xsupplier)[,\"rate\"]\n\txlimdn <- subset(confidata1849,supplier==xsupplier)[,\"limdn\"]\n\txlimup <- subset(confidata1849,supplier==xsupplier)[,\"limup\"]\n\txpred <- subset(confidata1849,supplier==xsupplier)[,\"predrate\"]\n\ty <- subset(confidata1849,supplier==xsupplier)[,\"seq\"]\n\tx1854adj <- subset(confidata1854,supplier==xsupplier)[,\"rateadj\"]\n\txplot <- plot(xmean, y,\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup,x1854adj)),\n\t ylim=rev(range(y)), col=\"red\", \n\t main=title,xlab=\"Mortality: 1849 red circle, 1854 blue diamond vs predicted (circle)\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xpred, y, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(y)), \n\t pch=1)\n\tlines(x1854adj, y, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(y)), col=\"blue\", \n\t pch=17)\n\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, y, xlimup, y, length=0.05, angle=90, code=3,lty=3)\n}\n\n# Plotting joint region for 1849 & 1854 with error bars for each\nplotcomp <- function(confidata1849,confidata1854,xsupplier,title) { \n\txmean <- subset(confidata1849,supplier==xsupplier)[,\"rate\"]\n\txlimdn <- subset(confidata1849,supplier==xsupplier)[,\"limdnact\"]\n\txlimup <- subset(confidata1849,supplier==xsupplier)[,\"limupact\"]\n\txpred <- subset(confidata1849,supplier==xsupplier)[,\"predrate\"]\n\ty <- subset(confidata1849,supplier==xsupplier)[,\"seq\"]\n\txmean1854 <- subset(confidata1854,supplier==xsupplier)[,\"rateadjyr\"]\n#\txlimdn1854 <- subset(confidata1854,supplier==xsupplier)[,\"limdn\"]\n#\txlimup1854 <- subset(confidata1854,supplier==xsupplier)[,\"limup\"]\n\txplot <- plot(xmean, y,\n\t xlim=range(c(xmean, xmean1854,xlimdn,xlimup)),\n\t ylim=rev(range(y)), col=\"red\",\n\t main=title,xlab=\"Mortality: 1849 red circle, 1854 blue diamond\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xmean1854, y, type=\"p\",\n\t xlim=range(c(xmean, xmean1854,xlimdn,xlimup)),\n\t ylim=rev(range(y)), col=\"blue\",\n\t pch=17)\n\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, y, xlimup, y, length=0.05, angle=90, code=3,,lty=3)\n#\txplot <- arrows(xlimdn1854, y, xlimup1854, y, length=0.05, angle=90, code=3)\n}\n\n\nploterrbars <- function(fittedmodel,plotname,single = \"single\") { # This is not a good way to do this because I am \n\t # changing globals from within the function (using <<- \n\t # instead of <-)\n\txfamily <- preperrdata(fittedmodel,single) # this function modifies global data\n\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"a.pdf\",sep=\"\"))\n\t\tplot2(x1849,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"b.pdf\",sep=\"\"))\n\t\tplot2(x1849,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"c.pdf\",sep=\"\"))\n\t\tplot3(x1849,x1854,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849vs1854 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"d.pdf\",sep=\"\"))\n\t\tplot3(x1849,x1854,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849vs1854 \"))\n\tdev.off()\n\tif (xfamily != \"poisson\") { # Plot comparison for joint region only for Negative Binomial\n\t\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"e.pdf\",sep=\"\"))\n\t\t\tplotcomp(x1849,x1854,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849vs1854 \"))\n\t\tdev.off()\n\t\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"f.pdf\",sep=\"\"))\n\t\t\tplotcomp(x1849,x1854,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849vs1854 \"))\n\t\tdev.off()\n\t}\n\n}\n\n\n\n", "meta": {"hexsha": "4f460458fcb9c5f81c12cacf54649a11fa70e5e0", "size": 10364, "ext": "r", "lang": "R", "max_stars_repo_path": "SnowPlotFns.r", "max_stars_repo_name": "tscoleman/SnowCholera", "max_stars_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-08T22:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:57:00.000Z", "max_issues_repo_path": "SnowPlotFns.r", "max_issues_repo_name": "tscoleman/SnowCholera", "max_issues_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "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": "SnowPlotFns.r", "max_forks_repo_name": "tscoleman/SnowCholera", "max_forks_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-07T10:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T10:59:14.000Z", "avg_line_length": 50.3106796117, "max_line_length": 121, "alphanum_fraction": 0.6987649556, "num_tokens": 3159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.436889021873531}}
{"text": "\nif (latitude < 0):\n if (sowingDay > sDsa_sh):\n fixPhyll = p * (1 - rp * min(sowingDay - sDsa_sh, sDws))\n else: fixPhyll = p\nelse:\n if (sowingDay < sDsa_nh):\n fixPhyll = p * (1 - rp * min(sowingDay, sDws))\n else: fixPhyll = p\n", "meta": {"hexsha": "6f3ca197afe98fb8621bce315b250b60224ecc96", "size": 252, "ext": "r", "lang": "R", "max_stars_repo_path": "test/data/phenology/crop2ml/algo/r/PhylSowingDateCorrection.r", "max_stars_repo_name": "brichet/PyCrop2ML", "max_stars_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "test/data/phenology/crop2ml/algo/r/PhylSowingDateCorrection.r", "max_issues_repo_name": "brichet/PyCrop2ML", "max_issues_repo_head_hexsha": "7177996f72a8d95fdbabb772a16f1fd87b1d033e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "test/data/phenology/crop2ml/algo/r/PhylSowingDateCorrection.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": 25.2, "max_line_length": 64, "alphanum_fraction": 0.5555555556, "num_tokens": 99, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.43688902187353085}}
{"text": "params <- chrpfdnm %>% group_by(ID) %>% summarise(n=n()) %>% summarise(mean=mean(n), sd=sd(n))\r\n\r\n##############################################################################\r\n# Calculate individual-level AUC from the GoNL DNMs\r\n#\r\n# Each iteration calculates the AUC for the following:\r\n# AUC under 3-mer model\r\n# Permuted AUC under 3-mer model\r\n# AUC under logit model\r\n# Permuted AUC under logit model\r\n##############################################################################\r\nnperm <- 258\r\n\r\naucperm <- rep(0,nperm)\r\naucperm3 <- aucperm\r\n\r\nids <- unique(chrpfdnm$ID)\r\nnumind <- length(ids)\r\naucind <- rep(0, numind)\r\naucind3 <- aucind\r\n\r\nfor(i in 1:nperm){\r\n\t### Run permutations\r\n\tcat(\"Permuting AUC\", \"(\", i, \"of\", nperm, \")...\\n\")\r\n\tndnms <- round(rnorm(1, params$mean, params$sd), 0)\r\n\tnsamp <- 1000000\r\n\r\n\tchrpsub <- rbind(chrpfdnm[sample(nrow(chrpfdnm), ndnms),], chrpfa) %>%\r\n\t\tarrange(MU)\r\n\tchrpsub$prop <- cumsum(chrpsub$OBS)/sum(chrpsub$OBS)\r\n\tchrpsub2 <- chrpsub[sample(nrow(chrpsub), nsamp),] %>%\r\n\t arrange(MU) %>%\r\n\t mutate(ntile=ntile(MU, 1000))\r\n\r\n\tchrpsub3 <- chrpsub %>% arrange(MU3)\r\n\tchrpsub3$prop <- cumsum(chrpsub3$OBS)/sum(chrpsub3$OBS)\r\n\tchrpsub3a <- chrpsub3[sample(nrow(chrpsub3), nsamp),] %>%\r\n\t\tarrange(MU3, prop) %>%\r\n\t\tmutate(ntile=ntile(MU3, 1000))\r\n\r\n\tauctmp <- chrpsub2 %>% summarise(AUC=1-sum(prop)/nsamp)\r\n\taucperm[i] <- auctmp$AUC\r\n\tauctmp3 <- chrpsub3a %>% summarise(AUC=1-sum(prop)/nsamp)\r\n\taucperm3[i] <- auctmp3$AUC\r\n\r\n\tcurid<-ids[i]\r\n\t### Get empirical AUC\r\n\tcat(\"Calculating AUC for\", curid, \"(\", i, \"of\", numind, \")...\\n\")\r\n\tdatid<-chrpfdnm %>% filter(ID==curid)\r\n\r\n\ttmpdat<-rbind(datid, chrpfa) %>% arrange(MU)\r\n\ttmpdat$prop<-cumsum(tmpdat$OBS)/sum(tmpdat$OBS)\r\n\ttmpdat2<-tmpdat[sample(nrow(tmpdat), nsamp),] %>%\r\n\t arrange(MU) %>%\r\n\t mutate(ntile=ntile(MU, 1000))\r\n\r\n\t### Repeat with 3-mer model\r\n\ttmpdat3<-tmpdat %>% arrange(MU3)\r\n\ttmpdat3$prop<-cumsum(tmpdat3$OBS)/sum(tmpdat3$OBS)\r\n\ttmpdat3s<-tmpdat3[sample(nrow(tmpdat3), nsamp),] %>%\r\n\t\tarrange(MU3, prop) %>%\r\n\t\tmutate(ntile=ntile(MU3, 1000))\r\n\r\n\ttmpauc <- tmpdat2 %>% summarise(AUC=1-sum(prop)/nsamp)\r\n\taucind[i]<-tmpauc$AUC\r\n\ttmpauc3 <- tmpdat3s %>% summarise(AUC=1-sum(prop)/nsamp)\r\n\taucind3[i]<-tmpauc3$AUC\r\n}\r\n\r\n##############################################################################\r\n# Calculate AUC for each individual under the logit and 3-mer models\r\n##############################################################################\r\n# ids<-unique(chrpfdnm$ID)\r\n# numind<-length(ids)\r\n# aucind<-rep(0, numind)\r\n# aucind3<-aucind\r\n#\r\n# for(i in 1:numind){\r\n# \tcurid<-ids[i]\r\n# \tcat(\"Calculating AUC for\", curid, \"(\", i, \"of\", numind, \")...\\n\")\r\n# \tdatid<-chrpfdnm %>% filter(ID==curid)\r\n# \ttmpdat<-rbind(datid, chrpfa) %>% arrange(MU)\r\n# \ttmpdat$prop<-cumsum(tmpdat$OBS)/sum(tmpdat$OBS)\r\n#\r\n# \tnsamp<-50000\r\n#\r\n# \ttmpdat2<-tmpdat[sample(nrow(tmpdat), nsamp),] %>%\r\n# \t arrange(MU) %>%\r\n# \t mutate(ntile=ntile(MU, 1000))\r\n#\r\n# \ttmpauc <- tmpdat2 %>% summarise(AUC=1-sum(prop)/nsamp)\r\n# \taucind[i]<-tmpauc$AUC\r\n#\r\n# \t### Repeat with 3-mer model\r\n# \ttmpdat3<-tmpdat %>% arrange(MU3)\r\n# \ttmpdat3$prop<-cumsum(tmpdat3$OBS)/sum(tmpdat3$OBS)\r\n#\r\n# \ttmpdat3s<-tmpdat3[sample(nrow(tmpdat3), nsamp),] %>%\r\n# \t\tarrange(MU3, prop) %>%\r\n# \t\tmutate(ntile=ntile(MU3, 1000))\r\n#\r\n# \ttmpauc3 <- tmpdat3s %>% summarise(AUC=1-sum(prop)/nsamp)\r\n# \taucind3[i]<-tmpauc3$AUC\r\n# }\r\n\r\n##############################################################################\r\n# Function checks if elements in a exist in b\r\n# Output is binary vector of length same as b\r\n##############################################################################\r\ntoBin <- function(a,b){\r\n\tas.numeric(is.element(b,a))\r\n}\r\n\r\n##############################################################################\r\n# Simulate mutations by randomly selecting sites and checking if\r\n# Bernoulli(mu)==1; loop continues until we have simulated the same number\r\n# of sites as in observed data\r\n##############################################################################\r\nnsim<-200\r\n\r\nfor(i in 1:nsim){\r\n\tcat(\"Running simulation\", i, \"of\", nsim, \"...\\n\")\r\n\tnsample <- 20000\r\n\tmutated <- c()\r\n\t# nsites<-round(rnorm(1, params$mean, params$sd), 0)\r\n nsites <- 10171\r\n\r\n\twhile(length(mutated) < nsites){\r\n\t\trowind <- sample(nrow(chrp), nsample)\r\n\t\trow <- chrp[rowind,]\r\n\t\tmu <- row$MU\r\n\r\n\t\tbatch <- sapply(mu, function(x) rbinom(1,1,x))\r\n\t\tmutated <- c(mutated, row$POS[which(as.logical(batch))])\r\n\t}\r\n\r\n\t# chrp$TMP <- toBin(mutated[1:nsites], chrp$POS)\r\n\tmus <- toBin(mutated, chrp$POS)\r\n\tnsimi <- sum(mus)\r\n\tchrp$last <- cumsum(mus)/nsimi\r\n\r\n\tcolnames(chrp)[ncol(chrp)] <- paste0(\"simprop\", i)\r\n}\r\n\r\n##############################################################################\r\n# Subsample 100k sites, resort by mu, add percentile column, and coerce\r\n# from wide to long format\r\n#\r\n# Can delete chrp after this step\r\n##############################################################################\r\ncat(\"Subsampling data...\\n\")\r\nnsamp<-100000\r\n\r\nchrp2<-chrp[sample(nrow(chrp), nsamp),] %>%\r\n arrange(MU) %>%\r\n mutate(ntile=ntile(MU, 1000)) %>%\r\n gather(group, val, .dots=grep(\"prop\", names(chrp)))\r\n\r\nauc <- chrp2 %>% group_by(group) %>% summarise(AUC=1-sum(val)/nsamp)\r\n\r\ncat(\"Cleaning up memory...\\n\")\r\ngc()\r\n\r\n##############################################################################\r\n# Summarize simulated data for ROC plots\r\n##############################################################################\r\nchrp2_nt_mean<-chrp2 %>%\r\n group_by(group, ntile) %>%\r\n summarise(val=mean(val))\r\n\r\n# Get subsets of true and simulated data\r\nchrp2_nt_sim<-chrp2_nt_mean[chrp2_nt_mean$group!=\"prop\",]\r\nchrp2_nt_obs<-chrp2_nt_mean[chrp2_nt_mean$group==\"prop\",]\r\n\r\n# Calculate lower/upper range from simulations\r\n# (can switch commented summarise() lines to use CI)\r\nchrp2_lb<-chrp2_nt_sim %>%\r\n group_by(ntile) %>%\r\n # summarise(lb=t.test(val)$conf.int[1]) %>%\r\n\tsummarise(lb=max(val)) %>%\r\n mutate(group=\"lb\") %>%\r\n dplyr::select(group, ntile, lb)\r\n\r\nchrp2_ub<-chrp2_nt_sim %>%\r\n group_by(ntile) %>%\r\n # summarise(ub=t.test(val)$conf.int[2]) %>%\r\n\tsummarise(ub=min(val)) %>%\r\n mutate(group=\"ub\") %>%\r\n dplyr::select(group, ntile, ub)\r\n\r\n# Add bounds to data frame\r\nchrp2_nt_obs$lb <- chrp2_lb$lb\r\nchrp2_nt_obs$ub <- chrp2_ub$ub\r\n\r\n##############################################################################\r\n# Combine AUC data to generate ROC plot\r\n##############################################################################\r\nfull_auc_dat<-rbind(data.frame(chrp2_nt_obs[,1:3]), data.frame(chrp3b))\r\nnames(full_auc_dat)[1]<-\"Model\"\r\nfull_auc_dat$Model<-ifelse(full_auc_dat$Model==\"prop\", \"Logit\", \"3-mer\")\r\nfull_auc_bounds<-chrp2_nt_obs[,c(2:5)]\r\n\r\nggplot()+\r\n geom_line(data=full_auc_dat,\r\n\t\taes(x=(1000-ntile)/1000, y=1-val, group=Model, colour=Model), size=1.2)+\r\n geom_abline(intercept=0, slope=1)+\r\n geom_ribbon(data=full_auc_bounds,\r\n\t\taes(x=(1000-ntile)/1000, y=1-val, ymin=1-ub, ymax=1-lb), alpha=0.2)+\r\n\tscale_colour_manual(values=cbbPalette[2:3])+\r\n coord_cartesian(xlim=c(0,1))+\r\n\txlab(\"False Positive Rate\")+\r\n\tylab(\"True Positive Rate\")+\r\n theme_bw()+\r\n\ttheme(\r\n\t\t# legend.position=\"none\",\r\n\t\taxis.title.x=element_text(size=20),\r\n\t\taxis.title.y=element_text(size=20))\r\n # scale_y_continuous(limits=c(0,1))+\r\n # scale_x_continuous(limits=c(0,1000), labels=c())\r\nggsave(\"/net/bipolar/jedidiah/mutation/images/pseudo_roc_curves.png\", height=4, width=7.25)\r\n\r\n##############################################################################\r\n# Get AUC data for distribution plots\r\n##############################################################################\r\nauc$model<-\"simulated\"\r\nauc$obs<-\"simulated\"\r\n\r\n# aucind_df<-data.frame(AUC=aucind, gp=\"ind\")\r\naucsim<-auc[-1,2:4]\r\nauclogitobs<-data.frame(AUC=aucind, model=\"logit\", obs=\"observed\")\r\nauc3merobs<-data.frame(AUC=aucind3, model=\"3-mer\", obs=\"observed\")\r\nauclogitperm<-data.frame(AUC=aucperm, model=\"logit\", obs=\"permuted\")\r\nauc3merperm<-data.frame(AUC=aucperm3, model=\"3-mer\", obs=\"permuted\")\r\n\r\n# All AUCs\r\nplotaucfull<-rbind(aucsim, auclogitobs, auc3merobs, auclogitperm, auc3merperm)\r\nplotaucfull$model<-as.factor(plotaucfull$model)\r\nplotaucfull$model<-relevel(plotaucfull$model, \"3-mer\")\r\n\r\n# No simulations\r\nplotaucnosim<-rbind(auclogitobs, auc3merobs, auclogitperm, auc3merperm)\r\nplotaucnosim$model<-as.factor(plotaucnosim$model)\r\nplotaucnosim$model<-relevel(plotaucnosim$model, \"3-mer\")\r\n\r\n# Only observed data (no simulation or permutations)\r\nplotaucobsonly<-rbind(auclogitobs, auc3merobs)\r\nplotaucobsonly$model<-as.factor(plotaucobsonly$model)\r\nplotaucobsonly$model<-relevel(plotaucobsonly$model, \"3-mer\")\r\n\r\n# Observed + Simulated (no permutations)\r\nplotaucnoperm<-rbind(aucsim, auclogitobs, auc3merobs)\r\nplotaucnoperm$model<-as.factor(plotaucnoperm$model)\r\nplotaucnoperm$model<-relevel(plotaucnoperm$model, \"3-mer\")\r\n\r\nplotaucmean<-plotaucobsonly %>%\r\n\tgroup_by(model, obs) %>%\r\n\tsummarise(AUC=mean(AUC))\r\n\r\nggplot()+\r\n\tgeom_density(data=plotaucfull, aes(x=AUC, colour=model, linetype=obs))+\r\n\tgeom_density(data=aucsim, aes(x=AUC), colour=\"black\")+\r\n\tscale_colour_manual(values=cbbPalette[c(2,3,1)])+\r\n\t# geom_vline(data=plotaucmean,\r\n\t# \taes(xintercept=AUC, colour=model, linetype=obs))+\r\n\ttheme_classic()+\r\n\tguides(linetype=F)+\r\n\ttheme(legend.position=\"bottom\")\r\nggsave(\"/net/bipolar/jedidiah/mutation/images/auc_hist.png\", height=4, width=4)\r\n\r\n# Add paternal age\r\nages<-read.table(\"/net/bipolar/jedidiah/mutation/reference_data/DNMs/gonl_fam_age.txt\", header=T)\r\nnames(ages)<-c(\"ID\", \"nDNM\", \"FatherAge\", \"MotherAge\", \"Coverage\")\r\nplotaucobsonly<-rbind(auclogitobs, auc3merobs)\r\nplotaucobsonly$ID<-c(ids, ids)\r\nplotaucobsonly<-merge(plotaucobsonly, ages, by=\"ID\")\r\n\r\n##############################################################################\r\n# Additional data summaries for paternal age, etc.\r\n##############################################################################\r\nauc_age_cor<-plotaucobsonly %>%\r\n\tgroup_by(model) %>%\r\n\tsummarise(cor=cor(AUC, FatherAge, method=\"spearman\"),\r\n\t\tcor.p=cor.test(AUC, FatherAge, method=\"spearman\")$p.value,\r\n\t\tcornum=cor(AUC, nDNM, method=\"spearman\"),\r\n\t\tcornum.p=cor.test(AUC, nDNM, method=\"spearman\")$p.value)\r\n\r\nfao<-plotaucobsonly %>%\r\n\tfilter(model==\"logit\") %>%\r\n\tfilter(AUC>0.669 | AUC<0.597) %>%\r\n\tmutate(quart=ifelse(AUC>0.669, \"yes\", \"no\")) %>%\r\n\tdplyr::select(quart, FatherAge) %>%\r\n\tspread(quart, FatherAge)\r\n\r\n# OLD VERSION--early attempt at pseudo-ROC curves\r\n# ggplot(chrp3, aes(x=1000-ntile, y=1-val, group=group, colour=group))+\r\n# geom_line()\r\n# ggsave(\"/net/bipolar/jedidiah/mutation/images/psuedo_roc_chr4a.png\")\r\n\r\n# OLD VERSION--uses true ROC calculations\r\n# devtools::install_github(\"hadley/ggplot2\")\r\n# devtools::install_github(\"sachsmc/plotROC\")\r\n# library(plotROC)\r\n#\r\n# basicplot2<-ggplot(chrp2, aes(d = OBS, m = MU))+\r\n# \tgeom_roc()\r\n#\r\n# basicplot2+annotate(\"text\", x = .75, y = .25,\r\n# label = paste(\"AUC =\", round(calc_auc(basicplot)$AUC, 2)))+\r\n# \tstyle_roc()\r\n# ggsave(\"/net/bipolar/jedidiah/mutation/images/chr18_roc2.png\")\r\n", "meta": {"hexsha": "033f17760fbf8cc96c1004bc0559ef2156976844", "size": 11086, "ext": "r", "lang": "R", "max_stars_repo_path": "sandbox/R_deprecated/roc_tmp.r", "max_stars_repo_name": "theandyb/smaug-genetics", "max_stars_repo_head_hexsha": "2e040aafb00bfecb698e83218c87dead07350630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-09-18T20:54:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-16T05:30:06.000Z", "max_issues_repo_path": "sandbox/R_deprecated/roc_tmp.r", "max_issues_repo_name": "theandyb/smaug-genetics", "max_issues_repo_head_hexsha": "2e040aafb00bfecb698e83218c87dead07350630", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-24T12:43:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-24T12:43:50.000Z", "max_forks_repo_path": "sandbox/R_deprecated/roc_tmp.r", "max_forks_repo_name": "theandyb/smaug-genetics", "max_forks_repo_head_hexsha": "2e040aafb00bfecb698e83218c87dead07350630", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-07-16T20:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T10:41:40.000Z", "avg_line_length": 35.6463022508, "max_line_length": 98, "alphanum_fraction": 0.5893018221, "num_tokens": 3478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.43610905095593877}}
{"text": "kasitsiTabel <-c( 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225)\r\npihta <- c(0, 0, 2, 3, 9, 12, 21, 26, 30, 35, 41, 46, 54, 59, 67, 74, 82, 89, 97, 106, 116, 125, 133, 144, 154, 163, 173, 184, 196, 207, 219, 230, 242, 255, 267, 280, 292, 305, 319, 332, 346, 361, 375, 390, 404, 419, 435, 450, 466, 481)\r\n\r\n#X11.options(type=\"nbcairo\")\r\nplot(kasitsiTabel, type=\"o\", col=\"blue\", ylim=c(0, 1300), xlab = \"N\", ylab=\"K\")\r\nlines(pihta, type=\"o\", pch=22, lty=2, col=\"red\")\r\n\r\nleg <- c(expression(\"k\"[0]), expression(\"k\"[1]))\r\ncols <- c(\"blue\", \"red\")\r\nlegend(0, 1300, leg, cex = 1, cols, pch=22, lty=1:2)\r\n", "meta": {"hexsha": "ad19df87865da1a6a4ee04286e2c714d771814ff", "size": 789, "ext": "r", "lang": "R", "max_stars_repo_path": "seminar_paper/r_graphs/T0vsN_graph.r", "max_stars_repo_name": "stenver/wilcoxon-test", "max_stars_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-04-05T09:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T14:35:01.000Z", "max_issues_repo_path": "seminar_paper/r_graphs/T0vsN_graph.r", "max_issues_repo_name": "stenver/wilcoxon-test", "max_issues_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "seminar_paper/r_graphs/T0vsN_graph.r", "max_forks_repo_name": "stenver/wilcoxon-test", "max_forks_repo_head_hexsha": "2158ed417996e91b09a1eab0b7265f723e42681b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-08-01T07:57:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-21T09:45:52.000Z", "avg_line_length": 71.7272727273, "max_line_length": 255, "alphanum_fraction": 0.5741444867, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.43575632574985323}}
{"text": "# 4. faza: Napredna analiza podatkov\n\nsource(\"lib/libraries.r\")\n\n# ==============================================================================\n# Uporabljene funkcije pri napredni analizi:\n# ==============================================================================\n\n# funkcije uporabljene pri razvrščanju v skupine:\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# 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 = \"black\"\n )+\n geom_line(\n mapping = aes(x = as.integer(k), y = visina),\n color = \"black\"\n )+\n geom_point(\n data = k.visina %>% filter(koleno),\n mapping = aes(x = k, y = visina),\n color = \"red\", size = 2.5\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}\n\ndiagram.skupine = function(podatki, oznake, skupine, k) {\n podatki = podatki %>%\n bind_cols(skupine) %>%\n rename(skupina = ...4)\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(h = c(180, 270)) +\n xlab(\"\") +\n ylab(\"\") +\n theme_classic() \n for (i in 1:k) {\n d = d + geom_encircle(\n data = podatki %>%\n filter(skupina == i)\n )\n }\n d\n}\n\nobrisi = function(podatki, hc = TRUE, od = 2, do = NULL) {\n n = nrow(podatki)\n if (is.null(do)) {\n do = n - 1\n }\n razdalje = dist(podatki)\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 k.obrisi\n}\n\nobrisi.povprecje = function(k.obrisi) {\n k.obrisi.povprecje = k.obrisi %>%\n group_by(k) %>%\n summarize(obrisi = mean(obrisi))\n}\n\nobrisi.k = function(k.obrisi) {\n obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n summarize(k = min(k)) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\ndiagram.obrisi = function(k.obrisi) {\n ggplot() +\n geom_boxplot(\n data = k.obrisi,\n mapping = aes(x = k, y = obrisi)\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = k, y = obrisi),\n color = \"red\"\n ) +\n geom_line(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = as.integer(k), y = obrisi),\n color = \"red\"\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n filter(k == min(k)),\n mapping = aes(x = k, y = obrisi),\n color = \"blue\"\n ) +\n xlab(\"število skupin (k)\") +\n ylab(\"obrisi (povprečje obrisov)\") +\n ggtitle(paste(\"Maksimalno povprečje obrisov pri k =\", obrisi.k(k.obrisi))) +\n theme_classic() \n}\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# funkcije za prečno preverjanje:\n\nucenje = function(podatki, formula, algoritem) {\n switch(\n algoritem,\n lin.reg = lm(formula, data = podatki),\n log.reg = glm(formula, data = podatki, family = \"binomial\"),\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 log.reg = ifelse(\n predict(model, podatki, type = \"response\") >= 0.5,\n 1, -1\n ),\n ng = predict(model, podatki)$predictions\n )\n}\n\nnapaka_regresije = function(podatki, model, algoritem) {\n podatki %>%\n bind_cols(yn.hat = napovedi(podatki, model, algoritem)) %>%\n mutate(\n izguba = (yn - yn.hat) ^ 2\n ) %>%\n select(izguba) %>%\n unlist() %>%\n mean()\n}\n\nnapaka_razvrscanja = function(podatki, model, algoritem) {\n podatki %>%\n bind_cols(yd.hat = napovedi(podatki, model, algoritem)) %>%\n mutate(\n izguba = (yd != yd.hat)\n ) %>%\n select(izguba) %>%\n unlist() %>%\n mean()\n}\n\n# Razreži vektor x na k enako velikih kosov\nrazbitje = function(x, k) {\n # Razreži indekse vektorja na k intervalov\n razrez = cut(seq_along(x), k, labels = FALSE)\n # Razbij vektor na k seznamov\n # na osnovi razreza intervalov\n split(x, razrez)\n}\n\npp.razbitje = function(n, k = 5, stratifikacija = NULL, seme = NULL) {\n # najprej nastavimo seme za naključna števila, če je podano\n if (!is.null(seme)) {\n set.seed(seme)\n }\n # če ne opravljamo stratifikacije, potem vrnemo navadno razbitje\n # funkcijo sample uporabimo zato, da naključno premešamo primere\n if (is.null(stratifikacija)) {\n return(razbitje(sample(1:n), k))\n }\n # če pa opravljamo stratifikacijo, razbitje izvedemo za vsako\n # vrednost spremenljive stratifikacija posebej in nato\n # podmnožice združimo v skupno razbitje\n r = NULL\n for (v in levels(stratifikacija)) {\n # Če smo pri prvi vrednosti vzpostavimo razbitje\n if (is.null(r)) {\n # opravimo razbitje samo za primere z vrednostjo v\n r = razbitje(sample(which(stratifikacija == v)), k)\n } else {\n # opravimo razbitje za vrednost v\n # in podmnožice združimo s trenutnim razbitjem\n r.v = razbitje(sample(which(stratifikacija == v)), k)\n for (i in 1:k) {\n r[[i]] = c(r[[i]], r.v[[i]])\n }\n }\n }\n r\n}\n\nprecno.preverjanje = function(podatki, razbitje, formula, algoritem, razvrscanje) {\n # pripravimo vektor za napovedi\n if (razvrscanje) {\n pp.napovedi = factor(rep(1, nrow(podatki)), levels = c(-1,1))\n } else {\n pp.napovedi = rep(0, nrow(podatki))\n }\n # gremo čez vse podmnožice Si razbitja S\n for (i in 1:length(razbitje)) {\n # naučimo se modela na množici S \\ Si\n model = podatki[ -razbitje[[i]], ] %>% ucenje(formula, algoritem)\n # naučen model uporabimo za napovedi na Si\n pp.napovedi[ razbitje[[i]] ] = podatki[ razbitje[[i]], ] %>% napovedi(model, algoritem)\n }\n if (razvrscanje) {\n mean(pp.napovedi != podatki$pricak)\n } else {\n mean((pp.napovedi - podatki$pricak) ^ 2)\n }\n}\n\n# Funkciji Predictor$new moramo povedati kako napovedujemo z modelom naključnih gozdov \npfun = function(model, newdata) {\n predict(model, data = newdata, predict.all = FALSE)$predictions\n}\n\n# ==============================================================================\n# RAZVRSTITEV V SKUPINE\n# ==============================================================================\n\n# 1) k-means\n\n# koliko skupin naj izberem pri razdelitvi z metodo voditeljev:\nr.hc = TURIZEM.EVROPA[, -1] %>% obrisi(hc = TRUE)\nr.km = TURIZEM.EVROPA[, -1] %>% obrisi(hc = FALSE)\n\nr.hc.plt <- diagram.obrisi(r.hc)\nr.km.plt <- diagram.obrisi(r.km)\n# oba predlagata dve skupini\n\n# - - - - - - - - -\n\nset.seed(42)\n\nk = 3\nskupine <- TURIZEM.EVROPA[,-1] %>%\n kmeans(centers = k) %>%\n getElement(\"cluster\") %>%\n as.ordered()\n# print(skupine)\n\ntabela.skupine.k.means <- TURIZEM.EVROPA %>% \n mutate(Skupine = as.numeric(skupine))\n\n# uvozim zemljevid, ki ga bom potrebovala tudi v nadaljevanju. Prikazala se bo samo Evropa\nzemljevid <-\n uvozi.zemljevid(\n \"http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/ne_50m_admin_0_countries.zip\",\n \"ne_50m_admin_0_countries\",\n mapa = \"zemljevidi\",\n pot.zemljevida = \"\",\n encoding = \"UTF-8\"\n ) %>%\n fortify() %>% \n filter(CONTINENT %in% c(\"Europe\"),\n long < 50 & long > -25 & lat > 35 & lat < 85)\n\nnames(tabela.skupine.k.means)[1] <- \"ADMIN\"\n\nzemljevid.kmeans <- ggplot() +\n aes(x = long, y = lat, group = group, fill = factor(Skupine)) +\n geom_polygon(data = tabela.skupine.k.means %>% \n right_join(zemljevid, by = \"ADMIN\"),\n color = \"grey38\", size = 0.2) +\n xlab(\"\") +\n ylab(\"\") +\n ggtitle(\"Razvrstitev Evropskih držav v tri skupine z metodo k-tih voditeljev\") +\n coord_fixed(ratio = 1) +\n guides(fill=guide_legend(title=\"Skupina\")) +\n theme_bw() +\n theme(plot.caption.position = \"plot\") +\n scale_fill_brewer(palette = \"YlGnBu\", \n na.translate = F,\n na.value=\"white\")\n\nzemljevid.kmeans\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\nset.seed(42)\n\nk = 4\nskupine4 <- TURIZEM.EVROPA[,-1] %>%\n kmeans(centers = k) %>%\n getElement(\"cluster\") %>%\n as.ordered()\n# print(skupine)\n\ntabela.skupine.k.means4 <- TURIZEM.EVROPA %>% \n mutate(Skupine = as.numeric(skupine4))\n\n# uvozim zemljevid, ki ga bom potrebovala tudi v nadaljevanju. Prikazala se bo samo Evropa\nzemljevid <-\n uvozi.zemljevid(\n \"http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/ne_50m_admin_0_countries.zip\",\n \"ne_50m_admin_0_countries\",\n mapa = \"zemljevidi\",\n pot.zemljevida = \"\",\n encoding = \"UTF-8\"\n ) %>%\n fortify() %>% \n filter(CONTINENT %in% c(\"Europe\"),\n long < 50 & long > -25 & lat > 35 & lat < 85)\n\nnames(tabela.skupine.k.means4)[1] <- \"ADMIN\"\n\nzemljevid.kmeans4 <- ggplot() +\n aes(x = long, y = lat, group = group, fill = factor(Skupine)) +\n geom_polygon(data = tabela.skupine.k.means4 %>% \n right_join(zemljevid, by = \"ADMIN\"),\n color = \"grey38\", size = 0.2) +\n xlab(\"\") +\n ylab(\"\") +\n ggtitle(\"Razvrstitev Evropskih držav v štiri skupine z metodo k-tih voditeljev\") +\n coord_fixed(ratio = 1) +\n guides(fill=guide_legend(title=\"Skupina\")) +\n theme_bw() +\n theme(plot.caption.position = \"plot\") +\n scale_fill_brewer(palette = \"YlGnBu\", \n na.translate = F,\n na.value=\"white\")\n\nzemljevid.kmeans4\n\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\n# 2) HIERARHIČNO RAZVRŠČANJE\n\nX <- TURIZEM.EVROPA[,-1] %>% as.matrix() %>% scale()\ndrzave <- TURIZEM.EVROPA[, 1] %>% unlist()\nrazdalje <- TURIZEM.EVROPA[, -1] %>% dist()\ndendrogram <- dist(X) %>% hclust(method = \"ward.D\")\n# plot(dendrogram,\n# labels = TURIZEM.EVROPA$Drzava,\n# ylab = \"višina\",\n# main = NULL)\n\n# izračun kolen:\nr = hc.kolena(dendrogram)\ndiagram.kolena(r)\n\n# za kolena predlaga: 2, 3, 4, 6\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\n# izberem število skupin:\nk = 4\n\nskupine <- TURIZEM.EVROPA[, 2] %>%\n dist() %>%\n hclust(method = \"ward.D\") %>%\n cutree(k = k) %>%\n as.ordered()\n\ntabela.skupine.hierarh <- TURIZEM.EVROPA %>%\n mutate(Skupine = as.numeric(skupine))\n\nnames(tabela.skupine.hierarh)[1] <- \"ADMIN\"\n\nzemljevid.hierarh <- ggplot() +\n aes(x = long, y = lat, group = group, fill = factor(Skupine)) +\n geom_polygon(data = tabela.skupine.hierarh %>% \n right_join(zemljevid, by = \"ADMIN\"),\n color = \"grey38\", size = 0.2) +\n xlab(\"\") +\n ylab(\"\") +\n ggtitle(\"Razvrstitev Evropskih držav v štiri skupine po Wardovi metodi\") +\n coord_fixed(ratio = 1) +\n guides(fill=guide_legend(title=\"Skupina\")) +\n theme_bw() +\n theme(plot.caption.position = \"plot\") +\n scale_fill_brewer(palette = \"YlGnBu\", \n na.translate = F,\n na.value=\"white\")\n\nzemljevid.hierarh\n\n# v skupini s Slovenijo:\n# tabela.skupine.hierarh[tabela.skupine.hierarh$Skupine == 1, 1]\n\n\n# ==============================================================================\n# NAPOVEDNI MODEL\n# ==============================================================================\n\n# priprava tabele:\nslovenija.turizem <- read_csv(\"podatki/turizem_svetovno.csv\",\n skip = 4,\n locale = locale(encoding = \"Windows-1250\"),\n col_names=TRUE, \n col_types = cols(.default = col_guess()))\nslovenija.turizem <- slovenija.turizem[slovenija.turizem$`Country Name` == \"Slovenia\",-c(2:39)]\nslovenija.turizem <- slovenija.turizem %>%\n pivot_longer(\n cols = colnames(slovenija.turizem)[-1],\n names_to = \"Leto\",\n values_to = \"Stevilo\"\n ) %>%\n na.omit() %>%\n dplyr::select(Leto, \"Stevilo\")\nslovenija.turizem$Stevilo <- as.integer(slovenija.turizem$Stevilo)\n\n# tabela in dva stolpca, prvi so leta, drugi pa število turističnih obiskov\n\nzamakni <- function(x, n){c(rep(NA, n), x)[1:length(x)]}\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# IZBIRA napovednega modela (z napako): med linearno regrasijo in naključnimi gozdovi\n# pogledala bom napake obeh modelov\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# 1) glede na pretekla 4 leta:\nnaredi.df.4 <- function(x){\n data.frame(pricak = x,\n \"Leto 2020\" = zamakni(x, 1),\n \"Leto 2019\" = zamakni(x, 2),\n \"Leto 2018\" = zamakni(x, 3),\n \"Leto 2017\" = zamakni(x, 4))\n}\n\ndf.4 <- drop_na(naredi.df.4(slovenija.turizem$Stevilo))\nucni.4 = pp.razbitje(nrow(df.4))\n\n# - naključni gozdovi:\nprecno.preverjanje(df.4, ucni.4, pricak ~ ., \"ng\", FALSE)\n\n# - linearna regrasija:\nprecno.preverjanje(df.4, ucni.4, pricak ~ ., \"lin.reg\", FALSE)\n\n# napaka z naključnimi gozdovi je manjša\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# 2) glede na pretekla 3 leta:\nnaredi.df.3 <- function(x){\n data.frame(pricak = x,\n \"Leto 2020\" = zamakni(x, 1),\n \"Leto 2019\" = zamakni(x, 2),\n \"Leto 2018\" = zamakni(x, 3))\n}\n\ndf.3 <- drop_na(naredi.df.3(slovenija.turizem$Stevilo))\nucni.3 = pp.razbitje(nrow(df.4))\n\n# - naključni gozdovi:\nprecno.preverjanje(df.3, ucni.3, pricak ~ ., \"ng\", FALSE)\n\n# - linearna regrasija:\nprecno.preverjanje(df.3, ucni.3, pricak ~ ., \"lin.reg\", FALSE)\n\n# napaka z naključnimi gozdovi je manjša\n\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# NAPOVEDOVANJE Z METODO NAKLJUČNIH GOZDOV\n\n# napovedovanje:\nzamakni <- function(x, n){c(rep(NA, n), x)[1:length(x)]}\n\n# napovedovanje glede na prejšnja 4 leta:\n\nnaredi.df.4 <- function(x){\n data.frame(pricak = x,\n \"Leto 2020\" = zamakni(x, 1),\n \"Leto 2019\" = zamakni(x, 2),\n \"Leto 2018\" = zamakni(x, 3),\n \"Leto 2017\" = zamakni(x, 4))\n}\n\ndf.4 <- naredi.df.4(slovenija.turizem$Stevilo)\nmodel = ranger(formula = pricak ~ ., data = df.4 %>% drop_na())\n\nn = nrow(df.4)\n\ndf.4.2 = df.4\nfor(i in 1:3){\n df.4.2 = naredi.df.4(c(df.4.2$pricak, NA))\n napoved = predict(model, data = df.4.2[n+i,])$predictions\n df.4.2[n+i, 1] = napoved\n}\n\n# napovedi za naslednja 3 leta:\nnapovedi = df.4.2[(n+1):(n+3),1]\n\n# s temi podaki bom dopolnila tabelo slovenija.turizem\nslovenija.turizem.z.napovednjo <- slovenija.turizem\nslovenija.turizem.z.napovednjo$Leto <- as.integer(slovenija.turizem.z.napovednjo$Leto)\nslovenija.turizem.z.napovednjo$Stevilo <- as.numeric(slovenija.turizem.z.napovednjo$Stevilo)\nzadnje_leto <- 2020\nfor (i in 1:3) {\n novo_leto <- as.integer(zadnje_leto + i)\n nov_podatek <- as.integer(napovedi[i])\n slovenija.turizem.z.napovednjo[nrow(slovenija.turizem.z.napovednjo) + 1, ] <-\n list(novo_leto, nov_podatek)\n}\n\nLeto <- 1995:2023\nnapovedovanje.graf <- ggplot(slovenija.turizem.z.napovednjo, \n aes(x = Leto, y = Stevilo)) +\n geom_line(color = \"black\") + \n slovenija.turizem.z.napovednjo %>%\n filter(Leto %in% c(2020:2023)) %>%\n geom_line(\n mapping = aes(x = Leto, y = Stevilo),\n color = \"red\"\n ) +\n labs(\n x = \"Leto\",\n y = \"Stevilo turističnih obiskov\",\n title = \"Stevilo turističnih obiskov Slovenija ob leta 1995 do 2020 z napovedjo \\nza leta 2021, 2022 in 2023 \"\n ) +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +\n scale_x_continuous(\"Leto\", labels = as.character(Leto), breaks = Leto)\n \nnapovedovanje.graf # ni vključen v poročilo\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# prečno preverjanje napovedovanja glede na pretekla 4 leta:\n\n# vrednosti NA motijo delovanje funckije\n\ndf.4 <- df.4 %>% drop_na()\n\nucni <- pp.razbitje(df.4, stratifikacija = df.4$pricak)\n\n# Pripravimo le napovedne spremenljivke, ki jih rabi funkcija Predictor$new\nX <- df.4[,-1]\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 model,\n data = X, y = df.4$pricak,\n predict.fun = pfun\n)\n\n# na koncu uporabimo funkcijo FeatureImp$new\nreg.moci = FeatureImp$new(reg.pred, loss = \"mse\")\n\nreg.moci.4.plot <- plot(reg.moci) + theme_bw()\nreg.moci.4.plot\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# napovedovanje glede na prejšnje 3 leta:\n\nnaredi.df.3 <- function(x){\n data.frame(pricak = x,\n \"Leto 2020\" = zamakni(x, 1),\n \"Leto 2019\" = zamakni(x, 2),\n \"Leto 2018\" = zamakni(x, 3))\n}\n\ndf.3 <- naredi.df.3(slovenija.turizem$Stevilo)\nmodel.3 = ranger(formula = pricak ~ ., data = df.3 %>% drop_na())\n\nn = nrow(df.3)\n\ndf.3.2 = df.3\nfor(i in 1:3){\n df.3.2 = naredi.df.3(c(df.3.2$pricak, NA))\n napoved = predict(model.3, data = df.3.2[n+i,])$predictions\n df.3.2[n+i, 1] = napoved\n}\n\n# napovedi za naslednja 3 leta:\nnapovedi.3 = df.3.2[(n+1):(n+3),1]\n\n# s temi podaki bom dopolnila tabelo slovenija.turizem\nslovenija.turizem.z.napovednjo.3 <- slovenija.turizem\nslovenija.turizem.z.napovednjo.3$Leto <- as.integer(slovenija.turizem.z.napovednjo.3$Leto)\nslovenija.turizem.z.napovednjo.3$Stevilo <- as.integer(slovenija.turizem.z.napovednjo.3$Stevilo)\nzadnje_leto <- 2020\nfor (i in 1:3) {\n novo_leto <- as.integer(zadnje_leto + i)\n nov_podatek <- as.integer(napovedi.3[i])\n slovenija.turizem.z.napovednjo.3[nrow(slovenija.turizem.z.napovednjo.3) + 1, ] <-\n list(novo_leto, nov_podatek)\n}\n\nLeto <- 1995:2023\nnapovedovanje.graf.3 <- ggplot(slovenija.turizem.z.napovednjo.3, \n aes(x = Leto, y = Stevilo)) +\n geom_line(color = \"black\") + \n slovenija.turizem.z.napovednjo.3 %>%\n filter(Leto %in% c(2020:2023)) %>%\n geom_line(\n mapping = aes(x = Leto, y = Stevilo),\n color = \"red\"\n ) +\n labs(\n x = \"Leto\",\n y = \"Stevilo turističnih obiskov\",\n title = \"Stevilo turističnih obiskov Slovenija ob leta 1995 do 2020 z napovedjo \\nza leta 2021, 2022 in 2023 \"\n ) +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +\n scale_x_continuous(\"Leto\", labels = as.character(Leto), breaks = Leto)\n\nnapovedovanje.graf.3 # ni vključen v poročilo\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n# prečno preverjanje napovedovanja glede na pretekla 3 leta:\n\n# vrednosti NA motijo delovanje funckije\ndf.3 <- df.3 %>% na.omit()\n\nucni.3 <- pp.razbitje(df.3, stratifikacija = df.3$pricak)\n\n# Pripravimo le napovedne spremenljivke, ki jih rabi funkcija Predictor$new\nX.3 <- df.3[,-1]\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.3 = Predictor$new(\n model.3,\n data = X.3, y = df.3$pricak,\n predict.fun = pfun\n)\n\n# na koncu uporabimo funkcijo FeatureImp$new\nreg.moci.3 = FeatureImp$new(reg.pred.3, loss = \"mse\")\n\nreg.moci.3.plot <- plot(reg.moci.3) + theme_bw()\nreg.moci.3.plot\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\n# skupni graf napovedovanja (za poročilo):\nLeto <- 1995:2023\nnapovedovanje.graf.skupaj <- ggplot(slovenija.turizem.z.napovednjo, \n aes(x = Leto, y = Stevilo)) +\n geom_line(color = \"black\") + \n slovenija.turizem.z.napovednjo %>%\n filter(Leto %in% c(2020:2023)) %>%\n geom_line(\n mapping = aes(x = Leto, y = Stevilo),\n color = \"goldenrod1\",\n size = 0.75\n ) +\n slovenija.turizem.z.napovednjo.3 %>%\n filter(Leto %in% c(2020:2023)) %>%\n geom_line(\n mapping = aes(x = Leto, y = Stevilo),\n color = \"red\",\n linetype = \"dotdash\",\n size = 0.75\n ) +\n labs(\n x = \"Leto\",\n y = \"Število turističnih obiskov\",\n title = \"Število turističnih obiskov Slovenija ob leta 1995 do 2020 z napovedjo \\nza leta 2021, 2022 in 2023 \"\n ) +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +\n scale_x_continuous(\"Leto\", labels = as.character(Leto), breaks = Leto) +\n annotate(geom=\"text\", x=2022, y=3000000, label=\"napoved glede \\nna pretekla \\n4 leta\",\n color=\"goldenrod1\", size = 2.5) +\n annotate(geom=\"text\", x=2022.5, y=1900000, label=\"napoved \\nglede na \\npretekla \\n3 leta\",\n color=\"red\", size = 2.5)\n\nnapovedovanje.graf.skupaj\n\n\n\n# ==============================================================================\n# LINEARNA REGRESIJA\n# ==============================================================================\n\nlinearna.regrasija.graf <- \n ggplot(slovenci.prenocitve, aes(x = Leto, y = Stevilo)) +\n geom_point(stat='identity', position='identity', aes(colour=Stevilo),size=1.3) +\n scale_colour_gradient(low='yellow', high='#de2d26') +\n labs(\n x = \"Leto\",\n y = \"Število prenočitev\",\n ) +\n ggtitle(\"Število prenočitev Slovencev v Sloveniji od leta 2010 do leta 2022\") +\n theme_bw() +\n theme(axis.text.x = element_text(angle = 90, vjust = 0.5),\n legend.position=\"none\") +\n geom_smooth(method = \"lm\", formula = y ~ x, colour=\"black\", size=0.7)\n\nlinearna.regrasija.graf\n\n", "meta": {"hexsha": "c17f6bb8fa551f05214d003a1e27c33be1cb9d40", "size": 22517, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "karolina-sa/APPR-2021-22", "max_stars_repo_head_hexsha": "122755a1cd493804aa42f1d375d5069f591b12d4", "max_stars_repo_licenses": ["MIT"], "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": "karolina-sa/APPR-2021-22", "max_issues_repo_head_hexsha": "122755a1cd493804aa42f1d375d5069f591b12d4", "max_issues_repo_licenses": ["MIT"], "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": "karolina-sa/APPR-2021-22", "max_forks_repo_head_hexsha": "122755a1cd493804aa42f1d375d5069f591b12d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-13T18:06:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T18:06:58.000Z", "avg_line_length": 29.5886990802, "max_line_length": 120, "alphanum_fraction": 0.5795621086, "num_tokens": 8395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.43471186627965547}}
{"text": "# Copyright (c) 2020, Zolisa Bleki\n# SPDX-License-Identifier: BSD-3-Clause\n\nmatrix_type <- c(\"regular\", \"diagonal\", \"identity\")\n\n\nvalidate_output <- function(res) {\n\n if (res$info < 0) {\n stop(\"Possible illegal value in one of the inputs\")\n }\n else if (res$info > 0) {\n stop(\n \"Either the leading minor of the \", res$info, \"'th order is not\n positive definite (meaning the covariance matrix is also not\n positive definite), or factorization of one of the inputs\n returned a factor with a zero in the \", res$info, \"'th diagonal.\"\n )\n }\n else {\n res$out\n }\n}\n\n\nhptrunc_mvn <- function(rng, mean, cov, g, r, diag, out) {\n\n stopifnot(\n is.vector(mean),\n is.matrix(cov),\n is.matrix(g),\n is.vector(r),\n is.logical(diag),\n length(mean) == nrow(cov),\n nrow(cov) == ncol(cov),\n nrow(cov) == ncol(g)\n )\n\n if (is.null(out))\n out <- rep(0, length(mean))\n\n res <- .Call(C_hpmvn, rng, mean, cov, g, r, diag, out, PACKAGE = \"htnorm\")\n\n validate_output(res)\n}\n\n\nstrprec_mvn <- function(rng, mean, a, phi, omega, str_mean, a_id, o_id, out) {\n\n stopifnot(\n is.vector(mean),\n is.matrix(a),\n is.matrix(phi),\n is.matrix(omega),\n is.logical(str_mean),\n nrow(omega) == ncol(omega),\n ncol(omega) == nrow(phi),\n length(mean) == nrow(a),\n nrow(a) == ncol(a)\n )\n\n if (!is.element(a_id, matrix_type) || !is.element(o_id, matrix_type))\n stop(\"`a_type` and `o_type` need to be one of {'regular', 'diagonal', 'identity'}\")\n\n a_id <- switch(\n a_id,\n \"regular\" = as.integer(0),\n \"diagonal\" = as.integer(1),\n \"identity\" = as.integer(2)\n )\n o_id <- switch(\n o_id,\n \"regular\" = as.integer(0),\n \"diagonal\" = as.integer(1),\n \"identity\" = as.integer(2)\n )\n\n if (is.null(out))\n out <- rep(0, length(mean))\n\n res <- .Call(\n C_spmvn,\n rng,\n mean,\n a,\n phi,\n omega,\n str_mean,\n a_id,\n o_id,\n out,\n PACKAGE = \"htnorm\"\n )\n\n validate_output(res)\n}\n\n\n#' Sample from a multivariate normal truncated on a hyperplane or a multivariate\n#' normal with a structured precision. `HTNGenerator` returns an object that\n#' can be used to sample from such a distribution.\n#'\n#' @param seed A random seed. It must be a positive integer. If not specified \n#' then it defaults to NULL, which means a random seed is used.\n#' @param gen The type of random number generator to use internally. It must\n#' either \"xrs128p\" (Xoroshiro128plus) or \"pcg64\" (PCG64). If not specified\n#' then this parameter defaults to \"xrs128p\".\n#' @return A generator object that can be used to sample from the supported\n#' distributions.\n#' @references Cong, Yulai; Chen, Bo; Zhou, Mingyuan. Fast Simulation of \n#' Hyperplane-Truncated Multivariate Normal Distributions. Bayesian Anal. \n#' 12 (2017), no. 4, 1017--1037. doi:10.1214/17-BA1052.\n#' https://projecteuclid.org/euclid.ba/1488337478\n#'\n#' @examples\n#' mean <- rnorm(1000)\n#' cov <- matrix(rnorm(1000 * 1000), ncol=1000)\n#' cov <- cov %*% t(cov)\n#' G <- matrix(rep(1, 1000), ncol=1000)\n#' r <- c(0)\n#' rng <- HTNGenerator(seed=12345, gen=\"pcg64\")\n#' samples <- rng$hyperplane_truncated_mvnorm(mean, cov, G, r)\n#' # verify if sampled values sum to zero\n#' sum(samples)\n#'\n#' out <- rep(0, 1000)\n#' eig <- eigen(cov)\n#' phi <- eig$vectors\n#' omega <- diag(eig$values)\n#' a <- diag(runif(length(mean)))\n#' rng$structured_precision_mvnorm(mean, a, phi, omega, a_type = \"diagonal\", out = out)\nHTNGenerator <- function(seed = NULL, gen = \"xrs128p\") {\n\n if (is.numeric(seed)) {\n if (seed < 0)\n stop(\"`seed` cannot be negative.\")\n seed <- as.integer(seed)\n if (!is.finite(seed))\n stop(\"`seed` cannot be converted to an integer\")\n }\n else if (!is.null(seed)) {\n stop(\"`seed` cannot be a non-numeric value\")\n }\n\n gen <- switch(gen, \"xrs128p\" = as.integer(0), \"pcg64\" = as.integer(1))\n if (is.null(gen))\n stop(\"`gen` needs to one of {'xrs128p', 'pcg64'}\")\n\n res <- list(\"rng\" = .Call(C_get_rng, seed, gen, PACKAGE = \"htnorm\"))\n class(res) <- \"HTNGenerator\"\n\n res$hyperplane_truncated_mvnorm <- function(\n mean, cov, g, r, diag = FALSE, out = NULL\n ) {\n if (is.null(out)) {\n hptrunc_mvn(res$rng, mean, cov, g, r, diag, out)\n }\n else {\n invisible(hptrunc_mvn(res$rng, mean, cov, g, r, diag, out))\n }\n }\n\n res$structured_precision_mvnorm <- function(\n mean, a, phi, omega, str_mean = FALSE, a_type = \"regular\", o_type = \"regular\", out= NULL\n ) {\n if (is.null(out)) {\n strprec_mvn(\n res$rng, mean, a, phi, omega, str_mean, a_type, o_type, out\n )\n }\n else {\n invisible(\n strprec_mvn(\n res$rng, mean, a, phi, omega, str_mean, a_type, o_type, out\n )\n )\n }\n }\n\n res\n}\n", "meta": {"hexsha": "558fa2dc79b6fcad23199f9cec964f25071f3f85", "size": 5142, "ext": "r", "lang": "R", "max_stars_repo_path": "R/htnorm.r", "max_stars_repo_name": "zoj613/htnorm", "max_stars_repo_head_hexsha": "da31350449c437bbffe2d30664c1d7a5f23e554c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2020-12-06T22:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T06:10:16.000Z", "max_issues_repo_path": "R/htnorm.r", "max_issues_repo_name": "zoj613/htnorm", "max_issues_repo_head_hexsha": "da31350449c437bbffe2d30664c1d7a5f23e554c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2021-07-20T18:43:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T07:48:11.000Z", "max_forks_repo_path": "R/htnorm.r", "max_forks_repo_name": "zoj613/htnorm", "max_forks_repo_head_hexsha": "da31350449c437bbffe2d30664c1d7a5f23e554c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-02-01T16:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T20:29:13.000Z", "avg_line_length": 28.2527472527, "max_line_length": 96, "alphanum_fraction": 0.5641773629, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43307687354066865}}
{"text": "########################################################\n# The MIT License (MIT)\n#\n# Copyright (c) 2014 Florian D. Schneider & Sonia Kéfi\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n########################################################\n\n\n### grazing model: Schneider and Kéfi (2015, in review)\n\ngrazing <- list()\nclass(grazing) <- \"ca_model\"\ngrazing$name <- \"Spatial Grazing Model\"\ngrazing$ref <- \"Schneider and Kéfi 2015, in review\"\ngrazing$states <- c(\"+\", \"0\", \"-\")\ngrazing$cols <- grayscale(3)\ngrazing$parms <- list(\n del = 0.9, # local seed dispersal\n b = 0.2, # environmental quality\n c_ = 0.2, # global competition\n m0 = 0.05, # intrinsic mortality\n g = 0.2, # grazing pressure\n r = 0.01, # regeneration rate of degraded cells\n f = 0.9, # local facilitation\n d = 0.2, # intrinsic degradation rate \n protect = 0.9 # associational resistance against grazing\n) \ngrazing$update <- function(x_old, parms_temp, delta = 0.2, subs = 10, timestep = NA) {\n \n x_new <- x_old\n \n for(s in 1:subs) {\n \n \n parms_temp$rho_plus <- sum(x_old$cells == \"+\")/(x_old$dim[1]*x_old$dim[2]) # get initial vegetation cover\n parms_temp$Q_plus <- count(x_old, \"+\")/4 # count local density of occupied fields for each cell:\n \n # 2 - drawing random numbers\n rnum <- runif(x_old$dim[1]*x_old$dim[2]) # one random number between 0 and 1 for each cell\n \n # 3 - setting transition probabilities\n \n if(parms_temp$rho_plus > 0) {\n recolonisation <- with(parms_temp, (del*rho_plus+(1-del)*Q_plus)*(b-c_*rho_plus)*1/subs)\n \n death <- with(parms_temp, (m0+g*(1-protect))*1/subs)\n death[death > 1] <- 1 \n } else {\n recolonisation <- 0\n death <- 1\n }\n \n regeneration <- with(parms_temp, (r + f*Q_plus)*1/subs)\n \n degradation <- with(parms_temp, (d*1/subs))\n \n # check for sum of probabilities to be inferior 1 and superior 0\n if(any(c(recolonisation+degradation, death, regeneration) > 1 )) warning(paste(\"a set probability is exceeding 1 in time step\", timestep, \"! decrease number of substeps!!!\")) \n if(any(recolonisation < 0)) warning(paste(\"recolonisation falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n if(any(degradation < 0)) warning(paste(\"degradation falls below 0 in time step\",timestep, \"! balance parameters!!!\"))\n if(any( death < 0)) warning(paste(\"death falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n if(any(regeneration < 0)) warning(paste(\"regeneration falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n \n # 4 - apply transition probabilities \n \n x_new$cells[which(x_old$cells == \"0\" & rnum <= recolonisation)] <- \"+\"\n x_new$cells[which(x_old$cells == \"+\" & rnum <= death)] <- \"0\"\n x_new$cells[which(x_old$cells == \"0\" & rnum > recolonisation & rnum <= recolonisation+degradation)] <- \"-\" \n x_new$cells[which(x_old$cells == \"-\" & rnum <= regeneration)] <- \"0\"\n \n # 5- store x_new as next x_old\n \n x_old <- x_new\n \n }\n \n ## end of single update call\n return(x_new)\n}\n\n\n", "meta": {"hexsha": "b0ea3aab324019f4c2af87de93db1ee28b8253d4", "size": 4095, "ext": "r", "lang": "R", "max_stars_repo_path": "R/grazing.r", "max_stars_repo_name": "skefi/SpatialStress", "max_stars_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-06-12T14:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-04T21:16:40.000Z", "max_issues_repo_path": "R/grazing.r", "max_issues_repo_name": "skefi/SpatialStress", "max_issues_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-12T08:03:31.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-25T08:35:31.000Z", "max_forks_repo_path": "R/grazing.r", "max_forks_repo_name": "skefi/SpatialStress", "max_forks_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-30T01:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T01:18:03.000Z", "avg_line_length": 40.95, "max_line_length": 180, "alphanum_fraction": 0.6561660562, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43247080693229945}}
{"text": "## --------------------\n## --------------------\n## --------------------\n## This file contains functions for Adaptive Penalized Tensor Decomposition.\n## Most function are only suitable for three dimension tensor. For higher-order tensor, codes should be modified adaptively.\n## --------------------\n## --------------------\n## --------------------\n\n\n\n\n## --------------------\n## Generate tensor given d u v w.\n## d @list \n## u @matrix\n## v @matrix\n## w @matrix\n## --------------------\ngenerate_tensor <- function(d, u, v, w) {\n if (length(d) == 1) {\n u <- t(matrix(as.numeric(u)))\n v <- t(matrix(as.numeric(v)))\n w <- t(matrix(as.numeric(w)))\n make_list <- list(\"mat\" = t(u), \"mat2\" = t(v), \"mat3\" = t(w))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), make_list, ms = c(1, 2, 3))\n return(d * aux)\n } else {\n temp <- NULL\n for (k0 in 1:length(d)) {\n make_list <- list(\"mat\" = as.matrix(u[k0, ]), \"mat2\" = as.matrix(v[k0, ]), \"mat3\" = as.matrix(w[k0, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), make_list, ms = c(1, 2, 3))\n if (is.null(temp)) {\n temp <- as.tensor(array(0, dim(aux)))\n }\n temp <- temp + d[k0] * aux\n }\n return(temp)\n }\n}\n\n## --------------------\n## Generate arbitrary penalty matrix.\n## --------------------\ncreate_D <- function(x, ord = 2, gamma = 1) {\n D <- list()\n if (is.null(nrow(x))) {\n m <- 1\n n <- length(x)\n } else {\n m <- nrow(x)\n n <- ncol(x)\n }\n for (i in 1:m) {\n D[[i]] <- diag(1 / abs(as.numeric(diff(diag(n), differences = ord) %*% as.matrix(x[i, ])))^gamma) %*% diff(diag(n), differences = ord)\n }\n return(D)\n}\n\n\n## --------------------\n## Generate sequences on log scale.\n## --------------------\nlseq <- function(from, to, length, decreasing = FALSE) {\n stopifnot(from > 0)\n out <- 10^(seq(log10(from), log10(to), length.out = length))\n out <- out[order(out, decreasing = decreasing)]\n return(out)\n}\n\n\n## --------------------\n## Calculate the mse if forecasting method is GAM, which is used in cross-validation function to select the best tuning parameters.\n## --------------------\ncal_pmse_gam_adj <- function(k, year, bs = \"tp\", return_pred = FALSE) {\n u <- tempresult[[k]]$u\n v <- tempresult[[k]]$v\n w <- tempresult[[k]]$w\n w_pred <- matrix(NA, nrow = num_components, ncol = year)\n\n for (k0 in 1:num_components) {\n model1 <- gam(y ~ s(x, bs = bs), data = data.frame(y = w[k0, ], x = seq(1, length(w[1, ]))))\n w_pred[k0, ] <- predict(model1, newdata = data.frame(x = seq((length(w[k0, ]) + 1), (length(w[k0, ]) + year))))\n }\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + tempresult[[k]]$d[k0] * aux1\n }\n # convert it back\n aux <- aux * sd1[[k]] + as.tensor(array(mean1[[k]], dim(aux)))\n\n e <- sqrt(fnorm(aux - V1[[k]])^2)\n if (!return_pred) {\n return(e)\n }\n if (return_pred) {\n return(list(e = e, w_pred = w_pred))\n }\n}\n\n\n## --------------------\n## Calculate the mse if forecasting method is ARIMA, which is used in cross-validation function to select the best tuning parameters.\n## --------------------\ncal_pmse_arima_adj <- function(k, year, return_pred = FALSE) {\n u <- tempresult[[k]]$u\n v <- tempresult[[k]]$v\n w <- tempresult[[k]]$w\n w_pred <- matrix(NA, nrow = num_components, ncol = year)\n\n for (k0 in 1:num_components) {\n w_pred1 <- rwf(as.matrix(w)[k0, ], h = year, drift = TRUE)\n w_pred[k0, ] <- as.data.frame(w_pred1)[, 1]\n }\n\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + tempresult[[k]]$d[k0] * aux1\n }\n\n #### convert back\n aux <- aux * sd1[[k]] + as.tensor(array(mean1[[k]], dim(aux)))\n\n e <- sqrt(fnorm(aux - V1[[k]])^2)\n if (!return_pred) {\n return(e)\n }\n if (return_pred) {\n return(list(e = e, w_pred = w_pred))\n }\n}\n\n## --------------------\n## Calculate the mse if forecasting method is Linear extrapolation, which is used in cross-validation function to select the best tuning parameters.\n## --------------------\ncal_pmse_linearextra_adj <- function(k, year, return_pred = FALSE) {\n u <- tempresult[[k]]$u\n v <- tempresult[[k]]$v\n w <- tempresult[[k]]$w\n w_pred <- matrix(NA, nrow = num_components, ncol = year)\n\n for (k0 in 1:num_components) {\n w_pred[k0, ] <- approxExtrap(x = seq(1, length(w[1, ])), y = w[k0, ], xout = seq(length(w[k0, ]) + 1, by = 1, length = year))$y\n }\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + tempresult[[k]]$d[k0] * aux1\n }\n\n #### convert back\n aux <- aux * sd1[[k]] + as.tensor(array(mean1[[k]], dim(aux)))\n\n e <- sqrt(fnorm(aux - V1[[k]])^2)\n if (!return_pred) {\n return(e)\n }\n if (return_pred) {\n return(list(e = e, w_pred = w_pred))\n }\n}\n\n\n## --------------------\n## Penalized Tensor Decomposition(trend-filtering) for single factor.\n## --------------------\nPTD_tf <- function(tnsr, c1, c2, c3, Niter = 1000, tol = 1e-5, ku, kv, kw, u_init = NULL, v_init = NULL, w_init = NULL) {\n # tuning parameters can be 0\n # trendfiltering\n # penalty matrix D is defined by default\n if (is.null(u_init)) {\n temp <- gen_startvals(1, tnsr = tnsr)\n u_init <- temp$u\n v_init <- temp$v\n w_init <- temp$w\n }\n counter <- 0\n diff <- 10\n cw_u <- u_init\n cw_v <- v_init\n cw_w <- w_init\n u <- t(matrix(as.numeric(u_init)))\n v <- t(matrix(as.numeric(v_init)))\n w <- t(matrix(as.numeric(w_init)))\n\n while (counter < Niter & diff > tol) {\n\n # update w\n lizt <- list(\"mat2\" = u, \"mat3\" = v)\n w <- ttl(tnsr, lizt, ms = c(1, 2))\n if (c3 != 0) {\n w <- glmgen::trendfilter(as.vector(w@data), k = kw, family = \"gaussian\", method = \"admm\", lambda = c3)\n w <- predict(w, lambda = c3)\n w <- t(as.matrix(w))\n w <- w / norm(w, \"F\")\n } else {\n w <- t(as.matrix(w@data))\n w <- w / norm(w, \"F\")\n }\n\n # update u\n lizt <- list(\"mat2\" = v, \"mat3\" = w)\n u <- ttl(tnsr, lizt, ms = c(2, 3))\n if (c1 != 0) {\n u <- glmgen::trendfilter(as.vector(u@data), k = ku, family = \"gaussian\", method = \"admm\", lambda = c1)\n u <- predict(u, lambda = c1)\n u <- t(as.matrix(u))\n u <- u / norm(u, \"F\")\n } else {\n u <- t(as.matrix(u@data))\n u <- u / norm(u, \"F\")\n }\n\n # update v\n lizt <- list(\"mat2\" = u, \"mat3\" = w)\n v <- ttl(tnsr, lizt, ms = c(1, 3))\n if (c2 != 0) {\n v <- glmgen::trendfilter(as.vector(v@data), k = kv, family = \"gaussian\", method = \"admm\", lambda = c2)\n v <- predict(v, lambda = c2)\n v <- t(as.matrix(v))\n v <- v / norm(v, \"F\")\n } else {\n v <- t(as.matrix(v@data))\n v <- v / norm(v, \"F\")\n }\n\n diff <- mean(c(as.numeric(abs(cw_u - u)), as.numeric(abs(cw_v - v)), as.numeric(abs(cw_w - w))))\n cw_u <- u\n cw_v <- v\n cw_w <- w\n counter <- counter + 1\n }\n\n\n lizt <- list(\"mat1\" = u, \"mat2\" = v, \"mat3\" = w)\n d <- ttl(tnsr, lizt, ms = c(1, 2, 3))\n\n\n return(list(u = u, v = v, w = w, d = as.numeric(d@data)))\n}\n\n\n## --------------------\n## Penalized Tensor Decomposition(trend-filtering) for multiple factors.\n## --------------------\nmultiple_tf_simple <- function(tnsr, num_components, d_hat = NULL, u_init = NULL, v_init = NULL, w_init = NULL, c1 = NULL, c2 = NULL, c3 = NULL, Niter = 1500, tol = 1e-05, ku, kv, kw, trace = TRUE) {\n ## specific tuning parameters\n if (is.null(u_init)) {\n temp <- gen_startvals(num_components, tnsr = tnsr)\n u_init <- temp$u\n v_init <- temp$v\n w_init <- temp$w\n }\n if (is.null(c1)) {\n c1 <- rep(0, num_components)\n }\n if (is.null(c2)) {\n c2 <- rep(0, num_components)\n }\n if (is.null(c3)) {\n c3 <- rep(0, num_components)\n }\n\n if (identical(d_hat, rep(0, num_components)) | is.null(d_hat)) {\n for (j in 1:num_components) {\n d_hat[j] <- product(tnsr, c(1, 2, 3), u_init[j, ], v_init[j, ], w_init[j, ])\n }\n }\n\n Y <- as.tensor(array(0, dim(tnsr)))\n\n for (j in 1:num_components) {\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n Y <- Y + d_hat[j] * aux\n } ## closing for j\n\n ################## 333\n counter <- 0\n diff <- 10\n cw_u <- u_init\n cw_v <- v_init\n cw_w <- w_init\n ######\n\n while (diff > tol & counter < Niter) {\n for (j in 1:num_components)\n {\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n Y <- Y - d_hat[j] * aux\n ##############################################\n\n\n Z <- tnsr - Y\n\n # if(iter==1)\n #\n temp <- PTD_tf(Z, c1[j], c2[j], c3[j], Niter = Niter, tol = tol, ku = ku, kv = kv, kw = kw, u_init = u_init[j, , drop = FALSE], v_init = v_init[j, , drop = FALSE], w_init = w_init[j, , drop = FALSE])\n\n ##############################################\n u_init[j, ] <- as.vector(temp$u)\n v_init[j, ] <- as.vector(temp$v)\n w_init[j, ] <- as.vector(temp$w)\n d_hat[j] <- product(Z, c(1, 2, 3), u_init[j, ], v_init[j, ], w_init[j, ])\n\n\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n\n Y <- Y + d_hat[j] * aux\n }\n\n diff <- mean(c(as.numeric(abs(u_init - cw_u)), as.numeric(abs(v_init - cw_v)), as.numeric(abs(w_init - cw_w))))\n if (trace) {\n message(\"Iteration: \", counter, \"\\t Difference: \", round(diff, 5))\n }\n\n cw_u <- u_init\n cw_v <- v_init\n cw_w <- w_init\n counter <- counter + 1\n }\n\n out <- list(u = u_init, v = v_init, w = w_init, d = d_hat, diff = diff)\n return(out)\n}\n\n## --------------------\n## Adaptive Penalized Tensor Decomposition for single factor.\n## --------------------\nPTD_D <- function(tnsr, c1, c2, c3, Niter = 1500, tol = 1e-5, Du, Dv, Dw, u_init, v_init, w_init) {\n # tuning parameters can be 0\n # Arbitrary penalty matrix\n # init must be unpenalized results\n counter <- 0\n diff <- 10\n\n u <- cw_u <- u_init\n v <- cw_v <- v_init\n w <- cw_w <- w_init\n\n while (counter < Niter & diff > tol) {\n\n # update w\n lizt <- list(\"mat2\" = u, \"mat3\" = v)\n w <- ttl(tnsr, lizt, ms = c(1, 2))\n if (c3 != 0) {\n w <- genlasso(as.vector(w@data), D = Dw)\n w <- predict(w, lambda = c3)$fit\n w <- t(as.matrix(w))\n w <- w / norm(w, \"F\")\n } else {\n lizt <- list(\"mat2\" = u, \"mat3\" = v)\n w <- ttl(tnsr, lizt, ms = c(1, 2))\n w <- t(as.matrix(w@data))\n w <- w / norm(w, \"F\")\n }\n\n # update u\n lizt <- list(\"mat2\" = v, \"mat3\" = w)\n u <- ttl(tnsr, lizt, ms = c(2, 3))\n if (c1 != 0) {\n u <- genlasso(as.vector(u@data), D = Du)\n u <- predict(u, lambda = c3)$fit\n u <- t(as.matrix(u))\n u <- u / norm(u, \"F\")\n } else {\n lizt <- list(\"mat2\" = v, \"mat3\" = w)\n u <- ttl(tnsr, lizt, ms = c(2, 3))\n u <- t(as.matrix(u@data))\n u <- u / norm(u, \"F\")\n }\n\n # update v\n lizt <- list(\"mat2\" = u, \"mat3\" = w)\n v <- ttl(tnsr, lizt, ms = c(1, 3))\n if (c2 != 0) {\n v <- genlasso(as.vector(v@data), D = Dv)\n v <- predict(v, lambda = c2)$fit\n v <- t(as.matrix(v))\n v <- v / norm(v, \"F\")\n } else {\n lizt <- list(\"mat2\" = u, \"mat3\" = w)\n v <- ttl(tnsr, lizt, ms = c(1, 3))\n v <- t(as.matrix(v@data))\n v <- v / norm(v, \"F\")\n }\n\n diff <- mean(c(as.numeric(abs(cw_u - u)), as.numeric(abs(cw_v - v)), as.numeric(abs(cw_w - w))))\n cw_u <- u\n cw_v <- v\n cw_w <- w\n counter <- counter + 1\n }\n\n\n lizt <- list(\"mat1\" = u, \"mat2\" = v, \"mat3\" = w)\n d <- ttl(tnsr, lizt, ms = c(1, 2, 3))\n\n\n return(list(u = u, v = v, w = w, d = as.numeric(d@data)))\n}\n\n\n## --------------------\n## Adaptive Penalized Tensor Decomposition for single factor.\n## --------------------\nmultiple_D_adaptive <- function(tnsr, num_components, d_hat = NULL, u_init, v_init, w_init, c1 = NULL, c2 = NULL, c3 = NULL, Niter = 15, tol = 1e-05, Du, Dv, Dw, trace = TRUE)\n # tuning parameters for each dimension are the same\n # inital values cant be null\n # Dv and Dw should be a list of matrices\n# to save computation time temp , only run 15 times\n{\n ## specific tuning parameters\n if (!is.list(Du)) {\n Du <- list(Du)\n }\n if (!is.list(Dv)) {\n Dv <- list(Dv)\n }\n if (!is.list(Dw)) {\n Dw <- list(Dw)\n }\n if (length(Dv) != num_components & length(Dw) != num_components & length(Du) != num_components) {\n return(print(\"wrong penalty matrix\"))\n }\n if (is.null(d_hat)) {\n for (j in 1:num_components) {\n d_hat[j] <- product(tnsr, c(1, 2, 3), u_init[j, ], v_init[j, ], w_init[j, ])\n }\n }\n Y <- as.tensor(array(0, dim(tnsr)))\n\n for (j in 1:num_components) {\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n Y <- Y + d_hat[j] * aux\n } ## closing for j\n\n ################## 333\n cw_u <- u_init\n cw_v <- v_init\n cw_w <- w_init\n counter <- 0\n diff <- 10\n\n ######\n\n while (diff > tol & counter < Niter) {\n for (j in 1:num_components)\n {\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n Y <- Y - d_hat[j] * aux\n ##############################################\n\n\n Z <- tnsr - Y\n\n # if(iter==1)\n #\n temp <- PTD_D(Z, c1[j], c2[j], c3[j],\n Niter = Niter, tol = tol, Du = Du[[j]], Dv = Dv[[j]], Dw = Dw[[j]],\n u_init = u_init[j, , drop = FALSE], v_init = v_init[j, , drop = FALSE], w = w_init[j, , drop = FALSE]\n )\n\n ##############################################\n u_init[j, ] <- as.vector(temp$u)\n v_init[j, ] <- as.vector(temp$v)\n w_init[j, ] <- as.vector(temp$w)\n d_hat[j] <- temp$d\n\n\n lizt <- list(\"mat\" = as.matrix(u_init[j, ]), \"mat2\" = as.matrix(v_init[j, ]), \"mat3\" = as.matrix(w_init[j, ]))\n aux <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n\n\n Y <- Y + d_hat[j] * aux\n }\n\n diff <- mean(c(as.numeric(abs(u_init - cw_u)), as.numeric(abs(v_init - cw_v)), as.numeric(abs(w_init - cw_w))))\n if (trace) {\n message(\"Iteration: \", counter, \"\\t Difference: \", round(diff, 5))\n }\n\n cw_u <- u_init\n cw_v <- v_init\n cw_w <- w_init\n counter <- counter + 1\n }\n\n out <- list(u = u_init, v = v_init, w = w_init, d = d_hat)\n return(out)\n}\n\n\n## --------------------\n## Prediction based on ATPD result.\n## Forecasting method is GAM.\n## --------------------\ngam_predict <- function(result, year, bs = \"tp\") {\n u <- result$u\n v <- result$v\n w <- result$w\n d <- result$d\n w_pred <- matrix(NA, nrow = nrow(u), ncol = year)\n num_components <- length(d)\n for (k0 in 1:num_components) {\n model1 <- mgcv::gam(y ~ s(x, bs = bs), data = data.frame(y = w[k0, ], x = seq(1, length(w[1, ]))))\n w_pred[k0, ] <- predict(model1, newdata = data.frame(x = seq((length(w[k0, ]) + 1), (length(w[k0, ]) + year))))\n }\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + d[k0] * aux1\n }\n return(aux)\n}\n\n\n## --------------------\n## Prediction based on ATPD result.\n## Forecasting method is ARIMA.\n## --------------------\narima_predict <- function(result, year) {\n u <- result$u\n v <- result$v\n w <- result$w\n d <- result$d\n w_pred <- matrix(NA, nrow = nrow(u), ncol = year)\n num_components <- length(d)\n\n for (k0 in 1:num_components) {\n w_pred1 <- rwf(as.matrix(w)[k0, ], h = year, drift = TRUE)\n w_pred[k0, ] <- as.data.frame(w_pred1)[, 1]\n }\n\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + d[k0] * aux1\n }\n\n\n return(aux)\n}\n\n## --------------------\n## Prediction based on ATPD result.\n## Forecasting method is Linear Extrapolation.\n## --------------------\nlinextrap_predict <- function(result, year) {\n u <- result$u\n v <- result$v\n w <- result$w\n d <- result$d\n w_pred <- matrix(NA, nrow = nrow(u), ncol = year)\n num_components <- length(d)\n\n for (k0 in 1:num_components) {\n w_pred[k0, ] <- approxExtrap(x = seq(1, length(w[1, ])), y = w[k0, ], xout = seq(length(w[k0, ]) + 1, by = 1, length = year))$y\n }\n\n aux <- 0\n for (k0 in 1:num_components) {\n lizt <- list(\"mat1\" = t(t(u[k0, ])), \"mat2\" = t(t(v[k0, ])), \"mat3\" = t(t(w_pred[k0, ])))\n # ggg<-as.array(g[k0])\n # dim(ggg)<-c(1,1,1)\n aux1 <- ttl(as.tensor(array(1, c(1, 1, 1))), lizt, ms = c(1, 2, 3))\n aux <- aux + d[k0] * aux1\n }\n\n return(aux)\n}", "meta": {"hexsha": "4b7235656e9c945c8e3fc0c06c0fd20faae2a3d0", "size": 19215, "ext": "r", "lang": "R", "max_stars_repo_path": "APTD.r", "max_stars_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_stars_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "APTD.r", "max_issues_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_issues_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APTD.r", "max_forks_repo_name": "lullabies777/Adaptive-Penalized-Tensor-Decomposition", "max_forks_repo_head_hexsha": "118c2cb77c17614103be5ea5e56d72c3e8bfd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9186046512, "max_line_length": 211, "alphanum_fraction": 0.4640645329, "num_tokens": 6249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43214596758517027}}
{"text": "library(tidyverse)\nlibrary(BBmisc)\nlibrary(caTools)\n\nsimulate_viral_load <- function(ids, ct_alpha, ct_beta, ct_max, ct_min, e_alpha, e_beta, e_max, e_min, rct, gamma_shape=2, gamma_scale=2)\n{\n\tn <- nrow(ids)\n\tct <- rbeta(n, ct_alpha, ct_beta) * (ct_max - ct_min) + ct_min\n\te <- rbeta(n, e_alpha, e_beta) * (e_max-e_min) + e_min\n\tvl <- rct / (1+e)^ct\n\tids$id_E <- e\n\tids$id_ct <- ct\n\tids$id_vl <- vl\n\n\tvlshape <- tibble(\n\t\tt=seq(0,21,length.out=2101),\n\t\tvlshape=dgamma(t, shape=gamma_shape, scale=gamma_scale)\n\t)\n\tvlshape$vlshape <- vlshape$vlshape / max(vlshape$vlshape)\n\tlen <- nrow(subset(vlshape, t <= 1))\n\ti1 <- sample(1:(which(vlshape$t == 18)[1]), n, replace=TRUE)\n\ti2 <- i1 + len * 3\n\tmax_vl <- rct / (1 + e)^ct\n\n\tvl1 <- max_vl * vlshape$vlshape[i1]\n\tvl2 <- max_vl * vlshape$vlshape[i2]\n\n\tct1 <- log(rct/vl1) / log(1+e)\n\tct2 <- log(rct/vl2) / log(1+e)\n\n\tids$id_ct1 <- ct1\n\tids$id_ct2 <- ct2\n\tids$id_vl1 <- vl1\n\tids$id_vl2 <- vl2\n\treturn(ids)\n}\n\nsimulate_infection <- function(ids, prevalence, spread, containment)\n{\n\t# Sample initial individuals\n\tdat <- tibble(\n\t\tid = sample(ids$id, nrow(ids) * prevalence, replace=FALSE),\n\t\tspread = rpois(length(id), spread)\n\t\t) %>%\n\t\tinner_join(ids, ., by=\"id\")\n\t\n\tnew_infecteds <- lapply(1:nrow(dat), function(i)\n\t{\n\t\tloc <- sample(1:3, dat$spread[i], replace=TRUE, prob=containment)\n\t\treturn(c(\n\t\t\tsample(subset(ids, circle == dat$circle[i])$id, min(dat$count[i], sum(loc==1)), replace=FALSE),\n\t\t\tsample(subset(ids, location == dat$location[i])$id, sum(loc==2), replace=FALSE),\n\t\t\tsample(ids$id, sum(loc==3), replace=FALSE)\n\t\t))\n\t}) %>% unlist %>% unique\n\tids$infected <- ids$id %in% c(dat$id, new_infecteds)\n\tids <- ids %>%\n\t\tgroup_by(location) %>%\n\t\tmutate(location_outbreak = sum(infected >= 2)) %>%\n\t\tungroup()\n\t\n\t# remove vl for anyone not infected\n\tids$id_vl[ids$infected==FALSE] <- 0\n\tids$id_vl1[ids$infected==FALSE] <- 0\n\tids$id_vl2[ids$infected==FALSE] <- 0\n\t# ids$cvl[ids$infected==FALSE] <- 0\n\t\n\treturn(ids)\n}\n\nallocate_pools <- function(ids, pool_size, random=FALSE)\n{\n\trandom_pools <- function(x, pool_size)\n\t{\n\t\tnpool <- ceiling(length(x) / pool_size)\n\t\trep(1:npool, each=pool_size)[1:length(x)] %>% sample\n\t}\n\n\tif(random)\n\t{\n\t\tids$assay_pool <- random_pools(1:nrow(ids), pool_size)\n\t\tids <- ids %>%\n\t\t\tgroup_by(assay_pool) %>%\n\t\t\tmutate(poolsize=n()) %>%\n\t\t\tungroup()\n\t\treturn(ids)\n\t}\n\n\t# First break up large circles \n\ttemp1 <- subset(ids, count > pool_size) %>%\n\t\tgroup_by(circle) %>%\n\t\tmutate(\n\t\t\tpoolbreak = cut(1:n(), ceiling(n()/pool_size)) %>% as.numeric(),\n\t\t\tpool = paste0(circle, \"-\", poolbreak)\n\t\t) %>% ungroup()\n\ttemp2 <- subset(ids, count <= pool_size) %>%\n\t\tmutate(\n\t\t\tpoolbreak = 1,\n\t\t\tpool = paste0(circle, \"-\", poolbreak)\n\t\t)\n\tids <- bind_rows(temp1, temp2)\n\tdat <- ids %>%\n\t\tgroup_by(pool) %>%\n\t\tsummarise(poolsize=n(), .groups=\"drop\")\n\t# Note that `cut` tries to make even cuts. this might not be optimal\n\t# Use bin packing algorithm to assign to pools\n\tdat$assay_pool <- BBmisc::binPack(dat$poolsize, pool_size)\n\tids <- inner_join(ids, dat, by=\"pool\") %>%\n\t\tgroup_by(assay_pool) %>%\n\t\tmutate(poolsize = n()) %>% ungroup()\n\treturn(ids)\n}\n\nassay_sensitivity_quad <- function(dilution, baseline, beta)\n{\n\tvec <- -beta * (dilution-1)^2 + baseline\n\tvec[vec < 0] <- 0\n\tvec\n}\n\nassay_sensitivity_decay <- function(dilution, baseline, beta)\n{\n\texp(-(dilution-1) * beta) * baseline\n}\n\nassay_sensitivity_sigmoid <- function(dilution)\n{\n\t1 / (1 + exp(-dilution/4+4)) * -1 + 1\n}\n\nassay_ppv <- function(sensitivity, prevalence, specificity)\n{\n\tsensitivity * prevalence / (sensitivity * prevalence + (1-specificity) * (1-prevalence))\n}\n\nlfd_prob <- function(x, asym, xmid, scal)\n{\n\tasym / (1 + exp((xmid - x)/scal))\n}\n\nsimulate_testing <- function(ids, ctthresh, rct, pcr_fp, lfd_Asym, lfd_xmid, lfd_scal, lfd_fp)\n{\n\tids$id_detected <- ids$id_ct < ctthresh\n\tids$id_detected1 <- ids$id_ct1 < ctthresh\n\tids$id_detected2 <- ids$id_ct2 < ctthresh\n\tids$id_detected[!ids$infected] <- rbinom(sum(!ids$infected), 1, pcr_fp)\n\tids$id_detected1[!ids$infected] <- rbinom(sum(!ids$infected), 1, pcr_fp)\n\tids$id_detected2[!ids$infected] <- rbinom(sum(!ids$infected), 1, pcr_fp)\n\tids$id_lfd_detected <- rbinom(nrow(ids), 1, lfd_prob(ids$id_ct, lfd_Asym, lfd_xmid, lfd_scal))\n\tids$id_lfd_detected1 <- rbinom(nrow(ids), 1, lfd_prob(ids$id_ct1, lfd_Asym, lfd_xmid, lfd_scal))\n\tids$id_lfd_detected2 <- rbinom(nrow(ids), 1, lfd_prob(ids$id_ct2, lfd_Asym, lfd_xmid, lfd_scal))\n\tids$id_lfd_detected[!ids$infected] <- rbinom(sum(!ids$infected), 1, lfd_fp)\n\tids$id_lfd_detected1[!ids$infected] <- rbinom(sum(!ids$infected), 1, lfd_fp)\n\tids$id_lfd_detected2[!ids$infected] <- rbinom(sum(!ids$infected), 1, lfd_fp)\n\n\tdetected_pools <- ids %>% group_by(assay_pool) %>%\n\t\tsummarise(\n\t\t\tpool_ninfected = sum(infected), \n\t\t\tpool_infected = pool_ninfected > 0,\n\t\t\tpool_E = min(id_E),\n\t\t\tpool_vl = sum(id_vl),\n\t\t\tpool_vl1 = sum(id_vl1),\n\t\t\tpool_vl2 = sum(id_vl2),\n\t\t\tpool_Rn = pool_vl / n() * (1 + pool_E)^ctthresh,\n\t\t\tpool_Rn1 = pool_vl1 / n() * (1 + pool_E)^ctthresh,\n\t\t\tpool_Rn2 = pool_vl2 / n() * (1 + pool_E)^ctthresh,\n\t\t\tpool_ct = log(rct / pool_vl) / log((1 + pool_E)),\n\t\t\tpool_ct1 = log(rct / pool_vl1) / log((1 + pool_E)),\n\t\t\tpool_ct2 = log(rct / pool_vl2) / log((1 + pool_E)),\n\t\t\tpool_detected = pool_ct < ctthresh,\n\t\t\tpool_detected1 = pool_ct1 < ctthresh,\n\t\t\tpool_detected2 = pool_ct2 < ctthresh,\n\t\t\t.groups=\"drop\"\n\t\t)\n\tdetected_pools$pool_detected[!detected_pools$pool_infected] <- rbinom(sum(!detected_pools$pool_infected), 1, pcr_fp)\n\tdetected_pools$pool_detected1[!detected_pools$pool_infected] <- rbinom(sum(!detected_pools$pool_infected), 1, pcr_fp)\n\tdetected_pools$pool_detected2[!detected_pools$pool_infected] <- rbinom(sum(!detected_pools$pool_infected), 1, pcr_fp)\n\tids <- inner_join(ids, detected_pools, by=\"assay_pool\")\n\tids <- ids %>% group_by(circle) %>%\n\t\tmutate(\n\t\t\tcircle_detected = any(pool_detected),\n\t\t\tcircle_detected1 = any(pool_detected1),\n\t\t\tcircle_detected2 = any(pool_detected2)\n\t\t)\n\tids <- ids %>% \n\t\tgroup_by(location) %>%\n\t\tmutate(\n\t\t\tind_outbreak_detected = sum(id_detected) > 2,\n\t\t\tpool_outbreak_detected = sum(pool_detected) > 2,\n\t\t\tpoolfollowup_outbreak_detected = sum(pool_detected * id_detected) > 2\n\t\t) %>% ungroup()\n\treturn(ids)\n}\n\n\nsummarise_simulations <- function(ids, cost_samplingkit, cost_test, cost_lfd)\n{\n\tnpool <- length(unique(ids$assay_pool))\n\tnfollowup <- sum(ids$pool_detected)\n\n\tob <- group_by(ids, location) %>%\n\t\tsummarise(\n\t\t\toutbreak = any(location_outbreak), \n\t\t\tind_outbreak_detected = any(ind_outbreak_detected),\n\t\t\tpool_outbreak_detected = any(pool_outbreak_detected),\n\t\t\tpoolfollowup_outbreak_detected = any(poolfollowup_outbreak_detected),\n\t\t\t.groups=\"drop\"\n\t\t)\n\n\ttibble(\n\t\tnstudents = nrow(ids),\n\t\ttrue_prevalence = sum(ids$infected) / nrow(ids),\n\t\tprevalence.ind_tests = sum(ids$id_detected) / nstudents,\n\t\tprevalence.ind_tests1 = sum(ids$id_detected1) / nstudents,\n\t\tprevalence.ind_tests2 = sum(ids$id_detected2) / nstudents,\n\t\tprevalence.pool_tests = sum(ids$pool_detected) / nstudents,\n\t\tprevalence.pool_tests1 = sum(ids$pool_detected1) / nstudents,\n\t\tprevalence.pool_tests2 = sum(ids$pool_detected2) / nstudents,\n\t\tprevalence.poolfollowup_tests = sum(ids$pool_detected & ids$id_detected) / nstudents,\n\t\tprevalence.poolfollowup_tests1 = sum(ids$pool_detected1 & ids$id_detected1) / nstudents,\n\t\tprevalence.poolfollowup_tests2 = sum(ids$pool_detected2 & ids$id_detected2) / nstudents,\n\n\t\tcost.ind_tests = nrow(ids) * cost_samplingkit + nrow(ids) * cost_test,\n\t\tcost.pool_tests = nrow(ids) * cost_samplingkit + npool * cost_test,\n\t\tcost.poolfollowup_tests = cost.pool_tests + nfollowup * cost_test,\n\t\tcost.lfd = nrow(ids) * cost_lfd,\n\n\t\treagentuse.ind_tests = nrow(ids),\n\t\treagentuse.pool_tests = npool,\n\t\treagentuse.poolfollowup_tests = npool + nfollowup,\n\n\t\tsensitivity.ind_tests = sum(ids$infected & ids$id_detected) / sum(ids$infected),\n\t\tsensitivity.ind_tests1 = sum(ids$infected & ids$id_detected1) / sum(ids$infected),\n\t\tsensitivity.ind_tests2 = sum(ids$infected & ids$id_detected2) / sum(ids$infected),\n\t\tsensitivity.pool_tests = sum(ids$pool_detected * ids$infected) / sum(ids$infected),\n\t\tsensitivity.pool_tests1 = sum(ids$pool_detected1 * ids$infected) / sum(ids$infected),\n\t\tsensitivity.pool_tests2 = sum(ids$pool_detected2 * ids$infected) / sum(ids$infected),\n\t\tsensitivity.poolfollowup_tests = sum(ids$pool_detected * ids$infected * ids$id_detected) / sum(ids$infected),\n\t\tsensitivity.poolfollowup_tests1 = sum(ids$pool_detected1 * ids$infected * ids$id_detected1) / sum(ids$infected),\n\t\tsensitivity.poolfollowup_tests2 = sum(ids$pool_detected2 * ids$infected * ids$id_detected2) / sum(ids$infected),\n\t\tsensitivity.lfd = sum(ids$infected & ids$id_lfd_detected) / sum(ids$infected),\n\t\tsensitivity.lfd1 = sum(ids$infected & ids$id_lfd_detected1) / sum(ids$infected),\n\t\tsensitivity.lfd2 = sum(ids$infected & ids$id_lfd_detected2) / sum(ids$infected),\n\t\tsensitivity.lfd_ever = sum(ids$infected & (ids$id_lfd_detected1 | ids$id_lfd_detected2)) / sum(ids$infected),\n\n\t\tspecificity.ind_tests = sum(!ids$id_detected & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.ind_tests1 = sum(!ids$id_detected1 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.ind_tests2 = sum(!ids$id_detected2 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.pool_tests = sum(!ids$pool_detected & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.pool_tests1 = sum(!ids$pool_detected1 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.pool_tests2 = sum(!ids$pool_detected2 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.poolfollowup_tests = 1 - sum(ids$pool_detected & ids$id_detected & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.poolfollowup_tests1 = 1 - sum(ids$pool_detected1 & ids$id_detected1 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.poolfollowup_tests2 = 1 - sum(ids$pool_detected2 & ids$id_detected2 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.lfd = sum(!ids$id_lfd_detected & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.lfd1 = sum(!ids$id_lfd_detected1 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.lfd2 = sum(!ids$id_lfd_detected2 & !ids$infected) / sum(!ids$infected),\n\t\tspecificity.lfd_ever = sum(!(ids$id_lfd_detected1 | ids$id_lfd_detected2) & !ids$infected) / sum(!ids$infected),\n\n\t\tsensitivity.outbreak.ind_tests = sum(ob$ind_outbreak_detected) / sum(ob$outbreak),\n\t\tsensitivity.outbreak.pool_outbreak_detected = sum(ob$pool_outbreak_detected) / sum(ob$outbreak),\n\t\tsensitivity.outbreak.poolfollowup_outbreak_detected = sum(ob$poolfollowup_outbreak_detected) / sum(ob$outbreak),\n\n\t\tspecificity.outbreak.ind_tests = sum(!ob$ind_outbreak_detected & !ob$outbreak) / sum(!ob$outbreak),\n\t\tspecificity.outbreak.pool_outbreak_detected = sum(!ob$pool_outbreak_detected & !ob$outbreak) / sum(!ob$outbreak),\n\t\tspecificity.outbreak.poolfollowup_outbreak_detected = sum(!ob$poolfollowup_outbreak_detected & !ob$outbreak) / sum(!ob$outbreak)\n\t)\n}\n\n\nrun_simulation <- function(ids, param, containment)\n{\n\tstopifnot(nrow(param) == 1)\n\tstopifnot(param$containment %in% names(containment))\n\tcont <- containment[[param$containment]]\n\n\tids <- simulate_viral_load(ids, param$ct_alpha, param$ct_beta, param$ct_max, param$ct_min, param$e_alpha, param$e_beta, param$e_max, param$e_min, param$rct)\n\tids <- simulate_infection(ids, param$prevalence, spread=param$spread, cont)\n\tids <- allocate_pools(ids, param$pool_size, random=param$random_pooling)\n\tids <- simulate_testing(ids, param$ctthresh, param$rct, param$pcr_fp, param$lfd_Asym, param$lfd_xmid, param$lfd_scal, param$lfd_fp)\n\tres <- summarise_simulations(ids, param$cost_samplingkit, param$cost_test, param$lfd_cost)\n\treturn(bind_cols(param, res))\n}\n", "meta": {"hexsha": "0d6c9cfa39b6359ff81aef215c98bfb2a13f1eaf", "size": 11653, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/functions.r", "max_stars_repo_name": "explodecomputer/covid-uob-pooling", "max_stars_repo_head_hexsha": "79ad1440f2dd8ebf4b3d0385366a6019ca821495", "max_stars_repo_licenses": ["MIT"], "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/functions.r", "max_issues_repo_name": "explodecomputer/covid-uob-pooling", "max_issues_repo_head_hexsha": "79ad1440f2dd8ebf4b3d0385366a6019ca821495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-10-03T07:30:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-02T23:53:14.000Z", "max_forks_repo_path": "scripts/functions.r", "max_forks_repo_name": "explodecomputer/covid-uob-pooling", "max_forks_repo_head_hexsha": "79ad1440f2dd8ebf4b3d0385366a6019ca821495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-10-12T19:25:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-12T19:25:19.000Z", "avg_line_length": 41.0316901408, "max_line_length": 157, "alphanum_fraction": 0.7137217884, "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4311205210148032}}
{"text": "## by peter m crosta: pmcrosta at gmail\n### Functions for oaxac decompositions in R given sample means and regression coefficients as inputs.\n\nsetwd('~/CSVs')\n# read in means file\nmeansraw <- read.csv('means.csv', header=T, stringsAsFactors=F)\n\n# read in coeffs file\ncoeffsraw <- read.csv('coeffs.csv', header=T, stringsAsFactors=F)\n\nmeansraw <- meansraw[meansraw$X!=\"\",]\ncoeffsraw <- coeffsraw[coeffsraw$X!=\"\",]\n\ncoefnames <- coeffsraw$X\nsumnames <- meansraw$X\n\ncoefcol <- colnames(coeffsraw)\nsumcol <- colnames(meansraw)\n\noaxaca <- function(mods) UseMethod(\"oaxaca\")\n\noaxaca.default <- function(mods) {\n ## Input is a charactervector. Likely taken from a list\n mod1 <- mods[1]\n mod2 <- mods[2]\n ### get model coefficients\n m1 <- as.numeric(coeffsraw[, which(mod1==coefcol)])\n m2 <- as.numeric(coeffsraw[, which(mod2==coefcol)])\n\n names(m1)<-coefnames\n names(m2)<-coefnames\n\n m1 <- na.omit(m1)\n m2 <- na.omit(m2)\n\n ## get means\n s1 <- as.numeric(meansraw[, which(mod1==sumcol)])\n s2 <- as.numeric(meansraw[, which(mod2==sumcol)])\n\n names(s1)<-sumnames\n names(s2)<-sumnames\n\n s1 <- na.omit(s1)\n s2 <- na.omit(s2)\n\n if (substr(mod1,1,1)==\"r\") depvar <- \"readdep\" else if (substr(mod1,1,1)==\"m\") depvar <- \"mathdep\"\n\n k <- NROW(m1)\n k1 <- NROW(m2)\n if (k != k1) stop(\"models are not the same size\")\n\n\n W <- list(\"W = 1 (Oaxaca, 1973)\" = diag(1, k),\n \"W = 0 (Blinder, 1973)\" = diag(0, k),\n \"W = 0.5 (Reimers 1983)\" = diag(0.5, k))\n\n mnames <- names(m1)[-which(names(m1)==\"Constant\")]\n X1 <- c(s1[mnames], 1)\n X2 <- c(s2[mnames], 1)\n\n Q <- sapply(W, function(w) crossprod(X1 - X2, w %*% m1 + (diag(1, k) - w) %*% m2))\n U <- sapply(W, function(w) (crossprod(X1, diag(1, k) - w) + crossprod(X2, w)) %*% (m1 - m2))\n\n attcoeff <- c(\"_Iattdec_2\", \"_Iattdec_3\", \"_Iattdec_4\", \"_Iattdec_5\", \"_Iattdec_6\", \"_Iattdec_7\", \"_Iattdec_8\", \"_Iattdec_9\", \"_Iattdec_10\")\n \n #Qa <- sapply(W, function(w) crossprod(X1['lnattend'] - X2['lnattend'], w[1] %*% m1['lnattend'] + (diag(1, 1) - w[1]) %*% m2['lnattend']))\n #Ua <- sapply(W, function(w) (crossprod(X1['lnattend'], diag(1, 1) - w[1]) + crossprod(X2['lnattend'], w[1])) %*% (m1['lnattend'] - m2['lnattend']))\n\n Qa <- Ua <- 0\n for (ii in attcoeff) {\n Qa <- Qa + sapply(W, function(w) crossprod(X1[ii] - X2[ii], w[1] %*% m1[ii] + (diag(1, 1) - w[1]) %*% m2[ii]))\n Ua <- Ua + sapply(W, function(w) (crossprod(X1[ii], diag(1, 1) - w[1]) + crossprod(X2[ii], w[1])) %*% (m1[ii] - m2[ii]))\n }\n\n KK<-length(X1)\n Qdetail <- sapply(W, function(w) sapply(1:KK, function(jj) crossprod(X1[jj] - X2[jj], w[1] %*% m1[jj] + (diag(1, 1) - w[1]) %*% m2[jj])))\n Udetail <- sapply(W, function(w) sapply(1:KK, function(jj) (crossprod(X1[jj], diag(1, 1) - w[1]) + crossprod(X2[jj], w[1])) %*% (m1[jj] - m2[jj])))\n rownames(Qdetail) <- rownames(Udetail) <- c(mnames, \"Constant\")\n \n # Var-covar matrices\n setwd('~/outregs')\n VB1 <- as.matrix(read.table(paste(mod1, 'mat.txt', sep='')))\n VB2 <- as.matrix(read.table(paste(mod2, 'mat.txt', sep='')))\n\n VX1 <- as.matrix(read.table(paste(mod1, 'cor.txt', sep='')))\n VX2 <- as.matrix(read.table(paste(mod2, 'cor.txt', sep='')))\n\n dep1 <- s1[depvar]\n dep2 <- s2[depvar]\n Ddep <- dep1-dep2\n \n ans <- list(R = Ddep,\n VR = crossprod(X1, VB1) %*% X1 + crossprod(m1, VX1) %*% m1 + sum(diag(VX1 %*% VB1)) +\n crossprod(X2, VB2) %*% X2 + crossprod(m2, VX2) %*% m2 + sum(diag(VX2 %*% VB2)))\n\n \n VQ <- sapply(W, function(w)\n sum(diag((VX1 + VX2) %*% (w %*% tcrossprod(VB1, w) + (diag(1, k) - w) %*% tcrossprod(VB2, diag(1, k) - w)))) +\n crossprod(X1 - X2, w %*% tcrossprod(VB1, w) + (diag(1, k) - w) %*% tcrossprod(VB2, diag(1, k) - w)) %*% (X1 - X2) +\n crossprod(w %*% m1 + (diag(1, k) - w) %*% m2, VX1 + VX2) %*% (w %*% m1 + (diag(1, k) - w) %*% m2))\n VU <- sapply(W, function(w)\n sum(diag((crossprod(diag(1, k) - w, VX1) %*% (diag(1, k) - w) + crossprod(w, VX2) %*% w) %*% (VB1 + VB2))) +\n crossprod(crossprod(diag(1, k) - w, X1) + crossprod(w, X2), VB1 + VB2) %*% (crossprod(diag(1, k) - w, X1) + crossprod(w, X2))+\n crossprod(m1 - m2, crossprod(diag(1, k) - w, VX1) %*% (diag(1, k) - w) + crossprod(w, VX2) %*% w) %*% (m1 - m2))\n\n \n ans$Q <- Q\n ans$U <- U\n ans$VQ <- VQ\n ans$VU <- VU\n ans$W <- W\n ans$Qa <- Qa\n ans$Ua <- Ua\n ans$call <- match.call()\n ans$mod1 <- mod1\n ans$mod2 <- mod2\n ans$Qdetail <- Qdetail\n ans$Udetail <- Udetail\n class(ans) <- \"oaxaca\"\n ans\n \n}\n\n\nprint.oaxaca <- function(x) {\n se <- sqrt(x$VQ)\n zval <- x$Q / se\n decomp <- cbind(Explained = x$Q, StdErr = se, \"z-value\" = zval, \"Pr(>|z|)\" = 2*pnorm(-abs(zval)))\n cat(\"\\nBlinder-Oaxaca decomposition\\n\\nCall:\\n\")\n print(x$call)\n cat(x$mod1, ' ', x$mod2, \"\\n\")\n decomp <- matrix(nrow = 1, ncol = 4)\n decomp[1, c(1, 2)] <- c(x$R, sqrt(x$VR))\n decomp[1, 3] <- c(decomp[, 1] / decomp[, 2])\n decomp[1, 4] <- c(2 * pnorm(-abs(decomp[, 3])))\n colnames(decomp) <- c(\"Difference\", \"StdErr\", \"z-value\", \"Pr(>|z|)\")\n rownames(decomp) <- \"Mean\"\n cat(\"\\n\")\n print(zapsmall(decomp))\n cat(\"\\nLinear decomposition:\\n\")\n for (i in 1:3) {\n cat(paste(\"\\nWeight: \", names(x$W[i]), \"\\n\"))\n decomp <- cbind(Difference = c(x$Q[i], x$U[i]), StdErr = c(sqrt(x$VQ[i]), sqrt(x$VU[i])))\n decomp <- cbind(decomp, \"z-value\" = decomp[, 1] / decomp[, 2])\n decomp <- cbind(decomp, \"Pr(>|z|)\" = 2 * pnorm(-abs(decomp[, 3])))\n decomp <- cbind(decomp, c(x$Qa[i], x$Ua[i]))\n colnames(decomp) <- c(\"Difference\", \"StdErr\", \"z-value\", \"Pr(>|z|)\", \"attendance\")\n rownames(decomp) <- c(\"Explained\", \"Unexplained\")\n print(zapsmall(decomp))\n }\n cat(\"\\n\")\n}\n\nwrite.oaxaca <- function(x) {\n if (class(x) != \"oaxaca\") stop(\"Input needs to be of class oaxaca\")\n #cat(x$mod1, ' ', x$mod2, \"\\n\")\n decomp <- matrix(nrow = 3, ncol = 5)\n decomp[1, c(1, 2)] <- c(x$R, sqrt(x$VR))\n decomp[1, 3] <- c(decomp[1, 1] / decomp[1, 2])\n decomp[1, 4] <- c(2 * pnorm(-abs(decomp[1, 3])))\n colnames(decomp) <- c(\"Difference\", \"StdErr\", \"z-value\", \"Pr(>|z|)\", paste(x$mod1, x$mod2, sep=''))\n if (substr(x$mod1,1,1)==\"r\") depvar <- \"Reading\" else if (substr(x$mod1,1,1)==\"m\") depvar <- \"Math\"\n rownames(decomp) <- c(depvar, \"Explained\", \"Unexplained\")\n i<-3\n decomp[2,1] <- x$Q[i]\n decomp[3,1] <- x$U[i]\n decomp[2,2] <- sqrt(x$VQ[i])\n decomp[3,2] <- sqrt(x$VU[i])\n decomp[2,3] <- decomp[2, 1] / decomp[2, 2]\n decomp[3,3] <- decomp[3, 1] / decomp[3, 2]\n decomp[2,4] <- 2 * pnorm(-abs(decomp[2, 3]))\n decomp[3,4] <- 2 * pnorm(-abs(decomp[3, 3]))\n decomp[2,5] <- x$Qa[i]\n decomp[3,5] <- x$Ua[i]\n zapsmall(decomp) \n}\n\ndetail.oaxaca <- function(x, depth=6) {\n if (class(x) != \"oaxaca\") stop(\"Input needs to be of class oaxaca\")\n ##only deal with Cotton/Reimers\n Qdet <- sort(x$Qdetail[,3])\n Udet <- sort(x$Udetail[,3])\n Qh <- head(Qdet, depth)\n Qt <- tail(Qdet, depth)\n Uh <- head(Udet, depth)\n Ut <- tail(Udet, depth)\n Qsum <- cbind(Qh, names(Qt), Qt)\n Usum <- cbind(Uh, names(Ut), Ut)\n ret.list <- list(Qsum, Usum)\n}\n\n### Below is code specific to the analysis\n### which decompositions do we want to do?\n### coefcol[-1] lists the options:\n### math, reading\n### pooled, fixed effects\n### racedum1-5, econdum1-4\n### remember: race: amerindian, asian, black, hispanic, white\n### remember: econ: not poor, free lunch, reduced lunch, other dis \n\n## For pooled and FE models: white-black, white-hispanic, hispanic-black\n## notpoor-free, notpoor-reduced, notpoor-other\n\n## This becomes: 5-3, 5-4, 4-3; 1-2, 1-3, 1-4\ngrouprace <- list(\n c('mpa4racedum5C', 'mpa4racedum3C'),\n c('rpa4racedum5C', 'rpa4racedum3C'),\n c('mfa4racedum5C', 'mfa4racedum3C'),\n c('rfa4racedum5C', 'rfa4racedum3C'),\n\n c('mpa4racedum5C', 'mpa4racedum4C'),\n c('rpa4racedum5C', 'rpa4racedum4C'),\n c('mfa4racedum5C', 'mfa4racedum4C'),\n c('rfa4racedum5C', 'rfa4racedum4C'),\n\n c('mpa4racedum4C', 'mpa4racedum3C'),\n c('rpa4racedum4C', 'rpa4racedum3C'),\n c('mfa4racedum4C', 'mfa4racedum3C'),\n c('rfa4racedum4C', 'rfa4racedum3C'))\n\ngroupecon <- list(\n c('mpa4econdum1C', 'mpa4econdum2C'),\n c('rpa4econdum1C', 'rpa4econdum2C'),\n c('mfa4econdum1C', 'mfa4econdum2C'),\n c('rfa4econdum1C', 'rfa4econdum2C'),\n\n c('mpa4econdum1C', 'mpa4econdum3C'),\n c('rpa4econdum1C', 'rpa4econdum3C'),\n c('mfa4econdum1C', 'mfa4econdum3C'),\n c('rfa4econdum1C', 'rfa4econdum3C'),\n\n c('mpa4econdum1C', 'mpa4econdum4C'),\n c('rpa4econdum1C', 'rpa4econdum4C'),\n c('mfa4econdum1C', 'mfa4econdum4C'),\n c('rfa4econdum1C', 'rfa4econdum4C'))\n\noax.race<-lapply(grouprace, oaxaca)\noax.econ<-lapply(groupecon, oaxaca)\n \n## oaxaca print out function\nlapply(oax.race, write.oaxaca)\nlapply(oax.econ, write.oaxaca)\n\n## print out detailed decomposition\nrace.det <- lapply(oax.race, detail.oaxaca)\nnames(race.det) <- sapply(grouprace, function(x) paste(x, collapse=''))\nrace.det\n\necon.det <- lapply(oax.econ, detail.oaxaca)\nnames(econ.det) <- sapply(groupecon, function(x) paste(x, collapse=''))\necon.det\n", "meta": {"hexsha": "ee9e045649eb987de079b988d2f28686e0582dce", "size": 9135, "ext": "r", "lang": "R", "max_stars_repo_path": "oaxaca.r", "max_stars_repo_name": "pmcrosta/misc", "max_stars_repo_head_hexsha": "9adb55b2aa3bdcd1d16162ce4946124d51b305d2", "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": "oaxaca.r", "max_issues_repo_name": "pmcrosta/misc", "max_issues_repo_head_hexsha": "9adb55b2aa3bdcd1d16162ce4946124d51b305d2", "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": "oaxaca.r", "max_forks_repo_name": "pmcrosta/misc", "max_forks_repo_head_hexsha": "9adb55b2aa3bdcd1d16162ce4946124d51b305d2", "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.25, "max_line_length": 152, "alphanum_fraction": 0.5799671593, "num_tokens": 3737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4307920457968234}}
{"text": "# This tool presents a new method to identify the vent location of tephra fall deposits \n# based on thickness or maximum clast size measurements.\n# It is temporarily named \"svl\", which is short for Source Vent Locator.\n# This file includes the associated R functions and their notations.\n\n###\n# Since the presented method gives estimate on the vent location and prevailing wind \n# direction, it can be used to produce the input for our method to model the thickness\n# or maximum clast size distribution of \n# tephra fall deposits (Yang and Bursik, 2016; https://vhub.org/resources/3957).\n###\n# Author: Qingyuan Yang, Marcus Bursik, and E. Bruce Pitman.\n###\n# License: GPL. Use at your own risk. \n###\n# The work was supported by National Science Foundation Hazard SEES grant number 1521855 to\n# G. Valentine, M. Bursik, E.B. Pitman and A.K. Patra, and National Science Foundation\n# DMS grant number 1621853 to A.K. Patra, M. Bursik, and E.B. Pitman.\n###\n# We appreciate your comments, suggestions, and feedback. \n# Please feel free to contact us through vhub or email: qyang5@buffalo.edu \n# Notes:\n#\tThe functions below are the version of the method that is coupled with the semi-\t\n#\tempirical model proposed by Yang and Bursik (2016).\n\n###### Functions ######\n#################################Intermediate functions#################################\n#################### Function name: sp_par_cal ####################\n# Function to calculate downwind and cross wind distance of the input sample sites given known\n# source vent and wind direction.\n# The name \"sp_par_cal\" is short for \"spatial parameter calculation\".\n# Input:\n\t# obs: \n\t#\tn-by-3 matrix of x, y, z, indicating coordinates and measured thickness \n\t#\tor maximum clast size of each sample site. x and y should be in utm coordinates,\n\t#\tand z should be in millimeter with a minimum value of 1 mm.\n\t# sv: \n\t#\ta vector of two elements (utm coordinates) indicating the assumed vent location.\n\t# wind_dir\n\t# \ta numeric value of assumed wind direction (from north clockwise).\n# Output:\n\t# an n-by-7 matrix, \n\t# The 1st and 2nd columns: \n\t#\toriginal coordinates of sample sites;\n\t# The 3-5th columns:\n\t#\ttotal distance (dist), downwind (dd), and crosswind (cd) distance \n\t# \twith respect to the source vent (sv).\n\t# The 6th column:\n\t#\tdifference between total distance and downwind distance. \n\t# The 7th column:\n\t#\tthickness or grain size measurement at each sample site.\n\t###### Brief description ######\n\t# This function uses basic vector/matrix multiplication in R to prepare the data for\n\t# calculating and fitting the objective function, GIVEN ASSUMED FIXED source \n\t# vent location and wind direction.\nsp_par_cal <- function(obs, sv, wind_dir){\n\tsv = as.vector(sv)\n\tzr <- obs[,3]\n\txy <- as.matrix(obs[,c(1,2)])\n\tnr <- nrow(obs)\n\tsv_matrix <- matrix(ncol=2, nrow=nr)\n\tsv_matrix[,1] <- rep(sv[1], nr)\n\tsv_matrix[,2] <- rep(sv[2], nr)\n\tunit_vector <- as.matrix(c(sin(wind_dir*pi/180),cos(wind_dir*pi/180)))\n\trel_xy <- xy - sv_matrix\n\tdist <- (rel_xy[,1]^2 + rel_xy[,2]^2)^0.5\n\tdd <- (rel_xy) %*% (unit_vector)\n\tcd <- (dist^2 - dd^2)^0.5 \n\toutput <- matrix(nrow = nr, ncol=7)\n\toutput[,1:2] <- xy\n\toutput[,3:5] <- cbind(dist, dd, cd)\n\toutput[,6] <- dist - dd \n\toutput[,7] <- zr\n\treturn(output)\n}\n\n#################### Function name: fi ####################\n# Function to calculate the sum of squared residuals (calculated under log-scale) \n# GIVEN FIXED source vent location and wind direction.\t\n# The name \"fi\" is short for \"fitting\".\t\t\t\t\t\t\t\t\t\t\t\t\n# Input:\n\t# obs, sv, and wind_dir: \n\t#\tinputs for function \"sp_par_cal\".\n\t###### Output ######\n\t# ssr:\n\t#\ta numeric value which is the sum of squared residuals (ssr) from the fitting.\n\t# Note:\n\t#\tThe method uses the semi-empirical model of Yang and Bursik (2016).\n\t#\tNote the line with \"***\" on the right, which is used for the\n\t#\tsemi-empirical model proposed by Gonzalez-Mellado and De la Cruz-Reyna \n\t# \t(2010). It is not used here.\nfi <- function(obs, sv, wind_dir){\n\ttd <- as.data.frame(sp_par_cal(obs, sv, wind_dir))\t\t\n\t\t# Call the \"sp_par_cal\" function, and turn the output to data.frame. \t\n\tcolnames(td) <- c(\"x\",\"y\",\"dist\",\"dd\",\"cd\", \"dif\",\"zr\") \t\n\t\t# Name the columns.\n\ttd$z = log10(td$zr)\t\t\t\t\t\t\n\t\t# Transform the thickness into log-scale.\n\t## Fitting and calculate the ssr\n# fit.res <- lm(z~dif+log(dist),data=td)\t\t# *** Case 1: power-law model, not used here.\n fit.res <- lm(z~dist+dd,data=td)\t\t# Case 2: exponential model.\n \tssr <- sum(fit.res$residuals^2)\t\t\t# Calculate the ssr.\n\treturn(ssr)\n}\n\n#################### Function name: fi2 ####################\t\t\t\t\t\t\t\n# This function is basically identical to the function \"fi\". \n# The only difference is the output.\n# It is called when the vent position is found. \n# In addition to \"ssr\" in function \"fi\", it also returns the fitted coefficients \n# of the semi-empirical model and the associated r-square value.\n# With these values, we could have a better understanding on the predicted result.\n# Input\n\t# Identical to the inputs for function \"fi\"\n# Output\n\t# a vector with five elements including:\n\t# ssr: sum of squared residuals;\n\t# fit.res$coefficients: fitted coefficients (three values) of the semi-empirical model given\n\t# \tfixed vent location and wind direction;\n\t# summary(fit.res)$r.squared): r-squared value of the fitted result given\n\t#\tfixed vent location and wind direction (a numeric value).\nfi2 <- function(obs, sv, wind_dir){\t\n\ttd <- as.data.frame(sp_par_cal(obs, sv, wind_dir))\n\tcolnames(td) <- c(\"x\",\"y\",\"dist\",\"dd\",\"cd\", \"dif\",\"zr\")\n\ttd$z = log10(td$zr)\n\t## Fitting and measure the ssr\n# \tfit.res <- lm(z~dif+log(dist),data=td)\t\t# Case 1: power-law model, not used here.\n \tfit.res <- lm(z~dist+dd,data=td)\t\t# Case 2: exponential model.\n \tssr <- sum(fit.res$residuals^2)\n\treturn(c(ssr, fit.res$coefficients, summary(fit.res)$r.squared))\n}\n\n\n#################### Function name: cg ####################\n# Function to generate points (in the x-y plane) around a given point. This given point\n# is the proposed vent location from the previous iteration.\n#\n# The generated points are proposed such that the following function compares if \n# one of them or the proposed vent location from the previous iteration is closer to the true vent location. \n# The generated points are located in the four cardinal directions with respect to the proposed vent location\n# from the previous iteration. \n# The function name is short for \"Circle Generator\". \n# Input:\n\t# sv: \n\t#\tthe proposed vent location from previous iteration.\n\t#\tIts form is identical to \"sv\" in \"sp_par_cal\".\n\t# h:\n\t#\ta numeric value (search radius), indicating how far the four generated points are \n\t#\tfrom the previous proposed vent location. \n\n# Output\n\t#\ta 4-by-2 matrix containing the coordinates of the four generated points.\ncg <- function(sv, h){\t\t\t\t\t\n\toutput = cbind(c(rep(sv[,1],4)+sin(0:3*90*pi/180)*h),\n\t\t c(rep(sv[,2],4)+cos(0:3*90*pi/180)*h))\n\treturn(output)\n}\n\n#################### Function name: baf_pre ####################\n# This function prepares for the function \"baf\" below. It is designed \n# to avoid local minima in estimating the wind direction.\n# The name \"baf_pre\" is short for \"best-fitted angle finder_prepare\".\n# Input\n\t# sv and obs:\n\t#\tinputs required for function \"sp_par_cal\" \n\t# nlps:\n\t#\tA numeric value indicating the number of iterations\n\t# \tused to estimate the prevailing wind direction.\n\t# \tIt is not used here, but is necessary for the ongoing functions.\n# Output\n\t# A vector containing two or three values:\n\t# \tIf the first element is 1, \n\t# \t\tno local minima occur. The 2nd element is a rough estimate\n\t#\t\ton the prevailing wind direction.\n\t#\tIf the first element is 2,\n\t# \t\tlocal minima are present. The next two elements are rough estimates\n\t#\t\ton the global and local minima of wind direction. Both of them will be applied to ongoing\n\t#\t\tfunctions.\nbaf_pre <- function(sv, obs, nlps){\n\tpot_ang <- as.data.frame((1:36)*10)\t\t\t\t\t\t\t\t\t\n\tpot_ssr <- apply(pot_ang, MARGIN = 1, FUN=fi, obs = obs, sv = sv)\n\t#lowest_rank = which(rank(pot_ssr)==1)\t\t\t# Power-law ***\n\t#next_lowest_rank = which(rank(pot_ssr)==2)\t\t# Power-law ***\n\tlowest_rank = min(which(rank(pot_ssr)<2))\t\t\t\t#exponential\n\tnext_lowest_rank = min(which(rank(pot_ssr)<4 & rank(pot_ssr)>2))\t#exponential\n\tif(abs(lowest_rank - next_lowest_rank)==1 || abs(lowest_rank - next_lowest_rank)==35){\n\t\treturn(c(1, pot_ang[lowest_rank,1]))\n\t}else{\n\t\treturn(c(2, pot_ang[lowest_rank,1], pot_ang[next_lowest_rank, 1]))\n\t}\n}\n\n#################### Function name: baf_processor ####################\n# Function to estimate the prevailing wind direction with an assumed and\n# fixed vent location. It uses a standard one-dimensional gradient descent method.\n# The name \"baf_processor\" is short for \"best-angle finder_processor\".\n# Input\n\t# sv and obs: inputs for the function \"sp_par_cal\".\n\t# nlps: number of loops for the 1d gradient descent method.\n\t# \tIt is sufficient to set its value to 20.\n\t# proposed_winddir: the proposed wind direction from the function \"baf_pre\".\n\t# This function uses the output from function \"baf_pre\" as \n\t# the initial guess on wind direction.\n# Output\n\t# a 1-by-2 matrix containing: \n\t#\tthe predicted wind direction;\n\t#\tthe corresponding sum of squared residuals.\nbaf_processor <- function(sv, obs, nlps, proposed_winddir){\t\t\t\t\t\t\t\t\t\t\n\tfdm <- matrix(c(-1,0,1,-1,0,1), nrow=2)\t\t\t\t\t\n\th <- 5\t\t\t\t \n\twarns <- 0\t\t\t\t\t\n\tresm <- data.frame(matrix(ncol=2,nrow=2))\n\tgdnt <- c()\t\n\twind_dir = proposed_winddir\n\tres <- fi(obs, sv, wind_dir)\n\tresm[1,1] <- wind_dir\n\tresm[1,2] <- res[1]\n\twind_dir <- wind_dir + h\n\tres <- fi(obs, sv, wind_dir)\n\tresm[2,1] <- wind_dir\n\tresm[2,2] <- res[1]\n\tif(resm[1,2] >= resm[2,2]){\n\t\tlid <- 1\t\n\t}else{\n\t\tlid <- -1\n\t}\n\tr = 1\n\t# lid=1 -> going forward, wind_direction+ ;\n\t# lid=-1 -> going backward, wind_direction- ;\n\t# lid=0 -> going in between, the wind direction is between the last two values;\n\t# r=0 -> h has just been shrunk;\n\t# r=1 -> the h has been shrunk for the last two iterations.\n\tfor(i in 3:nlps){\n\t\tif(lid == 1){\n\t\t\twind_dir <- resm[order(resm[,2]),][1,1] + h\n\t\t\tlid <- 1\n\t\t}else if(lid == -1){\n\t\t\twind_dir <- resm[order(resm[,2]),][1,1] - 2 * h\n\t\t\tlid <- -1\n\t\t}else if(lid == 0 && r == 1){\n\t\t\th <- h * 0.4\n\t\t\twind_dir <-resm[order(resm[,2]),][1,1] + h\n\t\t\tr = 0\n\t\t}else if(lid == 0 && r == 0){\n\t\t\twind_dir <-resm[order(resm[,2]),][1,1] - h\n\t\t\tr = 1\n\t\t}\n\t\n\t\tres <- fi(obs, sv, wind_dir)\n\t\tresm[i,1] <- wind_dir\n\t\tresm[i,2] <- res[1]\n\n\t\tresm <- resm[order(resm[,1]),]\n\t\t\tif(lid == 1){\n\t\t\t\tgdnt <- fdm %*% resm[c(i-2,i-1,i),2]\n\t\t\t}\n\t\t\tif(lid == -1){\n\t\t\t\tgdnt <- fdm %*% resm[c(1,2,3),2] \n\t\t\t}\n\t\t\tif(lid == 0 ){\t\n\t\t\t\tn <- which(resm[,2]==min(resm[,2]))\n\t\t\t\tgdnt <- fdm %*% resm[c(n-1,n, n+1) ,2]\n\t\t\t}\n\t\tif(gdnt[1]<0 && gdnt[2]>=0){lid <- 0}\n\t\tif(gdnt[1]>=0 && gdnt[2] >= 0){lid <- -1}\n\t\tif(gdnt[1]<0 && gdnt[2] <0){lid <- 1}\n\t\tif(gdnt[1] > 0 && gdnt[2] < 0){lid <- -1}\n\t\t\n\t\tif(h < 0.01){break}\n\t}\n\ttemp <- resm[which(resm[,2]==min(resm[,2])),]\n\toutput <- as.matrix(cbind(temp[1], temp[2]), nrow = 1)\n\t\n\treturn(output)\t\t\n}\t\n\n\n#################### Function name: baf ####################\n# As noted above, local minimum could occur for estimating the prevailing wind direciton.\n# Therefore this function is designed to receive outputs from the function \"baf_pre\".\n# It first identifies if local minima occur or not, then applies the proposed initial\n# guess(es) to the function \"baf_processor\", and collects the output.\n# If local minima occur, it compares the resultant two sum of squared residuals to\n# determine which one represents the true prevailing wind direction (global minimum). \n# Input\n\t# sv and obs:\n\t#\tinputs required for function \"sp_par_cal\".\n\t# nlps:\n\t#\ta numerical value required for the function \"baf_processor\",\n\t#\tas described before. \n# Output\n\t# Optimum output from function \"baf_processor\".\nbaf <- function(sv, obs, nlps){\n\traw_inference <- baf_pre(sv, obs, nlps)\n\tif(raw_inference[1] == 1){\n\t\toutput = baf_processor(sv, obs, nlps, raw_inference[2])\n\t\treturn(output)\n\t}else{\n\t\toutput_1 = baf_processor(sv, obs, nlps, raw_inference[2])\n\t\toutput_2 = baf_processor(sv, obs, nlps, raw_inference[3])\n\t\tif(output_1[2]0)){\n\t\treturn(1)\n\t}else{\n\t\tfirst_order_grad[first_order_grad > 0] = 0\t\n\t\tdirection = c(1,1,-1,-1)\n\t\tgrad_y = (-1*direction[c(1,3)])%*%first_order_grad[c(1,3)]\n\t\tgrad_x = (-1*direction[c(2,4)])%*%first_order_grad[c(2,4)]\n\t\tgrad_unit = c(grad_x/(grad_x^2+grad_y^2)^0.5, grad_y/(grad_x^2+grad_y^2)^0.5)\n\t\treturn(c(2,grad_unit))\n\t}\n}\n####################End of intermediate functions#################################\n\n#################### Function name: gd_simplified ####################\n# This function integrates the above functions, implements ANOTHER gradient descent \n# method in the x-y plane, and estimates the source vent location. \n# See notations in the file \"demo_svl_2.0.R\" for the description of this \n# function, and how to set values for the input parameters.\ngd_simplified <- function(sv, obs, runs, h, r, nlps, h_ratio, numb){\t\t\n \n\tobs = obs[numb,] \n\ttcoord <- as.data.frame(matrix(ncol=2))\t\t\t\n\tdec <- c()\n\thl <- c()\n\tihd <- h\n\n\tir=1\t\t\t\t\t\t\t\n\tjg <- 0\n\n\twarns <- 0\n\tfor(i in 1:runs){\n\t\t\tdec <- compare(sv, obs, h, nlps, h_ratio)\n\t\t\tif(dec[1]!= 1 && jg ==0){\n\t\t\t\t\tsv <- sv + h*dec[2:3]\n\t\t\t\t\ttcoord[i,] <- sv\n\t\t\t\t\thl[i] <- h\t\t\t\t\t\n\t\t\t\t\tjg <- 0\n\t\t\t}else if(dec[1] != 1 && jg == 1){\n\t\t\t\t\th <- h *(1 - r)\n\t\t\t\t\tsv <- sv + h*dec[2:3]\n\t\t\t\t\ttcoord[i,] <- sv\n\t\t\t\t\thl[i] <- h\t\t\t\t\t\n\t\t\t\t\tjg <- 0\n\t\t\t}else if(dec[1] == 1 && h/ihd >= 0.0001){\t\n\t\t\t\th = h * r\n\t\t\t\thl[i] <- h\t\n\t\t\t\tjg <- 1\n\t\t\t}\t\n\t\tif(h < 0.1){break}\n\t}\n\tbd <- baf(sv, obs, nlps)\n\trownames(tcoord) <- NULL\n\n\toutput_sv = tcoord[nrow(tcoord),]\n\toutput_ang = bd[1]\n\n\tfitted_results= fi2(obs, as.matrix(sv), output_ang)\n\n\treturn(as.matrix(cbind(sv, output_ang, h, coef = t(fitted_results[c(2,3,4)]), ssr = fitted_results[1], rsquare = fitted_results[5])))\n}\n########################################## End of functions #####################################################\n\n# References:\n#\tGonzalez-Mellado, A. O., and S. De la Cruz-Reyna. \"A simple semi-empirical approach to model thickness of \n# ash-deposits for different eruption scenarios.\" Natural Hazards and Earth System Sciences 10.11 (2010): 2241.\n# \tYang Q, Bursik M. A new interpolation method to model thickness, isopachs, extent, and volume of tephra fall \n# deposits. Bulletin of Volcanology, 2016, 78(10): 68.\n\n", "meta": {"hexsha": "6f20424bef57bb9e17388338fd5c977bfd9fb618", "size": 16338, "ext": "r", "lang": "R", "max_stars_repo_path": "pub_svl_2.0_exponential.r", "max_stars_repo_name": "yiqioyang/svl", "max_stars_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pub_svl_2.0_exponential.r", "max_issues_repo_name": "yiqioyang/svl", "max_issues_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pub_svl_2.0_exponential.r", "max_forks_repo_name": "yiqioyang/svl", "max_forks_repo_head_hexsha": "12f949a7f944fd6e4158ca4082035271185126f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8487804878, "max_line_length": 134, "alphanum_fraction": 0.6556494063, "num_tokens": 4834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43047156418765287}}
{"text": "##### Code for estimating country specific effective reproduction number with different methods ####\n##### parts of the code reutilizes already partly written code by othe researcrhes, the sources for these are:\n#####https://www.datacamp.com/community/tutorials/replicating-in-r-covid19\n##### https://www.r-bloggers.com/effective-reproduction-number-estimation/\n#####\n######\n######\n##### \n\n### instructions to run the code ####\n### 1. set the homedirectory in your computer where to save the results\n## ADD HOMEDIRECTORY, for example \"c:/DATA/COVID/RESULTS_CALCULATION\"\nHomedir<-\"ADD DIRECTORY TO SAVE RESULTS HERE\"\n\n### 2. Uncomment the package installations if they are not installed\n\n# install.packages(\"purrr\")\n# install.packages(\"knitr\")\n#install.packages(\"kableExtra\")\n# install.packages(\"viridis\")\n# install.packages(\"accelerometry\")\n# install.packages(\"tidyverse\")\n# install.packages(\"R0\")\n#install.packages(\"IRdisplay\")\n#install.packages(\"smoother\")\n#install.packages(\"HDInterval\")\n\n####### 3. Specify the country the analysis should be performed for #####\nCountry_Name<-\"France\"\n\n##### 4. Specify the date the analysis should start\nstarting_date <- \"2020-03-22\"\n\n### 5. Execute all the code, outputs will be saved in the homedirectory as a csv file with name \"Reproduction_number_estimates.csv\"\n\n\n#### Possible errors #####\n##### some error messages are displayed during the analysis, these are no real errors but mostly messages from different\n##### estimation tools on assumptions taken or if some parts of the analysis takes longer than expected\n##### only if the analysis stops and it not finished there can be an error. This error is due to the country specific data\n##### this can either depend tht the starting date is taken too early, some methods do not work in this situation. Other possibility \n#### is that in some countries zero cases can be reported for a longer timeperiod.\n############################\n\n\n\n\n\n\nsuppressPackageStartupMessages(library(purrr))\nsuppressPackageStartupMessages(library(knitr))\nsuppressPackageStartupMessages(library(kableExtra))\nsuppressPackageStartupMessages(library(viridis))\nsuppressPackageStartupMessages(library(accelerometry))\nsuppressPackageStartupMessages(library(tidyverse))\nsuppressPackageStartupMessages(library(IRdisplay))\nsuppressPackageStartupMessages(library(smoother))\nsuppressPackageStartupMessages(library(HDInterval))\n\nstarting_date <- \"2020-03-22\"\nCountry_Name<-\"France\"\n\n### Set up distribution on generation time\nGT_pmf <- structure( c(0, 0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.1), names=0:7)\nGT_obj <- R0::generation.time(\"empirical\", val=GT_pmf)\n\nGT_obj<-R0::generation.time(\"gamma\", c(6.6, 1.5))\n\nHomedir<-\"H:/COVID/R0_technical_paper/Graphs_test\"\n\n## Read in ECDC data ##\ndata_ECDC <- read.csv(\"https://opendata.ecdc.europa.eu/covid19/casedistribution/csv\", na.strings = \"\", fileEncoding = \"UTF-8-BOM\")\n\n\n##### Define functions to calculate effective reproduction number #######\n\n####### Functions to use for effective reproduction number calculations #######\n\n##### Kevin systrom method ########\n\nest_rt_Systrom <- function(covid_cases, state_selected) {\n \n \n R_T_MAX = 12\n r_t_range = seq(0, R_T_MAX, length = R_T_MAX*100 + 1)\n GAMMA = 1/7\n \n #' Compute new cases and smooth them\n smooth_new_cases_1 <- function(cases){\n cases %>%\n arrange(date) %>%\n mutate(new_cases = c(cases[1], diff(cases))) %>%\n mutate(new_cases_smooth = round(\n smoother::smth.gaussian(new_cases, window = 7, alpha=7/4, tails = FALSE)\n )) %>%\n select(state, date, new_cases, new_cases_smooth)\n }\n \n \n #' Start using data first when smoothed value is above 25\n smooth_new_cases_25 <- function(x){\n start_index <- which(x$new_cases_smooth > 25)[1]\n length_vector <-dim(x)[1]\n return(x[start_index:length_vector,])\n }\n \n \n compute_likelihood <- function(cases){\n likelihood <- cases %>%\n filter(new_cases_smooth > 0) %>%\n mutate(\n r_t = list(r_t_range),\n lambda = map(lag(new_cases_smooth, 1), ~ .x * exp(GAMMA * (r_t_range - 1))),\n likelihood_r_t = map2(new_cases_smooth, lambda, dpois, log = TRUE)\n ) %>%\n slice(-1) %>%\n select(-lambda) %>%\n unnest(c(likelihood_r_t, r_t))\n }\n \n \n compute_posterior <- function(likelihood){\n likelihood %>%\n arrange(date) %>%\n group_by(r_t) %>%\n mutate(posterior = exp(\n zoo::rollapplyr(likelihood_r_t, 7, sum, partial = TRUE)\n )) %>%\n group_by(date) %>%\n mutate(posterior = posterior / sum(posterior, na.rm = TRUE)) %>%\n # HACK: NaNs in the posterior create issues later on. So we remove them.\n mutate(posterior = ifelse(is.nan(posterior), 0, posterior)) %>%\n ungroup() %>%\n select(-likelihood_r_t)\n }\n \n \n \n \n \n # Estimate R_t and a 95% highest-density interval around it\n estimate_rt <- function(posteriors){\n posteriors %>%\n group_by(state, date) %>%\n summarize(\n r_t_simulated = list(sample(r_t_range, 10000, replace = TRUE, prob = posterior)),\n r_t_most_likely = r_t_range[which.max(posterior)]\n ) %>%\n mutate(\n r_t_lo = map_dbl(r_t_simulated, ~ hdi(.x)[1]),\n r_t_hi = map_dbl(r_t_simulated, ~ hdi(.x)[2])\n ) %>%\n select(-r_t_simulated)\n }\n \n estimates <- covid_cases %>%\n filter(state == state_selected) %>%\n smooth_new_cases_1() %>%\n smooth_new_cases_25() %>%\n compute_likelihood() %>%\n compute_posterior() %>%\n estimate_rt()\n \n return(estimates)\n \n}\n\n\n##### cislaghi method\n\n\n\nest_rt_Cislaghi <- function(ts, window_interval) {\n data1 <- accelerometry::movingaves(ts, window=5)\n names(data1) <- names(ts)[3:(length(ts)-2)]\n res <- sapply( (1+window_interval):length(data1), function(t) {\n data1[t]/data1[t-window_interval]\n })\n return(res)\n \n}\n\n\n###### JRC method ###########################\n\n\nest_rt_JRC <- function(ts, window_interval) {\n res <- sapply( 1:(length(ts)-window_interval), function(t) {\n ((log(ts[t+window_interval])-log(ts[t]))/window_interval)*7 + 1\n })\n return(res)\n \n}\n\n#### RKI method ##############################\n\nest_rt_rki <- function(ts, GT=4L) {\n # Sanity check\n if (!is.integer(GT) | !(GT>0)) stop(\"GT has to be postive integer.\")\n # Estimate, if s=1 is t-7\n res <- sapply( (2*GT):length(ts), function(t) {\n sum(ts[t-(0:(GT-1))]) / sum(ts[t-2*GT+1:GT])\n })\n names(res) <- names(ts)[(2*GT):length(ts)]\n return(res)\n}\n\n\n###### Exponential growth, Wallinga & Lipsitch ########\n\n\nR.from.r <- function (r, GT) {\n Tmax = length(GT$GT)\n R = 1/sum(GT$GT * (exp(-r * (0:(Tmax - 1)))))\n}\n\nest_rt_exp <- function(ts, GT_obj, half_window_width=3L) {\n # Loop over all time points where the sliding window fits in\n res <- sapply((half_window_width+1):(length(ts)-half_window_width), function(t) {\n # Define the sliding window\n idx <- (t-half_window_width):(t+half_window_width)\n data <- data.frame(Date=1:length(ts), y=as.numeric(ts))\n # Fit a Poisson GLM\n m <- glm( y ~ 1 + Date, family=poisson, data= data %>% slice(idx))\n # Extract the growth rate \n r <- as.numeric(coef(m)[\"Date\"])\n \n # Equation 2.9 from Wallinga & Lipsitch\n R <- R.from.r(r, GT_obj)\n return(R)\n })\n names(res) <- names(ts)[(half_window_width+1):(length(ts)-half_window_width)]\n return(res)\n}\n\n######### Wallinga & Teunis ##############\n\n\n\nest_rt_wt <- function(ts1, GT_obj) {\n end1 <- length(ts1) \n \n R0::est.R0.TD(ts1, GT=GT_obj, begin=1, end=as.numeric(end1),correct=TRUE, nsim=1000)\n}\n\n\n\n\n\n#### function to calculate country specific value\n\n\nEst_R0 <- function(start_date, country_name) {\n\n\n\n data2<-data_ECDC[,c(\"dateRep\", \"cases\", \"countriesAndTerritories\")]\n # Set cases with minus value to 0\n data2$cases[which(data2$cases <0)]<-0\n # change format of Dates \n data2$dateRep <- as.Date(as.character(data2$dateRep), format=\"%d/%m/%Y\")\n names(data2) <- c(\"Date\", \"y\", \"CountryName\")\n \n data2<-data_ECDC[,c(\"dateRep\", \"cases\", \"countriesAndTerritories\")]\n # Set cases with minus value to 0\n data2$cases[which(data2$cases <0)]<-0\n # change format of Dates \n data2$dateRep <- as.Date(as.character(data2$dateRep), format=\"%d/%m/%Y\")\n names(data2) <- c(\"Date\", \"y\", \"CountryName\")\n eval(parse(text=paste(\"index1 <- which(data2$CountryName ==\\\"\",country_name, \"\\\")\", sep=\"\" )))\n out <- data2[index1,]\n # Get starting date for the country\n out<-out[dim(out)[1]:1,]\n\n out <- out[out$Date %in% seq(from=as.Date(start_date) , to=out$Date[length(out$Date)] , by=1),]\n \n \nout3 <- out\n names(out3)<-c(\"date\", \"cases1\", \"state\")\n \n out3$cases[1] <-out3$cases1[1]\n for (j in 2:dim(out3)[1]) {\n out3$cases[j] <- out3$cases[j-1]+ out3$cases1[j]\n }\n \n \n #### cislaghi method ######\n \n \n rt_Cislaghi_3 <- est_rt_Cislaghi(out$y %>% setNames(out$Date), window_interval=3)\n rt_Cislaghi_4 <- est_rt_Cislaghi(out$y %>% setNames(out$Date), window_interval=4)\n rt_Cislaghi_5 <- est_rt_Cislaghi(out$y %>% setNames(out$Date), window_interval=5)\n rt_Cislaghi_6 <- est_rt_Cislaghi(out$y %>% setNames(out$Date), window_interval=6)\n \n rt_Cislaghi_3_df <- data.frame(Date=as.Date(names(rt_Cislaghi_3)), R_hat=rt_Cislaghi_3, Method=\" 3\")\n rt_Cislaghi_4_df <- data.frame(Date=as.Date(names(rt_Cislaghi_4)), R_hat=rt_Cislaghi_4, Method=\" 4\")\n rt_Cislaghi_5_df <- data.frame(Date=as.Date(names(rt_Cislaghi_5)), R_hat=rt_Cislaghi_5, Method=\" 5\")\n rt_Cislaghi_6_df <- data.frame(Date=as.Date(names(rt_Cislaghi_6)), R_hat=rt_Cislaghi_6, Method=\" 6\")\n \n \n #### Kevins Systrom method ######\n \n # r_t_range is a vector of possible values for R_t\n R_T_MAX = 12\n r_t_range = seq(0, R_T_MAX, length = R_T_MAX*100 + 1)\n \n # Gamma is 1/serial interval\n # https://wwwnc.cdc.gov/eid/article/26/6/20-0357_article\n GAMMA = 1/7\n \n \n eval(parse(text=paste(\" rt_Systrom <- est_rt_Systrom(covid_cases=out3, state_selected=\\\"\",country_name, \"\\\")\", sep=\"\" )))\n\n rt_Systrom_df <- data.frame(Date=rt_Systrom$date, R_hat=rt_Systrom$r_t_most_likely, upper=rt_Systrom$r_t_hi, lower=rt_Systrom$r_t_lo, Method=\"Systrom\")\n \n\n #### JRC method #######\n \n \n \n rt_jrc <- est_rt_JRC(out$y %>% setNames(out$Date), window_interval=7)\n \n rt_jrc_df <- data.frame(Date=as.Date(names(rt_jrc)), R_hat=rt_jrc, Method=\"JRC, GT=7\")\n \n \n ############# RKI method ################\n \n \n # RKI method as specified in 2020-04-24 version of the article\n rt_rki <- est_rt_rki(out$y %>% setNames(out$Date), GT=4L)\n \n rt_rki_df <- data.frame(Date=as.Date(names(rt_rki)), R_hat=rt_rki, Method=\"RKI, GT=4\")\n \n \n \n \n ###### Wallinga & Lipsitch method #############\n \n \n # Exponential growth with discrete Laplace transform of a GT \\equiv = 4 distribution\n rt_exp2 <- est_rt_exp( out$y %>% setNames(out$Date), GT_obj=R0::generation.time(\"empirical\", c(0,0,0,0,0,0,0,1)), half_window_width=3)\n \n # Exponential growth with discrete Laplace transform of the correct GT distribution\n rt_exp <- est_rt_exp( out$y %>% setNames(out$Date), GT_obj=GT_obj, half_window_width=3)\n \n rt_exp_df <- data.frame(Date=as.Date(names(rt_exp)), R_hat=rt_exp, Method=\"Stochastic generation time\")\n #rt_exp_df <- data.frame(Date=as.Date(names(rt_exp_int[1:dim(rt_exp_int)[2]])), R_hat=rt_exp_int[1,], lower= rt_exp_int[2,], upper=rt_exp_int[3,], Method=\"Exp-Growth, random GT\")\n \n rt_exp2_df <- data.frame(Date=as.Date(names(rt_exp2)), R_hat=rt_exp2, Method=\"Generation time 7 days (constant)\")\n \n \n ### Wallinga and Teuniss############\n \n rt_wt <- est_rt_wt( out$y, GT=GT_obj)\n \n rt_wt_df <- cbind(Date=out$Date[as.numeric(names(rt_wt$R))], R_hat=rt_wt$R, rt_wt$conf.int, Method=\"W & T, ramdom GT\")\n \n ### Create dataset with all estmates\n \n \n \n out_data <- data.frame(Date = as.Date(out$Date),Cases = out$y) \n\n # Merge the data\n\nnames(rt_Cislaghi_3_df)[2] <- \"Cislaghi_3\" \nout_data <- merge(x=out_data, y=rt_Cislaghi_3_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_Cislaghi_4_df)[2] <- \"Cislaghi_4\" \nout_data <- merge(x=out_data, y=rt_Cislaghi_4_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_Cislaghi_5_df)[2] <- \"Cislaghi_4\" \nout_data <- merge(x=out_data, y=rt_Cislaghi_5_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_Cislaghi_6_df)[2] <- \"Cislaghi_4\" \nout_data <- merge(x=out_data, y=rt_Cislaghi_6_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_Systrom_df)[2:4] <- c(\"Systrom\", \"Systrom_upper\", \"Systrom_lower\") \nout_data <- merge(x=out_data, y=rt_Systrom_df[,1:4], by = \"Date\", all.x=TRUE)\nnames(rt_jrc_df)[2] <- \"JRC\" \nout_data <- merge(x=out_data, y=rt_jrc_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_rki_df)[2] <- \"RKI\" \nout_data <- merge(x=out_data, y=rt_rki_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_exp_df)[2] <- \"Exp_growth_random_GT\" \nout_data <- merge(x=out_data, y=rt_exp_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_exp2_df)[2] <- \"Exp_growth_constant_GT\" \nout_data <- merge(x=out_data, y=rt_exp2_df[,1:2], by = \"Date\", all.x=TRUE)\nnames(rt_wt_df)[2:4] <- c(\"Wallinga_Teunis\", \"Wallinga_Teunis_Upper\", \"Wallinga_Teunis_lower\") \nout_data <- merge(x=out_data, y=rt_wt_df[,1:4], by = \"Date\", all.x=TRUE)\n\nreturn(out_data)\n\n}\n\n\nR_estimates <- Est_R0(start_date=starting_date, country_name=Country_Name)\n\nwrite.csv(R_estimates, file.path(Homedir, \"Reproduction_number_estimates.csv\"))\n", "meta": {"hexsha": "6b1c530c8adcc276d5a5dcc1801f18522adf56a7", "size": 13264, "ext": "r", "lang": "R", "max_stars_repo_path": "programs/ReprNumber/Make_country_specific_calculation.r", "max_stars_repo_name": "ec-jrc/COVID-19", "max_stars_repo_head_hexsha": "c9ef6ca3ae69edc8ba77b9f99d4a6875416136aa", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 43, "max_stars_repo_stars_event_min_datetime": "2020-04-23T08:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:49:50.000Z", "max_issues_repo_path": "programs/ReprNumber/Make_country_specific_calculation.r", "max_issues_repo_name": "ebuitragod/COVID-19", "max_issues_repo_head_hexsha": "b6989fe4cf9d10bdb47be7f840036f597d293e21", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 44, "max_issues_repo_issues_event_min_datetime": "2020-05-05T08:35:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T03:29:28.000Z", "max_forks_repo_path": "programs/ReprNumber/Make_country_specific_calculation.r", "max_forks_repo_name": "ebuitragod/COVID-19", "max_forks_repo_head_hexsha": "b6989fe4cf9d10bdb47be7f840036f597d293e21", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2020-05-19T16:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T06:00:59.000Z", "avg_line_length": 33.5797468354, "max_line_length": 180, "alphanum_fraction": 0.662017491, "num_tokens": 4080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4298855620311666}}
{"text": "#' Generic M-step function to re-estimate the paramters of an emission probability distribution.\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data\n#' @param wt weight matrix\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return the five types of M-step results\n#' @description Re-estimate the parameters of an emission distribution as part of the EM algorithm for HMM. \n#' This is called by the hext function.\n#' @usage mstep.generic(x, wt, model) \n#' @details see example code for usage\n#' @author Horace W Tso\n#' @export\nmstep.generic = function(x, wt, model) {\n # type codes (mtype):\n # discrete/binomial = 1\n # multivariate normal = 2\n # gamma = 3\n # beta = 4\n # gaussian mixture = 5\n D = model$D\n mtype = model$mtype\n ix1 = which(mtype == 1)\n if ( length(ix1) == 1 ) {\n # if there is only one column in obs, then no need to use ix1\n if ( length(mtype) == 1 ) {\n M1 = mstep.disc(x, wt, D)\n } else { \n # this is the case where there is only one discrete column\n # and one or more other types of observation, thus need ix1.\n M1 = mstep.disc(x[,ix1, drop=FALSE], wt, D)\n }\n } else if ( length(ix1) > 1 ) {\n M1 = mstep.mvdisc(x[,ix1], wt, D)\n } else {\n M1 = list(prob.l=list(), labels=NULL)\n }\n\n ix2 = which(mtype == 2)\n if ( length(ix2) == 1 ) {\n M2 = mstep.norm.hext(x[,ix2, drop=FALSE], wt)\n } else if ( length(ix2) > 1 ) {\n # =================================\n M2 = mstep.mvnorm.wish(x[,ix2], wt)\n # =================================\n } else {\n M2 = list(mu.l=list(), sigma.l=list())\n }\n\n ix3 = which(mtype == 3)\n if ( length(ix3) == 1 ) {\n M3 = mstep.gamma(x[,ix3, drop=FALSE], wt)\n } else if ( length(ix3) > 1 ) {\n M3 = mstep.mvgamma(x[,ix3], wt)\n } else {\n M3 = list(shape.l=list(), scale.l=list())\n }\n\n ix4 = which(mtype == 4)\n if ( length(ix4) == 1 ) {\n M4 = mstep.beta(x[,ix4, drop=FALSE], wt)\n } else if ( length(ix4) > 1 ) {\n M4 = mstep.mvbeta(x[,ix4], wt)\n } else {\n M4 = list(shape1.l=list(), shape2.l=list())\n }\n\n ix5 = which(mtype == 5)\n if ( length(ix5) > 0 ) {\n #cat(\"ix5:\", ix5, \"\\n\")\n # ====================================================================\n M5 = mstep.gaussian.mix(x[,ix5, drop=FALSE], wt, model)\n # ====================================================================\n } else {\n M5 = list(c.l=list(), mu.ll=rep(list(list()),K), sigma.ll=rep(list(list()),K))\n }\n return(list(M1=M1, M2=M2, M3=M3, M4=M4, M5=M5))\n}\n\n#' M-step re-estimation function for Gaussian Mixture emission distribution with inverse Wishart regularizer\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data\n#' @param w weight matrix, gamma from EStep C function\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of the gaussian mixture emission distribution as part of the EM algorithm for HMM. \n#' @details Ref : Snoussi, Mohammad-Djafari (2005), Degeneracy and likelihood penalization\n#' in multivariate gaussian mixture models, preprint. \n#' NOTE : gam.jk is *not* in log domain. \n#' @author Horace W Tso\n#' @export\nmstep.gaussian.mix = function (x, w, model) {\n idx = apply(is.na(x), 1, any)\n x = x[!idx, , drop = FALSE]\n w = w[!idx, , drop = FALSE]\n K = ncol(w) # should agree with model$K\n Ttot = NROW(x) # = sum(model$TT)\n p = NCOL(x) # = model$p\n M = model$M\n wdf = model$wdf\n \n if ( any(is.na(w)) | any(is.infinite(w))) {\n stop(\"na/infty found in w[].\")\n }\n if ( all(w < 1e-100) == TRUE ) {\n stop(\"all w[] are near zero.\")\n }\n w.tot = colSums(w) # denominator for the reestimation equations, 1 x K\n \n emission = list(c.l=list(), mu.ll=rep(list(list()),K), sigma.ll=rep(list(list()),K))\n for ( i in 1:K ) {\n emission$c.l[[i]] = rep(NA, M)\n }\n \n gam.jk = array(NA, dim=c(Ttot, K, M))\n for ( i in 1:K ) {\n mu.l = model$parms.emission$M5$mu.ll[[i]]\n #if ( length(mu.l) != M ) cat(\"length of mu.l <> M\\n\")\n sigma.l = model$parms.emission$M5$sigma.ll[[i]]\n #if ( any(is.na(sigma.l))) {\n # stop(\"na in sigma.l:\")\n #}\n #if ( length(sigma.l) != M ) cat(\"length of sigma.l <> M\\n\")\n c.v = model$parms.emission$M5$c.l[[i]] # c.v is a vector of length M\n #if ( length(c.v) != M ) cat(\"length of c.v <> M\\n\")\n # Compute the conditional probabilities of the gaussian components in log domain :\n logbb = matrix(NA, nrow=Ttot, ncol=M)\n for ( m in 1:M ) {\n logbb[,m] = log(c.v[m]) + Dmvnorm(x, mean=mu.l[[m]], sigma=sigma.l[[m]], log=TRUE)\n }\n # Sum the contribution from the individual gaussian components\n # <==> sum by rows ==> a vector of length Ttot\n denom = double(Ttot)\n for ( tt in 1:Ttot) {\n denom[tt] = Elnsum.vec(logbb[tt,]) # in the non-log version: denom = rowSums(bb)\n }\n for ( m in 1:M ) {\n tmp = logbb[,m] + log(w[,i]) - denom\n gam.jk[,i,m] = exp(tmp)\n }\n if ( any(is.na(gam.jk[,i,m])) | any(is.infinite(gam.jk[,i,m]))) {\n cat(\"na/inf in gam.jk: i, m \", i, m)\n stop(\"...\")\n }\n }\n \n for ( i in 1:K ) {\n # sum over mixture state k and time t, for every state i\n denom.j = sum(gam.jk[,i,]) # sum over mixture and sum over time, a scalar\n # cat(\"denom.j:\", denom.j, \"\\n\")\n for ( k in 1:M ) {\n if ( all(gam.jk[,i,k] < 1e-100) == FALSE ) {\n # c_jk =======================================================================\n emission$c.l[[i]][k] = sum(gam.jk[,i,k]) / denom.j # sum over t; scalar / scalar = scalar\n #if ( any(is.na(emission$c.l[[i]][k])) ) {\n # warning(\"na in c.l at m-step.\")\n #}\n # mu_jk ====================================================================================\n \n xx = gam.jk[,i,k] * x # (1 x T) (*) (T x p) = T x p, component by component multiplication\n denom.jk = sum(gam.jk[,i,k]) # summing over t for every i and k, result is a scalar\n mu.bar = colSums(xx) / denom.jk # (1 x p) / scalar = 1 x p\n #if ( any(is.na(mu.bar)) ) {\n # warning(\"na in mu.bar at m-step.\")\n #}\n emission$mu.ll[[i]][[k]] = mu.bar\n \n # sigma_jk =============================================================================================\n x.centered = sweep(x, 2, mu.bar) # T x p, 'sweep'' subtracts mu.bar ( 1 x p vector) from each row of x,\n # in effect, it is subtracting the mean from each column of\n # the multivariate observation vector (matrix), or (O_t - mu_jk)\n mat.sum = matrix(0, nrow=p, ncol=p) \n for ( tt in 1:Ttot ) {\n crossp = x.centered[tt,] %*% t(x.centered[tt,]) # x %*% t(x) = p x p matrix\n mat.w = crossp * gam.jk[tt,i,k] # p x p matrix * scalar = p x p\n mat.sum = mat.sum + mat.w # element by element addition : p x p\n }\n # Regularization with Inverse Wishart distribution ======================\n # Fraser, p. 55, regularized covariance matrix.\n # see p. 8 of Snoussi(2005), where nu = p + wdf, in numerator\n # nu + n + 1 = (p + wdf) + p + 1 = wdf + 2*p + 1, in denominator\n cov.mat = ( mat.sum + (p + wdf)*diag(p) ) / ( denom.jk + wdf + 2*p + 1 )\n # =======================================================================\n # cat(\"na in cov.mat:\", sum(is.na(cov.mat)), \"\\n\")\n # =============================================================\n # matrix's columns and rows must have the same names, otherwise\n # isSymmetric in dmvnorm complains\n rownames(cov.mat) = paste(\"X\", 1:p, sep=\"\")\n colnames(cov.mat) = rownames(cov.mat)\n #if ( any(is.na(cov.mat)) ) {\n # warning(\"na in cov.mat at m-step.\")\n #}\n emission$sigma.ll[[i]][[k]] = cov.mat \n } else {\n emission$c.l[[i]][k] = 0\n emission$mu.ll[[i]][[k]] = rep(0, p)\n emission$sigma.ll[[i]][[k]] = diag(p)\n }\n }\n }\n emission\n}\n\n#' M-step re-estimation function for multivariate gaussian emission distribution with inverse Wishart regularizer\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data (columns are features)\n#' @param w weight matrix, size T x K, where each row is the weight for a time step, and columns are states.\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of the multivariate normal emission distribution with inverse Wishart regularization.\n#' @details Ref : Snoussi, Mohammad-Djafari (2005), Degeneracy and likelihood penalization\n#' in multivariate gaussian mixture models, preprint. \n#' wdf : Wishart degree of freedom, i.e. wishart df = wdf + p, where p is the dimension of the data. Thus, wdf > -1.\n#' @author Horace W Tso\n#' @export\nmstep.mvnorm.wish = function (x, w, wdf=1) {\n ix = apply(is.na(x), 1, any)\n x = x[!ix, , drop = FALSE]\n w = w[!ix, , drop = FALSE]\n K = ncol(w)\n TT = NROW(x)\n p = NCOL(x)\n \n w.tot = colSums(w) # denominator for the reestimation equations, 1 x K\n #if ( any(w.tot < 1e-100) ) {\n # cat(\"w.tot :\", w.tot, \"\\n\") \n #stop(\"w.tot too small!\")\n #}\n emission = list(mu.l=list(), sigma.l=list())\n mat.sum = matrix(0, nrow=p, ncol=p)\n for ( i in 1:K ) {\n xx = w[,i] * x # (1 x T) x (T x p) = T x p\n mu.bar = colSums(xx) / w.tot[i] # (1 x p) x scalar = 1 x p\n x.centered = sweep(x, 2, mu.bar) # T x p \n for ( tt in 1:TT ) {\n crossp = x.centered[tt,] %*% t(x.centered[tt,]) \n mat.w = crossp * w[tt, i] # p x p matrix times a scalar = p x p\n mat.sum = mat.sum + mat.w # element by element addition : p x p\n }\n # Regularization using the Inverse Wishart distribution ==============\n # Ref : Snoussi (2005), p. 8, where the inverse scale matrix is to be taken\n # as a diagonal matrix, wish.df is nu, the degree of freedom, p is the \n # dimension of the data n.\n cov.mat = (mat.sum + (p + wdf)*diag(p)) / ( w.tot[i] + wdf + 2*p + 1 )\n # ====================================================================\n # matrix's columns and rows must have the same names, otherwise\n # isSymmetric() complains \n rownames(cov.mat) = paste(\"X\", 1:p, sep=\"\")\n colnames(cov.mat) = rownames(cov.mat)\n emission$mu.l[[i]] = mu.bar\n emission$sigma.l[[i]] = cov.mat \n }\n emission\n}\n\n#' M-step re-estimation function for multivariate gaussian emission distribution, no regularization\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data\n#' @param w weight matrix, gamma from EStep C function\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of the multivariate gaussian emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @author Horace W Tso\n#' @export\nmstep.mvnorm.hext = function (x, wt) {\n ix = apply(is.na(x), 1, any)\n x = x[!ix, , drop = FALSE]\n wt = wt[!ix, , drop = FALSE]\n emission = list(mu.l=list(), sigma.l=list())\n for (i in 1:ncol(wt)) {\n tmp <- cov.wt(x, wt[,i])\n emission$mu.l[[i]] <- tmp$center\n emission$sigma.l[[i]] <- tmp$cov\n }\n emission\n}\n\n#' M-step re-estimation function for univarite gaussian emission distribution, no regularization\n#'\n#' @param x numeric matrix, size T x p, where T is the number of observations, p the dimension of the obs data\n#' @param w weight matrix, gamma from EStep C function\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of the univariate gaussian emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @author Horace W Tso\n#' @export\nmstep.norm.hext = function (x, wt) {\n k = ncol(wt)\n mu = numeric(k)\n sigma = numeric(k)\n for (i in 1:k) {\n tmp = cov.wt(data.frame(x[!is.na(x)]), wt[!is.na(x),i])\n mu[i] = tmp$center\n sigma[i] = tmp$cov\n }\n list(mu.l = mu, sigma.l = sigma)\n}\n\n#' M-step re-estimation function for univariate discrete emission distribution\n#'\n#' @param x numeric matrix, size sum(T) x 1. All sequences stacked onto one column\n#' @param w weight matrix, size sum(T) x K, gamma(i, t)\n#' @param D number of alphabets in x\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of discrete emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @author Horace W Tso\n#' @export\nmstep.disc = function(x, w, D) {\n K = NCOL(wt)\n TT = NROW(x)\n w.sum = colSums(w) # a vector of length K\n if ( length(which(w.sum < 1e-300)) > 0 ) {\n stop(\"some of the wt column sums are too close to zero.\")\n }\n # prob.l is a list of matrices\n prob.l = list()\n # In this univariate case, b.vec is really just a vector; but to be consistent with\n # the usage in generic.density, i have to make it a single column matrix.\n b.vec = matrix(0, nrow=D, ncol=1)\n for ( j in 1:K ) {\n for ( fa in 1:D ) { \n ix = which( x == fa )\n b.vec[fa, 1] = sum(w[ix, j])\n } \n prob.l[[j]] = b.vec / w.sum[j]\n }\n list(prob.l=prob.l, labels=NULL)\n}\n\n#' M-step re-estimation function for multivariate discrete emission distribution\n#'\n#' @param x numeric matrix, size sum(T) x p\n#' @param w weight matrix, size T x K\n#' @param D number of alphabets in x, a vector of length equal to ncol(x)\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of discrete emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @author Horace W Tso\n#' @export\nmstep.mvdisc = function(x, w, D) {\n K = NCOL(wt)\n TT = NROW(x)\n p = NCOL(x)\n wt.sum = colSums(wt) # a vector of length K\n if ( length(which(wt.sum < 1e-300)) > 0 ) {\n stop(\"some of the wt column sums are too close to zero.\")\n }\n prob.l = list()\n lookup.mat = matrix(0, nrow=max(D), ncol=p)\n for ( j in 1:K ) {\n for ( k in 1:p ) {\n for ( fa in 1:D[k] ) {\n # IMPORTANT NOTE : here i assume the discrete obs take on numeric value\n # from 1 to D[k] for column k of the obs. The next line looks for all\n # occurences of the factor (fa) in obs x[,k],\n ix = which( x[,k] == fa )\n # then sum up the soft weights, i.e. probability of the occurence of fa\n # in x for state j.\n lookup.mat[fa, k] = sum(wt[ix, j])\n # RECALL : wt = P( x_t=fa | s_t=j )\n # it has as many rows as x and as many columns as the no of states\n }\n }\n prob.l[[j]] = lookup.mat / wt.sum[j]\n } \n list(prob.l=prob.l, labels=NULL)\n}\n\n#' M-step re-estimation function for univariate beta emission distribution\n#'\n#' @param x numeric matrix, size sum(T) x p\n#' @param w weight matrix, size T x K\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of univariate beta emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @details Needs the solnp function in the Rsolnp package.\n#' @author Horace W Tso\n#' @export\nmstep.beta = function(x, w) {\n require(Rsolnp)\n ix = which(is.na(x))\n if ( length(ix) > 0 ) {\n x = x[!ix]\n w = w[!ix, ,drop = FALSE]\n }\n para.start = c(runif(1,min=0.5,max=7), runif(1,min=0.5,max=7)) # c(shape1, shape2)\n lower.b = c(0.01, 0.01)\n upper.b = c(Inf, Inf)\n K = ncol(wt)\n Shape1 = list()\n Shape2 = list()\n i = 1\n nfail = 0\n while ( i <= K ) {\n sol = try(solnp(para.start, Qaux.beta, x=x, wt=w[,i],\n LB=lower.b, UB=upper.b,\n control=list(trace=FALSE, inner.iter=1000, outer.iter=1000,\n tol=1e-13, delta=1e-13)), FALSE)\n if ( !inherits(sol, \"try-error\") ) {\n Shape1[[i]] = sol$par[1]\n Shape2[[i]] = sol$par[2]\n i = i + 1\n } else {\n nfail = nfail + 1\n if ( nfail >= 5 ) {\n stop(\"Too many problems with solnp!\")\n }\n }\n }\n list(shape1.l=Shape1, shape2.l=Shape2)\n}\n\n#' M-step re-estimation function for multivariate beta emission distribution\n#'\n#' @param x numeric matrix, size sum(T) x p\n#' @param w weight matrix, size T x K\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of multivariate beta emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @details Needs the solnp function in the Rsolnp package.\n#' @author Horace W Tso\n#' @export\nmstep.mvbeta = function(x, wt) {\n require(Rsolnp)\n p = NCOL(x)\n K = NCOL(wt)\n ix = apply(is.na(x), 1, any)\n if ( length(ix) > 0 ) {\n x = x[!ix, ,drop = FALSE]\n wt = wt[!ix, ,drop = FALSE]\n }\n emission = list(shape1.l=list(), shape2.l=list())\n lower.b = c(0.01, 0.01)\n upper.b = c(Inf, Inf)\n h1.mat = matrix(NA, ncol=K, nrow=p)\n h2.mat = matrix(NA, ncol=K, nrow=p)\n for ( j in 1:p ) {\n i = 1\n nfail = 0\n while ( i <= K ) {\n para.start = c(runif(1,min=0.5,max=7), runif(1,min=0.5,max=7))\n sol <- try(solnp(para.start, Qaux.beta, x=x[,j], wt=wt[,i],\n LB=lower.b, UB=upper.b,\n control=list(trace=FALSE, inner.iter=1000, outer.iter=1000,\n tol=1e-13, delta=1e-13)), FALSE)\n if (!inherits(sol,\"try-error\")) {\n h1.mat[j,i] = sol$par[1]\n h2.mat[j,i] = sol$par[2]\n i = i + 1\n } else {\n nfail = nfail + 1\n if ( nfail >= 5 ) {\n stop(\"Too many problems with solnp!\")\n }\n }\n }\n }\n for ( i in 1:K ) {\n # columns are states\n emission$shape1.l[[i]] = h1.mat[,i]\n emission$shape2.l[[i]] = h2.mat[,i]\n }\n return(emission)\n}\n\n#' M-step re-estimation function for univariate gamma emission distribution\n#'\n#' @param x numeric vector\n#' @param w weight matrix, size T x K\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of univariate gamma emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @details Needs the solnp function in the Rsolnp package.\n#' @author Horace W Tso\n#' @export\nmstep.gamma = function(x, w) {\n require(Rsolnp)\n ix = which(is.na(x))\n if ( length(ix) > 0 ) {\n x = x[!ix]\n w = w[!ix, ,drop = FALSE]\n }\n lower.b = c(0.01, 0.01)\n upper.b = c(Inf, Inf)\n K = ncol(w)\n Shape = list()\n Scale = list()\n i = 1\n nfail = 0\n while( i <= K ) {\n para.start = c(runif(1,min=0.5,max=10), runif(1,min=0.1,max=2.5)) # c(shape, scale)\n sol <- try(solnp(para.start, Qaux.gamma, x=x, wt=w[,i],\n LB=lower.b, UB=upper.b,\n control=list(trace=FALSE, inner.iter=1000, outer.iter=1000,\n tol=1e-13, delta=1e-13)), FALSE)\n if ( !inherits(sol, \"try-error\")) {\n Shape[[i]] = sol$par[1]\n Scale[[i]] = sol$par[2]\n i = i + 1\n } else {\n nfail = nfail + 1\n if ( nfail >= 5 ) {\n stop(\"Too many problems with solnp!\")\n }\n }\n }\n list(shape.l=Shape, scale.l=Scale)\n}\n\n#' M-step re-estimation function for multivariate gamma emission distribution\n#'\n#' @param x numeric vector\n#' @param w weight matrix, size T x K\n#' @param model HMM model as defined in hmmspec.gen(..)\n#' @return emission slot of Hext object\n#' @description Re-estimates the parameters of multivariate gamma emission distribution as part of the EM algorithm for HMM. No regularizer is used.\n#' @details Needs the solnp function in the Rsolnp package.\n#' @author Horace W Tso\n#' @export\nmstep.mvgamma = function(x, w) {\n require(Rsolnp)\n p = NCOL(x)\n K = NCOL(w)\n ix = apply(is.na(x), 1, any)\n if ( length(ix) > 0 ) {\n x = x[!ix, ,drop = FALSE]\n w = w[!ix, ,drop = FALSE]\n }\n emission = list(shape.l=list(), scale.l=list())\n lower.b = c(0.01, 0.01)\n upper.b = c(Inf, Inf)\n a.mat = matrix(NA, ncol=K, nrow=p)\n s.mat = matrix(NA, ncol=K, nrow=p)\n for ( j in 1:p ) {\n i = 1\n nfail = 0\n while ( i <= K ) {\n para.start = c(runif(1,min=0.5,max=10), runif(1,min=0.1,max=2.5))\n sol <- try(solnp(para.start, Qaux.gamma, x=x[,j], wt=w[,i],\n LB=lower.b, UB=upper.b,\n control=list(trace=FALSE, inner.iter=1000, outer.iter=1000,\n tol=1e-13, delta=1e-13)), FALSE)\n if (!inherits(sol,\"try-error\")) {\n a.mat[j,i] = sol$par[1]\n s.mat[j,i] = sol$par[2]\n i = i + 1\n } else {\n nfail = nfail + 1\n if ( nfail >= 5 ) {\n stop(\"Too many problems with solnp!\")\n }\n }\n }\n }\n for ( i in 1:K ) {\n # columns are states\n emission$shape.l[[i]] = a.mat[,i]\n emission$scale.l[[i]] = s.mat[,i]\n }\n return(emission)\n}\n\n\n", "meta": {"hexsha": "f8245cfbee43b355a6e8dc83ef30c1eadbd3a057", "size": 21461, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Mstep.r", "max_stars_repo_name": "htso/Hext", "max_stars_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_stars_repo_licenses": ["MIT"], "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/Mstep.r", "max_issues_repo_name": "htso/Hext", "max_issues_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_issues_repo_licenses": ["MIT"], "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/Mstep.r", "max_forks_repo_name": "htso/Hext", "max_forks_repo_head_hexsha": "8f4d99d20019a0bdd4522873ee20d758e2cb8187", "max_forks_repo_licenses": ["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.0514184397, "max_line_length": 155, "alphanum_fraction": 0.55980616, "num_tokens": 6644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4296064019894863}}
{"text": "\ndecay_instant <- function(t, hl, C_max){\n C_max * 2^(-t/hl)\n }\n\ndecay_instant_integral <- function(t, hl, C_max){\n -hl * C_max * 2^(-t/hl)/log(2)\n }\n\nreturn_druginf <- function(){\n\n druginf <- list()\n\n druginf[['3TC']] <-\n c(IC_50 = 0.0298, slope = 1.15, c_max = 15.3, hl = 10, dosing = 2)\n druginf[['AZT']] <-\n c(IC_50 = 0.1823, slope = 0.85, c_max = 4.5, hl = 8.5, dosing = 2)\n druginf[['D4T']] <-\n c(IC_50 = 0.5524, slope = 1.13, c_max = 2.3, hl = 3.5, dosing = 2)\n druginf[['EFV']] <-\n c(IC_50 = 0.0035, slope = 1.69, c_max = 12.9, hl = 35.8, dosing = 1)\n druginf[['NFV']] <-\n c(IC_50 = 0.2360, slope = 1.88, c_max = 5.1, hl = 4.0, dosing = 3)\n druginf[['LPV']] <-\n c(IC_50 = 0.0380, slope = 2.1, c_max = 15.6, hl = 9.9, dosing = 2)\n druginf[['NVP']] <-\n c(IC_50 = 0.0490, slope = 1.49, c_max = 25.2, hl = 21.5, dosing = 1)\n \n return(druginf)\n}\n\n\nreturn_mutinf <- function(){\n mutinf <- list()\n\n\n #For 3TC, mutation options are: \n #K65R, M184V\n mutinf[['3TC']] <-\n c(\n #s is taken from K65R\n s = 0.41, \n #mu is equivalent \n mu = 1.1 * (10^-5), \n #rho and sigma are from M184V\n rho = 963, \n sigma = -0.58)\n\n #For AZT, mutation options are: \n #M184V, M41L, T215Y* (excluded, because multi-nuc)\n mutinf[['AZT']] <-\n c(\n #s is taken from M41L\n s = 0.17,\n #mu is taken from M184V\n mu = 1.1 * 10^(-5),\n #rho and sigma are taken from M41L\n rho = 2.2,\n sigma = 0.07)\n \n #For D4T, mutation options are: \n #M41L, T215Y* (excluded, because multi-nuc)\n #all parameters taken from M41L\n mutinf[['D4T']] <-\n c(s = 0.17, \n mu = 1.3 * 10^(-6),\n# rho = 1.0,\n# sigma = 0.07)\n rho = 1.08,\n sigma = -0.12)\n\n #For EFV, mutation options are:\n #G190S, K103N, Y181C\n mutinf[['EFV']] <-\n #s is taken from Y181C\n c(s = 0.26, \n #mu is taken from G190S\n mu = 2.2 * 10^(-5), \n #rho is taken from K103N\n rho = 85, \n sigma = -0.17)\n\n #For NFV, mutation options are\n #D30N, L90M, \n mutinf[['NFV']] <-\n #s is taken from D30N\n c(s = 0.27, \n #mut is taken from D30N\n mu = 5.5 * 10^(-5), \n #rho and sigma are taken from D30N\n rho = 2.3, \n sigma = -0.29)\n\n #For LPV/r, mutation options are\n #I47A*, I47V, V32I, V82A, V82F, \n mutinf[['LPV']] <-\n #s is taken from I47V\n c(s = 0.05, \n #mut is taken from V32I\n mu = 4.1 * 10^(-5), \n #rho and sigma are taken from I47V\n rho = 1.8, \n sigma = -0.29)\n\n #For NVP, mutation options are\n #G190S, K103N, Y181C, #Y181I\n mutinf[['NVP']] <-\n #s is taken from K103N\n c(s = 0.3, \n #mut is taken from G190S\n mu = 2.2 * 10^(-5), \n #rho and sigma are taken from K103N\n rho = 94, \n sigma = -0.15)\n\n return(mutinf)\n \n}\n\n\n", "meta": {"hexsha": "ed26d0ceef28c8ec8b90d899995e141ab9510ac1", "size": 3140, "ext": "r", "lang": "R", "max_stars_repo_path": "code/shared_functions.r", "max_stars_repo_name": "federlab/HIV-MDR-evolution", "max_stars_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_stars_repo_licenses": ["MIT"], "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/shared_functions.r", "max_issues_repo_name": "federlab/HIV-MDR-evolution", "max_issues_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_issues_repo_licenses": ["MIT"], "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/shared_functions.r", "max_forks_repo_name": "federlab/HIV-MDR-evolution", "max_forks_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_forks_repo_licenses": ["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.9504132231, "max_line_length": 76, "alphanum_fraction": 0.4636942675, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.42939825716643687}}
{"text": "#################################################################################\n# Monte Carlo method to calculate Multi-Species Indices (MSI) 3.0\n# CBS (Statistics Netherlands), june 2017\n# \t- generate MSIs with confidence interval, accounting for sampling error\n# - baseyear for simulated MSIs is flexible\n# - baseyear for plots can be set to 100 for index or for smoothed trend value\n#\t - linear trend classification\n# - smoothed trend classification\n# - compare linear trends before and after changepoint\n# - assess overall change and change in last years\n# - truncation of low indices (and their SE set to 0)\n#################################################################################\n# LOAD PACKAGES\nlibrary(ggplot2)\n\n# DATA IMPORT AND SPECIFICATIONS\nsetwd(\"E:/Ontwikkel/Lslt/Graadmeter/BASISTOOLS\") # set working directory for input and output files\nrdata <- read.table(\"Padhout.txt\", header=TRUE) # name of input file\njobname <- as.character (\"Padhout\") # generic name for output fileS\nnsim <- 1000\t\t # number of Monte Carlo simulations\nSEbaseyear <- 2013 # year to set SE to 0. SE of other years is relative to the SE of SEbaseyear\nplotbaseyear <- 1965 # year to set MSI or smoothed trend (dependend on 'index_smooth') to 100 in final MSI-plot\nindex_smooth <- \"SMOOTH\" # INDEX / SMOOTH: \"INDEX\" will cause the MSI in plotbaseyear set to 100; \"SMOOTH\" will set the smoothed trend value in the plotbaseyear to 100\nlastyears <- 10\t\t# last X years of time series for which separate trend (short-term trends) should be calculated\nmaxCV <- 3 # maximum allowed mean Coefficient of Variation (CV) of species indices (0.5 = 50%). Species with higher mean CV are excluded\nchangepoint <- 1994 # compare trends before and after this year\ntruncfac <- 10 # truncation factor (=maximum allowed year-to-year index ratio). Default for Living Planet Index = 10\nTRUNC <- 1 # set all indices below TRUNC to this value and their SE to 0. TRUNC <- 0 means no truncation\n# testyear <- 1994 # additional year smoothed trend values should be compared with \n# END OF SPECIFICATIONS\n\n# Define and calculate model parameters\nspecies <- rdata[,\"species\"]\nyear <- rdata[,\"year\"]\nindex <- rdata[,\"index\"]\nse <- rdata[,\"se\"]\nuspecies <- sort(unique(species))\nnspecies <- length(uspecies)\nuyear <- sort(unique(year))\nnyear <- length(unique(year))\nmeanindex <- tapply(index, species, mean, na.rm=TRUE)/100\nmnindex1 <- as.data.frame(rep(meanindex,each=nyear))\nminyear <- min(year)\nmaxyear <- max(year)\nplotbaseyear <- plotbaseyear-minyear+1\nbaseyear <- max(1,SEbaseyear-minyear+1)\nlastyears <- min(lastyears,nyear)\n# testyear <- nyear-(maxyear-testyear)\nINP <- data.frame(cbind(species, year, index, se))\nSPEC <- as.matrix(species)\nspecies <- sort(rep(uspecies,each=nyear))\nyear <- rep(uyear,nspecies)\nINP1 <- data.frame(cbind(species,year))\nINP2 <- merge(INP, INP1, by=c(\"species\",\"year\"), sort=TRUE, all=TRUE)\n\n# Calculate and plot mean CV for indices per species\nCVtemp <- INP2[INP2$index >= 10, ] # select records with index >= 10 for CV calculation\nCVtemp <- CVtemp[!is.na(CVtemp$index), ] # reject missing values\nCV1 <- CVtemp$se/CVtemp$index\nCV1[CV1== 0] <- NA\nCV1[CV1== Inf] <- NA\nspecies2 <- CVtemp$species\nmnCV <- tapply(CV1, species2, mean, na.rm=TRUE)\nplot(uspecies, mnCV, type=\"p\", pch=19, col=\"black\", main=jobname, xlab=\"species code\", ylab=\"meanCV\")\nCV <- as.data.frame(rep(mnCV, each=nyear))\n\n# replace small indices by TRUNC and their SE by zero\nINP3 <- data.frame(cbind(species, year, CV, mnindex1))\ncolnames(INP3) <- c(\"species\",\"year\", \"CV\", \"mnindex1\")\nINP4 <- merge(INP2, INP3, by=c(\"species\",\"year\"), sort=FALSE, all=TRUE)\nINP5 <- subset(INP4, CV < maxCV, select = c(species, year, index, se, mnindex1))\nINP5$index[INP5$index < TRUNC & !is.na(INP5$index)] <- TRUNC \nINP5$se[INP5$index == TRUNC & !is.na(INP5$index)] <- 0\n\n# reset parameters\nindex <- as.vector(INP5[\"index\"])\nse <- as.vector(INP5[\"se\"])\nnobs <- NROW(INP5)\nuspecies <- sort(unique(INP5$species))\nnspecies <- length(uspecies)\nyear <- rep(uyear, nspecies)\n\n# Transform indices and standard deviations to log scale (Delta method)\nLNindex <- as.vector(log(index))\nLNse <- as.vector(se/index)\n\n# Monte Carlo simulations of species indices\nMC <- matrix(NA, nobs, nsim)\nfor (s in 1:nsim) { \n MC[,s] <- rnorm(nobs, LNindex[,1], LNse[,1])\n } \nMC[MC < log(TRUNC)] <- log(TRUNC)\n\n# impute missing values using chain method\nCHAIN <- matrix(NA, nobs, nsim)\nfor (s in 1:nsim ){\n for (o in 1:nobs-1) {\n CHAIN[o,s] <- MC[o+1,s]-MC[o,s]\n }\n for (sp in 1:nspecies) {\n CHAIN[sp*nyear,s] <- NA\n }\n}\n\nCHAIN[CHAIN > log(truncfac)] <- log(truncfac)\nCHAIN[CHAIN < log(1/truncfac)] <- log(1/truncfac)\n\nmnCHAIN <- matrix(NA, nyear, nsim)\nfor (s in 1:nsim) {\n mnCHAIN[,s] <- tapply(CHAIN[,s], year, mean, na.rm=TRUE)\n}\n\nsimMSI <- matrix(NA, nyear, nsim)\nbmin <- baseyear-1\nbplus <- baseyear+1\nfor (s in 1:nsim){\nsimMSI[baseyear,s] <- log(100)\n for (y in bmin:min(bmin,1)){\n simMSI[y,s] <- simMSI[y+1,s] - mnCHAIN[y,s]\n }\n for (y in min(bplus,nyear):nyear){\n simMSI[y,s] <- simMSI[y-1,s] + mnCHAIN[y-1,s]\n }\n}\n\n# calculate MSI and SE\nmeanMSI <- array(NA, dim=c(1, nyear))\nstdevMSI <- array(NA, dim=c(1, nyear)) \nfor (y in 1:nyear) {\n meanMSI[y] <- mean(simMSI[y,])\n stdevMSI[y] <- sd(simMSI[y,])\n}\n\n# Monte Carlo simulations of MSI (for trend calculation)\nsimMSI <- matrix(NA, nyear, nsim)\nfor (s in 1:nsim) { \n for (y in 1:nyear) {\n simMSI[y,s] <- rnorm(1, meanMSI[y], stdevMSI[y])\n } \n}\n\n# Back-transformation of MSI to index scale (Delta method)\nmeanMSI <- array(NA, dim=c(1, nyear))\nstdevMSI <- array(NA, dim=c(1, nyear)) \nfor (y in 1:nyear) {\n meanMSI[y] <- round(exp(mean(simMSI[y,])), digits=2)\n stdevMSI[y] <- round(sd(simMSI[y,])*meanMSI[y], digits=2)\n}\n\n# Confidence interval of MSI on index-scale\nCI <- array(NA, dim=c(nyear, 2))\nfor (y in 1:nyear){\n CI[y,1] <- exp(mean(simMSI[y,])-1.96*sd(simMSI[y,]))\n CI[y,2] <- exp(mean(simMSI[y,])+1.96*sd(simMSI[y,]))\n}\n\n# Overall linear trend per simulation\nlrMSI <- array(NA, dim=c(2, nsim))\nfor (s in 1:nsim) {\n summ <- summary(lm(simMSI[,s] ~ uyear, na.action=na.exclude))\n lrMSI[1,s] <- round(summ$coefficients[2], digits=4)\t# coeff[2] = slope\n lrMSI[2,s] <- round(summ$coefficients[2,2], digits=4) \t# coeff[2,2] = se of slope \n}\nSLOPE <- mean(lrMSI[1,])\nsdSLOPE <- sd(as.vector(lrMSI[1,]))\n\n# Back transform trends to index scale:\nSLOPE_mult <- round(exp(SLOPE), digits=4)\nsdSLOPE_mult <- round(sdSLOPE*SLOPE_mult, digits=4)\n\n# Overall trend classification (see Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nTrendClass <- \"X\"\nif (SLOPE_mult - 1.96*sdSLOPE_mult > 1.05) {TrendClass <- \"strong increase\" } else\n if (SLOPE_mult + 1.96*sdSLOPE_mult < 0.95) { TrendClass <- \"steep decline\" } else\n if (SLOPE_mult - 1.96*sdSLOPE_mult > 1.00) { TrendClass <- \"moderate increase\"} else\n if (SLOPE_mult + 1.96*sdSLOPE_mult < 1.00) { TrendClass <- \"moderate decline\" } else\n if ((SLOPE_mult - 1.96*sdSLOPE_mult - 0.95)*(1.05 - SLOPE_mult + 1.96*sdSLOPE_mult) < 0.00) { TrendClass <- \"uncertain\"} else\n if ((SLOPE_mult + 1.96*sdSLOPE_mult) - (SLOPE_mult - 1.96*sdSLOPE_mult) > 0.10) { TrendClass <- \"uncertain\" } else\n {TrendClass <- \"stable\"}\nTrendClass\n\n# Short term linear trend per simulation\nlrMSI_short <- array(NA, dim=c(2, nsim))\nlyear <- c((maxyear-lastyears+1):maxyear)\nsimMSI_short <- array(NA, dim=c(lastyears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:lastyears) {\n simMSI_short[y, s] <- simMSI[(nyear-lastyears+y),s]\n }\n}\nfor (s in 1:nsim) {\n summ <- summary(lm(simMSI_short[,s] ~ lyear, na.action=na.exclude))\n lrMSI_short[1,s] <- round(summ$coefficients[2], digits=4)\t# coeff[2] = slope\n lrMSI_short[2,s] <- round(summ$coefficients[2,2], digits=4) \t# coeff[2,2] = sd of slope \n}\nSLOPE_short <- mean(lrMSI_short[1,])\nsdSLOPE_short <- sd(as.vector(lrMSI_short[1,]))\n\n# Back-transform short-term trends to index scale\nSLOPE_short_mult <- round(exp(SLOPE_short), digits=4)\nsdSLOPE_short_mult <- round(sdSLOPE_short*SLOPE_short_mult, digits=4)\n\n# Short term trend classification (Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nTrendClass_short <- \"X\"\nif (SLOPE_short_mult - 1.96*sdSLOPE_short_mult > 1.05) {TrendClass_short <- \"strong increase\" } else\n if (SLOPE_short_mult + 1.96*sdSLOPE_short_mult < 0.95) { TrendClass_short <- \"steep decline\" } else\n if (SLOPE_short_mult - 1.96*sdSLOPE_short_mult > 1.00) { TrendClass_short <- \"moderate increase\"} else\n if (SLOPE_short_mult + 1.96*sdSLOPE_short_mult < 1.00) { TrendClass_short <- \"moderate decline\" } else\n if ((SLOPE_short_mult - 1.96*sdSLOPE_short_mult - 0.95)*(1.05 - SLOPE_short_mult + 1.96*sdSLOPE_short_mult) < 0.00) { TrendClass_short <- \"uncertain\"} else\n if ((SLOPE_short_mult + 1.96*sdSLOPE_short_mult) - (SLOPE_short_mult - 1.96*sdSLOPE_short_mult) > 0.10) { TrendClass_short <- \"uncertain\" } else\n {TrendClass_short <- \"stable\"}\nTrendClass_short\n\n# linear trend before changepoint per simulation\nlrMSI_before <- array(NA, dim=c(2, nsim))\nbyear <- c(minyear:changepoint)\nbyears <- length(byear)\nsimMSI_before <- array(NA, dim=c(byears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:byears) {\n simMSI_before[y, s] <- simMSI[y,s]\n }\n}\nfor (s in 1:nsim) {\n summb <- summary(lm(simMSI_before[,s] ~ byear, na.action=na.exclude))\n lrMSI_before[1,s] <- round(summb$coefficients[2], digits=4) # coeff[2] = slope\n lrMSI_before[2,s] <- round(summb$coefficients[2,2], digits=4) \t# coeff[2,2] = sd of slope \n}\nSLOPE_before <- round(mean(lrMSI_before[1,]), digits=5)\nsdSLOPE_before <- round(sd(as.vector(lrMSI_before[1,])), digits=5)\n\n# Back-transform trends before changepoint to index scale\nSLOPE_before_mult <- round(exp(SLOPE_before), digits=4)\nsdSLOPE_before_mult <- round(sdSLOPE_before*SLOPE_before_mult, digits=4)\n\n# Trend classification before changepoint\nTrendClass_before <- \"X\"\nif (SLOPE_before_mult - 1.96*sdSLOPE_before_mult > 1.05) {TrendClass_before <- \"strong increase\" } else\n if (SLOPE_before_mult + 1.96*sdSLOPE_before_mult < 0.95) { TrendClass_before <- \"steep decline\" } else\n if (SLOPE_before_mult - 1.96*sdSLOPE_before_mult > 1.00) { TrendClass_before <- \"moderate increase\"} else\n if (SLOPE_before_mult + 1.96*sdSLOPE_before_mult < 1.00) { TrendClass_before <- \"moderate decline\" } else\n if ((SLOPE_before_mult - 1.96*sdSLOPE_before_mult - 0.95)*(1.05 - SLOPE_before_mult + 1.96*sdSLOPE_before_mult) < 0.00) { TrendClass_before <- \"uncertain\"} else\n if ((SLOPE_before_mult + 1.96*sdSLOPE_before_mult) - (SLOPE_before_mult - 1.96*sdSLOPE_before_mult) > 0.10) { TrendClass_before <- \"uncertain\" } else\n {TrendClass_before <- \"stable\"}\nTrendClass_before\n\n# linear trend after changepoint per simulation\nlrMSI_after <- array(NA, dim=c(2, nsim))\nayear <- c(changepoint:maxyear)\nayears <- length(ayear)\nsimMSI_after <- array(NA, dim=c(ayears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:ayears) {\n simMSI_after[y, s] <- simMSI[(byears-1+y),s]\n }\n}\nfor (s in 1:nsim) {\n summa <- summary(lm(simMSI_after[,s] ~ ayear, na.action=na.exclude))\n lrMSI_after[1,s] <- round(summa$coefficients[2], digits=4) # coeff[2] = slope\n lrMSI_after[2,s] <- round(summa$coefficients[2,2], digits=4) # coeff[2,2] = sd of slope \n}\nSLOPE_after <- round(mean(lrMSI_after[1,]), digits=5)\nsdSLOPE_after <- round(sd(as.vector(lrMSI_after[1,])),digits=5)\n\n# Trend classification before changepoint\nSLOPE_after_mult <- round(exp(SLOPE_after), digits=4)\nsdSLOPE_after_mult <- round(sdSLOPE_after*SLOPE_after_mult, digits=4)\n\n# Trend classification after changepoint\nTrendClass_after <- \"X\"\nif (SLOPE_after_mult - 1.96*sdSLOPE_after_mult > 1.05) {TrendClass_after <- \"strong increase\" } else\n if (SLOPE_after_mult + 1.96*sdSLOPE_after_mult < 0.95) { TrendClass_after <- \"steep decline\" } else\n if (SLOPE_after_mult - 1.96*sdSLOPE_after_mult > 1.00) { TrendClass_after <- \"moderate increase\"} else\n if (SLOPE_after_mult + 1.96*sdSLOPE_after_mult < 1.00) { TrendClass_after <- \"moderate decline\" } else\n if ((SLOPE_after_mult - 1.96*sdSLOPE_after_mult - 0.95)*(1.05 - SLOPE_after_mult + 1.96*sdSLOPE_after_mult) < 0.00) { TrendClass_after <- \"uncertain\"} else\n if ((SLOPE_after_mult + 1.96*sdSLOPE_after_mult) - (SLOPE_after_mult - 1.96*sdSLOPE_after_mult) > 0.10) { TrendClass_after <- \"uncertain\" } else\n {TrendClass_after <- \"stable\"}\nTrendClass_after\n\n# compare linear trends before and after changepoint\ncompare <- array(NA, dim=c(nsim, 1))\nfor (s in 1:nsim){\n compare[s,1] <- lrMSI_after[1,s]-lrMSI_before[1,s]\n}\nmeanTrendDiff <- mean(compare)\nseTrendDiff <- sd(as.vector(compare))\nsignificance <- NA\nif (abs(meanTrendDiff)-2.58*seTrendDiff > 0) { significance <- \"p<0.01\" } else\n if (abs(meanTrendDiff)-1.96*seTrendDiff > 0) { significance <- \"p<0.05\" } else\n {significance <- \"n.s.\"}\n\n# Smoothing\n# span = 0.75 is default in R and usually fits well. But trying other values may give better results, depending on your data\nloessMSI <- array(NA, dim=c(nyear, nsim))\nDiff <- array(NA, dim=c(nyear, nsim))\n# Difftest <- array(NA, dim=c(nyear, nsim))\nfor (s in 1:nsim) {\n smooth <- predict(loess(simMSI[,s]~uyear, span=0.75, degree=2, na.action=na.exclude),\n data.frame(uyear), se=TRUE)\n loessMSI[,s] <- round(smooth$fit, digits=4)\n\n for (y in 1:nyear) {\n Diff[y,s] <- loessMSI[nyear,s] - loessMSI[y,s]\n# Difftest[y,s] <- loessMSI[testyear,s] - loessMSI[y,s]\n } \n}\n\n# calculate overall change (first year set to 100) and change in last years\npct_CHANGE <- array(NA, dim=c(nsim, 2))\nfor (s in 1:nsim) {\npct_CHANGE[s,1] <- exp(loessMSI[nyear,s])*100/exp(loessMSI[1,s])-100\npct_CHANGE[s,2] <- exp(loessMSI[nyear,s])*100/exp(loessMSI[1,s])-exp(loessMSI[(nyear-lastyears+1),s])*100/exp(loessMSI[1,s])\n}\npct_CHANGE_long <- round(mean(pct_CHANGE[,1]),digits=3)\nsd_pct_CHANGE_long <- round(sd(pct_CHANGE[,1]), digits=3)\npct_CHANGE_short <- round(mean(pct_CHANGE[,2]),digits=3)\nsd_pct_CHANGE_short <- round(sd(pct_CHANGE[,2]), digits=3)\n\n# significance of percentage change\nsignificance_PCT_long <- NA\nif (abs(pct_CHANGE_long)-2.58*sd_pct_CHANGE_long > 0) { significance_PCT_long <- \"p<0.01\" } else\n if (abs(pct_CHANGE_long)-1.96*sd_pct_CHANGE_long > 0) { significance_PCT_long <- \"p<0.05\" } else\n {significance_PCT_long <- \"n.s.\"}\nsignificance_PCT_short <- NA\nif (abs(pct_CHANGE_short)-2.58*sd_pct_CHANGE_short > 0) { significance_PCT_short <- \"p<0.01\" } else\n if (abs(pct_CHANGE_short)-1.96*sd_pct_CHANGE_short > 0) { significance_PCT_short <- \"p<0.05\" } else\n {significance_PCT_short <- \"n.s.\"}\n\n# Test for difference in smoothed trend value between each year and 'testyear'\n# YEARTEST <- array(NA, dim=c(nyear, 4))\n# for (y in 1:nyear) {\n# YEARTEST[y,1] <- round(mean(Difftest[y,]), digits=3)\n# YEARTEST[y,2] <- round(sd(Difftest[y,]), digits=3)\n# YEARTEST[y,3] <- round(YEARTEST[y,1]-1.96*YEARTEST[y,2], digits=3)\n# YEARTEST[y,4] <- round(YEARTEST[y,1]+1.96*YEARTEST[y,2], digits=3)\n# }\n\n# create output for flexible trend estimates\nsmoothMSI <- array(NA, dim=c(nyear, 13))\nfor (y in 1:nyear) {\nsmoothMSI[y,1] <- round(mean(loessMSI[y,]), digits=4) # smooth MSI on log scale\nsmoothMSI[y,2] <- round(sd(loessMSI[y,]), digits=4) # SE of smooth MSI on log scale\nsmoothMSI[y,3] <- round(mean(Diff[y,]), digits=4) # Difference smooth MSI with last year on log scale\nsmoothMSI[y,4] <- round(sd(Diff[y,]), digits=4) # SE of difference with ast year\nsmoothMSI[y,12] <- round(smoothMSI[y,1]-1.96*smoothMSI[y,2], digits=2) # lower CI of smooth MSI on log scale\nsmoothMSI[y,13] <- round(smoothMSI[y,1]+1.96*smoothMSI[y,2], digits=2) # upper CI of smooth MSI on log scale\n}\n\n# Trendclassification, based on smoothed trends (Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nfor (y in 1:nyear) {\n smoothMSI[y,5] <- round(smoothMSI[nyear,1]/smoothMSI[y,1], digits=4)\t\t# = TCR\n smoothMSI[y,6] <- round(smoothMSI[y,5]-1.96*(smoothMSI[y,4]/smoothMSI[y,1]), digits=4)\t# = CI- TCR\n smoothMSI[y,7] <- round(smoothMSI[y,5]+1.96*(smoothMSI[y,4]/smoothMSI[y,1]), digits=4)\t# = CI+ TCR\n smoothMSI[y,8] <- round(exp(log(smoothMSI[y,5])/(nyear-y)), digits=4)\t\t# = YCR\n smoothMSI[y,9] <- round(exp(log(smoothMSI[y,6])/(nyear-y)), digits=4)\t\t# = CI- YCR\n smoothMSI[y,10] <- round(exp(log(smoothMSI[y,7])/(nyear-y)), digits=4)\t\t# = CI+ YCR\n}\nfor (y in 1:(nyear-1)) {\n if (smoothMSI[y,9] > 1.05) {smoothMSI[y,11] <- 1} else\n if (smoothMSI[y,10] < 0.95) {smoothMSI[y,11] <- 6} else\n if (smoothMSI[y,9] > 1.00) {smoothMSI[y,11] <- 2} else\n if (smoothMSI[y,10] < 1.00) {smoothMSI[y,11] <- 5} else\n if ((smoothMSI[y,9] - 0.95)*(1.05 - smoothMSI[y,10]) < 0.00) {smoothMSI[y,11] <- 3} else\n if ((smoothMSI[y,10]) - (smoothMSI[y,9]) > 0.10) {smoothMSI[y,11] <- 3} else\n {smoothMSI[y,11] <- 4}\n} \nTrendClass_flex <- matrix(NA, nrow= nyear, ncol=1)\nfor (y in 1:(nyear-1)) {\n if (smoothMSI[y,9] > 1.05) {TrendClass_flex[y] <- \"strong_increase\" } else\n if (smoothMSI[y,10] < 0.95) { TrendClass_flex[y] <- \"steep_decline\" } else\n if (smoothMSI[y,9] > 1.00) { TrendClass_flex[y] <- \"moderate_increase\"} else\n if (smoothMSI[y,10] < 1.00) { TrendClass_flex[y] <- \"moderate_decline\" } else\n if ((smoothMSI[y,9] - 0.95)*(1.05 - smoothMSI[y,10]) < 0.00) { TrendClass_flex[y] <- \"uncertain\"} else\n if ((smoothMSI[y,10]) - (smoothMSI[y,9]) > 0.10) { TrendClass_flex[y] <- \"uncertain\" } else\n {TrendClass_flex[y] <- \"stable\"}\n} \n\n# rescaling (for presentation of plot)\nrescale <- NA\n if (index_smooth ==\"INDEX\") {rescale <- 100/meanMSI[plotbaseyear]} else\n if (index_smooth ==\"SMOOTH\") {rescale <- 100/exp(smoothMSI[plotbaseyear,1])} else\n {rescale <- NA}\nsimMSImean <- round(as.vector(rescale*meanMSI), digits=2)\nsimMSIsd <- round(as.vector(rescale*stdevMSI), digits=2)\nuppCI_MSI <- round(rescale*CI[,2], digits=2)\nlowCI_MSI <- round(rescale*CI[,1], digits=2)\ntrend_flex <- round(rescale*exp(smoothMSI[,1]), digits=2)\nlowCI_trend_flex <- round(rescale*exp(smoothMSI[,12]), digits=2)\nuppCI_trend_flex <- round(rescale* exp(smoothMSI[,13]), digits=2)\n\n# create output file for MSI + smoothed trend\njobnameRESULTS <- paste (jobname, \"_RESULTS.csv\", sep = \"\")\nRES <- as.data.frame(cbind(uyear, simMSImean, simMSIsd, lowCI_MSI, uppCI_MSI, trend_flex, lowCI_trend_flex, uppCI_trend_flex))\nRES$trend_class <- TrendClass_flex\nnames(RES) <- c(\"year\", \"MSI\", \"sd_MSI\", \"lower_CL_MSI\", \"upper_CL_MSI\", \"Trend\", \"lower_CL_trend\", \"upper_CL_trend\", \"trend_class\")\nwrite.csv2(RES, file=jobnameRESULTS, row.names=FALSE, quote=FALSE)\n\n# create output file with all linear trends\nSIMTRENDS <- t(rbind(lrMSI[1,],lrMSI_short[1,]))\njobnameSIMTRENDS <- paste (jobname, \"_SIMTRENDS.csv\", sep = \"\")\nwrite.csv2(SIMTRENDS, file=jobnameSIMTRENDS, row.names=FALSE)\n\n# create output for linear trend estimates and % change\nrownames <- rbind(\"overall trend\",\"SE overall trend\", \"trend last years\", \"SE trend last years\", \"changepoint\",\n \"trend before changepoint\", \"SE trend before changepoint\", \"trend after changepoint\", \"SE trend after changepoint\",\n \"% change\", \"SE % change\", \"% change last years\", \"SE % change last years\")\noutput <- cbind(SLOPE_mult, sdSLOPE_mult, SLOPE_short_mult, sdSLOPE_short_mult,\n changepoint, SLOPE_before_mult, sdSLOPE_before_mult, SLOPE_after_mult, sdSLOPE_after_mult,\n pct_CHANGE_long, sd_pct_CHANGE_long, pct_CHANGE_short, sd_pct_CHANGE_short)\nTRENDS <- as.data.frame(t(output), row.names=rownames)\nTRENDS$significance <- \"\"\nTRENDS[\"changepoint\", \"significance\"] <- significance\nTRENDS[1, \"significance\"] <- TrendClass\nTRENDS[3, \"significance\"] <- TrendClass_short\nTRENDS[6, \"significance\"] <- TrendClass_before\nTRENDS[8, \"significance\"] <- TrendClass_after\nTRENDS[10, \"significance\"] <- significance_PCT_long\nTRENDS[12, \"significance\"] <- significance_PCT_short\nnames(TRENDS) <- c(\"value\", \"significance\")\njobnameTRENDS <- paste (jobname, \"_TRENDS.csv\", sep = \"\")\nwrite.csv2(TRENDS, file=jobnameTRENDS)\n\n# graph without error bars\nlimits <- aes(ymax = simMSImean+simMSIsd, ymin=simMSImean-simMSIsd)\njobnameGRAPH <- paste (jobname, \"_GRAPH.jpg\", sep = \"\")\nx_position <- ifelse(SLOPE>0, maxyear-nyear/1.5, minyear+1)\ny_position <- 50\nlegend10 <- paste(nspecies, \"species\")\nlegend11 <- paste(\"overall trend:\", round(SLOPE_mult*100-100, digits=1), \"% / yr,\", TrendClass)\nlegend12 <- paste(\"last\", lastyears, \"years:\", round(SLOPE_short_mult*100-100, digits=1), \"% / yr,\", TrendClass_short)\nylab <- paste(\"MSI (\",plotbaseyear+minyear-1,\"= 100 )\") \nlastyear01 <- c(rep(0,nyear-lastyears), rep(1,lastyears))\nggplot(RES, aes(x=year, y=MSI))+\n scale_color_manual(values=c(\"blue\", \"dark green\"))+\n geom_point(colour = \"dark green\",size=3)+\n ylim(0, NA)+\n ylab(ylab)+\n ggtitle(jobname)+ \n theme(plot.title = element_text(size = 25, face = \"bold\"),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=20,face=\"bold\"),\n axis.text = element_text(size = 20),\n panel.background = element_blank(),\n panel.border = element_rect(colour = \"black\", fill=NA, size=1))+\n geom_ribbon(aes(ymin=lowCI_trend_flex, ymax=uppCI_trend_flex), alpha=0.2)+\n geom_line(aes(y=trend_flex), colour=\"dark green\", size=1)+\n annotate(\"text\", x=x_position, y=y_position, label = legend10, size=7, fontface=2, hjust=0)+\n annotate(\"text\", x=x_position, y=y_position-15, label = legend11, size=7, hjust=0)+\n annotate(\"text\", x=x_position, y=y_position-30, label = legend12, size=7, hjust=0)\nggsave(jobnameGRAPH)\n\n# graph with error bars\n# limits <- aes(ymax = simMSImean+simMSIsd, ymin=simMSImean-simMSIsd)\njobnameGRAPH2 <- paste (jobname, \"_GRAPH2.jpg\", sep = \"\")\nggplot(RES, aes(x=year, y=MSI))+\n scale_color_manual(values=c(\"blue\", \"dark green\"))+\n geom_point(colour = \"dark green\",size=3)+\n ylim(0, NA)+\n ylab(ylab)+\n ggtitle(jobname)+ \n theme(plot.title = element_text(size = 25, face = \"bold\"),\n axis.title.x=element_blank(),\n axis.title.y=element_text(size=20,face=\"bold\"),\n axis.text = element_text(size = 20),\n panel.background = element_blank(),\n panel.border = element_rect(colour = \"black\", fill=NA, size=1))+\n geom_ribbon(aes(ymin=lowCI_trend_flex, ymax=uppCI_trend_flex), alpha=0.2)+\n geom_line(aes(y=trend_flex), colour=\"dark green\", size=1)+\n geom_pointrange(limits, colour=\"dark green\")+\nannotate(\"text\", x=x_position, y=y_position, label = legend10, size=7, fontface=2, hjust=0)+\nannotate(\"text\", x=x_position, y=y_position-15, label = legend11, size=7, hjust=0)+\nannotate(\"text\", x=x_position, y=y_position-30, label = legend12, size=7, hjust=0)\nggsave(jobnameGRAPH2)\n", "meta": {"hexsha": "4acf60c4867439bf5389de944113373115337591", "size": 22730, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/MSI_30.r", "max_stars_repo_name": "sacrevert/NPMSTrends2", "max_stars_repo_head_hexsha": "9be6d23a729dca086b4392062adca1c9f0ef42a1", "max_stars_repo_licenses": ["MIT"], "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/MSI_30.r", "max_issues_repo_name": "sacrevert/NPMSTrends2", "max_issues_repo_head_hexsha": "9be6d23a729dca086b4392062adca1c9f0ef42a1", "max_issues_repo_licenses": ["MIT"], "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/MSI_30.r", "max_forks_repo_name": "sacrevert/NPMSTrends2", "max_forks_repo_head_hexsha": "9be6d23a729dca086b4392062adca1c9f0ef42a1", "max_forks_repo_licenses": ["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.9535864979, "max_line_length": 168, "alphanum_fraction": 0.6826220853, "num_tokens": 7875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4291760805280773}}
{"text": "library(related)\nlibrary(ggplot2)\n\n# read in genotypes (modify this name as necessary for different colonies or datasets)\nx <- read.table(\"filtered_100kbp.related\", stringsAsFactors=F)\n\n# input species name (e.g., herculeanus, laevigatus, or modoc)\nspecies <- \"laevigatus\"\n\n# input colony number (e.g., 1, 2, or 3)\ncolony_number <- 1\n\n# define number of simulations\nnsims <- 100\n\n# simulations\n# first, obtain overall allele freqs for each locus\n# allow 5% variation of allele frequencies (i.e., a little randomness)\nn_loci <- (ncol(x) - 1) / 2\nalleles <- list()\nallele_freqs <- list()\nfor(a in 1:n_loci) {\n\talleles[[a]] <- c(x[,a * 2], x[,a * 2 + 1])\n\taf1 <- length(alleles[[a]][alleles[[a]] == 1]) / length(alleles[[a]])\n\t# add +/- 5% variation to allele frequencies (some stochasticity for small sample sizes)\n\taf1 <- af1 + sample(seq(from=-0.05, to=0.05, by=0.001), 1)\n\t# make sure the frequency is between 0.01 and 0.99\n\tif(af1 < 0.01) {\n\t\taf1 <- 0.01\n\t} else if (af1 > 0.99) {\n\t\taf1 <- 0.99\n\t}\n\t# change to integer on zero to one hundred scale\n\taf1 <- round(af1, digits=2) * 100\n\taf2 <- 100 - af1\n\tallele_freqs[[a]] <- c(rep(1, af1), rep(5, af2))\n}\n\n# output sim lists\noffspring_sims <- list()\nhalf_sibs <- list()\nunrelated <- list()\n# loop for simulations (this may take up to 30-60 minutes)\nfor(a in 1:nsims) {\n\tif(a %% 10 == 0) {\n\t\twriteLines(paste(\"Simulation \", a, \" started.\", sep=\"\"))\n\t}\n\t\n\t# generate a haploid male\n\tmale <- list()\n\tfor(b in 1:n_loci) {\n\t\tmale[[b]] <- sample(allele_freqs[[b]], 1)\n\t}\n\tmale <- unlist(male)\n\t\n\t# sample a diploid female\n\tfemale_1 <- list()\n\tfemale_2 <- list()\n\tfor(b in 1:n_loci) {\n\t\tfemale_1[[b]] <- sample(allele_freqs[[b]], 1)\n\t\tfemale_2[[b]] <- sample(allele_freqs[[b]], 1)\n\t}\n\tfemale_1 <- unlist(female_1)\n\tfemale_2 <- unlist(female_2)\n\t\n\t# create 1st offspring of the two parents\n\toffspring1 <- list()\n\tfor(b in 1:length(female_1)) {\n\t\toffspring1[[b]] <- sort(c(male[b], sample(c(female_1[b], female_2[b]), 1)))\n\t}\n\toffspring1 <- unlist(offspring1)\n\n\t# create 2nd offspring of the two parents\n\toffspring2 <- list()\n\tfor(b in 1:length(female_1)) {\n\t\toffspring2[[b]] <- sort(c(male[b], sample(c(female_1[b], female_2[b]), 1)))\n\t}\n\toffspring2 <- unlist(offspring2)\n\t\n\t# combine two offspring's data into one dataframe\n\tsim <- as.data.frame(cbind(c(paste(\"offspring1__\", a, sep=\"\"), paste(\"offspring2__\", a, sep=\"\")), rbind(offspring1, offspring2)))\n\t# make sure the first column of sim is character\n\tsim[,1] <- as.character(sim[,1])\n\t# add to offspring sims\n\toffspring_sims[[a]] <- sim\n\t\n\t# for half sib relationships with queen and two males mated\n\t# generate a second haploid male\n\tmale2 <- list()\n\tfor(b in 1:n_loci) {\n\t\tmale2[[b]] <- sample(allele_freqs[[b]], 1)\n\t}\n\tmale2 <- unlist(male2)\n\n\t# create 1st offspring of the one female and male 1\n\thalfsib1 <- list()\n\tfor(b in 1:length(female_1)) {\n\t\thalfsib1[[b]] <- sort(c(male[b], sample(c(female_1[b], female_2[b]), 1)))\n\t}\n\thalfsib1 <- unlist(halfsib1)\n\t\n\t# create 2nd offspring of the one female, but mated to male 2\n\thalfsib2 <- list()\n\tfor(b in 1:length(female_1)) {\n\t\thalfsib2[[b]] <- sort(c(male2[b], sample(c(female_1[b], female_2[b]), 1)))\n\t}\n\thalfsib2 <- unlist(halfsib2)\n\t\n\t# combine two halfsib's data into one dataframe\n\tsim <- as.data.frame(cbind(c(paste(\"halfsib1__\", a, sep=\"\"), paste(\"halfsib2__\", a, sep=\"\")), rbind(halfsib1, halfsib2)))\n\t# make sure the first column of sim is character\n\tsim[,1] <- as.character(sim[,1])\n\t# add to halfsib sims\n\thalf_sibs[[a]] <- sim\n\t\n\t# unrelated individuals\n\t# sample a random genotype (x2) from the allele freqs\n\trandom_1 <- list()\n\trandom_2 <- list()\n\tfor(b in 1:n_loci) {\n\t\trandom_1[[b]] <- sample(allele_freqs[[b]], 2)\n\t\trandom_2[[b]] <- sample(allele_freqs[[b]], 2)\n\t}\n\trandom_1 <- unlist(random_1)\n\trandom_2 <- unlist(random_2)\n\t\n\t# combine two randoms' data into one dataframe\n\tsim <- as.data.frame(cbind(c(paste(\"unrelated1__\", a, sep=\"\"), paste(\"unrelated2__\", a, sep=\"\")), rbind(random_1, random_2)))\n\t# make sure the first column of sim is character\n\tsim[,1] <- as.character(sim[,1])\n\t# add to unrelated sims\n\tunrelated[[a]] <- sim\n}\n\n# add all real and simulated data into a single data frame for relatedness estimates\ntotal <- x\noffspring_sims2 <- do.call(\"rbind\", offspring_sims)\nhalf_sibs2 <- do.call(\"rbind\", half_sibs)\nunrelated2 <- do.call(\"rbind\", unrelated)\ntotal <- rbind(total, offspring_sims2, half_sibs2, unrelated2)\n\n# clean up objects no longer needed and clean up garbage\nrm(offspring_sims2, half_sibs2, unrelated2, offspring_sims, half_sibs, unrelated)\n\n# measure relatedness of all real and simulated individuals (this may take up to 30-60 minutes)\ntotal_relate <- coancestry(total, lynchli=2, wang=2)\n\n# extract point estimates of relatedness for each grouping\n# real data\nreal_data_relatedness <- total_relate$relatedness[total_relate$relatedness$group == \"C-C-\",]\nreal_data_95CI <- total_relate$relatedness.ci95[total_relate$relatedness.ci95$group == \"C-C-\",]\n\n# full sister simulations\nfull_sister_relatedness <- total_relate$relatedness[total_relate$relatedness$group == \"ofof\",]\nfull_sister_relatedness <- full_sister_relatedness[sapply(strsplit(full_sister_relatedness[,2], \"__\"), \"[[\", 2) == sapply(strsplit(full_sister_relatedness[,3], \"__\"), \"[[\", 2), ]\n\n# half sister simulations\nhalf_sister_relatedness <- total_relate$relatedness[total_relate$relatedness$group == \"haha\",]\nhalf_sister_relatedness <- half_sister_relatedness[sapply(strsplit(half_sister_relatedness[,2], \"__\"), \"[[\", 2) == sapply(strsplit(half_sister_relatedness[,3], \"__\"), \"[[\", 2), ]\n\n# unrelated individuals simulations\nunrelated_relatedness <- total_relate$relatedness[total_relate$relatedness$group == \"unun\",]\nunrelated_relatedness <- unrelated_relatedness[sapply(strsplit(unrelated_relatedness[,2], \"__\"), \"[[\", 2) == sapply(strsplit(unrelated_relatedness[,3], \"__\"), \"[[\", 2), ]\n\n\n# save the work\nsave.image(paste(species, \"__\", colony_number, \"__relatedness.RData\", sep=\"\"))\n\n# make a merged data frame for boxplots of simulations\nfull_sister_related <- data.frame(Relationship=as.character(rep(\"Full Sister\", nrow(full_sister_relatedness)*2)), Measurement=as.character(c(rep(\"Wang (2002)\", nrow(full_sister_relatedness)), rep(\"Li et al. (1993)\", nrow(full_sister_relatedness)))), Relatedness=as.numeric(c(full_sister_relatedness$wang, full_sister_relatedness$lynchli)))\nhalf_sister_related <- data.frame(Relationship=as.character(rep(\"Half Sister\", nrow(half_sister_relatedness)*2)), Measurement=as.character(c(rep(\"Wang (2002)\", nrow(half_sister_relatedness)), rep(\"Li et al. (1993)\", nrow(half_sister_relatedness)))), Relatedness=as.numeric(c(half_sister_relatedness$wang, half_sister_relatedness$lynchli)))\nunrelated_sister_related <- data.frame(Relationship=as.character(rep(\"Unrelated\", nrow(unrelated_relatedness)*2)), Measurement=as.character(c(rep(\"Wang (2002)\", nrow(unrelated_relatedness)), rep(\"Li et al. (1993)\", nrow(unrelated_relatedness)))), Relatedness=as.numeric(c(unrelated_relatedness$wang, unrelated_relatedness$lynchli)))\n\n# combine the three into one\ntotal_related <- rbind(full_sister_related, half_sister_related, unrelated_sister_related)\n\n# make a boxplot\nggplot(total_related, aes(x=Relationship, y=Relatedness, fill=Measurement)) + geom_boxplot()\n\n# save a pdf of the boxplot (change the name as necessary)\npdf(file=paste(species, \"__\", colony_number, \"__simboxplot.pdf\", sep=\"\"), width=5, height=7)\nggplot(total_related, aes(x=Relationship, y=Relatedness, fill=Measurement)) + geom_boxplot()\ndev.off()\n\n\n# combine the real data into a nice data matrix and save the table\nreal_data_output <- data.frame(Ind1=as.character(real_data_relatedness$ind1.id),\n\t\t\t\t\t\t\t Ind2=as.character(real_data_relatedness$ind2.id),\n\t\t\t\t\t\t\t Species=as.character(species),\n\t\t\t\t\t\t\t Colony=as.character(colony_number),\n\t\t\t\t\t\t\t Wang=as.numeric(real_data_relatedness$wang),\n\t\t\t\t\t\t\t Wang_low=as.numeric(real_data_95CI$wang.low),\n\t\t\t\t\t\t\t Wang_high=as.numeric(real_data_95CI$wang.high),\n\t\t\t\t\t\t\t Li=as.numeric(real_data_relatedness$lynchli),\n\t\t\t\t\t\t\t Li_low=as.numeric(real_data_95CI$lynchli.low),\n\t\t\t\t\t\t\t Li_high=as.numeric(real_data_95CI$lynchli.high))\n# print the matrix to look at\nreal_data_output\n# write the matrix to table\nwrite.table(real_data_output, file=paste(species, \"__\", colony_number, \"__relatedness.txt\", sep=\"\"), sep=\"\\t\",\n\t\t\tquote=F, col.names=T, row.names=F)\n\n\n", "meta": {"hexsha": "969e0f0761ef4ab6633473eb053daec8ab332e96", "size": 8372, "ext": "r", "lang": "R", "max_stars_repo_path": "07_relatedness_per_colony.r", "max_stars_repo_name": "jdmanthey/camponotus_relatedness", "max_stars_repo_head_hexsha": "f728f60a1cbecf379a7fbd86dbfa130325c6fe53", "max_stars_repo_licenses": ["MIT"], "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_relatedness_per_colony.r", "max_issues_repo_name": "jdmanthey/camponotus_relatedness", "max_issues_repo_head_hexsha": "f728f60a1cbecf379a7fbd86dbfa130325c6fe53", "max_issues_repo_licenses": ["MIT"], "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_relatedness_per_colony.r", "max_forks_repo_name": "jdmanthey/camponotus_relatedness", "max_forks_repo_head_hexsha": "f728f60a1cbecf379a7fbd86dbfa130325c6fe53", "max_forks_repo_licenses": ["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.0392156863, "max_line_length": 339, "alphanum_fraction": 0.7105828954, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42914988424042644}}
{"text": "#!/usr/bin/env Rscript\n#autor: Joao Sollari Lopes\n#local: University of Reading, Reading, UK\n#Rversion: 3.2.3\n#criado: 01.03.2010\n#modificado: 20.11.2017\n\n# @arg data_file - file with summary of 'real' data (.trg)\n# @arg rej_file - file with rejection step results (.rej)\n# @arg pri_file - file with sample of priors (.pri)\nreg_step <- function(data_file , rej_file , pri_file){\n\n\t#import libraries\n\tlibrary(locfit)\n\tlibrary(nnet)\n library(abc)\n\n\t#import Mark Beaumont's scripts\n\tsource(\"make_pd2.r\")\n\n\t#demographic parameters' priors (minimum and maximum values)\n\tmintev <- 0\n\tmaxtev <- 10000\n\tminNe1 <- 0\n\tmaxNe1 <- 12500\n\tminNe2 <- 0\n\tmaxNe2 <- 40000\n\tminNeA <- 0\n\tmaxNeA <- 10000\n\tminmig1 <- 0\n\tmaxmig1 <- 0.0005\n\tminmig2 <- 0\n\tmaxmig2 <- 0.0005\n\n truetev <- 5000\n trueNe1 <- 10000\n trueNe2 <- 20000\n trueNeA <- 5000\n truemig1 <- 0.0001\n truemig2 <- 0.0001\n\n\t#import the .rej file\n\tabc.rej <- data.matrix(read.table(rej_file))\n\n\t#import the .pri files\n\tpriors <- data.matrix(read.table(pri_file))\n\n\t#import the .trg files\n\ttarget <- data.matrix(read.table(data_file))\n\n\t# Plot line for splitting time and save it in a .eps file\n\tabc.reg.tev <- makepd4(target,abc.rej[,7],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.tev <- abc(target,abc.rej[,7],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/tev_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.tev$x,weight=abc.reg.tev$wt,xlim=c(mintev,maxtev)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"tev\",col=\"blue\")\n\tlines(locfit(~abc.nn.tev$adj.values,weight=abc.nn.tev$weights,xlim=c(mintev,maxtev)),col=\"purple\")\n\tlines(locfit(~priors[,7],xlim=c(mintev,maxtev)),col=\"black\")\n abline(v=truetev,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"tev done.\")\n\n\t# Plot line for effective size of population 1 and save it in a .eps file\n\tabc.reg.ne1 <- makepd4(target,abc.rej[,8],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.ne1 <- abc(target,abc.rej[,8],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/Ne1_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.ne1$x,weight=abc.reg.ne1$wt,xlim=c(minNe1,maxNe1)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"Ne1\",col=\"blue\")\n\tlines(locfit(~abc.nn.ne1$adj.values,weight=abc.nn.ne1$weights,xlim=c(minNe1,maxNe1)),col=\"purple\")\n\tlines(locfit(~priors[,8],xlim=c(minNe1,maxNe1)),col=\"black\")\n abline(v=trueNe1,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"Ne1 done.\")\n\n\t# Plot line for effective size of population 2 and save it in a .eps file\n\tabc.reg.ne2 <- makepd4(target,abc.rej[,9],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.ne2 <- abc(target,abc.rej[,9],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/Ne2_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.ne2$x,weight=abc.reg.ne2$wt,xlim=c(minNe2,maxNe2)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"Ne2\",col=\"blue\")\n\tlines(locfit(~abc.nn.ne2$adj.values,weight=abc.nn.ne2$weights,xlim=c(minNe2,maxNe2)),col=\"purple\")\n\tlines(locfit(~priors[,9],xlim=c(minNe2,maxNe2)),col=\"black\")\n abline(v=trueNe2,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"Ne2 done.\")\n\n\t# Plot line for effective size of ancestor population and save it in a .eps file\n\tabc.reg.nea <- makepd4(target,abc.rej[,10],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.nea <- abc(target,abc.rej[,10],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/NeA_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.nea$x,weight=abc.reg.nea$wt,xlim=c(minNeA,maxNeA)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"NeA\",col=\"blue\")\n\tlines(locfit(~abc.nn.nea$adj.values,weight=abc.nn.nea$weights,xlim=c(minNeA,maxNeA)),col=\"purple\")\n\tlines(locfit(~priors[,10],xlim=c(minNeA,maxNeA)),col=\"black\")\n abline(v=trueNeA,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"NeA done.\")\n\n\t# Plot line for migration rate of population 1 and save it in a .eps file\n\tabc.reg.mig1 <- makepd4(target,abc.rej[,11],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.mig1 <- abc(target,abc.rej[,11],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/mig1_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.mig1$x,weight=abc.reg.mig1$wt,xlim=c(minmig1,maxmig1)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"mig1\",col=\"blue\")\n\tlines(locfit(~abc.nn.mig1$adj.values,weight=abc.nn.mig1$weights,xlim=c(minmig1,maxmig1)),col=\"purple\")\n\tlines(locfit(~priors[,11],xlim=c(minmig1,maxmig1)),col=\"black\")\n abline(v=truemig1,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"mig1 done.\")\n\n\t# Plot line for migration rate of population 2 and save it in a .eps file\n\tabc.reg.mig2 <- makepd4(target,abc.rej[,12],abc.rej[,13:21],tol=1,rej=F,transf=\"log\")\n\tabc.nn.mig2 <- abc(target,abc.rej[,12],abc.rej[,13:21],tol=1,method=\"neuralnet\",transf=\"log\")\n fname <- \"../results/mig2_reg.eps\"\n postscript(file=fname,width=7,height=7,colormodel=\"rgb\",horizontal=FALSE,onefile=FALSE,paper=\"special\")\n\tplot(locfit(~abc.reg.mig2$x,weight=abc.reg.mig2$wt,xlim=c(minmig2,maxmig2)),main=\"prior (black) and posterior (blue) distributions\",xlab=\"mig2\",col=\"blue\")\n\tlines(locfit(~abc.nn.mig2$adj.values,weight=abc.nn.mig2$weights,xlim=c(minmig2,maxmig2)),col=\"purple\")\n\tlines(locfit(~priors[,12],xlim=c(minmig2,maxmig2)),col=\"black\")\n abline(v=truemig2,lty=2,col=\"black\")\n\tdev.off()\n\tprint(\"mig2 done.\")\n\n}\n\nargs = commandArgs(trailingOnly=TRUE)\nreg_step(args[1],args[2],args[3])\n", "meta": {"hexsha": "6213a7defdca84cddae547c5eac2b79097aa1eb1", "size": 5929, "ext": "r", "lang": "R", "max_stars_repo_path": "practicals/practical6/bin/practical6.r", "max_stars_repo_name": "jsollari/IABC2017", "max_stars_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practicals/practical6/bin/practical6.r", "max_issues_repo_name": "jsollari/IABC2017", "max_issues_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practicals/practical6/bin/practical6.r", "max_forks_repo_name": "jsollari/IABC2017", "max_forks_repo_head_hexsha": "d69ba6a9b4fb25f8bdcb56a9dd9ecb7ad93e6545", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6850393701, "max_line_length": 156, "alphanum_fraction": 0.7004553888, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933491161065, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4291488628849238}}
{"text": "# Demo 3: T tests and ANOVA\n# Example script for handout\n# Heini Saarimäki 2.10.2014\n\n# -----\n\n# 1. Data preparations and descriptive statistics\n\n# ---\n\n# 1.2 Load and prepare your data\n\nsetwd('Z:/Desktop/Demo3')\n\ndeprivation <- read.csv('http://becs.aalto.fi/~heikkih3/deprivation.csv')\n\n# Look at the data:\n\nhead(deprivation)\t\t# 10 variables\ndim(deprivation)\t\t# 47 rows (i.e. 47 participants, one per row)\n\nsummary(deprivation)\t\n\n# categorical variables ID, age and education are not yet coded as factors\n# --> change ID, age and education to factors\n\ndeprivation$ID <- factor(deprivation$ID)\ndeprivation$age <- factor(deprivation$age)\ndeprivation$education <- factor(deprivation$education)\n\nsummary(deprivation)\t# looks allright now\n\n# look for missing values:\n\nsummary(deprivation)\nboxplot(deprivation[5:7])\t# take boxplot for digit symbol scores at all time points\nboxplot(deprivation[8:10])\t# similar boxplot for benton error scores\n\n# no very extreme outliers (at least no wrongly coded missing values)\n# so no missing values in the data, no need to correct these\n\n# when you're happy with how the data looks like, use attach:\n\nattach(deprivation)\n\n# ---\n\n# 1.3 Describe your data\n\n# check frequencies for each group in all categorical variables:\n\nsummary(deprivation[2:4])\n\n# you can also check for contingency tables:\n\ntable(age,education)\ntable(age, ht_group)\ntable(education, ht_group)\n\n# table of descriptive statistics for continuous variables:\n\nlibrary('psych')\t\t\t# load package 'psych' to get describe function\ndescribe(deprivation[5:10])\t# take descriptive statistics\n\n# if you want to save the descriptive stats table for further use:\n\ndeprivation.descriptives <- describe(deprivation[5:10])\nwrite.csv(deprivation.descriptives, \"deprivation_descriptives.csv\")\n\n# plot continuous variables:\n\nlayout(matrix(c(1,2,3,4,5,6),3,2))\t\t# create 6-cell display first\nboxplot(digitsymbol_1, ylim=c(0,80), main=\"Digit symbol score, time 1\")\nboxplot(digitsymbol_2, ylim=c(0,80), main=\"Digit symbol score, time 2\")\nboxplot(digitsymbol_3, ylim=c(0,80), main=\"Digit symbol score, time 3\")\nboxplot(bentonerror_1, ylim=c(0,14), main=\"Benton error score, time 1\")\nboxplot(bentonerror_2, ylim=c(0,14), main=\"Benton error score, time 2\")\nboxplot(bentonerror_3, ylim=c(0,14), main=\"Benton error score, time 3\")\n\n# -----\n\n\n\n# 2. Distributions\n\n# 2.1 Normal distribution\n\n# the original distribution of 10000 samples of random integers between 0 and 10 is uniform:\n\nhist(runif(10000)*10, main=\"\") # here, runif function creates your simulated values\n\n# calculate mean for 10000 samples of 5 integers between 0 and 10 using for-loop:\n\nmeans <- numeric(10000)\nfor (i in 1:10000) {means[i] <- mean(runif(5)*10) }\n\n# finally, see how these means are normally distributed:\n\nhist(means, ylim=c(0,1600))\n\n# let's add a normal curve:\n\nh <- hist(means, freq=F, ylim=c(0,0.35))\nx <- seq(min(h$breaks),max(h$breaks), by=0.1)\ny <- dnorm(x, mean=mean(means), sd=sd(means))\nlines(x,y,col=\"red\", lty=\"dashed\", lwd=3)\n\n# ---\n\n# 2.2 Student's t-distribution\n\n# create a vector that includes simulated values between -4 and 4:\n\nsimu <- seq(-4,4,0.01)\n\n# draw a normal distribution:\n\nplot(simu, dnorm(simu), type=\"l\", lty=2, ylab=\"Probability density\", xlab=\"Deviates\")\n\n# add t-distributions for different sample sizes \n\nlines(simu, dt(simu, df=5), col=\"red\")\t\t# sample size 5\nlines(simu, dt(simu, df=10), col=\"green\")\t\t# sample size 10\nlines(simu, dt(simu, df=20), col=\"yellow\")\t# sample size 20\nlines(simu, dt(simu, df=30), col=\"blue\")\t\t# sample size 30\nlines(simu, dt(simu, df=100), col=\"grey\")\t\t# sample size 100\n\n# notice that when sample size increases to 30 and beyond, t-distribution resembles normal distribution\n\n# ---\n\n# 2.3 F-distribution\n\n# create a vector that includes simulated values between 0 and 4\n\nsimu2 <- seq(0,4,0.01)\n\n# draw an F-distribution with degrees of freedom 1 and 1:\n\nplot(simu2, df(simu2, 1,1), type=\"l\", lty=2, ylab=\"Probability density\", xlab=\"Deviates\")\n\n# try changing each degrees of freedom:\n\nlines(simu2, df(simu2, 1,10), col=\"red\")\t\t# df1 = 1, df2 = 10\nlines(simu2, df(simu2, 1,40), col=\"magenta\")\t# df1 = 1, df2 = 40\n\nlines(simu2, df(simu2, 2,40), col=\"blue\")\t\t# df1 = 2, df2 = 40\nlines(simu2, df(simu2, 3,40), col=\"cyan\")\t\t# df1 = 3, df2 = 40\nlines(simu2, df(simu2, 4,40), col=\"green\")\t# df1 = 4, df2 = 40\n\n# -----\n\n# 3. Tests for normality\n\n# descriptive statistics:\n\ndescribe(deprivation[5:10])\t\t# look for mean, median, skewness\n# for normality, mean should be close to median and skewness close to 0\n\n# histograms:\n\nlayout(matrix(c(1,2,3,4,5,6), 3,2))\t\t\t# set layout to 6-cell\nhist(digitsymbol_1, main=\"Digit symbol 1\")\nhist(digitsymbol_2, main=\"Digit symbol 2\")\nhist(digitsymbol_3, main=\"Digit symbol 3\")\nhist(bentonerror_1, main=\"Benton error 1\")\nhist(bentonerror_2, main=\"Benton error 2\")\nhist(bentonerror_3, main=\"Benton error 3\")\n\n# note the skewness in Benton error scores\n\n# use quantile-quantile plots (observed values = dots should be close to line)\n\nqqnorm(digitsymbol_1)\nqqline(digitsymbol_1)\n\n# tests for normality:\n\n# Kolmogorov-Smirnov for Digit symbol score time 1:\nks.test(digitsymbol_1, \"pnorm\", mean=mean(digitsymbol_1), sd=sd(digitsymbol_1))\n# suggests normality\n\n# Shapiro-Wilk:\nshapiro.test(digitsymbol_1)\n# suggests normality\n\n# ---\n\n# 3.1 Exercises\n\n# Question 1\n\nlayout(matrix(c(1,2,3,4,5,6), 3,2))\t\t\t# set layout to 6-cell\nqqnorm(digitsymbol_1, main=\"Digit symbol 1\")\nqqline(digitsymbol_1)\nqqnorm(digitsymbol_2, main=\"Digit symbol 2\")\nqqline(digitsymbol_2)\nqqnorm(digitsymbol_3, main=\"Digit symbol 3\")\nqqline(digitsymbol_3)\nqqnorm(bentonerror_1, main=\"Benton error 1\")\nqqline(bentonerror_1)\nqqnorm(bentonerror_2, main=\"Benton error 2\")\nqqline(bentonerror_2)\nqqnorm(bentonerror_3, main=\"Benton error 3\")\nqqline(bentonerror_3)\n\n# all variables look relatively normally distributed\n\n# -\n\n# Question 2\n\n# Digit symbol time point 1:\nks.test(digitsymbol_1, \"pnorm\", mean=mean(digitsymbol_1), sd=sd(digitsymbol_1))\nshapiro.test(digitsymbol_1)\n# --> normally distributed\n\n# Digit symbol time point 2:\nks.test(digitsymbol_2, \"pnorm\", mean=mean(digitsymbol_2), sd=sd(digitsymbol_2))\nshapiro.test(digitsymbol_2)\n# --> normally distributed\n\n# Digit symbol time point 3:\nks.test(digitsymbol_3, \"pnorm\", mean=mean(digitsymbol_3), sd=sd(digitsymbol_3))\nshapiro.test(digitsymbol_3)\n# --> normally distributed\n\n# Benton error time point 1:\nks.test(bentonerror_1, \"pnorm\", mean=mean(bentonerror_1), sd=sd(bentonerror_1))\nshapiro.test(bentonerror_1)\n# --> normally distributed\n\n# Benton error time point 2:\nks.test(bentonerror_2, \"pnorm\", mean=mean(bentonerror_2), sd=sd(bentonerror_2))\nshapiro.test(bentonerror_2)\n# --> KS suggests normality SW does not\n\n# Benton error time point 3:\nks.test(bentonerror_3, \"pnorm\", mean=mean(bentonerror_3), sd=sd(bentonerror_3))\nshapiro.test(bentonerror_3)\n# --> KS suggests normality SW does not\n\n# Benton error scores at times 2 and 3 might not be normally distributed.\n# For t tests and ANOVA we assume normality, so this assumption might not\n# be fulfilled in these two variables.\n# You might want to consider non-parametric tests.\n\n# However, here for practice purpose, we consider all variables normally distributed.\n\n# -----\n\n# 4 T tests\n\n# --\n\n# 4.1 One-sample t test\n\n# compare sample mean to population mean:\n\nsummary(digitsymbol_1)\t\t# sample mean 42.23, population mean 40\n\n# is this difference statistically significant?\n# use one-sample t-test:\n\nt.test(digitsymbol_1, mu=40)\n\n# --> mean of our sample does not differ from population mean (t(46)=1.33, p>.05)\n\n# ---\n\n# 4.2 Independent samples t-test\n\n# take t test for age differences in Digit symbol score time 1:\n\nt.test(digitsymbol_1 ~ age)\t# categorical variable after ~ \n\n# --> mean in the two age groups does not differ (t(35)=0.27, p>.05)\n\n# without correction for equality of variances:\n\nt.test(digitsymbol_1 ~ age, var.equal=T)\n\n# in this case the results are the same regardless of the equality variances assumption\n\n# visualize results:\n\nboxplot(digitsymbol_1 ~ age, xlab=\"Age group\", ylab=\"Digit symbol score\")\n\n# ---\n\n# 4.3 Repeated-measures t-test\n\n# take t test for Digit score differences between time points 1 and 2:\n\nt.test(digitsymbol_1, digitsymbol_2, paired=T)\n\n# --> no differences between time points 1 and 2 (t(46)=-0.79, p>.05)\n\n# visualize results:\n\nboxplot(digitsymbol_1, digitsymbol_2, ylab=\"Digit symbol score\", xlab=\"Time point\")\n\n# ---\n\n# 4.4 Exercises\n\n# Question 3\n\n# (i) Differences in Digit symbol baseline performance between hormone treatment groups?\n\nt.test(digitsymbol_1 ~ ht_group)\t\n\n# --> no differences (t(44)=-0.17, p>.05)\n\n# (ii) Differences in Benton error baseline performance between hormone treatment groups?\n\nt.test(bentonerror_1 ~ ht_group) \n\n# --> control group has higher number of errors (t(45)=3.01, p<.01)\n\n# use boxplot to visualize this result:\n\nboxplot(bentonerror_1 ~ ht_group, xlab=\"Hormone treatment\", ylab=\"Benton error score\")\n\n# -\n\n# Question 4\n\n# (i) Differences in Digit symbol scores between times 1 and 3\n\nt.test(digitsymbol_1, digitsymbol_3, paired=T)\nboxplot(digitsymbol_1, digitsymbol_3, xlab=\"Time point\", ylab=\"Digit symbol score\")\n\n# --> test scores are higher at time 3 (t(46)=-6.94, p<.001)\n# interpretation: test scores improve due to learning? (from 1st to 3rd measurement)\n\n# (ii) Differences in Digit symbol scores between times 2 and 3\n\nt.test(digitsymbol_2, digitsymbol_3, paired=T)\nboxplot(digitsymbol_2, digitsymbol_3, xlab=\"Time point\", ylab=\"Digit symbol score\")\n\n# --> test scores are higher at time 3 (t(46)=-10.60, p<.001)\n# interpretation: test scores improve after a night of normal sleep\n\n# -\n\n# Question 5\n\n# (i) Differences in Benton error scores between times 1 and 2\n\nt.test(bentonerror_1, bentonerror_2, paired=T)\n\n# --> no differences (t(46)=1.53, p>.05)\n# interpretation: no effect of sleep deprivation on error rate (maybe learning effect cancels this effect?)\n\n# (ii) Differences in Benton error scores between times 1 and 3\n\nt.test(bentonerror_1, bentonerror_3, paired=T)\nboxplot(bentonerror_1,bentonerror_3, xlab=\"Time point\", ylab=\"Benton error score\")\n\n# --> error rates are lower at time 3 (t(46)=5.83, p<.001)\n# interpretation: error rates improve due to learning? (from 1st to 3rd measurement)\n\n# (iii) Differences in Benton error scores between times 2 and 3\n\nt.test(bentonerror_2, bentonerror_3, paired=T)\nboxplot(bentonerror_2, bentonerror_3, xlab=\"Time point\", ylab=\"Benton error score\")\n\n# --> error rates are lower at time 3 (t(46)=5.99, p<.001)\n# interpretation: test scores improve after a night of normal sleep\n\n\n# -----\n\n# 5. Analysis of variance\n\n# --\n\n# 5.1 One-way ANOVA\n\n# Does baseline performance in Digit symbol task vary between education groups?\n\nA1 <- aov(digitsymbol_1 ~ education)\nsummary(A1)\n\n# --> no differences between groups (F(2,44)=2.16, p>.05)\n\nmodel.tables(A1, \"means\")\t# mean score for each group\n\n# visualize results:\n\nboxplot(digitsymbol_1 ~ education, xlab = \"Education group\", ylab=\"Digit symbol score\",\tmain=\"Baseline Digit symbol score by education group\", col=\"grey\")\n\n# get diagnostic plots:\n\nlayout(matrix(c(1,2,3,4),2,2))\nplot(A1)\n\n# --\n\n# 5.1.1 ANOVA assumptions\n\n# test for homogeneity of variances:\n\ninstall.packages('car')\nlibrary('car')\nleveneTest(digitsymbol_1 ~ education)\nbartlett.test(digitsymbol_1 ~ education)\n\n# variances are equal in Digit symbol task at time point 1\n\n# --\n\n# 5.1.2 Visualizing results\n\n# familiar box plot:\n\nboxplot(digitsymbol_1 ~ education)\n\n# means with confidence intervals:\n\ninstall.packages('gplots')\nlibrary('gplots')\nplotmeans(digitsymbol_1 ~ education, ylim=c(10,70), n.label=FALSE)\n\n# ---\n\n# 5.2 Two-way between subject ANOVA\n\n# Does Digit symbol baseline performance differ between age and hormone treatment groups?\n\nA2 <- aov(digitsymbol_1 ~ age*ht_group)\nsummary(A2)\nmodel.tables(A2, \"means\")\nlayout(matrix(c(1,2,3,4),2,2))\nplot(A2)\n\n# --> no age main effect (F(1,43)=0.08, p>.05)\n# --> no hormone treatment main effect (F(1,43)=0.89, p>.05)\n# --> age and hormone treatment have a significant interaction effect (F(1,43)=6.81, p<.05)\n\n# visualize results:\n\nboxplot(digitsymbol_1 ~ age*ht_group, col=c(\"green\", \"grey\"))\t# not very clear..\n\ninteraction.plot(age, ht_group, digitsymbol_1, type=\"b\", col=c(1:3),\n\tleg.bty=\"o\", leg.bg=\"beige\", lwd=2, pch=c(18,24,22), \n\txlab=\"Age group\", ylab=\"Digit symbol score\", main=\"Interaction plot\")\n\n# --\n\n# 5.2.1 Type of Sums of Squares\n\nlibrary(car)\nAnova(A2, type=3)\t\t\t# ANOVA with type 3 sums of squares\n\n# --\n\n# 5.2.2 Post-hoc comparisons\n\n# Test where are the differences you found in ANOVA between age and hormone treatment effects:\n\npairwise.t.test(digitsymbol_1, education, p.adj=\"none\")\npairwise.t.test(digitsymbol_1, education, p.adj=\"bonf\")\t# Bonferroni correction\t\npairwise.t.test(digitsymbol_1, education, p.adj=\"holm\")\t# Holm correction\n\nTukeyHSD(A1)\t\t\t\t\t\t\t\t# Tukey's test\n\n# ---\n\n# 5.3 Exercises\n\n# Question 6\n\n# Does hormone treatment affect Digit symbol baseline differently in different education groups?\n\nanova1 <- aov(digitsymbol_1~ht_group*education)\nsummary(anova1)\n\n# --> no it does not, because interaction effect is nonsignificant (F(2,41)=1.24, p>.05)\n# --> education and hormone treatment do not affect Digit symbol baseline performance (non-significant main effects)\n\n# -\n\n# Question 7\n\n# Do education and age together affect the Digit symbol baseline performance?\n\nanova2 <- aov(digitsymbol_1 ~ age*education)\nsummary(anova2)\n\n# --> no they don't (only a trend towards significance in interaction effect) (F(2,41)=2.73, p>.05)\n# --> age and education do not affect Digit symbol baseline performance (non-significant main effects)\n\n# -\n\n# Question 8\n\n# Age, education and hormone treatment effects in Benton task baseline performance?\n\nanova3 <- aov(bentonerror_1 ~ age*education*ht_group)\nsummary(anova3)\n\n# --> only hormone treatment has a main effect on Benton task score (F(1,35)=10.21, p<.01)\n# --> age and education do not have main effects\n# --> age and education have an interaction effect (F(2,35)=3.66, p<.05)\n# --> education and hormone treatment group have an interaction effect (F(2,35)=3.46, p>.05)\n\n# visualize results:\n\nboxplot(bentonerror_1 ~ ht_group, xlab=\"Hormone treatment group\", ylab=\"Benton errors\")\n# --> hormone treatment group makes less errors than control group at baseline\n\ninteraction.plot(education,age,bentonerror_1)\n# --> higher education improves scores (=less errors) in younger group, opposite trend in older group (!?)\n\ninteraction.plot(education,ht_group, bentonerror_1)\n# --> higher education improves scores in hormone treatment group, slightly opposite in control group\n\n# -----\n\n# 6. Exercises\n\n# Load in data:\nnaming <- read.csv('http://becs.aalto.fi/~heikkih3/naming_wide.csv')\n\n# Get familiar with the data:\nhead(naming)\nsummary(naming)\ndim(naming)\n\n# It seems that the factors (sex, reading_time) are already coded as factors.\n# No missing values (actually NA's from previous weeks have been removed totally!)\n# Note that now 'ms' variable is split to 'ms.regular' and 'ms.regular\n# - this explains why data has only half the rows from previous weeks:\n# now one participant has all the variables in a single row.\n\ndetach()\t\t\t# detach all previous data frames\nattach(naming)\t\t# attach naming data frame\n\n# -\n\n# Question 9\n\nt.test(iq, mu=100)\n\n# --> intelligence does not differ from the population mean (t(997)=0, p>.05).\n\n# -\n\n# Question 10\n\nt.test(iq ~ sex)\n\n# --> no sex differences in intelligence (t(961)=1.07, p>.05).\n\n# -\n\n# Question 11\n\nt.test(hrs ~ sex)\n\n# --> no sex differences in hours spent on reading (t(972)=0.29, p>.05).\n\n# -\n\n# Question 12\n\nanova.1 <- aov(iq ~ reading_time)\nsummary(anova.1)\n\n# --> no differences between reading categories in intelligence (F(2,995)=0.03, p>.05).\n\n# -\n\n# Question 13\n\nt.test(ms.regular, ms.exception, paired=T)\nmean(ms.regular)\nmean(ms.exception)\nboxplot(ms.regular, ms.exception, xlab=\"Word type (1=regular, 2=exceptional))\", ylab=\"Time (ms)\")\n\n# --> reading times are shorter for regular words (t(997)=-68.8, p<.001).\n\n# -\n\n# Question 14\n\n# Regular words: \n\nanova.2 <- aov(ms.regular ~ reading_time)\nsummary(anova.2)\nboxplot(ms.regular ~ reading_time)\t\n\n# take a closer look at the differences using post-hoc comparison:\npairwise.t.test(ms.regular, reading_time, p.adj=\"bonf\")\ntapply(ms.regular, reading_time, mean)\ntapply(ms.regular, reading_time, sd)\n\n# --> there are differences between reading categories (based on hours spent on reading)\n# in time taken to read regular words (F(2,995)=3.52, p<.05).\n# --> post-hoc comparisons using a Bonferroni corrected pairwise t-test\n# revealed that the differences are between the highest reading category (mean=993, sd=70.39)\n# and the lowest one (mean=1009, sd=79).\n\n\n# Exceptional words:\n\nanova.3 <- aov(ms.exception ~ reading_time)\nsummary(anova.3)\nboxplot(ms.exception ~ reading_time)\n\n# take a closer look at the differences using post-hoc comparison:\npairwise.t.test(ms.exception, reading_time, p.adj=\"bonf\")\ntapply(ms.exception, reading_time, mean)\ntapply(ms.exception, reading_time, sd)\n\n# --> there are differences between reading categories (based on hours spent on reading)\n# in time taken to read exceptional words (F(2,995)=38.99, p<.001).\n# --> post-hoc comparisons using a Bonferroni corrected pairwise t-test\n# revealed that all groups differ from each other:\n# highest group (mean=1173, sd=76) has higher scores than the two other groups,\n# and middle group (mean=1203, sd=79) has higher scores than the lowest group (mean=1228, sd=76).\n\n# -\n\n# Question 15\n\n# Regular words:\n\nanova.4 <- aov(ms.regular ~ sex * reading_time) \nsummary(anova.4)\n\n# interaction plot:\ninteraction.plot(reading_time, sex, ms.regular)\n\n# --> sex does not modify the effect of reading time in \n# time taken to read regular words\n\n\n# Exceptional words:\n\nanova.5 <- aov(ms.exception ~ sex * reading_time) \nsummary(anova.5)\n\n# interaction plot:\ninteraction.plot(reading_time, sex, ms.exception)\n\nt.test(ms.exception ~ sex)\nboxplot(ms.exception ~ sex)\n\n# neither does sex modify the effect of reading time in\n# time taken to read exceptional words\n\n# -----\n\n", "meta": {"hexsha": "44641306f584d068181730f151684dd6ea926154", "size": 18077, "ext": "r", "lang": "R", "max_stars_repo_path": "files/expmethodsI_demo3_exercise-solutions.r", "max_stars_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_stars_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "files/expmethodsI_demo3_exercise-solutions.r", "max_issues_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_issues_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/expmethodsI_demo3_exercise-solutions.r", "max_forks_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_forks_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_forks_repo_licenses": ["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.5144596651, "max_line_length": 154, "alphanum_fraction": 0.7272777563, "num_tokens": 5258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4288634419721168}}
{"text": "subroutine initad(j,nadj,madj,x,y,ntot,eps,ntri,nerror)\n\n# Initial adding-in of a new point j.\n# Called by addpt.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\ninteger tau(3)\ninteger tadj(1000)\n\n# Find the triangle containing vertex j.\ncall trifnd(j,tau,nedge,nadj,madj,x,y,ntot,eps,ntri,nerror)\nif(nerror > 0) return\n\n# If the new point is on the edge of a triangle, detach the two\n# vertices of that edge from each other. Also join j to the vertex\n# of the triangle on the reverse side of that edge from the `found'\n# triangle (defined by tau) -- given that there ***is*** such a triangle.\nif(nedge!=0) {\n ip = nedge\n i = ip-1\n if(i==0) i = 3 # Arithmetic modulo 3.\n call pred(k,tau(i),tau(ip),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n call succ(kk,tau(ip),tau(i),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n call delet(tau(i),tau(ip),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n if(k==kk) call insrt(j,k,nadj,madj,x,y,ntot,nerror,eps)\n\tif(nerror > 0) return\n}\n\n# Join the new point to each of the three vertices.\ndo i = 1,3 {\n\tcall insrt(j,tau(i),nadj,madj,x,y,ntot,nerror,eps)\n\tif(nerror > 0) return\n}\nif(j==580) {\n nj = nadj(j,0)\n do jc = 1,nj {\n tadj(jc) = nadj(j,jc)\n }\n call intpr(\"Initial adjacency list of point 580:\",-1,tadj,nj)\n}\n\nreturn\nend\n", "meta": {"hexsha": "44d1f2fd48c340b84b37921d3f2bf66e9bdc696b", "size": 1378, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/SavedRatfor/initad.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/SavedRatfor/initad.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/SavedRatfor/initad.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": 28.7083333333, "max_line_length": 73, "alphanum_fraction": 0.6516690856, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4285933067533125}}
{"text": "\n# Listing 17.7 은 가급적 돌리지 말것. 많은 시간이 소요되며 잘 반영되지 않음.\n# 본 코드를 수행하기 위해서는 \n# 원본 데이터를 아래와 같이 변형해야 함 head(kbo)참조. \n\n# 원 데이터는 두팀이 한row에 있으며 모든 자료가 같은 row를 차지하고 있음.\n# 팀명으로 홈 어웨이를 구분(hOrA)하고 같은 row의 자료를 아래로 Rbind하여 위 데이터셋을 만들어야 함. \n# 마지막에 있는 코드는 각 분류방법에 대한 정확도와 민감도를 나타냄. 가장 좋은 것은 역시 랜덤포레스트.\n\n\n# install.packages(c(\"rpart\", \"party\", \"randomForest\", \"e1071\", \"rpart.plot\", \"readr\"))\n# install.packages(\"partykit\")\nlibrary(rpart)\nlibrary(party)\nlibrary(randomForest)\nlibrary(e1071)\nlibrary(rpart.plot)\nlibrary(readr)\nlibrary(readxl)\n\nkbo <- read_csv(\"kbolist_re.csv\")\nhead(kbo)\n\ndf <- kbo[-1]\ndf$winOrloss <- factor(df$winOrloss, levels=c(1,0), \n labels=c(\"win\", \"loss\"))\n\nset.seed(1234)\ntrain <- sample(nrow(df), 0.7*nrow(df))\ndf.train <- df[train,]\ndf.validate <- df[-train,]\ntable(df.train$winOrloss)\n# win loss \n# 2443 2422 \ntable(df.validate$winOrloss)\n# win loss \n# 1032 1053 \n\n# Listing 17.2 - Logistic regression with glm()\nfit.logit <- glm(winOrloss~., data=df.train, family=binomial())\nsummary(fit.logit)\n##############################################################################################\n# Call:\n# glm(formula = winOrloss ~ ., family = binomial(), data = df.train)\n# \n# Deviance Residuals: \n# Min 1Q Median 3Q Max \n# -2.0658 -1.0863 -0.5907 1.0797 2.0736 \n# \n# Coefficients:\n# Estimate Std. Error z value Pr(>|z|) \n# (Intercept) 0.307633 0.160909 1.912 0.055897 . \n# hOrA -0.414391 0.060146 -6.890 5.59e-12 ***\n# inning -0.232867 0.098284 -2.369 0.017821 * \n# tajasu 0.214432 0.054491 3.935 8.31e-05 ***\n# tugusu -0.000244 0.003561 -0.069 0.945372 \n# tasu -0.160913 0.047018 -3.422 0.000621 ***\n# anta 0.013630 0.033197 0.411 0.681376 \n# fourball -0.181790 0.057509 -3.161 0.001572 ** \n# homerun 0.083115 0.044310 1.876 0.060690 . \n# samjin -0.009144 0.016582 -0.551 0.581337 \n# siljum 0.130653 0.049832 2.622 0.008744 ** \n# jacheck -0.041126 0.048831 -0.842 0.399676 \n# score -0.096739 0.008490 -11.395 < 2e-16 ***\n# ---\n# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n# \n# (Dispersion parameter for binomial family taken to be 1)\n# \n# Null deviance: 6744.2 on 4864 degrees of freedom\n# Residual deviance: 6326.0 on 4852 degrees of freedom\n# AIC: 6352\n# \n# Number of Fisher Scoring iterations: 4\n##############################################################################################\nprob <- predict(fit.logit, df.validate, type=\"response\")\nlogit.pred <- factor(prob > .5, levels=c(FALSE, TRUE), \n labels=c(\"win\", \"loss\"))\nlogit.perf <- table(df.validate$winOrloss, logit.pred,\n dnn=c(\"Actual\", \"Predicted\"))\nlogit.perf\n#prob\n# Predicted\n# Actual win loss\n# win 686 346\n# loss 359 694\n##############################################################################################\n\n# Listing 17.3 - Creating a classical decision tree with rpart()\nlibrary(rpart)\nset.seed(1234)\ndtree <- rpart(winOrloss ~ ., data=df.train, method=\"class\", \n parms=list(split=\"information\"))\ndtree$cptable\nplotcp(dtree)\n\ndtree.pruned <- prune(dtree, cp=.0125) \n\nlibrary(rpart.plot)\n#?prp()\nprp(dtree.pruned, type = 2, extra = 104, \n fallen.leaves = TRUE, main=\"Decision Tree\")\n\ndtree.pred <- predict(dtree.pruned, df.validate, type=\"class\")\ndtree.perf <- table(df.validate$winOrloss, dtree.pred, \n dnn=c(\"Actual\", \"Predicted\"))\ndtree.perf\n\n\n# Listing 17.4 - Creating a conditional inference tree with ctree()\nlibrary(party)\nfit.ctree <- ctree(winOrloss~., data=df.train)\nplot(fit.ctree, main=\"Conditional Inference Tree\")\n\nctree.pred <- predict(fit.ctree, df.validate, type=\"response\")\nctree.perf <- table(df.validate$winOrloss, ctree.pred, \n dnn=c(\"Actual\", \"Predicted\"))\nctree.perf\n\n\nlibrary(partykit)\nplot(as.party(dtree.pruned))\n\n# Listing 17.5 - Random forest\nlibrary(randomForest)\nset.seed(1234)\nfit.forest <- randomForest(winOrloss~., data=df.train, \n na.action=na.roughfix,\n importance=TRUE) \nfit.forest\nimportance(fit.forest, type=2) \nforest.pred <- predict(fit.forest, df.validate) \nforest.perf <- table(df.validate$winOrloss, forest.pred, \n dnn=c(\"Actual\", \"Predicted\"))\nforest.perf\n\nvarImpPlot(fit.forest)\n\n\n\n# Listing 17.6 - A support vector machine\nlibrary(e1071)\nset.seed(1234)\nfit.svm <- svm(winOrloss~., data=df.train)\nfit.svm\nsvm.pred <- predict(fit.svm, na.omit(df.validate))\nsvm.perf <- table(na.omit(df.validate)$winOrloss, \n svm.pred, dnn=c(\"Actual\", \"Predicted\"))\nsvm.perf\n\n\n# Listing 17.7 Tuning an RBF support vector machine (this can take a while)\n# many time spend..... if you have a dull, please cancel this process.\n#set.seed(1234)\n#tuned <- tune.svm(winOrloss~., data=df.train,\n# gamma=10^(-6:1),\n# cost=10^(-10:10))\n#tuned\n#fit.svm <- svm(winOrloss~., data=df.train, gamma=.01, cost=1)\n#svm.pred <- predict(fit.svm, na.omit(df.validate))\n#svm.perf <- table(na.omit(df.validate)$winOrloss,\n# svm.pred, dnn=c(\"Actual\", \"Predicted\"))\n#svm.perf\n\n\n# Listing 17.8 Function for assessing binary classification accuracy\nperformance <- function(table, n=2){\n if(!all(dim(table) == c(2,2)))\n stop(\"Must be a 2 x 2 table\")\n tn = table[1,1]\n fp = table[1,2]\n fn = table[2,1]\n tp = table[2,2]\n sensitivity = tp/(tp+fn)\n specificity = tn/(tn+fp)\n ppp = tp/(tp+fp)\n npp = tn/(tn+fn)\n hitrate = (tp+tn)/(tp+tn+fp+fn)\n result <- paste(\"Sensitivity = \", round(sensitivity, n) ,\n \"\\nSpecificity = \", round(specificity, n),\n \"\\nPositive Predictive Value = \", round(ppp, n),\n \"\\nNegative Predictive Value = \", round(npp, n),\n \"\\nAccuracy = \", round(hitrate, n), \"\\n\", sep=\"\")\n cat(result)\n}\n\n\n# Listing 17.9 - Performance of breast cancer data classifiers\nperformance(dtree.perf)\nperformance(ctree.perf)\nperformance(forest.perf)\nperformance(svm.perf)\n\n\n", "meta": {"hexsha": "4897dbfa6ba3e138143a7f7009258f16a4442e66", "size": 6165, "ext": "r", "lang": "R", "max_stars_repo_path": "kbo.r", "max_stars_repo_name": "capricorn08/kbo_reg", "max_stars_repo_head_hexsha": "b9a15345955925f932f166e2da41fe762e934263", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kbo.r", "max_issues_repo_name": "capricorn08/kbo_reg", "max_issues_repo_head_hexsha": "b9a15345955925f932f166e2da41fe762e934263", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kbo.r", "max_forks_repo_name": "capricorn08/kbo_reg", "max_forks_repo_head_hexsha": "b9a15345955925f932f166e2da41fe762e934263", "max_forks_repo_licenses": ["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.6153846154, "max_line_length": 94, "alphanum_fraction": 0.5894566099, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42851231151640823}}
{"text": "#' @export\n#'\n#' @title checkConvergence - Check the convergence of a mcmc.list object\n#'\n#' @description Run various diagnostic procedures in the \\code{coda} package\n#' to check convergence of a set of mcmc chains.\n#'\n#' @param obj An mcmc.list object from the \\code{rjags} package. These are output\n#' by the \\code{coda.samples} function. This mcmc.list must contain 2 or more chains.\n#'\n#' @param quiet Whether to print any output on screen.\n#'\n#' @details This routine runs the Gelman and Rubin (1992) diagnostic for\n#' a set of MCMC chains by calling \\code{gelman.diag} in the \\code{coda} package.\n#'\n#' @return A list with the following components\n#' \\itemize{\n#' \\item converged: If the uppper limits of the 'potential scale\n#' reduction factors' associated with all parameters are less than\n#' \\code{criterion}, the chain is declared converged and this is TRUE.\n#' Otherwise, this component of the returns is FALSE.\n#' \\item Rhats: the 'potential scale reduction factors' or Rhats\n#' associated with all parameters.\n#' }\n#'\n#' @author Trent McDonald\n#'\n#' @references\n#' Gelman, A and Rubin, DB (1992) Inference from iterative simulation\n#' using multiple sequences, Statistical Science, 7, 457-511.\n#'\n#' @seealso \\code{\\link{gelman.diag}}, \\code{\\link{checkIsConverged}}\n#'\n#' @examples\n#' \\dontrun{\n#' jags = jags.model(file=\"someJAGSFile.txt\",\n#' data=someJAGS.data, inits=someJAGS.inits,\n#' n.chains=3,n.adapt=100)\n#' update(jags, n.iter=1000)\n#' out = coda.samples(jags,\n#' variable.names=c(\"someParameter\"),\n#' n.iter=1000,\n#' thin=2)\n#'\n#' conf <- chechIsConverged(out)\n#' }\n\n\ncheckIsConverged <- function(obj, criterion=1.1, quiet=FALSE){\n\n Rhats <- gelman.diag(obj)\n if(!quiet){\n cat(paste0(paste(rep(\"-\",4),collapse=\"\"),\" Checking convergence:\\n\"))\n print(Rhats)\n }\n vnames <- dimnames(Rhats$psrf)[[1]]\n Rhats <- Rhats$psrf[,\"Upper C.I.\"]\n names(Rhats) <- vnames\n if( any(Rhats > criterion, na.rm=TRUE) ){\n if(!quiet){\n cat(\"The following coefficients probably did not converge (Rhat > 1.1):\\n\")\n print(names(Rhats)[Rhats > criterion])\n cat(\"Try increasing nburns and/or nthins or informing the coefficient's priors.\\n\")\n }\n ans <- FALSE\n } else {\n if(!quiet){\n cat(\"The model converged. All Rhats < 1.1\\n\")\n }\n ans <- TRUE\n }\n\n ans <- list(converged=ans, Rhats=Rhats)\n\n}\n", "meta": {"hexsha": "cee6e7a5fd9a9713fe93755c74908bc23fa13281", "size": 2375, "ext": "r", "lang": "R", "max_stars_repo_path": "R/checkIsConverged.r", "max_stars_repo_name": "tmcd82070/EoAR", "max_stars_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_stars_repo_licenses": ["MIT"], "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/checkIsConverged.r", "max_issues_repo_name": "tmcd82070/EoAR", "max_issues_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_issues_repo_licenses": ["MIT"], "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/checkIsConverged.r", "max_forks_repo_name": "tmcd82070/EoAR", "max_forks_repo_head_hexsha": "30bdd48e88046332fdb1c97d55fb9a6a1a983e06", "max_forks_repo_licenses": ["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.25, "max_line_length": 89, "alphanum_fraction": 0.672, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.42850866893114975}}
{"text": "#!/usr/local/bin/Rexec\n########### set arguments list ###############################\nargs<-commandArgs();\nargs_start=grep(\"--args\",args)+1;\nif (length(args_start)>0 && args_start < length(args) ) { \n args<-args[args_start:length(args)]\n} else {\n args=c()\n}\n#############################################################\nrm(list=ls())\n\nmwpp<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n s1=exp((r+1)/r);\n deltat = 0;\n\n if(tau1>=tau2)\n {\n dw = -k^2*(2*r-2*r*exp(r+1)+r^2-1)/(tau1*exp(r+1)*(r+1)^3)\n } else if(tau1=tau2)\n {\n deltat = -tau1*(r^2+r-2)/(r+1) \n dw = k^2*exp(-(r+3)/(r+1))/(tau1*(r+1)^2) \n } else\n {\n deltat = tau1*(-2*r^2+r+1)/(r+1) \n dw = k^2*(3*r-1)*exp(-(2*r^2+3*r-1)/(r*(r+1)))/(tau1*(r+1)^3)\n }\n\n return(c(deltat,dw))\n}\n\nmwpn<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n s1=exp((r+1)/r)\n\n deltat = -(r*tau1*( s1 -r +3*r*s1 +2*r^2 -1 ))/( (r + s1)*(r+1));\n dw = k^2*(r+s1)*exp(-(s1+3*r*s1+4*r^2*s1+r^2+3*r^3)/(r*(r+s1)*(r+1)))/(tau1*(r+1)^2);\n\n return(c(deltat,dw));\n}\n\nmwps<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n s1=exp((r+1)/r);\n\n deltat = r*tau1* ( 2*r -2*r*s1 -r^2 +1 )/( (r+s1)*(r+1));\n dw = k^2*r*(r+s1)*exp(-( s1+2*r*s1+3*r^2*s1+2*r^3 ) /(r*(r+s1)*(r+1)) )/((r+1)^2);\n return(c(deltat,dw))\n}\n\nmwsp<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n s1=exp((r+1));\n\n deltat = -tau1* ( 2*r -2*r*s1 +r^2 -1 )/( (r*s1+1)*(r+1));\n dw = k^2*(r*s1+1)*exp(-( 3*r*s1+2*r^2*s1+r^3*s1+2 ) /((r*s1+1)*(r+1)) )/((r+1)^2);\n\n return(c(deltat,dw))\n}\n\nmwns<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n if(tau1>=tau2)\n {\n deltat = 2*tau1/(r+1);\n dw = k^2*r*exp(-(2/(r+1)))/(r+1)^2;\n }\n else\n {\n deltat = tau1*(-r^2+2*r+1)/(r+1);\n dw = k^2*r^2*exp(-(2*r/(r+1)))/(r+1)^2;\n }\n\n return(c(deltat,dw))\n}\n\nmwsn<-function(tau1,tau2,k)\n{\n r=tau2/tau1;\n if(tau1>=tau2)\n {\n deltat = -tau1*(r^2+2*r-1)/(r+1);\n dw = k^2*exp(-(2/(r+1)))/(r+1)^2;\n }\n else\n {\n deltat = -2*r^2*tau1/(r+1);\n dw = k^2*r*exp(-(2*r/(r+1)))/(r+1)^2;\n }\n\n return(c(deltat,dw))\n}\n\n\n\n\ndwnnh<-function(deltat,tau1,tau2,k) \n{\n y = \n exp(-(deltat+tau1+tau2)/tau1)*\n k^2* \n (-tau1^2+2*tau1*tau2+tau2^2+deltat*(tau1+tau2)\n )/ \n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwnnl<-function(deltat,tau1,tau2,k) \n{\n y = \n -exp(-(-deltat+tau1+tau2)/tau2)*\n k^2* \n (-tau1^2-2*tau1*tau2+tau2^2+deltat*(tau1+tau2)\n )/ \n (tau1+tau2)^3;\n return(y);\n}\n\n\n\ndwnph<-function(deltat,tau1,tau2,k) \n{\n y = \n exp(-(deltat+tau1+tau2)/tau1)*\n k^2* \n (\n exp(1+tau2/tau1)*\n tau2*(-2*tau1^2+deltat*(tau1+tau2))+ \n tau1*(-tau1^2+2*tau1*tau2+tau2^2+deltat*(tau1+tau2))\n )/ \n (tau1*(tau1+tau2)^3);\n return(y);\n}\n\ndwnpl<-function(deltat,tau1,tau2,k) \n{\n\n y = \n -exp(-(deltat*tau2+(tau1+tau2)^2)/(tau1*tau2))*\n k^2* \n (\n exp(1+(tau1/(tau2)))*\n (tau1^2-2*tau1*tau2-tau2^2-deltat*(tau1+tau2))+ \n exp(((deltat+tau2)*(tau1+tau2))/(tau1*tau2))*\n (tau1^2+2*tau1*tau2-tau2^2-deltat*(tau1+tau2))\n )/ ((tau1+tau2)^3);\n return(y);\n}\n\n\ndwnsh<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-deltat/tau1)*\n k^2*\n tau2*(tau1*(-tau1+tau2)+deltat*(tau1+tau2))/ \n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwnsl<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-(-deltat+tau1+tau2)/tau2)*\n k^2*\n tau2*(-deltat*(tau1+tau2)+tau1*(tau1+3*tau2))/\n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwpnh<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-(deltat*tau2+(tau1+tau2)^2)/(tau1*tau2))*\n k^2*\n (\n exp(1+((tau1)/(tau2)))*\n (tau1^2-2*tau1*tau2-tau2^2-deltat*(tau1+tau2))+\n exp(((deltat+tau2)*(tau1+tau2))/(tau1*tau2))*\n (tau1^2+2*tau1*tau2-tau2^2-deltat*(tau1+tau2))\n )/\n ((tau1+tau2)^3);\n return(y);\n}\n\ndwpnl<-function(deltat,tau1,tau2,k) \n{\n\n y = \n -exp(-(-deltat+tau1+tau2)/(tau2))*\n k^2*\n (\n tau2*(-tau1^2-2*tau1*tau2+tau2^2+deltat*(tau1+tau2))+\n exp(1+((tau1)/(tau2)))*\n tau1*(2*tau2^2+deltat*(tau1+tau2))\n )/\n (tau2*((tau1+tau2)^3));\n\n return(y);\n}\n\ndwpph<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-1-deltat/(tau1)-(tau1)/(tau2))*\n k^2* \n (\n -exp(1+tau1/tau2)*\n tau2*(-2*tau1^2+deltat*(tau1+tau2))+ \n exp(deltat*(1/tau1+1/tau2))*\n tau1*(-tau1^2-2*tau1*tau2+tau2^2+deltat*(tau1+tau2))\n )/ \n (tau1*(tau1+tau2)^3);\n return(y);\n}\n\ndwppl<-function(deltat,tau1,tau2,k) \n{\n y = \n exp(-(deltat+tau1+tau2)/(tau1))*\n k^2*\n (\n -tau2*(-tau1^2+2*tau1*tau2+tau2^2+deltat*(tau1+tau2))+\n exp(((deltat+tau2)*(tau1+tau2))/(tau1*tau2))*\n tau1*(2*tau2^2+deltat*(tau1+tau2))\n )/\n (tau2*((tau1+tau2)^3));\n\n\n return(y);\n}\n\ndwppml<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-(-deltat+tau1+tau2)/tau2)*\n k^2*\n (tau2*(-tau1^2-2*tau1*tau2+tau2^2 +\n deltat*(tau1+tau2))+\n exp(1+tau1/tau2)*\n tau1*(2*tau2^2+deltat*(tau1+tau2))\n )/(tau2*(tau1+tau2)^3);\n\n return(y);\n}\n\ndwppmr<-function(deltat,tau1,tau2,k) \n{\n y = \n exp(-(deltat+tau1+tau2)/tau1)*\n k^2*\n (\n -deltat*(tau1+tau2)*\n (tau1+exp(1+tau2/tau1)*tau2)+\n tau1*(tau1^2+2*(-1+exp(1+tau2/tau1))*tau1*tau2-tau2^2)\n )/\n (tau1*(tau1+tau2)^3);\n\n\n return(y);\n}\n\n\ndwpsh<-function(deltat,tau1,tau2,k) \n{\n\n\n y = \n exp(-1-deltat/tau1-tau1/tau2)*\n k^2*\n tau2* (\n exp(1+tau1/tau2)*(tau1*(tau1-tau2)-deltat*(tau1+tau2))+ \n exp(deltat*(1/tau1+1/tau2))*\n (-deltat*(tau1+tau2)+tau1*(tau1+3*tau2))\n )/\n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwpsl<-function(deltat,tau1,tau2,k) \n{\n\n y = \n -exp(-(-deltat+tau1+tau2)/tau2)*\n k^2* \n (\n exp(1+tau1/tau2)*\n tau1*(tau2*(-tau1+tau2)+deltat*(tau1+tau2))+ \n tau2*(deltat*(tau1+tau2)-tau1*(tau1+3*tau2))\n )/ \n (tau1+tau2)^3;\n return(y);\n}\n\ndwsnh<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-((deltat+tau1+tau2)/tau1))*\n k^2*\n tau1*(deltat*(tau1+tau2)+tau2*(3*tau1+tau2))/\n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwsnl<-function(deltat,tau1,tau2,k) \n{\n y = \n -exp(deltat/tau2)*\n k^2*\n tau1*(tau2*(-tau1+tau2)+deltat*(tau1+tau2))/\n (tau1+tau2)^3;\n\n\n return(y);\n}\n\n\ndwsph<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-(deltat+tau1+tau2)/tau1)*\n k^2*\n (\n exp(1+tau2/tau1)*\n tau2*(tau1*(-tau1+tau2)+deltat*(tau1+tau2))+\n tau1*(deltat*(tau1+tau2)+tau2*(3*tau1+tau2))\n )/\n (tau1+tau2)^3;\n\n return(y);\n}\n\ndwspl<-function(deltat,tau1,tau2,k) \n{\n\n y = \n exp(-((deltat+tau1+tau2)/tau1))*\n k^2*\n tau1*(\n deltat*tau1+\n deltat*tau2+\n 3*tau1*tau2+\n tau2^2+\n exp((deltat+tau2)*(tau1+tau2)/(tau1*tau2))* \n (tau2*(-tau1+tau2)+deltat*(tau1+tau2)))/\n (tau1+tau2)^3;\n\n return(y);\n}\n\n\n\nicomponents<-function(\n width=4,\n height=6,\n name='',\n EPS=FALSE,\n dt=.01,\n tau1=1,\n tau2=1,\n k=1,\n gpp=0,\n gnp=0,\n gpn=0,\n gnn=0,\n eps=0,\n esp=0,\n ens=0,\n esn=0) \n{\n\n\n id=diag(8);\n\n\n\n gap=.01;\n range=seq(-20,20,gap);\n trange=length(range);\n tt=1:trange;\n w=rep(0,length(range));\n\n if ( tau1 >= tau2 ) {\n t = 1;\n for (deltat in range) \n {\n if ( deltat <= -tau2 ) \n {\n w[t] = \n gnn*dwnnl(deltat,tau1,tau2,k) + \n gpn*dwpnl(deltat,tau1,tau2,k) + \n esn*dwsnl(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n eps*dwpsl(deltat,tau1,tau2,k);\n } else if ( deltat <= 0 )\n {\n w[t] = \n gpp*dwppl(deltat,tau1,tau2,k) + \n gnn*dwnnl(deltat,tau1,tau2,k) + \n gpn*dwpnh(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwspl(deltat,tau1,tau2,k) + \n eps*dwpsl(deltat,tau1,tau2,k);\n } else if ( deltat <= (tau1 - tau2) )\n {\n w[t] = \n gpp*dwppmr(deltat,tau1,tau2,k) + \n gnn*dwnnl(deltat,tau1,tau2,k) + \n gpn*dwpnh(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwsph(deltat,tau1,tau2,k) + \n eps*dwpsh(deltat,tau1,tau2,k);\n } else if ( deltat <= tau1 )\n {\n w[t] = \n gpp*dwpph(deltat,tau1,tau2,k) + \n gnn*dwnnh(deltat,tau1,tau2,k) + \n gnp*dwnpl(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwsph(deltat,tau1,tau2,k) + \n eps*dwpsh(deltat,tau1,tau2,k);\n } else \n {\n w[t] = \n gnn*dwnnh(deltat,tau1,tau2,k) + \n gnp*dwnph(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsh(deltat,tau1,tau2,k) + \n esp*dwsph(deltat,tau1,tau2,k);\n }\n t = t + 1;\n }\n }\n else \n {\n t = 1;\n for (deltat in range) \n {\n if ( deltat <= -tau2 )\n {\n w[t] = \n gnn*dwnnl(deltat,tau1,tau2,k) + \n gpn*dwpnl(deltat,tau1,tau2,k) + \n esn*dwsnl(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n eps*dwpsl(deltat,tau1,tau2,k);\n } else if ( deltat <= (tau1 - tau2) )\n {\n w[t] = \n gpp*dwppl(deltat,tau1,tau2,k) + \n gnn*dwnnl(deltat,tau1,tau2,k) + \n gpn*dwpnh(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwspl(deltat,tau1,tau2,k) + \n eps*dwpsl(deltat,tau1,tau2,k);\n } else if ( deltat <= 0 )\n {\n w[t] = \n gpp*dwppml(deltat,tau1,tau2,k) + \n gnn*dwnnh(deltat,tau1,tau2,k) + \n gnp*dwnpl(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwspl(deltat,tau1,tau2,k) + \n eps*dwpsl(deltat,tau1,tau2,k);\n } else if ( deltat <= tau1 )\n {\n w[t] = \n gpp*dwpph(deltat,tau1,tau2,k) + \n gnn*dwnnh(deltat,tau1,tau2,k) + \n gnp*dwnpl(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsl(deltat,tau1,tau2,k) + \n esp*dwsph(deltat,tau1,tau2,k) + \n eps*dwpsh(deltat,tau1,tau2,k);\n } else\n {\n w[t] = \n gnn*dwnnh(deltat,tau1,tau2,k) + \n gnp*dwnph(deltat,tau1,tau2,k) + \n esn*dwsnh(deltat,tau1,tau2,k) + \n ens*dwnsh(deltat,tau1,tau2,k) + \n esp*dwsph(deltat,tau1,tau2,k);\n }\n t = t + 1;\n }\n }\n\n graphics.off();\n\n xgap=range[length(range)]/4;\n xlim=c((range[1]-4*xgap),range[length(range)]+3*xgap) \n ylim=c(-3*max(w)/10,max(w)+3*(max(w)/10))\n axlim=c((range[1]-xgap/2),range[length(range)]+xgap/2) \n aylim=c(-3*max(w)/10,max(w)+3*(max(w)/10))\n\n\n if(EPS==TRUE) {\n postscript(\n paste('integral_component_',name,'.eps',sep=''),\n onefile=FALSE,\n horizontal=FALSE, \n width=width,height=height,\n pointsize=11,\n family=\"Times\");\n }\n\n par(mar=c(100,100,1,1)*.005)\n\n plot(\n range,\n w,\n type='l',\n frame.plot=FALSE,\n axes=FALSE,\n xlab='',\n ylab='',\n lwd=1,\n xlim=xlim,\n ylim=ylim,\n family=\"serif\")\n polygon(c(range[1],range,range[length(range)]),c(0,w,0), col='#DDDDDD',border=NA) \n lines(range,w,lwd=1);\n\n d<-c()\n d<-rbind(d,c(rbind(axlim,aylim*0)))\n d<-rbind(d,c(rbind(axlim*0,aylim)))\n arrows(d[,1],d[,2],d[,3],d[,4],lwd=1,length=.08,code=3);\n \n rr = (aylim[2]-aylim[1])/2;\n\n kappa=(k/100)/2;\n\n arrows(\n axlim[1]-10,\n rr-kappa,\n axlim[1]-10,\n rr+kappa,\n ,lwd=.5,length=.01,angle=90,code=3);\n text(axlim[1]-8,(aylim[2]-aylim[1])/2,expression( paste(\"\") %prop% italic(kappa)),adj=c(.1,.5),cex=1)\n\n arrows(\n axlim[2]+6,\n rr+rr/8,\n (axlim[2]+6)-tau1,\n rr+rr/8,\n ,lwd=.5,length=.01,angle=90,code=3);\n text(axlim[2]+10,\n rr+rr/8,\n expression(italic(tau[1])),adj=c(.5,.5),cex=1)\n arrows(\n axlim[2]+6,\n rr-rr/8,\n (axlim[2]+6)-tau2,\n rr-rr/8,\n ,lwd=.5,length=.01,angle=90,code=3);\n text(axlim[2]+10,\n rr-rr/8,\n expression(italic(tau[2])),adj=c(.5,.5),cex=1)\n\n\n lmax<-c('pp','np','pn','nn','ps','sp','ns','sn')\n cc<-sum(c(gpp,gnp,gpn,gnn,eps,esp,ens,esn)*1:8);\n\n #ssubs=substitute(w[index],list(index=lmax[cc]));\n ssubs=\"w\";\n text(-1.2*xgap,ylim[2]-(1/20)*ylim[2],substitute(bolditalic(paste(Delta,index,sep='')),list(index=ssubs)),cex=1)\n text(axlim[2]+6,0,expression(italic(paste(Delta,t))),adj=c(.5,.5),cex=1)\n text(axlim[1]-12,0,expression(italic(-paste(Delta,t))),adj=c(.5,.5),cex=1)\n \n # if(tau2>tau1) {\n # txt=expression(italic(tau[1]tau2) {\n # txt=expression(italic(tau[2]3)col.ind<-lapply(1:(k-2),function(x)matrix(nrow=choose(k-1,x+1),ncol=choose(x+1,x)))\r\n \r\n\tfor(cross in 1:(k-1)){\r\n component.array[[cross]]<-array(m+1,dim=c(m^cross,k-1,choose(k-1,cross)))\r\n\t\t# component.array also gives the labeling of all intersection hypotheses.\r\n\t\t# However, we may locate certain intersection hypothesis through component.array\r\n matrix.comb<-combn(k-1,cross)\r\n active.array[[cross]]<-matrix(NA,nrow=m^cross,ncol=cross)\r\n for(a in 1:cross)active.array[[cross]][,a]<-as.numeric(sapply(1:m,function(x)rep(x,m^(cross-a))))\r\n # active.array[[cross]] gives the possible combination of endpoints in a \"cross\"-way intersection.\r\n\t\t\r\n\t\tfor(i in 1:choose(k-1,cross))component.array[[cross]][,matrix.comb[,i],i]<-active.array[[cross]]\r\n # component.array[[cross]] is an array, which consists of \"choose(k-1,cross)\" matrices. \r\n\t\t#\tThe number \"cross\" indicates how many original hypotheses involved in the intersection.\r\n\t\t#\tEach matrix, for example, component.array[[cross]][,,1], has each row a label for one paticular\r\n\t\t#\tintersection. The number of rows in each matrix is m^cross.\r\n\t\tComp.Amat[[cross]]<-list()\r\n # Comp.Amat are the constraint matrix for the component hypothesis.\r\n\t\t# It provide guidance on how to compute the restricted MLEs and the likelihood ratio statistics.\r\n\t\t# Comp.Amat[[1]] contain the constraint matrix for all the elementary hypotheses\r\n\t\t# Comp.Amat[[2]] contain the constraint matrix for all 2 way intersection hypotheses\r\n\t\t# \tect... up to k-1.\r\n\t\tfor(i in 1:choose(k-1,cross)){\r\n Comp.Amat[[cross]][[i]]<-list()\r\n for(j in 1:m^cross) Comp.Amat[[cross]][[i]][[j]]<-.Constraint(label=component.array[[cross]][j,,i],k=k)\r\n }\r\n \r\n\t\t# The list row.ind and col.ind tells how to perform the consonant adjustment.\r\n\t\t# Read the instruction in function .rNull.dist for definitions on ComponentLRT first.\r\n\t\t# Since each intersection hypothesis is located by one cell in the matrix of ComponentLRT[[1]][,,i],\r\n\t\t#\tComponentLRT[[2]][,,i], and ComponentLRT[[3]][,,i] for the ith replication, we give the index of those\r\n\t\t#\tintersection hypotheses that needs to be tested in consonance adjustment.\r\n\t\t\r\n\t\t# For example, a three way intersection hypothesis H_121, will be located in ComponentLRT[[3]].\r\n\t\t#\tAccording to active.array[[3]], it is on the 3rd row of ComponentLRT[[3]]. And ComponentLRT[[3]][,,i] only\r\n\t\t#\thas one column. So the index for H_121 is ComponentLRT[[3]][3,1,i].\r\n\t\t# To reject H_121, we need to also reject at least two of H_123, H_131 and H_321. They are associated with three\r\n\t\t#\tindices in ComponentLRT.\r\n\t\t# First, since they are all two-way intersections, they all located in ComponentLRT[[2]].\r\n\t\t#\trow.ind[[2]][3,]=c(2,1,3) gives the three row index of these hypotheses,\r\n\t\t#\tcol.ind[[2]][1,]=c(1,2,3) gives the three col index of these hypotheses.\r\n\t\t#\tThey are ComponentLRT[[2]][2,1,i], ComponentLRT[[2]][1,2,i] and ComponentLRT[[2]][3,3,i].\r\n\t\tif(cross>1){\r\n row.ind[[cross-1]]<-matrix(NA,nrow=m^cross,ncol=cross)\r\n combn.mat<-combn(cross,cross-1)\r\n for(a in 1:m^cross)for(b in 1:cross)\r\n row.ind[[cross-1]][a,b]<-which(sapply(1:m^(cross-1),function(x)all(active.array[[cross-1]][x,1:(cross-1),drop=F]==active.array[[cross]][a,combn.mat[,b]])))\r\n combn.mat<-combn(k-1,cross-1)\r\n for(a in 1:nrow(col.ind[[cross-1]]))\r\n col.ind[[cross-1]][a,]<-which(sapply(1:choose(k-1,cross-1),function(x)all(combn.mat[,x]%in%combn(k-1,cross)[,a])))\r\n }\r\n }\r\n return(list('matrix'=npmtrx,'Comp.Amat'=Comp.Amat,'component.array'=component.array,'row.ind'=row.ind,'col.ind'=col.ind,'balanced'=balanced))\r\n}\r\n\r\n\r\n# LR compute the likelihood ratio statistics for each intersection hypothesis.\r\nlibrary(quadprog)\r\n.LR<-function(Amat,k=4,m=2,Ybar,sigma,n=rep(50,4)){\r\n # Ybar is a m-by-k matrix, the last column in Ybar is the control.\r\n\t# sigma is a length m vector, includes stdev of each endpoint.\r\n\t# Amat is the constraint matrix for certain dose-endpoint combination from Comp.Amat\r\n sigma<-sum(n-1)*sigma^2\r\n ynullp<-solve.QP(Dmat=diag(n),dvec=diag(n)%*%Ybar[1,],Amat=Amat$hnullp)$solution\r\n ynulls<-solve.QP(Dmat=diag(n),dvec=diag(n)%*%Ybar[2,],Amat=Amat$hnulls)$solution\r\n LR<-( sigma[1]*sigma[2]\r\n /(sigma[1]+sum(n*(Ybar[1,]-ynullp)^2))/(sigma[2]+sum(n*(Ybar[2,]-ynulls)^2)) )^(-sum(n)/2)\r\n # To the power of -sum(n)/2 so that reject the null if LR > critical value.\r\n return(LR)\r\n}\r\n\r\n\r\n# .rNull.dist generate samples from the null distribution and compute their test statistics.\r\nlibrary(mvtnorm)\r\n.rNull.dist<-function(n=rep(50,4),simu=10^5,rho=0){\r\n # n is the sample size for each dose. It is a vector of length 4, the last elements is the control.\r\n # The number of doses in this example, including control, is 4.\r\n # The number of endpoints is fixed at 2, for this function.\r\n k<-length(n)\r\n balanced<-(length(unique(n[1:(k-1)]))==1)\r\n NP<-.naturalpartition(k=k,m=2,balanced=balanced)\r\n # Generate null distribution\r\n sigma<-matrix(nrow=simu,ncol=2)\r\n Ybar<-array(dim=c(2,k,simu))\r\n ComponentLRT<-list()\r\n for(cross in 1:(k-1)) ComponentLRT[[cross]]<-array(dim=c(2^cross,choose(k-1,cross),simu))\r\n # ComponentLRT[[cross]] is a 2^cross * choose(k-1,cross) * simu array, where simu is the replication.\r\n\t# In the case of 4 treatment groups and 2 endpoints,\r\n\t#\tComponentLRT[[1]] is 2 by choose(3,1)=3 matrix, each cell is a one-way intersection hypothesis with\r\n\t#\t\tindex of the form x33, 3x3 or 33x. The x can be 1 or 2 for two endpoints, thus two rows.\r\n\t#\tComponentLRT[[2]] is 4 by choose(3,2)=3 matrix, each cell indicates a two-way intersection hypothesis\r\n\t#\t\twith index of the form xx3, x3x or 3xx. The xx can be 11, 12, 21 and 22 from two endpoints, thus \r\n\t#\t\tthere are 4 rows.\r\n\t#\tComponentLRT[[3]] is 8 by choose(3,3)=1 matrix, each cell indicates a three-way intersection hypothesis\r\n\t#\t\twith index of the form xxx. The xxx comes for two endpoints combinations.\r\n\t\r\n\t# Each intersection hypothesis fits into one cell of the matrix in ComponentLRT[[1]][,,i], ComponentLRT[[2]][,,i],\r\n\t#\tand ComponentLRT[[3]][,,i] for the ith replication. There are in total 26 of them.\r\n\t\r\n\t# The following piece of code comes from Normal random variable generating function.\r\n\t# To same computation time, part of the repeating computation is done here only once.\r\n retval<-list()\r\n VC<-matrix(rho,nrow=2,ncol=2)+(1-rho)*diag(2)\r\n for(i in 1:k){\r\n altersigma<-VC/n[i]\r\n ev<-eigen(altersigma, symmetric = TRUE)\r\n retval[[i]] <- ev$vectors %*% diag(sqrt(ev$values), length(ev$values)) %*% t(ev$vectors)\r\n }\r\n\r\n for(i in 1:simu){\r\n sigma[i,]<-rchisq(2,df=sum(n-1))/sum(n-1)\r\n # sigma[i,] is the pooled estimate of the standard deviation, it is a vector\r\n # of length 2, corresponding to each endpoint.\r\n\r\n Ybar[,,i]<-sapply(1:k,function(x)matrix(rnorm(2), nrow = 1) %*% retval[[x]])\r\n # 2 by 4 matrix, the last column is the control.\r\n\r\n for(cross in 1:(k-1))\r\n #ComponentLRT[[cross]][,,i]<-sapply(1:choose(k-1,cross),function(j)sapply(1:2^cross,function(x) .LR(Amat=NP$Comp.Amat[[cross]][[j]][[x]],k=k,m=2,Ybar=Ybar[,,i],sigma=sigma[i,],n=n)))\r\n for(j in 1:choose(k-1,cross))\r\n ComponentLRT[[cross]][,j,i]<-sapply(1:2^cross,function(x) .LR(Amat=NP$Comp.Amat[[cross]][[j]][[x]],k=k,m=2,Ybar=Ybar[,,i],sigma=sigma[i,],n=n))\r\n\t\t\t# Compute all the likelihood ratio statistics. For some reason, it is faster to use a for loop.\r\n }\r\n return(list('ComponentLRT'=ComponentLRT,'NP'=NP,'n'=n,'simu'=simu))\r\n}\r\n\r\n#t<-proc.time()[1]\r\n#set.seed(10)\r\n#PS4.null<-.rNull.dist(n=rep(50,4),simu=10^3)\r\n#proc.time()[1]-t\r\n\r\n# .rAlternative.dist generate samples from alternative/true distribution and compute likelihood ratio statistics.\r\n# It returns several statistics for different uses.\r\n#\tComponentLRT is used by consonant likelihood ratio test\r\n#\ttstat is used by Dunnett gatekeeping procedure\r\n#\tDP.object is used by Decision path partition testing\r\n#\tNP, scenario, powersimu and delta is carried out to identify the problem.\r\n.rAlternative.dist<-function(n=rep(50,4),powersimu=10^5,rho=0.3,delta=c(0,0),scenario=matrix(0,nrow=2,ncol=3)){\r\n # delta is the difference between treatment and control that we want to detect.\r\n\tk<-length(n)\r\n balanced<-(length(unique(n[1:(k-1)]))==1)\r\n NP<-.naturalpartition(k=k,m=2,balanced=balanced)\r\n\r\n sigma<-matrix(nrow=powersimu,ncol=2)\r\n Ybar<-array(dim=c(2,k,powersimu))\r\n ComponentLRT<-list()\r\n\ttstat<-array(dim=c(2,k-1,powersimu))\r\n # tstat is the t statistics used in Dunnett Gatekeeping procedure.\r\n\tfor(cross in 1:(k-1)) ComponentLRT[[cross]]<-array(dim=c(2^cross,choose(k-1,cross),powersimu))\r\n if(length(delta)!=2)stop(\"delta should be of the same length as the number of endpoints!\")\r\n trtmean<-cbind(scenario,delta)\r\n\r\n retval<-list()\r\n VC<-matrix(rho,nrow=2,ncol=2)+(1-rho)*diag(2)\r\n for(i in 1:k){\r\n altersigma<-VC/n[i]\r\n ev<-eigen(altersigma, symmetric = TRUE)\r\n retval[[i]] <- ev$vectors %*% diag(sqrt(ev$values), length(ev$values)) %*% t(ev$vectors)\r\n }\r\n\r\n object<-list()\r\n for(i in 1:powersimu){\r\n sigma[i,]<-rchisq(2,df=sum(n-1))/sum(n-1)\r\n # sigma[i,] is the pooled estimate of the standard deviation, it is a vector\r\n # of length 2, corresponding to each endpoint.\r\n\r\n Ybar[,,i]<-sapply(1:k,function(x) sweep(matrix(rnorm(2), nrow = 1) %*% retval[[x]], 2, trtmean[,x], \"+\") )\r\n # 2 by 4 matrix, the last column is the control\r\n\r\n for(cross in 1:(k-1))\r\n for(j in 1:choose(k-1,cross))\r\n ComponentLRT[[cross]][,j,i]<-sapply(1:2^cross,function(x) .LR(Amat=NP$Comp.Amat[[cross]][[j]][[x]],k=k,m=2,Ybar=Ybar[,,i],sigma=sigma[i,],n=n))\r\n\r\n }\r\n return(list('ComponentLRT'=ComponentLRT,'NP'=NP,'scenario'=scenario,'delta'=delta,'powersimu'=powersimu))\r\n}\r\n\r\n#t<-proc.time()[1]\r\n#PS4.alter<-.rAlternative.dist(n=rep(50,4),powersimu=10^4,rho=0.3,delta=c(0,0),scenario=matrix(c(0,0.65,0.65,0.65,0,0.65),nrow=2,ncol=3,byrow=T))\r\n#proc.time()[1]-t\r\n\r\n\r\n# In Windows System\r\n#if(!is.loaded(\"consonant.adj\")) dyn.load('./consonant.adj.dll')\r\n# In Linux System\r\ndyn.load(\"src/clrt.so\")\r\n.CLRT.PS4.cv<-function(alpha=0.025,null){\r\n # The number of endpoints comes from null, which is fixed at 2.\r\n\tn<-null$n\r\n simu<-null$simu\r\n k<-length(n)\r\n balanced<-(length(unique(n[1:(k-1)]))==1)\r\n NP<-null$NP\r\n ComponentLRT.cv<-list()\r\n for(cross in 1:(k-1)) ComponentLRT.cv[[cross]]<-matrix(nrow=2^cross,ncol=choose(k-1,cross))\r\n\r\n if(balanced){\r\n ComponentLRT.cv[[1]][1,]<-ComponentLRT.cv[[1]][2,]<-quantile(null$ComponentLRT[[1]],probs=1-alpha)\r\n for(cross in 2:(k-1)){\r\n n.adj<-dim(NP$col.ind[[cross-1]])[2]\r\n # List of variables needed by .C function\r\n\t\t# NP$col.ind[[cross-1]] is a choose(k-1,cross) by cross matrix\r\n # NP$row.ind[[cross-1]] is a 2^cross by cross matrix\r\n\t\t#\tthey share the same number of columns cross, which is the number of hypotheses to test in\r\n\t\t#\tthe consonance adjustment. Denoted by n.adj (equal to cross).\r\n # null$ComponentLRT[[cross-1]] is a 2^(cross-1) * choose(k-1,cross-1) * simu array\r\n # null$ComponentLRT[[cross]] is a 2^cross * choose(k-1,cross) * simu array\r\n for(a in 1:2^cross){\r\n cv<-sapply(1:choose(k-1,cross), function(j)\r\n sapply(1:n.adj,function(x)ComponentLRT.cv[[cross-1]][NP$row.ind[[cross-1]][a,x],NP$col.ind[[cross-1]][j,x]]))\r\n # cv is a n.adj (cross) by choose(k-1,cross) matrix\r\n\t\t\t\r\n\t\t\t# The following .C code is the consonance adjustment, it will replace the likelihood ratio statistics of\r\n\t\t\t#\tthose intersection hypotheses do not satisfy consonance with 0.\r\n null$ComponentLRT[[cross]][a,,]<-.C(\"component_adj\",\r\n as.double(null$ComponentLRT[[cross-1]]),\r\n as.integer(2^(cross-1)),\r\n as.integer(choose(k-1,cross-1)),\r\n ComponentLRT_post=as.double(null$ComponentLRT[[cross]][a,,]),\r\n as.integer(choose(k-1,cross)),\r\n as.integer(NP$row.ind[[cross-1]][a,]),\r\n as.integer(NP$col.ind[[cross-1]]),\r\n as.double(cv),\r\n as.integer(n.adj),\r\n as.integer(simu),\r\n PACKAGE=\"clrt\" \r\n )$ComponentLRT_post\r\n }\r\n\t\t# For balanced case, the critical constants are the same among intersection hypotheses with the same number\r\n\t\t#\tof treatments involved regardless of endpoints involved.\r\n for(unq in k:1){\r\n L<-which(sapply(1:2^cross,function(x)length(unique(NP$component.array[[cross]][x,,1]))==unq))\r\n if(length(L)==0)next\r\n ComponentLRT.cv[[cross]][L,]<-quantile(null$ComponentLRT[[cross]][L,,],probs=1-alpha)\r\n }\r\n }\r\n }\r\n\r\n else{\r\n for(j in 1:(k-1))ComponentLRT.cv[[1]][,j]<-quantile(null$ComponentLRT[[1]][,j,],probs=1-alpha)\r\n for(cross in 2:(k-1)){\r\n n.adj<-dim(NP$col.ind[[cross-1]])[2]\r\n for(a in 1:2^cross){\r\n cv<-sapply(1:choose(k-1,cross), function(j)\r\n sapply(1:n.adj,function(x)ComponentLRT.cv[[cross-1]][NP$row.ind[[cross-1]][a,x],NP$col.ind[[cross-1]][j,x]]))\r\n null$ComponentLRT[[cross]][a,,]<-.C(\"component_adj\",\r\n as.double(null$ComponentLRT[[cross-1]]),\r\n as.integer(2^(cross-1)),\r\n as.integer(choose(k-1,cross-1)),\r\n ComponentLRT_post=as.double(null$ComponentLRT[[cross]][a,,]),\r\n as.integer(choose(k-1,cross)),\r\n as.integer(NP$row.ind[[cross-1]][a,]),\r\n as.integer(NP$col.ind[[cross-1]]),\r\n as.double(cv),\r\n as.integer(n.adj),\r\n as.integer(simu),\r\n PACKAGE=\"clrt\" \r\n )$ComponentLRT_post\r\n }\r\n for(unq in k:1){\r\n L<-which(sapply(1:2^cross,function(x)length(unique(NP$component.array[[cross]][x,,1]))==unq))\r\n if(length(L)==0)next\r\n ComponentLRT.cv[[cross]][L,]<-sapply(1:choose(k-1,cross),function(j)quantile(null$ComponentLRT[[cross]][L,j,],probs=1-alpha))\r\n }\r\n }\r\n }\r\n\r\n return(ComponentLRT.cv)\r\n}\r\n\r\n#a<-proc.time()[1]\r\n#cv<-.CLRT.PS4.cv(alpha=0.025,PS4.null)\r\n#(proc.time()[1]-a)\r\n#dyn.unload('./consonant.adj.dll')\r\n\r\n.CLRT.PS4.test<-function(alpha=0.05,cv=NULL,n=rep(50,4),ybar,sigma,alter=NULL,powersimu=NULL,null=NULL,rho=0,delta=c(0,0),scenario=NULL){\r\n # The number of endpoints in this function is fixed at 2.\r\n\t# This function can take existing observations generated by .rAlternative.dist before, specify \"alter\".\r\n\t#\tThe delta and scenario will be obtained from the list \"alter\".\r\n\t# This function can also generate samples using .rAlternative.dist, give the desired sample size by \"powersimu\".\r\n\t#\tAnd specify the correlation between endpoints with \"rho\" and the scenario want to test.\r\n\t# Otherwise, this function is used to test a specific observation, give their mean matrix and variance vector\r\n\t#\tby \"ybar\" and \"sigma\". ybar is a m-by-k matrix treatment means, the last column is the control. sigma is\r\n\t#\ta vector of length m, the stdev of each endpoint.\r\n\tk=length(n)\r\n m=2\r\n balanced<-(length(unique(n[1:(k-1)]))==1)\r\n\t\r\n\tif(is.null(cv))cv=.CLRT.PS4.cv(alpha=alpha,null=null)\r\n\t\r\n if(is.null(powersimu)){\r\n NP<-.naturalpartition(k=k,m=2,balanced=balanced)\r\n if(is.null(alter)){\r\n powersimu=1\r\n alter<-list('ComponentLRT'=list())\r\n for(cross in 1:(k-1)) alter$ComponentLRT[[cross]]<-array(dim=c(2^cross,choose(k-1,cross),1))\r\n ybar[,k]<-ybar[,k]+delta\r\n for(cross in 1:(k-1))\r\n for(j in 1:choose(k-1,cross))\r\n alter$ComponentLRT[[cross]][,j,1]<-sapply(1:2^cross,function(x) .LR(Amat=NP$Comp.Amat[[cross]][[j]][[x]],k=k,m=2,Ybar=ybar,sigma=sigma,n=n))\r\n }\r\n else{\r\n powersimu<-alter$powersimu\r\n scenario<-alter$scenario\r\n delta<-alter$delta\r\n }\r\n }else{\r\n alter<-.rAlternative.dist(n=n,powersimu=powersimu,rho=rho,delta=delta,scenario=scenario)\r\n NP<-alter$NP\r\n }\r\n\r\n for(cross in 2:(k-1)){\r\n n.adj<-dim(NP$col.ind[[cross-1]])[2]\r\n for(a in 1:2^cross){\r\n cc<-sapply(1:choose(k-1,cross), function(j)\r\n sapply(1:n.adj,function(x)cv[[cross-1]][NP$row.ind[[cross-1]][a,x],NP$col.ind[[cross-1]][j,x]]))\r\n # The following .C code is the consonance adjustment, it will replace the likelihood ratio statistics of\r\n\t\t\t#\tthose intersection hypotheses do not satisfy consonance with 0.\r\n alter$ComponentLRT[[cross]][a,,]<-.C(\"component_adj\",\r\n as.double(alter$ComponentLRT[[cross-1]]),\r\n as.integer(2^(cross-1)),\r\n as.integer(choose(k-1,cross-1)),\r\n ComponentLRT_post=as.double(alter$ComponentLRT[[cross]][a,,]),\r\n as.integer(choose(k-1,cross)),\r\n as.integer(NP$row.ind[[cross-1]][a,]),\r\n as.integer(NP$col.ind[[cross-1]]),\r\n as.double(cc),\r\n as.integer(n.adj),\r\n as.integer(powersimu),\r\n PACKAGE=\"clrt\" \r\n )$ComponentLRT_post\r\n }\r\n }\r\n\t# After the consonance adjustment, compare the likelihood ratio statistics with critical constants.\r\n if(is.null(null)){\r\n\t\trejection<-matrix(nrow=(m+1)^(k-1)-1,ncol=powersimu)\r\n\t\tfor(cross in 1:(k-1)){\r\n\t\t\tfor(i in 1:choose(k-1,cross)){\r\n\t\t\t\tfor(j in 1:m^cross){\r\n\t\t\t\t\tfor(h in 1:((m+1)^(k-1)-1)){\r\n\t\t\t\t\t\tif(all(NP$matrix[h,]==NP$component.array[[cross]][j,,i])){\r\n\t\t\t\t\t\t\trejection[h,]<-sapply(1:powersimu,function(x)alter$ComponentLRT[[cross]][j,i,x]>cv[[cross]][j,i])\r\n\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t}\r\n\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\t# If p-value is desired, then compare likelihood ratio statistics with the null distribution and calculate p-value.\r\n\telse{\r\n\t\tpvalue<-rejection<-matrix(nrow=(m+1)^(k-1)-1,ncol=powersimu)\r\n\t\tfor(cross in 1:(k-1)){\r\n\t\t\tfor(i in 1:choose(k-1,cross)){\r\n\t\t\t\tfor(j in 1:m^cross){\r\n\t\t\t\t\tfor(h in 1:((m+1)^(k-1)-1)){\r\n\t\t\t\t\t\tif(all(NP$matrix[h,]==NP$component.array[[cross]][j,,i])){\r\n\t\t\t\t\t\t\tpvalue[h,]<-sapply(1:powersimu,function(x)mean(null$ComponentLRT[[cross]][j,i,]>alter$ComponentLRT[[cross]][j,i,x]))\r\n\t\t\t\t\t\t\trejection[h,]<-pvalue[h,] 0){\n\t\t# Determine Cartesian (Original projection)\n\t\torg_cart = LatLong_Cartesian(out_latlon$LATITUDE[i_trans], out_latlon$LONGITUDE[i_trans], org_en$PROJECTION[i_trans])\n\t\t\n\t\t# Apply Helmert transformation to convert original projections to WGS84 (Cartesian in WGS84)\n\t\thelm_tran = helmert_trans(x =org_cart$x, y = org_cart$y, z = org_cart$z, trans = paste(org_en$PROJECTION[i_trans],\"toWGS84\", sep=\"\"))\n\t\t\n\t\t# Convert Cartesian coordinates to Latitude/Longitude (Lat Lon in WGS84)\n\t\tout_latlon[i_trans,] = Cartesian_LatLong(helm_tran$x, helm_tran$y, helm_tran$z, \"UTM30\")\n }\n # Return output\n return(out_latlon)\n}\n\n#### ADDINTIONAL FUNCTIONS ####\n\ngr_det_country <-\n function(gridref){\n # Create variable to store output\n cty_out = rep(NA, length(gridref))\n \n \"(^[[:upper:]]{1,2}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{1,2}[[:digit:]]{2,}$)\"\n \n # Find British Gridrefs\n cty_out[grepl('(^[[:upper:]]{2}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{2}[[:digit:]]{2,}$)',gridref) & !grepl('^(WA)|(WV)',gridref)] = \"OSGB\"\n \n # Find Irish Gridrefs\n cty_out[grepl('(^[[:upper:]]{1}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{1}[[:digit:]]{2,}$)',gridref)] = \"OSNI\"\n \n # Find Channel Islands Gridrefs\n cty_out[grepl('(^(WA)|(WV)[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^(WA)|(WV)[[:digit:]]{2,}$)',gridref)] = \"UTM30\"\n \n # Return output object\n return(cty_out)\n }\n\n\ngr_let2num <-\n function(gridref, centre = FALSE, gr_prec = NULL, return_projection = FALSE){\n # Function required to calculate easting in Letter Grid\n spmod = function(x, mod){\n ret_obj = x %% mod\n ret_obj[ret_obj == 0] = mod\n return(ret_obj)\n }\n \n # Validate grid reference format (removing any spaces or hyphens)\n gr_comps = gr_components(gridref)\n gridref = gsub(\"[ -]\",\"\",toupper(gridref))\n \n # Setup variable to hold output\n len_grvec = nrow(gr_comps)\n if(return_projection){\n ret_obj = data.frame( EASTING = rep(NA,len_grvec), NORTHING = rep(NA, len_grvec), PROJECTION = rep(NA, len_grvec), row.names = NULL ) # row.names set to null to stop duplicate row names error\n } else {\n ret_obj = data.frame( EASTING = rep(NA,len_grvec), NORTHING = rep(NA, len_grvec), row.names = NULL ) # row.names set to null to stop duplicate row names error\n }\n \n # First find all British Gridrefs\n cty_inds = which(grepl('(^[[:upper:]]{2}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{2}[[:digit:]]{2,}$)',gr_comps$VALID_GR) & !grepl('^(WA)|(WV)',gr_comps$VALID_GR))\n \n # If British Gridrefs found then calc easting and northings\n if(length(cty_inds) > 0){\n # Get position of gridref letters in grid\n l1 = match(substr(gr_comps$CHARS[cty_inds],1,1), LETTERS[-9])\n l2 = match(substr(gr_comps$CHARS[cty_inds],2,2), LETTERS[-9])\n # Determine initial easting northing digits based on 500km square\n e = (spmod(l1,5) - 1)*5\n n = floor(abs(l1 - 25)/5)*5\n # Modify initial easting/northing digits based on 100km square\n e = e + (spmod(l2,5) - 1)\n n = n + floor(abs(l2 - 25)/5)\n # Recalulate for false origin (SV) of British Grid\n e = e - 10\n n = n - 5\n # Extend so easting and northing digits so that nchars of east_num/north_num = 5 right padded with zeros\n east_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_EAST[cty_inds], width = 5))\n north_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_NORTH[cty_inds], width = 5))\n # append numeric part of references to grid index\n e = paste(e,east_num, sep=\"\")\n n = paste(n,north_num, sep=\"\")\n # Overwrite placeholder values in ret_obj\n ret_obj[cty_inds,c(\"EASTING\", \"NORTHING\")] = c(as.numeric(e), as.numeric(n))\n if(return_projection){\n ret_obj[cty_inds,\"PROJECTION\"] = \"OSGB\"\n }\n }\n \n # Find all Irish Gridrefs\n cty_inds = which(grepl('(^[[:upper:]]{1}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{1}[[:digit:]]{2,}$)',gr_comps$VALID_GR))\n # If Irish Gridrefs found the calc easting and northings\n if(length(cty_inds) > 0){\n # Get position of gridref letters in grid\n l2 = match(substr(gr_comps$CHARS[cty_inds],1,1), LETTERS[-9])\n # Determine initial easting/northing digits based on 100km square\n e = spmod(l2,5) - 1\n n = floor(abs(l2 - 25)/5)\n # Extend so easting and northing digits so that nchars of east_num/north_num = 5 right padded with zeros\n east_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_EAST[cty_inds], width = 5))\n north_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_NORTH[cty_inds], width = 5))\n # append numeric part of references to grid index\n e = paste(e,east_num, sep=\"\")\n n = paste(n,north_num, sep=\"\")\n # Overwrite placeholder values in ret_obj\n ret_obj[cty_inds,c(\"EASTING\", \"NORTHING\")] = c(as.numeric(e), as.numeric(n))\n if(return_projection){\n ret_obj[cty_inds,\"PROJECTION\"] = \"OSNI\"\n }\n }\n \n # Find all Channel Islands Gridrefs\n cty_inds = which(grepl('(^(WA)|(WV)[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^(WA)|(WV)[[:digit:]]{2,}$)',gr_comps$VALID_GR))\n # If CI gridrefs found then calc easting and northings\n if(length(cty_inds) > 0){\n # Determine initial easting/northing based on letters\n e = rep(5, length(cty_inds))\n n = ifelse(grepl('^(WA)[[:digit:]]{2,}$',gr_comps$VALID_GR[cty_inds]),55,54)\n # Extend so easting and northing digits so that nchars of east_num/north_num = 5 right padded with zeros\n east_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_EAST[cty_inds], width = 5))\n north_num = gsub(\" \",\"0\", format(gr_comps$DIGITS_NORTH[cty_inds], width = 5))\n # append numeric part of references to grid index\n e = paste(e,east_num, sep=\"\")\n n = paste(n,north_num, sep=\"\")\n # Overwrite placeholder values in ret_obj\n ret_obj[cty_inds,c(\"EASTING\", \"NORTHING\")] = c(as.numeric(e), as.numeric(n))\n if(return_projection){\n ret_obj[cty_inds,\"PROJECTION\"] = \"UTM30\"\n }\n }\n \n # If any grid refs contained a tetrad or quadrant code then need to modify the easting and northing\n # Find all grid refs with a tetrad code\n cty_inds = which(!is.na(gr_comps$TETRAD))\n # For these grid refs modify the eastings and northings accordingly\n if(length(cty_inds) > 0){\n # Get list of tetrad codes (all letters but O)\n tet_codes = LETTERS[-15]\n # Determine the position in the tetrad codes vector for each code\n code_match = match(gr_comps$TETRAD[cty_inds], tet_codes)\n # Modify easting\n ret_obj[cty_inds, \"EASTING\"] = ret_obj[cty_inds,\"EASTING\"] + ((code_match-1) %/% 5)*2000\n # Modify northing\n ret_obj[cty_inds, \"NORTHING\"] = ret_obj[cty_inds,\"NORTHING\"] + ((code_match-1) %% 5)*2000\n }\n \n # Find all grid refs with a quadrant code\n cty_inds = which(!is.na(gr_comps$QUADRANT))\n # For these grid refs modify the eastings and northings accordingly\n if(length(cty_inds) > 0){\n # Get list of tetrad codes (all letters but O)\n quad_codes = c(\"SW\",\"NW\",\"SE\",\"NE\")\n # Determine the position in the tetrad codes vector for each code\n code_match = match(gr_comps$QUADRANT[cty_inds], quad_codes)\n # Modify easting\n ret_obj[cty_inds, \"EASTING\"] = ret_obj[cty_inds,\"EASTING\"] + ((code_match-1) %/% 2)*5000\n # Modify northing\n ret_obj[cty_inds, \"NORTHING\"] = ret_obj[cty_inds,\"NORTHING\"] + ((code_match-1) %% 2)*5000\n }\n \n # If centre is true the determine precision and give easting and northing for centre of gridref\n if(centre){\n # Determine precision (if gr_prec not supplied)\n if(is.null(gr_prec)){\n gr_prec = gr_comps$PRECISION\n }\n # Add half of precision to easting and northing\n ret_obj[,c(\"EASTING\", \"NORTHING\")] = ret_obj[,c(\"EASTING\", \"NORTHING\")] + (gr_prec/2)\n }\n # Return easting and Northings\t\n return(ret_obj)\n }\n\n\nOSGridstoLatLong <-\n function(Easting, Northing, Datum = \"OSGB\", datum_params = NULL, full_output = FALSE) {\n # If datum_params is null then defaults data.frame included with package will be used\n if(is.null(datum_params)){\n\n # Set datum_params to datum_vars\n datum_params = datum_vars\n }\n \n # Determine length of Easting & check same as Northing\n east_len = length(Easting)\n if(length(Northing) != east_len){\n stop(\"ERROR: 'Easting' & 'Northing' are of different lengths\")\n }\n \n # Get list of Datums to be converted from Datum\n # If length of Datum input not 1 or same length as Easting/Northing then stop\n if(!length(Datum) %in% c(1,east_len)){\n stop(\"ERROR: Length of 'Datum' does not match length of Easting/Northing values\")\n }\n datum_list = na.omit(unique(Datum))\n # Check all Datum are in datum_params data frame\n miss_datum = which(!datum_list %in% datum_params$Datum)\n if(length(miss_datum) > 0){\n stop(paste(\"ERROR: Datum present in data for which parameters have not been given (\",paste(sQuote(datum_list[miss_datum]), collapse=\",\"), \")\", sep=\"\"))\n }\n \n # Setup object to hold output data\n if(full_output){\n ret_obj = data.frame(EASTING = Easting, NORTHING = Northing, DATUM = Datum, LATITUDE = rep(NA, east_len), LONGITUDE =rep(NA, east_len), stringsAsFactors = FALSE)\n } else {\n ret_obj = data.frame(LATITUDE = rep(NA, east_len), LONGITUDE =rep(NA, east_len), stringsAsFactors = FALSE)\n }\n \n # Loop through datum and extract params and then calculate lat long\n for(i_datum in 1:length(datum_list)){\n \n # Extract indices of easting/northing values corresponding to current datum\n if(length(Datum) == 1){\n dat_inds = 1:east_len\n } else {\n dat_inds = which(Datum == datum_list[i_datum])\n }\n \n # Extract datum params from datum_params (at same time covert lat0 and lon0 from degrees to radians\n par_ind = which(datum_params$Datum == datum_list[i_datum])\n # Check only one row of datum parameters data frame matches current datum\n if(length(par_ind) > 1){\n stop(paste(\"ERROR: More than one match for current Datum (\",sQuote(datum_list[i_datum]),\") found in datum_params data frame\",sep=\"\"))\n }\n a = datum_params$a[par_ind]\n b = datum_params$b[par_ind]\n F0 = datum_params$F0[par_ind]\n lat0 = datum_params$lat0[par_ind] * (pi/180) # Converting to radians\n lon0 = datum_params$lon0[par_ind] * (pi/180) # Converting to radians\n N0 = datum_params$N0[par_ind]\n E0 = datum_params$E0[par_ind]\n \n \n # Calculate other derived variables for projection/datum\n e2 = 1 - (b^2)/(a^2)\t\t# eccentricity squared\n n = (a-b)/(a+b)\n n2 = n^2 \t\t\t\t\t# Calculate n squared (used several times so store as variable)\n n3 = n^3\t\t\t\t\t# Calculate n cubed (used several times so store as variable)\n \n # Iterate to estimate value of lat and M\n # Intial values\n # Lat\n lat = ( (Northing[dat_inds] - N0) / (a * F0) ) + lat0\n # Meridional Arc\n Ma = ( 1 + n + ((5/4)*n2) + ((5/4)*n3) ) * (lat-lat0)\n Mb = ( (3*n) + (3*n2) + ((21/8)*n3) ) * sin(lat-lat0) * cos(lat+lat0)\n Mc = ( ((15/8)*n2) + ((15/8)*n3) ) * sin(2*(lat-lat0)) * cos(2*(lat+lat0))\n Md = ( (35/24)*n3) * sin(3*(lat-lat0)) * cos(3*(lat+lat0))\n M = (b * F0) * (Ma - Mb + Mc - Md)\t\t\t# Calculate Developed Meridional arc (M)\n # Setup index for lats that need further iteration\n iter_inds = which(abs( Northing[dat_inds] - N0 - M) >= 0.01)\n while(length(iter_inds) > 0){\n # Lat\n lat[iter_inds] = ( (Northing[dat_inds][iter_inds] - N0 - M[iter_inds]) / (a * F0) ) + lat[iter_inds]\n # Meridional Arc\n Ma[iter_inds] = ( 1 + n + ((5/4)*n2) + ((5/4)*n3) ) * (lat[iter_inds]-lat0)\n Mb[iter_inds] = ( (3*n) + (3*n2) + ((21/8)*n3) ) * sin(lat[iter_inds]-lat0) * cos(lat[iter_inds]+lat0)\n Mc[iter_inds] = ( ((15/8)*n2) + ((15/8)*n3) ) * sin(2*(lat[iter_inds]-lat0)) * cos(2*(lat[iter_inds]+lat0))\n Md[iter_inds] = ( (35/24)*n3) * sin(3*(lat[iter_inds]-lat0)) * cos(3*(lat[iter_inds]+lat0))\n M[iter_inds] = (b * F0) * (Ma[iter_inds] - Mb[iter_inds] + Mc[iter_inds] - Md[iter_inds])\t\t\t# Calculate Developed Meridional arc (M)\n # Recalculate iteration index\n iter_inds = which(abs( Northing[dat_inds] - N0 - M) >= 0.01)\n }\n \n sinLat = sin(lat)\n tanLat = tan(lat)\n tan2Lat = tanLat^2\n tan4Lat = tanLat^4\n tan6Lat = tanLat^6\n secLat = 1 / cos(lat)\n \n elon = Easting[dat_inds] - E0\n \n nu = (a * F0)*(1-e2*sinLat^2)^-0.5 # transverse radius of curvature\n rho = (a * F0) * (1-e2)*(1-e2*sinLat^2)^-1.5 # meridional radius of curvature\n eta2 = (nu/rho)-1\t\t\t\t\t\t\t\t# East-west component of the deviation of the vertical squared\n \n VII = tanLat / (2*rho*nu)\n VIII = ( tanLat / (24*rho*nu^3) ) * ( 5 + (3*tan2Lat) + eta2 - (9 * tan2Lat * eta2) )\n IX = (tanLat/(720*rho*nu^5)) * (61 + (90*tan2Lat) + (45*tan4Lat))\n X = secLat / nu\n XI = (secLat / (6 * nu^3)) * ( (nu/rho) + 2*tan2Lat)\n XII = (secLat / (120 * nu^5)) * (5 + (28*tan2Lat) + (24*tan4Lat))\n XIIA = (secLat / (5040 * nu^7)) * (61 + (662*tan2Lat) + (1320*tan4Lat) + (720*tan6Lat))\n \n Lat_rad = lat - (VII*elon^2) + (VIII*elon^4) - (IX*elon^6)\n Long_rad = lon0 + (X*elon) - (XI*elon^3) + (XII*elon^5) - (XIIA*elon^7)\n \n Latitude = Lat_rad * (180/pi)\n Longitude = Long_rad * (180/pi)\n \n ret_obj[dat_inds,c(\"LATITUDE\",\"LONGITUDE\")] = data.frame(Latitude, Longitude)\n }\n return (ret_obj)\n }\n\n\nLatLong_Cartesian <-\n function(Latitude, Longitude, Datum = \"OSGB\", datum_params = NULL, H = NULL, full_output = FALSE){\n # If datum_params is null then defaults data.frame included with package will be used\n if(is.null(datum_params)){\n # Set datum_params to datum_vars\n datum_params = datum_vars\n }\n \n # Determine length of Latitude & check same as Longitude\n lat_len = length(Latitude)\n if(length(Longitude) != lat_len){\n stop(\"ERROR: 'Latitude' & 'Longitude' are of different lengths\")\n }\n \n # Get list of Datums to be converted from Datum\n # If length of Datum input not 1 or same length as Latitude/Longitude then stop\n if(!length(Datum) %in% c(1,lat_len)){\n stop(\"ERROR: Length of 'Datum' does not match length of Latitude/Longitude values\")\n }\n datum_list = na.omit(unique(Datum))\n # Check all Datum are in datum_params data frame\n miss_datum = which(!datum_list %in% datum_params$Datum)\n if(length(miss_datum) > 0){\n stop(paste(\"ERROR: Datum present in data for which parameters have not been given (\",paste(sQuote(datum_list[miss_datum]), collapse=\",\"), \")\", sep=\"\"))\n }\n \n # Setup object to hold output data (Cartesian Coordinates)\n if(full_output){\n ret_obj = data.frame(LATITUDE = Latitude, LONGITUDE = Longitude, DATUM = Datum, x = rep(NA, lat_len), y = rep(NA, lat_len), z = rep(NA, lat_len), stringsAsFactors = FALSE)\n } else {\n ret_obj = data.frame(x = rep(NA, lat_len), y = rep(NA, lat_len), z = rep(NA, lat_len), stringsAsFactors = FALSE)\n }\n \n # Loop through datum and extract params and then calculate Cartesian Coordinates\n for(i_datum in 1:length(datum_list)){\n \n # Extract indices of lat/long values corresponding to current datum\n if(length(Datum) == 1){\n dat_inds = 1:lat_len\n } else {\n dat_inds = which(Datum == datum_list[i_datum])\n }\n \n # Extract datum params from datum_params (at same time covert lat0 and lon0 from degrees to radians\n par_ind = which(datum_params$Datum == datum_list[i_datum])\n # Check only one row of datum parameters data frame matches current datum\n if(length(par_ind) > 1){\n stop(paste(\"ERROR: More than one match for current Datum (\",sQuote(datum_list[i_datum]),\") found in datum_params data frame\",sep=\"\"))\n }\n a = datum_params$a[par_ind]\n b = datum_params$b[par_ind]\n \n # Height (H) assummed to be 0 unless specified\n if(is.null(H)){\n H = 0\n } else {\n H = H\n }\n \n # Convert latitude/longitude values into radians\n lat = Latitude[dat_inds] * (pi/180)\n lon = Longitude[dat_inds] * (pi/180)\n \n # Calculate eccentricity squared (e2)\n e2 = (a^2 - b^2)/a^2\n \n # Calculate Cartezian coordinates \n v = a / sqrt(1 - e2*sin(lat)^2)\n x = (v + H)*cos(lat)*cos(lon)\n y = (v + H)*cos(lat)*sin(lon)\n z = (((1-e2)*v) + H)*sin(lat)\n \n # Write values to ret_obj\n ret_obj[dat_inds,c(\"x\",\"y\",\"z\")] = data.frame(x,y,z)\n \n }\n return(ret_obj)\n }\n\n\nhelmert_trans <-\n function(x, y, z, trans = \"OSNItoOSGB\", trans_params = NULL, full_output = FALSE){\n # If trans_params is null then check where helmert_trans_vars data.frame has been loaded from package\n if(is.null(trans_params)){\n\n # set trans_params = helmert_trans_vars\n trans_params = helmert_trans_vars\n }\n \n # Determine length of input vars x,y,z and check all 3 variables are same length\n len_x = length(x)\n if(length(y) != len_x | length(z) != len_x){\n stop(\"ERROR: input variables 'x', 'y' and 'z' are of different lengths\")\n }\n \n # Get list of trans to be performed from trans\n # If length of trans input not 1 or same length as input vars then stop\n if(!length(trans) %in% c(1,len_x)){\n stop(\"ERROR: Length of 'trans' does not match length of input 'x','y' & 'z' values\")\n }\n trans_list = unique(trans)\n # Check all Datum present in data are in datum_params data frame\n miss_trans = which(!trans_list %in% trans_params$TRANS)\n if(length(miss_trans) > 0){\n stop(paste(\"ERROR: Transformation requested for which parameters have not been given (\",paste(sQuote(trans_list[miss_trans]), collapse=\",\"), \")\", sep=\"\"))\n }\n \n # Setup object to hold output data (x,y,z)\n if(full_output){\n ret_obj = data.frame(org_x = x, org_y = y, org_z = z, TRANS = trans, x = rep(NA, len_x), y = rep(NA, len_x), z = rep(NA, len_x), stringsAsFactors = FALSE)\n } else {\n ret_obj = data.frame(x = rep(NA, len_x), y = rep(NA, len_x), z = rep(NA, len_x), stringsAsFactors = FALSE)\n }\n \n # Loop through transformations and extract params and then perform helmert transformation\n for(i_trans in 1:length(trans_list)){\n # Extract indices of x,y,z values corresponding to current transformation\n if(length(trans) == 1){\n dat_inds = 1:len_x\n } else {\n dat_inds = which(trans == trans_list[i_trans])\n }\n # Select relevant helmert transformation parameters\n tp = trans_params[trans_params$TRANS == trans_list[i_trans],]\n # Convert trans paras for rotation from degress to radians\n tp[,c(\"rx\",\"ry\",\"rz\")] = (tp[,c(\"rx\",\"ry\",\"rz\")]/3600) * (pi/180)\n # Normalise s to ppm\n tp[,\"s\"] = tp$s*1e-6\n # Apply transformation\n x_out = x[dat_inds] + (x[dat_inds]*tp$s) - (y[dat_inds]*tp$rz) + (z[dat_inds]*tp$ry) + tp$tx\n y_out = (x[dat_inds]*tp$rz) + y[dat_inds] + (y[dat_inds]*tp$s) - (z[dat_inds]*tp$rx) + tp$ty\n z_out = (-1*x[dat_inds]*tp$ry) + (y[dat_inds]*tp$rx) + z[dat_inds] + (z[dat_inds]*tp$s) + tp$tz\n \n # Insert transformed cartesian coordincates into output variable\n ret_obj[dat_inds,c(\"x\",\"y\",\"z\")] = data.frame(x = x_out, y = y_out, z = z_out)\n }\n return(ret_obj)\n }\n\n\nCartesian_LatLong <-\n function(x,y,z, Datum = \"OSGB\", datum_params = NULL, full_output = FALSE ){\n # If datum_params is null then defaults data.frame included with package will be used\n if(is.null(datum_params)){\n # Determine if datum variables data.frame is already loaded from package\n\n # Set datum_params to datum_vars\n datum_params = datum_vars\n }\n \n # Determine length of input vars x,y,z and check all 3 variables are same length\n len_x = length(x)\n if(length(y) != len_x | length(z) != len_x){\n stop(\"ERROR: input variables 'x', 'y' and 'z' are of different lengths\")\n }\n \n # Get list of Datums to be converted from Datum\n # If length of Datum input not 1 or same length as input vars then stop\n if(!length(Datum) %in% c(1,len_x)){\n stop(\"ERROR: Length of 'Datum' does not match length of input 'x','y' & 'z' values\")\n }\n datum_list = na.omit(unique(Datum))\n # Check all Datum present in data are in datum_params data frame\n miss_datum = which(!datum_list %in% datum_params$Datum)\n if(length(miss_datum) > 0){\n stop(paste(\"ERROR: Datum present in data for which parameters have not been given (\",paste(sQuote(datum_list[miss_datum]), collapse=\",\"), \")\", sep=\"\"))\n }\n \n # Setup object to hold output data (Latitude/Longitude)\n if(full_output){\n ret_obj = data.frame(x = x, y = y, z = z, DATUM = Datum, LATITUDE = rep(NA, len_x), LONGITUDE = rep(NA, len_x), HEIGHT = rep(NA, len_x), stringsAsFactors = FALSE)\n } else {\n ret_obj = data.frame(LATITUDE = rep(NA, len_x), LONGITUDE = rep(NA, len_x), stringsAsFactors = FALSE)\n }\n \n # Setup precision variable (used to determine when to stop iteration)\n prec = 1\n \n # Loop through datum and extract params and then calculate Latitude and Longitude\n for(i_datum in 1:length(datum_list)){\n \n # Extract indices of lat/long values corresponding to current datum\n if(length(Datum) == 1){\n dat_inds = 1:len_x\n } else {\n dat_inds = which(Datum == datum_list[i_datum])\n }\n \n # Extract datum params from datum_params (at same time covert lat0 and lon0 from degrees to radians\n par_ind = which(datum_params$Datum == datum_list[i_datum])\n # Check only one row of datum parameters data frame matches current datum\n if(length(par_ind) > 1){\n stop(paste(\"ERROR: More than one match for current Datum (\",sQuote(datum_list[i_datum]),\") found in datum_params data frame\",sep=\"\"))\n }\n a = datum_params$a[par_ind]\n b = datum_params$b[par_ind]\n \n \n # Calculate eccentricity squared (e2)\n e2 = (a^2 - b^2)/a^2\n \n # Determine longitude\n lon = atan(y[dat_inds]/x[dat_inds])\n # Iteratively determine latitude\n p = sqrt(x[dat_inds]^2 + y[dat_inds]^2)\n lat = atan( z[dat_inds] / (p * (1 - e2)) )\n v = a / sqrt(1 - e2*sin(lat)^2)\n lat2 = atan( (z[dat_inds] + e2*v*sin(lat))/p )\n d_lat = lat - lat2\n iter_inds = which(d_lat > prec)\n while(length(iter_inds) > 0){\n # Change lat to lat2 and recalculate lat2\n lat[iter_inds] = lat2[iter_inds]\n v[iter_inds] = a[dat_inds][iter_inds] / sqrt(1 - e2*sin(lat[iter_inds])^2)\n lat2[iter_inds] = atan( (z[dat_inds][iter_inds] + e2*v[iter_inds]*sin(lat[iter_inds]))/p[iter_inds] )\n d_lat[iter_inds] = lat[iter_inds] - lat2[iter_inds]\n # Recalculate which rows need further iteration\n iter_inds = which(d_lat > prec)\n }\n # Calculate Height (although in majority of cases not really needed/wanted)\n H = (p / cos(lat)) - v\n # Convert Lat / long back to degrees\n lat = lat * (180/pi)\n lon = lon * (180/pi)\n \n # Setup return object\n if(full_output){\n ret_obj[dat_inds,c(\"LATITUDE\",\"LONGITUDE\", \"HEIGHT\")] = data.frame(lat, lon, H)\n } else {\n ret_obj[dat_inds,c(\"LATITUDE\",\"LONGITUDE\")] = data.frame(lat, lon)\n }\n \n }\n # Return output object\n return(ret_obj)\n }\n\nfmt_gridref = function(gridref, gr_fmt = NULL){\n # Setup object to hold output grid refs\n gr_out = rep(NA, length(gridref))\n # convert gridref string to upper case\n gridref = toupper(gridref)\n # Replace any spaces, punctuation or control characters\n gridref = gsub(\"[[:space:][:cntrl:][:punct:]]\", \"\", gridref)\n # Check that gridref conforms to grid reference pattern after removals\n # Get indices of gridrefs which are in a valid format\n gr_inds = which(grepl(\"^[[:upper:]]{1,2}[[:digit:]]{2,}([[:upper:]]?|[[:upper:]]{2})$\", gridref))\n # Copy valid gridrefs to output object\n gr_out[gr_inds] = gridref[gr_inds]\n # Extract components where gr_fmt is not NULL (1 = Whole gridref minus tet/quad codes, 2 = Inital letter(s), 3 = Digits only, 4 = Tetrad/Quad only, 5 = Tetrad only, 6 = Quadrant only)\n if(!is.null(gr_fmt)){\n gr_out = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", paste(\"\\\\\",gr_fmt, sep=\"\"), gr_out)\n }\n # Return formatted gridref\n return(gr_out)\n}\n\ndet_gr_precision <- function(\n gridref\n){\n # Convert letters to uppercase\n gridref = toupper(gridref)\n \n # Set up variable to store output\n prec_out = rep(NA,length(gridref))\n \n # Find valid gridrefs\n v_inds = which(grepl(\"(^[[:upper:]]{1,2}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{1,2}[[:digit:]]{2,}$)\", gridref) & nchar(gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\3\", gridref)) %% 2 == 0)\n \n # Split into components\n gr_char = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\2\", gridref[v_inds])\n gr_digits = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\3\", gridref[v_inds])\n gr_tet = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\5\", gridref[v_inds])\n gr_quad = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\6\", gridref[v_inds])\n \n # Determine number of digits pairs\n n_pairs = nchar(gr_digits)/2\n \n # Determine precison based on gr\n gr_prec = 10^5 / 10^n_pairs\n \n # If gr_tet contains valid letter then ignore precision based on gridref length and assign 2000\n gr_prec[gr_tet %in% LETTERS[-15]] = 2000\n # If not valid tetrad code in gr_tet then set to NA (i.e. O is not a valid tetrad code)\n gr_prec[!gr_tet %in% LETTERS[-15] & gr_tet != \"\"] = NA\n \n # If gr_quad contains valid letter then ignore precision based on gridref length and assign 5000\n gr_prec[gr_quad %in% c(\"NW\",\"NE\",\"SW\",\"SE\")] = 5000\n # If not valid quadrant code in gr_tet then set to NA\n gr_prec[!gr_quad %in% c(\"NW\",\"NE\",\"SW\",\"SE\") & gr_quad != \"\"] = NA\n \n # Write gr_prec values to output variable\n prec_out[v_inds] = gr_prec\n \n # Return output variable\n return(prec_out)\n}\ngr_components <- function(gridref, output_col = NULL){\n \n # Convert letters to uppercase\n gridref = toupper(gridref)\n \n # Set up variable to store output\n gr_comps = data.frame(GRIDREF = gridref, VALID_GR = NA, PRECISION = NA, CHARS = NA, DIGITS = NA, DIGITS_EAST = NA, DIGITS_NORTH = NA, TETRAD = NA, QUADRANT = NA)\n \n # Check values for output_col if supplied\n if(!is.null(output_col)){\t\n if(!all(toupper(output_col) %in% names(gr_comps))){\n stop(\"Supplied output column name not recognised, valid values are:\\n\\t\", paste(shQuote(names(gr_comps)), collapse = \", \"))\n }\n }\n \n # Find valid gridrefs\n v_inds = which(grepl(\"(^[[:upper:]]{1,2}[[:digit:]]{2}([[:upper:]]?|[[:upper:]]{2})$)|(^[[:upper:]]{1,2}[[:digit:]]{2,}$)\", gsub(\"[ -]\",\"\",gridref)) & nchar(gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\3\", gsub(\"[ -]\",\"\",gridref))) %% 2 == 0)\n \n if(length(v_inds) > 0){\n \n # Update valid gridrefs to data.frame\n gr_comps[v_inds,\"VALID_GR\"] = gsub(\"[ -]\",\"\", gridref[v_inds])\n \n # Split into components\n # Characters\n gr_comps[v_inds,\"CHARS\"] = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\2\", gr_comps$VALID_GR[v_inds])\n # Digits\n gr_comps[v_inds,\"DIGITS\"] = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\3\", gr_comps$VALID_GR[v_inds])\n # split digits into east and north\n len_digit = nchar(gr_comps$DIGITS[v_inds])\n gr_comps[v_inds, \"DIGITS_EAST\"] = substr(gr_comps$DIGITS[v_inds], 1, len_digit/2)\n gr_comps[v_inds, \"DIGITS_NORTH\"] = substr(gr_comps$DIGITS[v_inds], (len_digit/2)+1, len_digit)\n # Determine precision based on digits\n gr_comps[v_inds,\"PRECISION\"] = 10^5 / 10^(len_digit[v_inds]/2)\n # Tetrad\n gr_comps[v_inds,\"TETRAD\"] = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\5\", gr_comps$VALID_GR[v_inds])\n # Find blank string values in gr_tet and replace with NA\n na_inds = which(!gr_comps$TETRAD %in% LETTERS[-15])\n if(length(na_inds) > 0){\n gr_comps[na_inds,\"TETRAD\"] = NA\n }\n # Quadrant\n gr_comps[v_inds,\"QUADRANT\"] = gsub(\"^(([[:upper:]]{1,2})([[:digit:]]{2,}))(([[:upper:]]?)|([[:upper:]]{2}))$\", \"\\\\6\", gr_comps$VALID_GR[v_inds])\n # Find blank string values in gr_tet and replace with NA\n na_inds = which(!gr_comps$QUADRANT %in% c(\"NW\",\"NE\",\"SW\",\"SE\"))\n if(length(na_inds) > 0){\n gr_comps[na_inds,\"QUADRANT\"] = NA\n }\n \n # Modify precision if tetrad or quadrant is not null\n # Tetrad\n gr_comps[grepl(\"^[[:upper:]]{1,2}[[:digit:]]{2}[[:upper:]]{1,2}$\", gr_comps$VALID_GR) & !is.na(gr_comps$TETRAD),\"PRECISION\"] = 2000\n # quadrant\n gr_comps[grepl(\"^[[:upper:]]{1,2}[[:digit:]]{2}[[:upper:]]{1,2}$\", gr_comps$VALID_GR) & !is.na(gr_comps$QUADRANT),\"PRECISION\"] = 5000\n \n # Modify valid_gr to remove any gridrefs that had non-valid tetrad/quadrant codes\n na_inds = which(grepl(\"^[[:upper:]]{1,2}[[:digit:]]{2}[[:upper:]]{1,2}$\", gr_comps$VALID_GR) & is.na(gr_comps$TETRAD) & is.na(gr_comps$QUADRANT))\n if(length(na_inds) > 0){\n gr_comps[na_inds,-1] = NA\n }\n }\t\t\n \n # If output_col is null then output all columns otherwise only output requested columns\n if(is.null(output_col)){\n out_obj = gr_comps\n } else {\n out_obj = gr_comps[,toupper(output_col)]\n }\n \n # Return output object\n return(out_obj)\n}\n\ndet_tet_quad <- function(\n gridref,\n precision = NULL,\n prec_out = NULL\n){\n # Setup output object\n out_obj = data.frame(TETRAD_GR = rep(NA, length(gridref)), QUADRANT_GR = NA)\n \n # Split gridref into components (will also check gridref sytax is correct)\n gr_comps = gr_components(gridref)\n \n gr_inds = which(nchar(gr_comps$DIGITS) >= 2 & !is.na(gr_comps$VALID_GR))\t\n sq10 = rep(NA, length(gridref))\n sq10[gr_inds] = paste(gr_comps$CHARS[gr_inds], substr(gr_comps$DIGITS_EAST[gr_inds],1,1), substr(gr_comps$DIGITS_NORTH[gr_inds],1,1), sep=\"\")\n \n # All gridrefs that have valid tetrad/quadrant codes can be filled directly to out_obj\n # Tetrads\n gr_inds = which(!is.na(gr_comps$TETRAD))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"TETRAD_GR\"] = paste(sq10[gr_inds], gr_comps$TETRAD[gr_inds], sep=\"\")\n }\n #Quadrants\n gr_inds = which(!is.na(gr_comps$QUADRANT))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds], gr_comps$QUADRANT[gr_inds], sep=\"\")\n }\n \n # If original gridref had tetrad code then where can be mapped directly to quadrant then do so\n # Find gridrefs with calculated precision of 2000 i.e. those that had a tetrad code in the grid ref\n gr_inds = which(gr_comps$PRECISION == 2000)\n if(length(gr_inds) > 0){\n # SW\n gr_inds = which(gr_comps$PRECISION == 2000 & gr_comps$TETRAD %in% c(\"A\",\"B\",\"F\",\"G\"))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds], \"SW\", sep=\"\") \n }\n # NW\n gr_inds = which(gr_comps$PRECISION == 2000 & gr_comps$TETRAD %in% c(\"D\",\"E\",\"J\",\"I\"))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds], \"NW\", sep=\"\") \n }\n # SE\n gr_inds = which(gr_comps$PRECISION == 2000 & gr_comps$TETRAD %in% c(\"Q\",\"R\",\"V\",\"W\"))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds], \"SE\", sep=\"\") \n }\n # NE\n gr_inds = which(gr_comps$PRECISION == 2000 & gr_comps$TETRAD %in% c(\"T\",\"U\",\"Y\",\"Z\"))\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds], \"NE\", sep=\"\") \n }\n }\t\t\n \n \n # Find all valid gridrefs where precision is high enough\n gr_inds = which(gr_comps$PRECISION <= 1000)\n \n if(length(gr_inds) > 0){\n \n # Extract relevant digits for tetrad/quadrant estimation\n code_e = as.numeric(substr(gr_comps$DIGITS_EAST[gr_inds],2,2))\n code_n = as.numeric(substr(gr_comps$DIGITS_NORTH[gr_inds],2,2))\n \n # Determine tetrad code from easting and northing digits (can perhaps\n # Get list of tetrad codes (no O)\n tet_codes = LETTERS[-15]\n # Get tetrad code for each gridref of suitable precision\n tets = tet_codes[(code_e%/%2)*5 + (code_n%/%2)+1]\n out_obj[gr_inds,\"TETRAD_GR\"] = paste(sq10[gr_inds],tets, sep=\"\")\n \n # Determine quadrant codes from easting and northing digits\n # Build vector of quadrant codes (in correct order)\n quad_codes = c(\"SW\",\"NW\",\"SE\",\"NE\")\n # Get tetrad code for each gridref of suitable precision\n quads = quad_codes[(code_e%/%5)*2 + (code_n%/%5)+1]\n out_obj[gr_inds,\"QUADRANT_GR\"] = paste(sq10[gr_inds],quads, sep=\"\")\n \n } \n \n # If precision is supplied determine if it matches value estimated from gridref\n if(!is.null(precision)){\n # Check that precision is either a vector of length gridref or a single value\n if( !(length(precision) == 1 | length(precision) == length(gridref)) ){\n stop(\"precision does not match gridref length, supply either single value or vector of same length as gridref\")\n }\n # Find non-matching precisions\n # Find non-matching non padded gridrefs (i.e. ones that shouldn't be wrong)\n gr_inds = which(gr_comps$PRECISION != precision & gr_comps$PRECISION != 1000 & (precision != 2000 | precision != 5000) )\n # Find all non-matched precision values\n if(length(gr_inds) > 0){\n stop(\"Precision supplied does not match determined precision for\", length(gr_inds), \" grid refs\")\n }\n # If estimated precision = 1000 and supplied prec = 2000 or 5000 then assume tetrad/quadrant padded values (e.g. BRC type data)\n # Padded tetrads\n # Note if tetrad grid ref and tetrad code in (C,H,K,L,M,N,P,S,X) then quadrant cannot be uniquely determined\n # Find grid refs matching this criteria\n gr_inds = which(gr_comps$PRECISION != precision & gr_comps$PRECISION == 1000 & precision == 2000 & grepl(\"^[[:alpha:]]{1,2}[[:digit:]]{2}[CHKLMNPSX]$\",out_obj$TETRAD_GR))\n # Set quadrant to NA\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"QUADRANT_GR\"] = NA\n }\n # Padded Quadrant\n # For all padded quadrant codes tetrad cannot be uniquely determined\n gr_inds = which(gr_comps$PRECISION != precision & gr_comps$PRECISION == 1000 & precision == 5000)\n # Set quadrant to NA\n if(length(gr_inds) > 0){\n out_obj[gr_inds,\"TETRAD_GR\"] = NA\t\n }\n \n }\t\t\n \n # Return output object based on prec_out value\n if(is.null(prec_out)){\n return(out_obj)\n } else if(prec_out == 2000){\n return(out_obj$TETRAD_GR)\n } else if(prec_out == 5000){\n return(out_obj$QUADRANT_GR)\n }\n}", "meta": {"hexsha": "ddc58e722d8dd0c76976170c1a2cccf3d4813804", "size": 40062, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gr2gps_latlon.r", "max_stars_repo_name": "AugustT/rnbn", "max_stars_repo_head_hexsha": "ab068f1a30071849e5813e22c090b3c70ae0f676", "max_stars_repo_licenses": ["MIT"], "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/gr2gps_latlon.r", "max_issues_repo_name": "AugustT/rnbn", "max_issues_repo_head_hexsha": "ab068f1a30071849e5813e22c090b3c70ae0f676", "max_issues_repo_licenses": ["MIT"], "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/gr2gps_latlon.r", "max_forks_repo_name": "AugustT/rnbn", "max_forks_repo_head_hexsha": "ab068f1a30071849e5813e22c090b3c70ae0f676", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.9755501222, "max_line_length": 285, "alphanum_fraction": 0.5737357097, "num_tokens": 11371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.427753099210801}}
{"text": "#' backsolve\n#' \n#' Solve a triangular system.\n#' \n#' @param r,l\n#' A triangular coefficients matrix.\n#' @param x\n#' The right hand sides.\n#' @param k\n#' The number of equations (columns of r + rows of x) to use.\n#' @param upper.tri\n#' Should the upper triangle be used? (if not the lower is)\n#' @param transpose\n#' Should the transposed coefficients matrix be used? More efficient than\n#' manually transposing with \\code{t()}.\n#' \n#' @examples\n#' library(float)\n#' \n#' s = flrunif(10, 3)\n#' cp = crossprod(s)\n#' y = fl(1:3)\n#' backsolve(cp, y)\n#' \n#' @useDynLib float R_backsolve_spm\n#' @name backsolve\n#' @rdname backsolve\nNULL\n\n\n\nbacksolve_float32 = function(r, x, k=ncol(r), upper.tri=TRUE, transpose=FALSE)\n{\n if (is.integer(r))\n {\n if (is.float(x))\n r = fl(r)\n }\n \n if (is.integer(x))\n {\n if (is.float(r))\n x = fl(x)\n }\n \n if (is.double(r) || is.double(x))\n {\n if (is.float(r))\n r = dbl(r)\n if (is.float(x))\n x = dbl(x)\n \n backsolve(r, x, k, upper.tri, transpose)\n }\n else\n {\n if (!is.numeric(k) || k < 1 || k > nrow(r) || is.na(k))\n stop(\"invalid 'k' argument\")\n \n ret = .Call(R_backsolve_spm, DATA(r), DATA(x), as.integer(upper.tri), as.integer(transpose), as.integer(k))\n float32(ret)\n }\n}\n\nforwardsolve_float32 = function(l, x, k=ncol(l), upper.tri=FALSE, transpose=FALSE)\n{\n backsolve_float32(l, x, k, upper.tri, transpose)\n}\n\n\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"backsolve\", signature(r=\"float32\", x=\"float32\"), backsolve_float32)\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"backsolve\", signature(r=\"float32\", x=\"BaseLinAlg\"), backsolve_float32)\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"backsolve\", signature(r=\"BaseLinAlg\", x=\"float32\"), backsolve_float32)\n\n\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"forwardsolve\", signature(l=\"float32\", x=\"float32\"), forwardsolve_float32)\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"forwardsolve\", signature(l=\"float32\", x=\"BaseLinAlg\"), forwardsolve_float32)\n\n#' @rdname backsolve\n#' @export\nsetMethod(\"forwardsolve\", signature(l=\"BaseLinAlg\", x=\"float32\"), forwardsolve_float32)\n", "meta": {"hexsha": "10b7abeef85bf0f80cc68454bc21af37e40cb91c", "size": 2113, "ext": "r", "lang": "R", "max_stars_repo_path": "R/backsolve.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/backsolve.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/backsolve.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": 21.7835051546, "max_line_length": 111, "alphanum_fraction": 0.6431613819, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42674594988941755}}
{"text": "#!/usr/local/bin/Rscript --vanilla\n\n###############################################################################\n# METAREP : High-Performance Comparative Metagenomics Framework (http://www.jcvi.org/metarep)\n# Copyright(c) J. Craig Venter Institute (http://www.jcvi.org)\n#\n# Licensed under The MIT License\n# Redistributions of files must retain the above copyright notice.\n#\n# link http://www.jcvi.org/metarep METAREP Project\n# package metarep\n# version METAREP v 1.3.2\n# author Johannes Goll\n# lastmodified 2010-07-09\n# license http://www.opensource.org/licenses/mit-license.php The MIT License\n###############################################################################\n\nargs \t\t= commandArgs(TRUE)\ninfile \t\t= args[1];\noutfile \t= args[2];\ntest \t\t= args[3];\npropround \t= as.numeric(args[4]);\npvalround \t= as.numeric(args[5]);\n\ndata = read.table(file=infile,sep=\"\\t\",header=F,colClasses=c(\"character\",\"numeric\",\"numeric\",\"numeric\",\"numeric\"));\nn = nrow(data);\n\n## specify result columns\ncolums = c(\"id\",\"count1\",\"count2\",\"prop1\",\"prop2\",\"odds_ratio\",\"relative_risk\",\"p_value\",\"b_value\",\"q_value\");\n\n## init result data frame\nresult = data.frame(data[,1],matrix(cbind(data[,2],data[,4],matrix(rep(NA,n*(length(colums)-3)),ncol=length(colums)-3)),ncol=length(colums)-1,nrow=n),stringsAsFactors=FALSE);\n\n## set column names for data frame\ncolnames(result) = colums;\n\n## iterate through features\nfor(i in 1:n) {\n\t\n\t## generate 2-2 matrix\n\tm = matrix(as.numeric(data[i,2:5]),ncol=2,nrow=2);\n\t\n\t## proportion one\n\tresult[i,4] = round((m[1,1]/sum(m[,1])),propround);\t\n\t\n\t## proportion two\n\tresult[i,5] = round((m[1,2]/sum(m[,2])),propround);\t\n\n\t## log odds_ratio \t\t \n\tresult[i,6] = round(log((m[1,1]*m[2,2])/(m[2,1]*m[1,2])),3);\n\t\n\t## relative_risk\n\tresult[i,7] = round((m[1,1]/sum(m[,1]))/((m[1,2]/sum(m[,2]))),4);\t\n\t\n\t## execute test\n\tresult[i,8] = do.call(test,list(m))$p.value;\t\n}\n\n## correct for multiple testing and round adjusted p/q-values\nresult[,9] = round(p.adjust(result$p_value, method = \"bonferroni\"),pvalround);\nresult[,10] = round(p.adjust(result$p_value, method = \"fdr\"),pvalround);\n\n## round non adjusted p-value after using the non-rounded values for multi-testing correction\nresult[,8] = round(result$p_value,pvalround);\nwrite.table(result, file=outfile, row.names=F,sep=\"\\t\", eol = \"\\n\",append=F,quote=F)\nq(status=0)", "meta": {"hexsha": "b4b6c35bc347df5b3add86565f38e7fa79a47c6c", "size": 2338, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/r/two_way_sample_test.r", "max_stars_repo_name": "allenlab/PhyloMetarep", "max_stars_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_stars_repo_licenses": ["MIT"], "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/r/two_way_sample_test.r", "max_issues_repo_name": "allenlab/PhyloMetarep", "max_issues_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_issues_repo_licenses": ["MIT"], "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/r/two_way_sample_test.r", "max_forks_repo_name": "allenlab/PhyloMetarep", "max_forks_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_forks_repo_licenses": ["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.4242424242, "max_line_length": 174, "alphanum_fraction": 0.6381522669, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4262736009385053}}
{"text": "#' @export\n#' @title cor.prob\n#' @description couldn't accurately describe\n#' @param \\code{X} \n#' @param \\code{dfr} degrees of freedom\n#' @return \\code{} \n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\ncor.prob <- function(X, dfr = nrow(X) - 2) {\n\t R <- cor(X)\n\t above <- row(R) < col(R)\n\t r2 <- R[above]^2\n\t Fstat <- r2 * dfr / (1 - r2)\n\t R[above] <- 1 - pf(Fstat, 1, dfr)\n\t R\n}\n", "meta": {"hexsha": "7274a83421aea3aeee5e5679bb3a3e05dd47570e", "size": 430, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cor.prob.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/cor.prob.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/cor.prob.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": 23.8888888889, "max_line_length": 53, "alphanum_fraction": 0.5860465116, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42608257720784254}}
{"text": "# Fast version of trigraf assuming that \n# ie(m) < je(m)\n# ie[is in ascending order\n# je is in ascending order within ie,\n# that is, je(ie==i) is in ascending order for each fixed i.\n# Code adapted from C code in trigraf.c, from the spatstat package\n# by Adrian Baddeley.\n#\n\nsubroutine trigraf(nv, ne, ie, je, nt, it, jt, kt)\n#\n# nv --- number of points being triangulated.\n# ne --- number of triangle edges\n# ie and je --- vectors of indices of ends of each edge\n# nt --- number of triangles assumed to be at most ne\n# it, jt, kt --- vectors of indices of vertices of triangles\n#\ninteger firstedge, lastedge;\ndimension ie(1), je(1), it(1), jt(1), kt(1)\n\n# Initialise output.\nnt = 1\nlastedge = 0\nwhile(lastedge < ne) {\n# Consider next vertex i.\n# The edges (i,j) with i < j appear contiguously in the edge list.\n firstedge = lastedge + 1\n i = ie(firstedge)\n do m = firstedge+1,ne {\n if ( ie(m) != i ) break\n }\n lastedge = m-1\n# Consider each pair j, k of neighbours of i, where i < j < k. \n# Scan entire edge list to determine whether j, k are joined by an edge.\n# If so, save triangle (i,j,k) \n if(lastedge > firstedge) {\n do mj = firstedge,lastedge-1 {\n j = je(mj)\n do mk = firstedge+1,lastedge {\n k = je(mk)\n# Run through edges to determine whether j, k are neighbours.\n do m = 1,ne {\n if(ie(m) >= j) break\n }\n while(m <= ne & ie(m) == j) {\n if(je(m) == k) {\n# Add (i, j, k) to list of triangles.\n it(nt) = i;\n jt(nt) = j;\n kt(nt) = k;\n nt = nt+1\n }\n m = m+1\n }\n }\n }\n }\n }\n\nreturn\nend\n", "meta": {"hexsha": "d0c2946850800a32ee9c580826f827dba36b8f87", "size": 1612, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/trigraf.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/code.discarded/trigraf.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/code.discarded/trigraf.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": 26.0, "max_line_length": 72, "alphanum_fraction": 0.5918114144, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4258869025344649}}
{"text": "#################################################################################\n# Monte Carlo method to calculate Multi-Species Indices (MSI)\n# CBS (Statistics Netherlands), july 2016\n# \t- generate MSIs with confidence interval, accounting for sampling error\n# - baseyear for simulated MSIs is flexible\n# - baseyear for plots can be set to 100 for index or for smoothed trend value\n#\t - linear trend classification\n# - smoothed trend classification\n# - compare linear trends before and after changepoint\n# - assess overall change and change in last years\n# - truncation of low indices (and their SE set to 0)\n#################################################################################\n\n#################################################################################\n# Input file has at least these 4 columns:\n# - species (species code)\n# - year\n# - index (base year has index 100; anny year can be the base year)\n# - se (standard error of index; base year has SE zero)\n#################################################################################\n\n# Data import and specificatons\nsetwd(\"E:/MSI/data\") # the path for input and output files.\nrdata <- read.table(\"farmland.txt\", header=TRUE) # name of input file.\njobname <- as.character (\"farmland\") # generic name for output files.\nnsim <- 1000\t\t # number of Monte Carlo simulations.\nSEbaseyear <- 1990 # desired year to set MSI to 1000 and SE to 0; usually the first year of the time series.\nplotbaseyear <- 1990 # desired year to set to 100 in plots.\nindex_smooth <- \"SMOOTH\" # INDEX / SMOOTH: \"INDEX\" will cause the index in plotbaseyear set to 100; \"SMOOTH\" will set the smoothed trend value in the plotbaseyear to 100.\nlastyears <- 10\t\t# last X years of time series for which separate trend (short-term trends) should be calculated.\nmaxCV <- 3 # maximum allowed mean Coefficient of Variation (CV) of species indices (0.5 = 50%). Species with higher mean CV are excluded.\nchangepoint <- 2000 # compare trends before and after this year.\ntruncfac <- 10 # truncation factor (=max year-to-year index ratio). Default for Living Planet Index = 10.\nTRUNC <- 1 # set all indices below TRUNC to this value and their SE to 0. TRUNC <- 0 means no truncation.\n\n# set names of output files\njobnameRESULTS <- paste (jobname, \"_RESULTS.csv\", sep = \"\")\njobnameTRENDS <- paste (jobname, \"_TRENDS.csv\", sep = \"\")\njobnameSIMTRENDS <- paste (jobname, \"_SIMTRENDS.csv\", sep = \"\")\njobnameGRAPH <- paste (jobname, \"_GRAPH.jpg\", sep = \"\")\n\n# Define and calculate model parameters\nspecies <- rdata[,\"species\"]\nyear <- rdata[,\"year\"]\nindex <- rdata[,\"index\"]\nse <- rdata[,\"se\"]\nuspecies <- sort(unique(species))\nnspecies <- length(uspecies)\nuyear <- sort(unique(year))\nnyear <- length(unique(year))\nmeanindex <- tapply(index, species, mean, na.rm=TRUE)/100\nmnindex1 <- as.data.frame(rep(meanindex,each=nyear))\nminyear <- min(year)\nmaxyear <- max(year)\nplotbaseyear <- plotbaseyear-minyear+1\nbaseyear <- max(1,SEbaseyear-minyear+1)\nlastyears <- min(lastyears,nyear)\nINP <- data.frame(cbind(species, year, index, se))\nSPEC <- as.matrix(species)\nspecies <- sort(rep(uspecies,each=nyear))\nyear <- rep(uyear,nspecies)\nINP1 <- data.frame(cbind(species,year))\nINP2 <- merge(INP, INP1, by=c(\"species\",\"year\"), sort=TRUE, all=TRUE)\n\n# Calculate and plot mean CV for indices per species\nCVtemp <- INP2[INP2$index >= 10, ] # select records with index >= 10 for CV calculation\nCVtemp <- CVtemp[!is.na(CVtemp$index), ] # reject missing values\nCV1 <- CVtemp$se/CVtemp$index\nCV1[CV1== 0] <- NA\nCV1[CV1== Inf] <- NA\nspecies2 <- CVtemp$species\nmnCV <- tapply(CV1, species2, mean, na.rm=TRUE)\nplot(uspecies, mnCV, type=\"p\", pch=19, col=\"black\", main=jobname, xlab=\"species code\", ylab=\"meanCV\")\nCV <- as.data.frame(rep(mnCV, each=nyear))\n\n# replace small indices by TRUNC and their SE by zero\nINP3 <- data.frame(cbind(species, year, CV, mnindex1))\ncolnames(INP3) <- c(\"species\",\"year\", \"CV\", \"mnindex1\")\nINP4 <- merge(INP2, INP3, by=c(\"species\",\"year\"), sort=FALSE, all=TRUE)\nINP5 <- subset(INP4, CV < maxCV, select = c(species, year, index, se, mnindex1))\nINP5$index[INP5$index < TRUNC & !is.na(INP5$index)] <- TRUNC \nINP5$se[INP5$index == TRUNC & !is.na(INP5$index)] <- 0\n\n# reset parameters\nindex <- as.vector(INP5[\"index\"])\nse <- as.vector(INP5[\"se\"])\nnobs <- NROW(INP5)\nuspecies <- sort(unique(INP5$species))\nnspecies <- length(uspecies)\nyear <- rep(uyear, nspecies)\n\n# Transform indices and standard deviations to log scale (Delta method)\nLNindex <- as.vector(log(index))\nLNse <- as.vector(se/index)\n\n# Monte Carlo simulations of species indices\nMC <- matrix(NA, nobs, nsim)\nfor (s in 1:nsim) { \n for (o in 1:nobs) {\n MC[o,s] <- rnorm(1, LNindex[o,1], LNse[o,1])\n } \n }\nMC[MC < log(TRUNC)] <- log(TRUNC)\n\n# impute missing values using chain method\nCHAIN <- matrix(NA, nobs, nsim)\nfor (s in 1:nsim ){\n for (o in 1:nobs-1) {\n CHAIN[o,s] <- MC[o+1,s]-MC[o,s]\n }\n for (sp in 1:nspecies) {\n CHAIN[sp*nyear,s] <- NA\n }\n}\n\nCHAIN[CHAIN > log(truncfac)] <- log(truncfac)\nCHAIN[CHAIN < log(1/truncfac)] <- log(1/truncfac)\n\nmnCHAIN <- matrix(NA, nyear, nsim)\nfor (s in 1:nsim) {\n mnCHAIN[,s] <- tapply(CHAIN[,s], year, mean, na.rm=TRUE)\n}\n\nsimMSI <- matrix(NA, nyear, nsim)\nbmin <- baseyear-1\nbplus <- baseyear+1\nfor (s in 1:nsim){\nsimMSI[baseyear,s] <- log(100)\n for (y in bmin:min(bmin,1)){\n simMSI[y,s] <- simMSI[y+1,s] - mnCHAIN[y,s]\n }\n for (y in min(bplus,nyear):nyear){\n simMSI[y,s] <- simMSI[y-1,s] + mnCHAIN[y-1,s]\n }\n}\n\n# calculate MSI and SE\nmeanMSI <- array(NA, dim=c(1, nyear))\nstdevMSI <- array(NA, dim=c(1, nyear)) \nfor (y in 1:nyear) {\n meanMSI[y] <- mean(simMSI[y,])\n stdevMSI[y] <- sd(simMSI[y,])\n}\n\n# Monte Carlo simulations of MSI (for trend calculation)\nsimMSI <- matrix(NA, nyear, nsim)\nfor (s in 1:nsim) { \n for (y in 1:nyear) {\n simMSI[y,s] <- rnorm(1, meanMSI[y], stdevMSI[y])\n } \n}\n\n# Back-transformation of MSI to index scale (Delta method)\nmeanMSI <- array(NA, dim=c(1, nyear))\nstdevMSI <- array(NA, dim=c(1, nyear)) \nfor (y in 1:nyear) {\n meanMSI[y] <- round(exp(mean(simMSI[y,])), digits=2)\n stdevMSI[y] <- round(sd(simMSI[y,])*meanMSI[y], digits=2)\n}\n\n# Confidence interval of MSI on index-scale\nCI <- array(NA, dim=c(nyear, 2))\nfor (y in 1:nyear){\n CI[y,1] <- exp(mean(simMSI[y,])-1.96*sd(simMSI[y,]))\n CI[y,2] <- exp(mean(simMSI[y,])+1.96*sd(simMSI[y,]))\n}\n\n# Overall linear trend per simulation\nlrMSI <- array(NA, dim=c(2, nsim))\nfor (s in 1:nsim) {\n summ <- summary(lm(simMSI[,s] ~ uyear, na.action=na.exclude))\n lrMSI[1,s] <- round(summ$coefficients[2], digits=4)\t# coeff[2] = slope\n lrMSI[2,s] <- round(summ$coefficients[2,2], digits=4) \t# coeff[2,2] = se of slope \n}\n\nSLOPE <- mean(lrMSI[1,])\nsdSLOPE <- sd(as.vector(lrMSI[1,]))\n\n# Back transform trends to index scale:\nSLOPE_mult <- round(exp(SLOPE), digits=4)\nsdSLOPE_mult <- round(sdSLOPE*SLOPE_mult, digits=4)\n\nSLOPE\nsdSLOPE\nSLOPE_mult\nsdSLOPE_mult\n\n# Overall trend classification (see Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nTrendClass <- \"X\"\nif (SLOPE_mult - 1.96*sdSLOPE_mult > 1.05) {TrendClass <- \"strong increase\" } else\n if (SLOPE_mult + 1.96*sdSLOPE_mult < 0.95) { TrendClass <- \"steep decline\" } else\n if (SLOPE_mult - 1.96*sdSLOPE_mult > 1.00) { TrendClass <- \"moderate increase\"} else\n if (SLOPE_mult + 1.96*sdSLOPE_mult < 1.00) { TrendClass <- \"moderate decline\" } else\n if ((SLOPE_mult - 1.96*sdSLOPE_mult - 0.95)*(1.05 - SLOPE_mult + 1.96*sdSLOPE_mult) < 0.00) { TrendClass <- \"uncertain\"} else\n if ((SLOPE_mult + 1.96*sdSLOPE_mult) - (SLOPE_mult - 1.96*sdSLOPE_mult) > 0.10) { TrendClass <- \"uncertain\" } else\n {TrendClass <- \"stable\"}\nTrendClass\n\n# Short term linear trend per simulation\nlrMSI_short <- array(NA, dim=c(2, nsim))\nlyear <- c((maxyear-lastyears+1):maxyear)\nsimMSI_short <- array(NA, dim=c(lastyears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:lastyears) {\n simMSI_short[y, s] <- simMSI[(nyear-lastyears+y),s]\n }\n}\nfor (s in 1:nsim) {\n summ <- summary(lm(simMSI_short[,s] ~ lyear, na.action=na.exclude))\n lrMSI_short[1,s] <- round(summ$coefficients[2], digits=4)\t# coeff[2] = slope\n lrMSI_short[2,s] <- round(summ$coefficients[2,2], digits=4) \t# coeff[2,2] = sd of slope \n}\n\nSLOPE_short <- mean(lrMSI_short[1,])\nsdSLOPE_short <- sd(as.vector(lrMSI_short[1,]))\n\n# Back-transform short-term trends to index scale\nSLOPE_short_mult <- round(exp(SLOPE_short), digits=4)\nsdSLOPE_short_mult <- round(sdSLOPE_short*SLOPE_short_mult, digits=4)\n\nSLOPE_short\nsdSLOPE_short\nSLOPE_short_mult\nsdSLOPE_short_mult\n\n# Short term trend classification (Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nTrendClass_short <- \"X\"\nif (SLOPE_short_mult - 1.96*sdSLOPE_short_mult > 1.05) {TrendClass_short <- \"strong increase\" } else\n if (SLOPE_short_mult + 1.96*sdSLOPE_short_mult < 0.95) { TrendClass_short <- \"steep decline\" } else\n if (SLOPE_short_mult - 1.96*sdSLOPE_short_mult > 1.00) { TrendClass_short <- \"moderate increase\"} else\n if (SLOPE_short_mult + 1.96*sdSLOPE_short_mult < 1.00) { TrendClass_short <- \"moderate decline\" } else\n if ((SLOPE_short_mult - 1.96*sdSLOPE_short_mult - 0.95)*(1.05 - SLOPE_short_mult + 1.96*sdSLOPE_short_mult) < 0.00) { TrendClass_short <- \"uncertain\"} else\n if ((SLOPE_short_mult + 1.96*sdSLOPE_short_mult) - (SLOPE_short_mult - 1.96*sdSLOPE_short_mult) > 0.10) { TrendClass_short <- \"uncertain\" } else\n {TrendClass_short <- \"stable\"}\nTrendClass_short\n\n# linear trend before changepoint per simulation\nlrMSI_before <- array(NA, dim=c(2, nsim))\nbyear <- c(minyear:changepoint)\nbyears <- length(byear)\nsimMSI_before <- array(NA, dim=c(byears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:byears) {\n simMSI_before[y, s] <- simMSI[y,s]\n }\n}\nfor (s in 1:nsim) {\n summb <- summary(lm(simMSI_before[,s] ~ byear, na.action=na.exclude))\n lrMSI_before[1,s] <- round(summb$coefficients[2], digits=4) # coeff[2] = slope\n lrMSI_before[2,s] <- round(summb$coefficients[2,2], digits=4) \t# coeff[2,2] = sd of slope \n}\nSLOPE_before <- round(mean(lrMSI_before[1,]), digits=5)\nsdSLOPE_before <- round(sd(as.vector(lrMSI_before[1,])), digits=5)\n\n\n# Back-transform trends before changepoint to index scale\nSLOPE_before_mult <- round(exp(SLOPE_before), digits=4)\nsdSLOPE_before_mult <- round(sdSLOPE_before*SLOPE_before_mult, digits=4)\n\nSLOPE_before\nsdSLOPE_before\nSLOPE_before_mult\nsdSLOPE_before_mult\n\n# Trend classification before changepoint\nTrendClass_before <- \"X\"\nif (SLOPE_before_mult - 1.96*sdSLOPE_before_mult > 1.05) {TrendClass_before <- \"strong increase\" } else\n if (SLOPE_before_mult + 1.96*sdSLOPE_before_mult < 0.95) { TrendClass_before <- \"steep decline\" } else\n if (SLOPE_before_mult - 1.96*sdSLOPE_before_mult > 1.00) { TrendClass_before <- \"moderate increase\"} else\n if (SLOPE_before_mult + 1.96*sdSLOPE_before_mult < 1.00) { TrendClass_before <- \"moderate decline\" } else\n if ((SLOPE_before_mult - 1.96*sdSLOPE_before_mult - 0.95)*(1.05 - SLOPE_before_mult + 1.96*sdSLOPE_before_mult) < 0.00) { TrendClass_before <- \"uncertain\"} else\n if ((SLOPE_before_mult + 1.96*sdSLOPE_before_mult) - (SLOPE_before_mult - 1.96*sdSLOPE_before_mult) > 0.10) { TrendClass_before <- \"uncertain\" } else\n {TrendClass_before <- \"stable\"}\nTrendClass_before\n\n# linear trend after changepoint per simulation\nlrMSI_after <- array(NA, dim=c(2, nsim))\nayear <- c(changepoint:maxyear)\nayears <- length(ayear)\nsimMSI_after <- array(NA, dim=c(ayears, nsim))\nfor (s in 1:nsim) {\n for (y in 1:ayears) {\n simMSI_after[y, s] <- simMSI[(byears-1+y),s]\n }\n}\nfor (s in 1:nsim) {\n summa <- summary(lm(simMSI_after[,s] ~ ayear, na.action=na.exclude))\n lrMSI_after[1,s] <- round(summa$coefficients[2], digits=4) # coeff[2] = slope\n lrMSI_after[2,s] <- round(summa$coefficients[2,2], digits=4) # coeff[2,2] = sd of slope \n}\nSLOPE_after <- round(mean(lrMSI_after[1,]), digits=5)\nsdSLOPE_after <- round(sd(as.vector(lrMSI_after[1,])),digits=5)\n\n# Trend classification before changepoint\nSLOPE_after_mult <- round(exp(SLOPE_after), digits=4)\nsdSLOPE_after_mult <- round(sdSLOPE_after*SLOPE_after_mult, digits=4)\n\nSLOPE_after\nsdSLOPE_after\nSLOPE_after_mult\nsdSLOPE_after_mult\n\n# Trend classification after changepoint\nTrendClass_after <- \"X\"\nif (SLOPE_after_mult - 1.96*sdSLOPE_after_mult > 1.05) {TrendClass_after <- \"strong increase\" } else\n if (SLOPE_after_mult + 1.96*sdSLOPE_after_mult < 0.95) { TrendClass_after <- \"steep decline\" } else\n if (SLOPE_after_mult - 1.96*sdSLOPE_after_mult > 1.00) { TrendClass_after <- \"moderate increase\"} else\n if (SLOPE_after_mult + 1.96*sdSLOPE_after_mult < 1.00) { TrendClass_after <- \"moderate decline\" } else\n if ((SLOPE_after_mult - 1.96*sdSLOPE_after_mult - 0.95)*(1.05 - SLOPE_after_mult + 1.96*sdSLOPE_after_mult) < 0.00) { TrendClass_after <- \"uncertain\"} else\n if ((SLOPE_after_mult + 1.96*sdSLOPE_after_mult) - (SLOPE_after_mult - 1.96*sdSLOPE_after_mult) > 0.10) { TrendClass_after <- \"uncertain\" } else\n {TrendClass_after <- \"stable\"}\nTrendClass_after\n\n# compare linear trends before and after changepoint\ncompare <- array(NA, dim=c(nsim, 1))\nfor (s in 1:nsim){\n compare[s,1] <- lrMSI_after[1,s]-lrMSI_before[1,s]\n}\nmeanTrendDiff <- mean(compare)\nseTrendDiff <- sd(as.vector(compare))\nsignificance <- NA\nif (abs(meanTrendDiff)-2.58*seTrendDiff > 0) { significance <- \"p<0.01\" } else\n if (abs(meanTrendDiff)-1.96*seTrendDiff > 0) { significance <- \"p<0.05\" } else\n {significance <- \"n.s.\"}\n\n# Smoothing\n# span = 0.75 is default in R and usually fits well. But trying other values may give better results, depending on your data\nloessMSI <- array(NA, dim=c(nyear, nsim))\nDiff <- array(NA, dim=c(nyear, nsim))\nfor (s in 1:nsim) {\n smooth <- predict(loess(simMSI[,s]~uyear, span=0.75, degree=2, na.action=na.exclude),\n data.frame(uyear), se=TRUE)\n loessMSI[,s] <- round(smooth$fit, digits=4)\n\n for (y in 1:nyear) {\n Diff[y,s] <- loessMSI[nyear,s] - loessMSI[y,s]\n } \n}\n\n# calculate overall change (first year set to 100) and change in last years\npct_CHANGE <- array(NA, dim=c(nsim, 2))\nfor (s in 1:nsim) {\npct_CHANGE[s,1] <- exp(loessMSI[nyear,s])*100/exp(loessMSI[1,s])-100\npct_CHANGE[s,2] <- exp(loessMSI[nyear,s])*100/exp(loessMSI[1,s])-exp(loessMSI[(nyear-lastyears+1),s])*100/exp(loessMSI[1,s])\n}\npct_CHANGE_long <- round(mean(pct_CHANGE[,1]),digits=3)\nsd_pct_CHANGE_long <- round(sd(pct_CHANGE[,1]), digits=3)\npct_CHANGE_long\nsd_pct_CHANGE_long\npct_CHANGE_short <- round(mean(pct_CHANGE[,2]),digits=3)\nsd_pct_CHANGE_short <- round(sd(pct_CHANGE[,2]), digits=3)\npct_CHANGE_short\nsd_pct_CHANGE_short\n\n# significance of percentage change\nsignificance_PCT_long <- NA\nif (abs(pct_CHANGE_long)-2.58*sd_pct_CHANGE_long > 0) { significance_PCT_long <- \"p<0.01\" } else\n if (abs(pct_CHANGE_long)-1.96*sd_pct_CHANGE_long > 0) { significance_PCT_long <- \"p<0.05\" } else\n {significance_PCT_long <- \"n.s.\"}\n\nsignificance_PCT_short <- NA\nif (abs(pct_CHANGE_short)-2.58*sd_pct_CHANGE_short > 0) { significance_PCT_short <- \"p<0.01\" } else\n if (abs(pct_CHANGE_short)-1.96*sd_pct_CHANGE_short > 0) { significance_PCT_short <- \"p<0.05\" } else\n {significance_PCT_short <- \"n.s.\"}\n\n# create output for flexible trend estimates\nsmoothMSI <- array(NA, dim=c(nyear, 13))\nfor (y in 1:nyear) {\n smoothMSI[y,1] <- round(mean(loessMSI[y,]), digits=4) # smooth MSI on log scale\n smoothMSI[y,2] <- round(sd(loessMSI[y,]), digits=4) # SE of smooth MSI on log scale\n smoothMSI[y,3] <- round(mean(Diff[y,]), digits=4) # Difference smooth MSI with last year on log scale\n smoothMSI[y,4] <- round(sd(Diff[y,]), digits=4) # SE of difference with ast year\n smoothMSI[y,12] <- round(smoothMSI[y,1]-1.96*smoothMSI[y,2], digits=2) # lower CI of smooth MSI on log scale\n smoothMSI[y,13] <- round(smoothMSI[y,1]+1.96*smoothMSI[y,2], digits=2) # upper CI of smooth MSI on log scale\n}\n\n# Trendclassification, based on smoothed trends (Soldaat et al. 2007 (J. Ornithol. DOI 10.1007/s10336-007-0176-7))\nfor (y in 1:nyear) {\n smoothMSI[y,5] <- round(smoothMSI[nyear,1]/smoothMSI[y,1], digits=4)\t\t# = TCR\n smoothMSI[y,6] <- round(smoothMSI[y,5]-1.96*(smoothMSI[y,4]/smoothMSI[y,1]), digits=4)\t# = CI- TCR\n smoothMSI[y,7] <- round(smoothMSI[y,5]+1.96*(smoothMSI[y,4]/smoothMSI[y,1]), digits=4)\t# = CI+ TCR\n smoothMSI[y,8] <- round(exp(log(smoothMSI[y,5])/(nyear-y)), digits=4)\t\t# = YCR\n smoothMSI[y,9] <- round(exp(log(smoothMSI[y,6])/(nyear-y)), digits=4)\t\t# = CI- YCR\n smoothMSI[y,10] <- round(exp(log(smoothMSI[y,7])/(nyear-y)), digits=4)\t\t# = CI+ YCR\n}\n\nfor (y in 1:(nyear-1)) {\n if (smoothMSI[y,9] > 1.05) {smoothMSI[y,11] <- 1} else\n if (smoothMSI[y,10] < 0.95) {smoothMSI[y,11] <- 6} else\n if (smoothMSI[y,9] > 1.00) {smoothMSI[y,11] <- 2} else\n if (smoothMSI[y,10] < 1.00) {smoothMSI[y,11] <- 5} else\n if ((smoothMSI[y,9] - 0.95)*(1.05 - smoothMSI[y,10]) < 0.00) {smoothMSI[y,11] <- 3} else\n if ((smoothMSI[y,10]) - (smoothMSI[y,9]) > 0.10) {smoothMSI[y,11] <- 3} else\n {smoothMSI[y,11] <- 4}\n} \n\nTrendClass_flex <- matrix(NA, nrow= nyear, ncol=1)\nfor (y in 1:(nyear-1)) {\n if (smoothMSI[y,9] > 1.05) {TrendClass_flex[y] <- \"strong_increase\" } else\n if (smoothMSI[y,10] < 0.95) { TrendClass_flex[y] <- \"steep_decline\" } else\n if (smoothMSI[y,9] > 1.00) { TrendClass_flex[y] <- \"moderate_increase\"} else\n if (smoothMSI[y,10] < 1.00) { TrendClass_flex[y] <- \"moderate_decline\" } else\n if ((smoothMSI[y,9] - 0.95)*(1.05 - smoothMSI[y,10]) < 0.00) { TrendClass_flex[y] <- \"uncertain\"} else\n if ((smoothMSI[y,10]) - (smoothMSI[y,9]) > 0.10) { TrendClass_flex[y] <- \"uncertain\" } else\n {TrendClass_flex[y] <- \"stable\"}\n} \n\n# rescaling (for presentation of plot)\nrescale <- NA\n if (index_smooth ==\"INDEX\") {rescale <- 100/meanMSI[plotbaseyear]} else\n if (index_smooth ==\"SMOOTH\") {rescale <- 100/exp(smoothMSI[plotbaseyear,1])} else\n {rescale <- NA}\nsimMSImean <- round(as.vector(rescale*meanMSI), digits=2)\nsimMSIsd <- round(as.vector(rescale*stdevMSI), digits=2)\nuppCI_MSI <- round(rescale*CI[,2], digits=2)\nlowCI_MSI <- round(rescale*CI[,1], digits=2)\ntrend_flex <- round(rescale*exp(smoothMSI[,1]), digits=2)\nlowCI_trend_flex <- round(rescale*exp(smoothMSI[,12]), digits=2)\nuppCI_trend_flex <- round(rescale* exp(smoothMSI[,13]), digits=2)\n\n# create output file for MSI + smoothed trend\nRES <- as.data.frame(cbind(uyear, simMSImean, simMSIsd, lowCI_MSI, uppCI_MSI, trend_flex, lowCI_trend_flex, uppCI_trend_flex))\nRES$trend_class <- TrendClass_flex\nnames(RES) <- c(\"year\", \"MSI\", \"sd_MSI\", \"lower_CL_MSI\", \"upper_CL_MSI\", \"Trend\", \"lower_CL_trend\", \"upper_CL_trend\", \"trend_class\")\nwrite.csv2(RES, file=jobnameRESULTS, row.names=FALSE, quote=FALSE)\n\n# create output file with all linear trends\nSIMTRENDS <- t(rbind(lrMSI[1,],lrMSI_short[1,]))\nwrite.csv2(SIMTRENDS, file=jobnameSIMTRENDS, row.names=FALSE)\n\n# create output for linear trend estimates and % change\nrownames <- rbind(\"overall trend\",\"SE overall trend\", \"trend last years\", \"SE trend last years\", \"changepoint\",\n \"trend before changepoint\", \"SE trend before changepoint\", \"trend after changepoint\", \"SE trend after changepoint\",\n \"% change\", \"SE % change\", \"% change last years\", \"SE % change last years\")\noutput <- cbind(SLOPE_mult, sdSLOPE_mult, SLOPE_short_mult, sdSLOPE_short_mult,\n changepoint, SLOPE_before_mult, sdSLOPE_before_mult, SLOPE_after_mult, sdSLOPE_after_mult,\n pct_CHANGE_long, sd_pct_CHANGE_long, pct_CHANGE_short, sd_pct_CHANGE_short)\nTRENDS <- as.data.frame(t(output), row.names=rownames)\nTRENDS$significance <- \"\"\nTRENDS[\"changepoint\", \"significance\"] <- significance\nTRENDS[1, \"significance\"] <- TrendClass\nTRENDS[3, \"significance\"] <- TrendClass_short\nTRENDS[6, \"significance\"] <- TrendClass_before\nTRENDS[8, \"significance\"] <- TrendClass_after\nTRENDS[10, \"significance\"] <- significance_PCT_long\nTRENDS[12, \"significance\"] <- significance_PCT_short\nnames(TRENDS) <- c(\"value\", \"significance\")\nwrite.csv2(TRENDS, file=jobnameTRENDS)\n\n# create output file with plot\nmaxy <- max(uppCI_MSI) + 10\njpeg(filename = jobnameGRAPH, width = 480, height = 480,units = \"px\", pointsize = 12, bg = \"white\", res = NA, restoreConsole = TRUE)\nlegend1 <- paste(nspecies, \"species\")\nlegend2 <- paste(TrendClass)\nlegend3 <- paste(\"last\", lastyears, \"years:\", TrendClass_short)\nplot(uyear, simMSImean, type=\"p\", pch=19, col=\"black\", main=jobname, xlab=\"\", ylab=\"Index\", xlim = c(minyear, maxyear), ylim = c(0,maxy))\ntext(minyear, 40, legend1, adj=0, cex=0.8)\ntext(minyear, 25, legend2, adj=0, cex=0.8)\ntext(minyear, 10, legend3, adj=0, cex=0.8)\nlines(uyear, rescale*exp(smoothMSI[,1]), lty=1, col=\"black\")\nlines(uyear, rescale*exp(smoothMSI[,12]), lty=3, col=\"black\")\nlines(uyear, rescale*exp(smoothMSI[,13]), lty=3, col=\"black\")\n#arrows(uyear, simMSImean, uyear, (simMSImean-simMSIsd), angle = 90, code = 3, length=0)\n#arrows(uyear, simMSImean, uyear, (simMSImean+simMSIsd), angle = 90, code = 3, length=0)\ndev.off()\n\n# plot to screen\nmaxy <- max(uppCI_MSI) + 10\nplot(uyear, simMSImean, type=\"p\", pch=19, col=\"black\", main=jobname, xlab=\"\", ylab=\"Index\", xlim = c(minyear, maxyear), ylim = c(0,maxy))\ntext(minyear, 40, legend1, adj=0, cex=0.8)\ntext(minyear, 25, legend2, adj=0, cex=0.8)\ntext(minyear, 10, legend3, adj=0, cex=0.8)\nlines(uyear, rescale*exp(smoothMSI[,1]), lty=1, col=\"black\")\nlines(uyear, rescale*exp(smoothMSI[,12]), lty=3, col=\"black\")\nlines(uyear, rescale*exp(smoothMSI[,13]), lty=3, col=\"black\")\narrows(uyear, simMSImean, uyear, (simMSImean-simMSIsd), angle = 90, code = 3, length=0)\narrows(uyear, simMSImean, uyear, (simMSImean+simMSIsd), angle = 90, code = 3, length=0)\n", "meta": {"hexsha": "9bd64dc64a8278aa2fc7707d1f1e2103f1fb16cd", "size": 21782, "ext": "r", "lang": "R", "max_stars_repo_path": "raw_scripts/STERF_butterfly_temporal_tendency/MSI_tool.r", "max_stars_repo_name": "sbenateau/Galaxy-E", "max_stars_repo_head_hexsha": "beea770b1a7192a90e22d845bc040c6a0833d6ac", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-10-24T14:18:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-07T07:52:08.000Z", "max_issues_repo_path": "raw_scripts/STERF_butterfly_temporal_tendency/MSI_tool.r", "max_issues_repo_name": "sbenateau/Galaxy-E", "max_issues_repo_head_hexsha": "beea770b1a7192a90e22d845bc040c6a0833d6ac", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 13, "max_issues_repo_issues_event_min_datetime": "2017-11-28T14:47:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T05:51:59.000Z", "max_forks_repo_path": "raw_scripts/STERF_butterfly_temporal_tendency/MSI_tool.r", "max_forks_repo_name": "sbenateau/Galaxy-E", "max_forks_repo_head_hexsha": "beea770b1a7192a90e22d845bc040c6a0833d6ac", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-10-25T08:01:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T21:56:11.000Z", "avg_line_length": 45.5690376569, "max_line_length": 170, "alphanum_fraction": 0.6782664585, "num_tokens": 7622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4256530554485706}}
{"text": "#----------------------------------------------------------------------------------------------------------\n# Name: EV_RP.r\n# Purpose: This main function estimates return periods using the block maxima/minima approach\n#\t\t\t\ton gridded data. All external modules are called within this script.\n# Author: Francesco Tonini\n# Email: \t f_tonini@hotmail.com\n# Created: 11/1/2009\n# Copyright: (c) 2009 by Francesco Tonini\n# License: \tGNU General Public License (GPL)\n# Software: Tested successfully using R-2.14.0 64-bit version(http://www.r-project.org/)\n#-------------------------------------------------------------------------------------------\n\n##Define the main working directory\n##Always use either / or \\\\ to specify the path\nmainDir <- 'C:/Temp'\n#mainDir <- '~/Desktop/Temp' #if you are on a MacOSX environment\n\n##Let's set the working directory\nsetwd(file.path(mainDir))\n\n##Define the subdirectory(ies) where your output files will be saved\nsubDir <- 'Output'\n\n##Create a physical copy of the subdirectory folder(s) where you save your output\n##If the directory already exists it gives a warning, BUT we can suppress it using showWarnings = FALSE\ndir.create(file.path(mainDir, subDir), showWarnings = FALSE)\n\n##Use an external source file w/ all modules (functions) used within this script. \n##Use FULL PATH if source file is not in the same folder w/ this script\nsource('myEVfunctions.r')\n\n##Path to folders in which you want to save all your output files\nworkdir_Output <- file.path(mainDir, subDir)\n\n##Load all required libraries\nprint('Loading required libraries...')\nload.packages()\n\n##Let's set the simulation parameters:\n\n##Alamata.tot is the dataset we built for the Alamata woreda, Tigray (Ethiopia).\n##This can be replaced by an entire region or country (the bigger the extent, the more the code will take to finish)\ndataset <- Alamata.tot\n\n##Number of pixels within the chosen dataset\nnpixels <- length(unique(dataset$id))\n\n##Let's specify the return level(s) for which we want to calculate the associated probability of exceedance\n##(i.e. return period)\nreturn_levels <- c(-0.15,-0.05)\n\t\t\n##Let's create a dataframe to store the parameters of the GEV distributions and their confidence intervals\t\ntab.parameters <- data.frame(matrix(NA,npixels,11))\ncolnames(tab.parameters) <- c('id.pix','gum.flag','mu','sig','shp','mu.inf','mu.sup','sig.inf','sig.sup','shp.inf','shp.sup')\n\t\n##Let's create some labels for the return levels estimates and their upper and lower confidence intervals\nRP_labels <- paste('prob_',return_levels,sep='')\n\t\n##Let's create a dataframe to store return levels estimates and their upper and lower confidence intervals\ntab.prob <- data.frame(matrix(NA, npixels, length(return_levels) + 1))\ncolnames(tab.prob) <- c(\"id.pix\",RP_labels)\n\n##Create an empty vector in which we would save the pixel IDs\n##whose GEV/Gumbel parameter estimates did not converge\t\npx.idWarning <- c() \n\n######################################################################\n##Flagged values (in DN) by VITO for SPOT VGT S10\n#251=missing, 252=cloud, 253=snow, 254=sea, 255=background\n#Converted to ADVI values using: ADVI = -1.25 + 0.01 * DN\n#1.26=missing, 1.27=cloud, 1.28=snow, 1.29=sea, 1.30=background\n######################################################################\n\n##Create a Tk window element as a container\nroot <- tktoplevel()\ntktitle(root) <- 'Extreme Value Analysis'\n##Define the label of a progress bar\nlab <- tk2label(root)\n##Define the length and create a progress bar\npb <- tk2progress(root, length = 300)\n#Configure \ntkconfigure(pb, value=0, maximum = npixels-1)\n##Pack all labels and progress bars inside the Tk container\ntkpack(lab)\ntkpack(pb)\n##Refresh the Tk window\ntcl('update')\n\n##LOOP through each pixel, create its time series of maxima/minima, \n##estimate GEV parameters and return levels\t\t\t\nfor (pix in 1:npixels){\n\t\n\t#update progress bar according to the pixel currently being processed\n\ttkconfigure(lab, text = paste('Pixel',pix,'Out of',npixels, ' (',round(pix/npixels*100),'% )'))\n tkconfigure(pb, value = pix - 1)\n\ttcl('update')\n\t\t\n\t##Slice the main dataset by extracting only historical records for the current pixel\n\tpix.dataset <- dataset[dataset$id == pix,]\n\t\n\t##This section was developed specifically for the case of having dekadal (1 dekad = 10days) \n\t##time series and extracting monthly (1 month = 3 dekads) MINIMA.\n\t##NOTE: If you are interested in taking monthly MAXIMA just use FUN = max \n\t##NOTE2: If you wanna take YEARLY minima/maxima then you should use:\n\t##etiq <- factor(pix.dataset$year) ...BUT make sure the time series is longer than at least 30 years\n\t##otherwise the GEV estimates will not be reliable, as well as the return level estimates.\n\t\t\n\t##Identify the 'dekadal' variable in the dataset\n\tDekads <- pix.dataset$decads\n\t\n\t##Identify the 'Year' variable in the dataset\n\tYears <- pix.dataset$year\n\t\n\t##Identify the 'Value' variable in the dataset\n\tValues <- pix.dataset$val\n\n\t##Let's store the labels (as factors) of all existing dekad-year pairs (regardless of the dekad number)\n\tetiq <- factor( paste(substring(Dekads,1,3), Years, sep='') )\n\t\n\t##Let's extract the minima (use FUN = max if you want maxima) for each unique level of the factor\n\tmonthExtract <- tapply(Values, etiq, FUN = min)\n\t\n\t##Since values in 'monthExtract' have an alphabetical order relative to the month (Apr1998,Apr1999,Apr2000,etc.)\n\t##we need to sort them so that the series of values follows the real time line\n\t\n\t##If your are taking YEARLY minima/maxima skip (1-2-3) and use only (4). This, because\n\t##years already have a natural ascending order:\n\t\n\t#(1) by taking unique factor levels, we have a natural time line order\n\tUniqueEtiq <- unique(etiq)\n\t\n\t#(2) let's now match the correct ordered position of unique factors with our monthly values\n\tPosIdx <- match(as.character(UniqueEtiq), names(monthExtract))\n\t\n\t#(3) now that we got all the correct positions, let's put all our values in a numerical vector. This\n\t#is the time series to be used with extreme value models\n\tpx.min <- as.vector(monthExtract[PosIdx])\n\t\n\t#(4) Uncomment the next line and use it to build your YEARLY maxima/minima time series\n\t#px.min <- as.vector(monthExtract) \n\t\n\t#If the pixel is coded as 1.29=sea or 1.30=background we simply put 999 \n\tif ( any(px.min == 1.29) | any(px.min == 1.30) ) {\n\t\ttab.parameters[pix,] <- 999 \n\t\ttab.prob[pix,] <- 999\n\t\tnext\n\t}\n\t\n\t#Let's now look at values 1.26=missing, 1.27=cloud, 1.28=snow. They will need to be removed from the\n\t#numerical vector, otherwise the extreme models will be biased. Since in our study area there are very few \n\t#or no cloud values, snow, or missing, we can either remove them from the numerical vector, or \n\t#replace them with a simple average between N previous/following values. \n\tFlags <- c(1.26, 1.27, 1.28)\n\t\n\t#replace flagged values with NAs (if there are any)\n\tpx.min[ px.min %in% Flags] <- NA\n\t\n\t#if there are flagged values, count them and see if their number exceeds 15% of the total time series\n\tif (any(is.na(px.min))) {\n\t\tNA.sum <- sum(is.na(px.min))\n\t\t#print a warning on screen to let the user know that model estimates may be biased\n\t\tif (NA.sum / length(px.min) * 100 >= 15) cat('\\nATTENTION: More than 15% of values are flagged.\\nModel estimates may be biased')\n\t}\n\t\n\t#override the original time series by removing any NA (flagged) values\n\tpx.min <- px.min[!is.na(px.min)]\n\t\n\t#estimate GEV model (if you are working with maxima, DO NOT use the '-' sign \n\tminimi.gev <- gev.fit(-px.min,show=F)\n\tclass(minimi.gev) <- \"gev.fit\"\n\t\n\t#estimate Gumbel model (if you are working with maxima, DO NOT use the '-' sign \n\tminimi.gum <- gum.fit(-px.min,show=F)\n\tclass(minimi.gum) <- \"gum.fit\"\n\t\n\t#If the MLE estimation procedure does not converge, save the pixel ID into\n\t#the warning vector\n\tif (minimi.gev$conv > 0 | minimi.gum$conv > 0){\n\t\n\t\tpx.idWarning <- c(px.idWarning, pix)\n\t\n\t}else{\n\n\t\t# Likelihood Ratio method to compare two models\n\t\tlik.ratio <- 2 * (minimi.gum$nllh - minimi.gev$nllh)\n\t\tpvalue <- (1 - pchisq(lik.ratio,1))\n\t\t\n\t\t#if the p-value is not significant (>.05) we use the gumbel distr. (shape parameter --> 0)\n\t\tif (pvalue > 0.05){\n\t\t\t\n\t\t\t#use a variable to flag the use of a gumbel distr.\n\t\t\tgum.flag <- 1\n\t\t\tmu <- minimi.gum$mle[1] #location\n\t\t\tsig <- minimi.gum$mle[2] #scale\n\t\t\tshp <- 0 #shape\n\t\t\t#conf. intervals (based ~ N(0,1))\n\t\t\tmu.inf <- minimi.gum$mle[1] - 1.96 * minimi.gum$se[1] \n\t\t\tmu.sup <- minimi.gum$mle[1] + 1.96 * minimi.gum$se[1]\n\t\t\tsig.inf <- minimi.gum$mle[2] - 1.96 * minimi.gum$se[2]\n\t\t\tsig.sup <- minimi.gum$mle[2] + 1.96 * minimi.gum$se[2]\n\t\t\tshp.inf <- 0\n\t\t\tshp.sup <- 0\n\t\t\t\n\t\t\t#calculate probability of observing the desired return level(s)\t\n\t\t\t#if you are using MAXIMA, go to the myEVfunctions.r file and adjust\n\t\t\t#the code within the prob_fun(). Follow the comments.\n\t\t\tprob <- prob_fun()\t\t\n\t\t\t\t\n\t\t}else{ #otherwise use the GEV distr.\n\t\t\t\n\t\t\t#use a variable to flag the NON use of a gumbel distr.\t\t\t\n\t\t\tgum.flag <- 0\n\t\t\tmu <- minimi.gev$mle[1] #location\n\t\t\tsig <- minimi.gev$mle[2] #scale\n\t\t\tshp <- minimi.gev$mle[3] #shape\n\t\t\t#conf. intervals (based ~ N(0,1))\n\t\t\tmu.inf <- minimi.gev$mle[1] - 1.96 * minimi.gev$se[1]\n\t\t\tmu.sup <- minimi.gev$mle[1] + 1.96 * minimi.gev$se[1]\n\t\t\tsig.inf <- minimi.gev$mle[2] - 1.96 * minimi.gev$se[2]\n\t\t\tsig.sup <- minimi.gev$mle[2] + 1.96 * minimi.gev$se[2]\n\t\t shp.inf <- minimi.gev$mle[3] - 1.96 * minimi.gev$se[3]\n\t\t\tshp.sup <- minimi.gev$mle[3] + 1.96 * minimi.gev$se[3]\n\t\t\t\t\t\t\n\t\t\t#calculate probability of observing the desired return level(s)\t\n\t\t\t#if you are using MAXIMA, go to the myEVfunctions.r file and adjust\n\t\t\t#the code within the prob_fun(). Follow the comments.\t\t\n\t\t\tprob <- prob_fun()\t\t\t\n\t\t}\n\t\t\n\t\t#let's store the parameter and probability of exceedance estimates in their respective dataset, for the row\n\t\t#corresponding to the current pixel in the LOOP\n\t\ttab.parameters[pix,] <- c(pix,gum.flag,round(mu,2),round(sig,2),round(shp,2),round(mu.inf,2),round(mu.sup,2),\n\t\t\t\t\t\t\t\t round(sig.inf,2),round(sig.sup,2),round(shp.inf,2),round(shp.sup,2))\n\n\t\ttab.prob[pix,] <- c(pix, prob)\n\t\t\n\t} \n\t\t\t\t\t\n}\n\n#For those pixels whose return levels could not be computed, use the median of the 4 nearest neighbors\nif(length(px.idWarning) > 0) median.interp_RP()\n\n#Save files to output folder\nsave_files_RP()\n\t\ntkmessageBox(title = \"Message\", message = 'Done! Output Files Saved To Folder', icon = \"info\", type = \"ok\")\n##Suppress the progress bar\ntkdestroy(root)\n\n\n\n\t\n\n\n\n\n\t\t", "meta": {"hexsha": "d42c82beb00f64ea3e40b62746a4566a4696b6df", "size": 10527, "ext": "r", "lang": "R", "max_stars_repo_path": "EV_RP.r", "max_stars_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_stars_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EV_RP.r", "max_issues_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_issues_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EV_RP.r", "max_forks_repo_name": "f-tonini/Extreme-Values-For-Gridded-Data", "max_forks_repo_head_hexsha": "528440f8a0e5a4d74b58e72b773657766b2dfab3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8023255814, "max_line_length": 130, "alphanum_fraction": 0.6789208701, "num_tokens": 3039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.42518928993572724}}
{"text": "#' ms2mph\n#' \n#' Conversion speed from meter per second to knots.\n#'\n#' @param numeric ms Speed in meter per second.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords ms2mph\n#' \n#' @export\n#'\n#'\n#'\n#'\n\nms2mph<-function(ms)\n{\n return (ms * 2.23694);\n}", "meta": {"hexsha": "0127c1298ff08e062483c054e54313c99a260013", "size": 336, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ms2mph.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/ms2mph.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ms2mph.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0, "max_line_length": 101, "alphanum_fraction": 0.6428571429, "num_tokens": 115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.42428027333302853}}
{"text": "model_snowdepthtrans <- function (Sdepth = 0.0,\n Pns = 100.0){\n #'- Name: SnowDepthTrans -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: snow cover depth conversion\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: snow cover depth in cm\n #'- inputs:\n #' * name: Sdepth\n #' ** description : snow cover depth Calculation\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : m\n #' ** uri : \n #' * name: Pns\n #' ** description : density of the new snow\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 100.0\n #' ** min : \n #' ** max : \n #' ** unit : cm/m\n #' ** uri : \n #'- outputs:\n #' * name: Sdepth_cm\n #' ** description : snow cover depth in cm\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : cm\n #' ** uri : \n Sdepth_cm <- Sdepth * Pns\n return (list('Sdepth_cm' = Sdepth_cm))\n}", "meta": {"hexsha": "a70cc6ed9bdadb1de2e54f208b9033cf7d018964", "size": 1930, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Snowdepthtrans.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/Snowdepthtrans.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/Snowdepthtrans.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": 45.9523809524, "max_line_length": 84, "alphanum_fraction": 0.3238341969, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4242396384197204}}
{"text": "path <- '/home/maanitou/programming/fsharp/rufc/Samples/schrodinger/'\n\ncontent_f <- read.table(paste(path, 'output_schrodinger_forward.txt', sep=\"\"))\ncontent_b <- read.table(paste(path, 'output_schrodinger_backward.txt', sep=\"\"))\n\nfactor <- 1000000\n\nXf <- sapply(content_f, function(x) as.numeric(x)/factor)\nXb <- sapply(content_b, function(x) as.numeric(x)/factor)\n\npar(mfrow=c(1,1))\n\nplot(1:128, Xf[1,], type='l', xlim=c(0,256), ylim=c(min(Xf),max(Xf)))\nlines(1:128, Xf[2,], type='l')\nlines(129:256, Xb[1,], type='l')\nlines(129:256, Xb[2,], type='l')\n\nfor (i in 0:(nrow(Xf)/2-1)) {\n lines(1:128, Xf[2*i+1,], type='l', col='red', xlim=c(0,256), ylim=c(min(Xf),max(Xf)))\n lines(1:128, Xf[2*i+2,], type='l', col='black')\n lines(129:256, Xb[2*i+1,], type='l', col='red')\n lines(129:256, Xb[2*i+2,], type='l', col='black')\n #Sys.sleep(1)\n}\n\n#pdf(file=\"/home/maanitou/Desktop/PAT_2021/project/schrodinger.pdf\", width=8, height=4)\npar(mfrow=c(3,4), oma=c(0,0,0,0), mar=c(.5,.5,.5,.5))\n for (i in c(seq(0,999,91),999)) {\n #for (i in c(seq(0,4999,455),4999)) {\n #for (i in c(seq(0,1999,182),1999)) {\n plot(1:128, Xf[2*i+1,], type='l', col='black',\n xlim=c(0,256), ylim=c(min(Xf),max(Xf)),\n xlab=\"\", ylab=\"\", xaxt='n', yaxt='n')\n lines(1:128, Xf[2*i+2,], type='l', col='red')\n lines(129:256, Xb[2*i+1,], type='l', col='red')\n lines(129:256, Xb[2*i+2,], type='l', col='black')\n abline(v=128, lty=2)\n}\n#dev.off()", "meta": {"hexsha": "1b98331ea0790beb7bcb252cb8672cea7dd5a7db", "size": 1422, "ext": "r", "lang": "R", "max_stars_repo_path": "Samples/schrodinger/code_forward_backward.r", "max_stars_repo_name": "maanitou/rufc", "max_stars_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Samples/schrodinger/code_forward_backward.r", "max_issues_repo_name": "maanitou/rufc", "max_issues_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-18T14:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T15:14:49.000Z", "max_forks_repo_path": "Samples/schrodinger/code_forward_backward.r", "max_forks_repo_name": "maanitou/rufc", "max_forks_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_forks_repo_licenses": ["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.4615384615, "max_line_length": 87, "alphanum_fraction": 0.6047819972, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.4241690844118396}}
{"text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n#' Evaluation of the maximum likelihood using FaST-LMM method\n#'\n#' Last update: January 11, 2017\n#' \n#' @author Xiaolei Liu (modified)\n#' \n#' @param pheno a two-column phenotype matrix\n#' @param snp.pool matrix for pseudo QTNs\n#' @param X0 covariates matrix\n#' @param ncpus number of threads used for parallel computation\n#'\n#' @return\n#' Output: beta - beta effect\n#' Output: delta - delta value\n#' Output: LL - log-likelihood\n#' Output: vg - genetic variance\n#' Output: ve - residual variance\n#' \n`MVP.FaSTLMM.LL` <- function(pheno, snp.pool, X0=NULL, ncpus=2){\n y=pheno\n p=0\n deltaExpStart = -5\n deltaExpEnd = 5\n snp.pool=snp.pool[,]\n if(!is.null(snp.pool)&&var(snp.pool)==0){\n deltaExpStart = 100\n deltaExpEnd = deltaExpStart\n }\n if(is.null(X0)) {\n X0 = matrix(1, nrow(snp.pool), 1)\n }\n X=X0\n #########SVD of X\n K.X.svd <- svd(snp.pool)\n d=K.X.svd$d\n d=d[d>1e-08]\n d=d^2\n U1=K.X.svd$u\n U1=U1[,1:length(d)]\n #handler of single snp\n if(is.null(dim(U1))) U1=matrix(U1,ncol=1)\n n=nrow(U1)\n U1TX=crossprod(U1,X)\n U1TY=crossprod(U1,y)\n yU1TY <- y-U1%*%U1TY\n XU1TX<- X-U1%*%U1TX\n IU = -tcrossprod(U1)\n diag(IU) = rep(1,n) + diag(IU)\n IUX=crossprod(IU,X)\n IUY=crossprod(IU,y)\n #Iteration on the range of delta (-5 to 5 in glog scale)\n delta.range <- seq(deltaExpStart,deltaExpEnd,by=0.1)\n m <- length(delta.range)\n #for (m in seq(deltaExpStart,deltaExpEnd,by=0.1)){\n beta.optimize.parallel <- function(ii){\n #p=p+1\n delta <- exp(delta.range[ii])\n #----------------------------calculate beta-------------------------------------\n #######get beta1\n beta1=0\n for(i in 1:length(d)){\n one=matrix(U1TX[i,], nrow=1)\n beta=crossprod(one,(one/(d[i]+delta))) #This is not real beta, confusing\n beta1= beta1+beta\n }\n \n #######get beta2\n beta2=0\n for(i in 1:nrow(U1)){\n one=matrix(IUX[i,], nrow=1)\n beta = crossprod(one)\n beta2= beta2+beta\n }\n beta2<-beta2/delta\n \n #######get beta3\n beta3=0\n for(i in 1:length(d)){\n one1=matrix(U1TX[i,], nrow=1)\n one2=matrix(U1TY[i,], nrow=1)\n beta=crossprod(one1,(one2/(d[i]+delta)))\n beta3= beta3+beta\n }\n \n ###########get beta4\n beta4=0\n for(i in 1:nrow(U1)){\n one1=matrix(IUX[i,], nrow=1)\n one2=matrix(IUY[i,], nrow=1)\n beta=crossprod(one1,one2)\n beta4= beta4+beta\n }\n beta4<-beta4/delta\n \n #######get final beta\n zw1 <- ginv(beta1+beta2)\n #zw1 <- try(solve(beta1+beta2))\n #if(inherits(zw1, \"try-error\")){\n #zw1 <- ginv(beta1+beta2)\n #}\n \n zw2=(beta3+beta4)\n beta=crossprod(zw1,zw2)\n \n #----------------------------calculate LL---------------------------------------\n ####part 1\n part11<-n*log(2*3.14)\n part12<-0\n for(i in 1:length(d)){\n part12_pre=log(d[i]+delta)\n part12= part12+part12_pre\n }\n part13<- (nrow(U1)-length(d))*log(delta)\n part1<- -1/2*(part11+part12+part13)\n \n ###### part2\n part21<-nrow(U1)\n ######part221\n \n part221=0\n for(i in 1:length(d)){\n one1=U1TX[i,]\n one2=U1TY[i,]\n part221_pre=(one2-one1%*%beta)^2/(d[i]+delta)\n part221 = part221+part221_pre\n }\n \n part222=0\n for(i in 1:n){\n one1=XU1TX[i,]\n one2=yU1TY[i,]\n part222_pre=((one2-one1%*%beta)^2)/delta\n part222= part222+part222_pre\n }\n part22<-n*log((1/n)*(part221+part222))\n part2<- -1/2*(part21+part22)\n \n ################# likihood\n LL<-part1+part2\n part1<-0\n part2<-0\n \n return(list(beta=beta,delta=delta,LL=LL))\n }\n #} # end of Iteration on the range of delta (-5 to 5 in glog scale)\n\n llresults <- lapply(1:m, beta.optimize.parallel)\n\n for(i in 1:m){\n if(i == 1){\n beta.save = llresults[[i]]$beta\n delta.save = llresults[[i]]$delta\n LL.save = llresults[[i]]$LL\n }else{\n if(llresults[[i]]$LL > LL.save){\n beta.save = llresults[[i]]$beta\n delta.save = llresults[[i]]$delta\n LL.save = llresults[[i]]$LL\n }\n }\n }\n #--------------------update with the optimum------------------------------------\n beta=beta.save\n delta=delta.save\n LL=LL.save\n \n #--------------------calculating Va and Vem-------------------------------------\n #sigma_a1\n sigma_a1=0\n for(i in 1:length(d)){\n one1=matrix(U1TX[i,], ncol=1)\n one2=matrix(U1TY[i,], nrow=1)\n #sigma_a1_pre=(one2-one1%*%beta)^2/(d[i]+delta)\n sigma_a1_pre=(one2-crossprod(one1,beta))^2/(d[i]+delta)\n sigma_a1= sigma_a1+sigma_a1_pre\n }\n \n ### sigma_a2\n sigma_a2=0\n \n for(i in 1:nrow(U1)){\n one1=matrix(IUX[i,], ncol=1)\n one2=matrix(IUY[i,], nrow=1)\n #sigma_a2_pre<-(one2-one1%*%beta)^2\n sigma_a2_pre<-(one2-crossprod(one1,beta))^2\n sigma_a2= sigma_a2+sigma_a2_pre\n }\n \n sigma_a2<-sigma_a2/delta\n sigma_a<- 1/n*(sigma_a1+sigma_a2)\n sigma_e<-delta*sigma_a\n \n return(list(beta=beta, delta=delta, LL=LL, vg=sigma_a, ve=sigma_e))\n}\n", "meta": {"hexsha": "2ee9c0da8531d3b8223e150575dbb51f0087d473", "size": 6115, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.FaSTLMM.LL.r", "max_stars_repo_name": "xiaolei-lab/rMVP", "max_stars_repo_head_hexsha": "6ad1b94c208becc190b5facb2bbc9a9fff9a8353", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 99, "max_stars_repo_stars_event_min_datetime": "2019-10-14T09:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T08:45:16.000Z", "max_issues_repo_path": "R/MVP.FaSTLMM.LL.r", "max_issues_repo_name": "hxxonly/rMVP", "max_issues_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39, "max_issues_repo_issues_event_min_datetime": "2019-10-20T15:07:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:20:16.000Z", "max_forks_repo_path": "R/MVP.FaSTLMM.LL.r", "max_forks_repo_name": "hxxonly/rMVP", "max_forks_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 38, "max_forks_repo_forks_event_min_datetime": "2019-10-18T02:22:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T08:19:43.000Z", "avg_line_length": 29.3990384615, "max_line_length": 88, "alphanum_fraction": 0.5174161897, "num_tokens": 1883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.42400429293793174}}
{"text": "########################################################\n# The MIT License (MIT)\n#\n# Copyright (c) 2014 Florian D. Schneider & Sonia Kéfi\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n########################################################\n\n### mussel bed model (Guichard et al 2003)\n\n\nmusselbed <- list()\nclass(musselbed) <- \"ca_model\"\nmusselbed$name <- \"Mussel Disturbance Model\"\nmusselbed$ref <- \"Guichard et al 2003, American Naturalist, Vol. 161, pp. 889–904\"\nmusselbed$states <- c(\"+\", \"0\", \"-\")\nmusselbed$cols <- grayscale(3)\nmusselbed$parms <- list(\n r = 0.4, # recolonisation of empty sites dependent on local density\n d = 0.9, # probability of disturbance of occupied sites if at least one disturbed site\n delta = 0.01 # intrinsic disturbance rate\n) \nmusselbed$update <- function(x_old, parms_temp, delta = 0.2, subs = 10, timestep = NA) {\n \n x_new <- x_old\n \n for(s in 1:subs) {\n \n parms_temp$rho_plus <- sum(x_old$cells == \"+\")/(x_old$dim[1]*x_old$dim[2]) # get initial vegetation cover\n parms_temp$localdisturbance <- count(x_old, \"-\") > 0 # any disturbance in neighborhood?\n parms_temp$localcover <- count(x_old, \"+\")/4 # any occupied in neighborhood? \n \n # 2 - drawing random numbers\n rnum <- runif(x_old$dim[1]*x_old$dim[2]) # one random number between 0 and 1 for each cell\n \n # 3 - setting transition probabilities\n \n if(parms_temp$rho_plus > 0) {\n recolonisation <- with(parms_temp, (r*localcover)*1/subs)\n \n disturbance <- with(parms_temp, (delta+d*localdisturbance)*1/subs)\n disturbance[disturbance > 1] <- 1 \n } else {\n recolonisation <- 0\n disturbance <- 1\n }\n \n regeneration <- 1*1/subs\n \n # check for sum of probabilities to be inferior 1 and superior 0\n if(any(c(recolonisation, disturbance, regeneration) > 1 )) warning(paste(\"a set probability is exceeding 1 in time step\", timestep, \"! decrease number of substeps!!!\")) \n if(any(recolonisation < 0)) warning(paste(\"recolonisation falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n if(any( disturbance < 0)) warning(paste(\"disturbance falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n if(any(regeneration < 0)) warning(paste(\"regeneration falls below 0 in time step\",timestep, \"! balance parameters!!!\")) \n \n # 4 - apply transition probabilities \n \n x_new$cells[which(x_old$cells == \"0\" & rnum <= recolonisation)] <- \"+\"\n x_new$cells[which(x_old$cells == \"+\" & rnum <= disturbance)] <- \"-\"\n x_new$cells[which(x_old$cells == \"-\" & rnum <= regeneration)] <- \"0\"\n \n # 5- store x_new as next x_old\n \n x_old <- x_new\n \n }\n \n ## end of single update call\n return(x_new)\n}\n", "meta": {"hexsha": "0fb679af8b1247136711aa0368009feea5edc835", "size": 3741, "ext": "r", "lang": "R", "max_stars_repo_path": "R/musselbed.r", "max_stars_repo_name": "skefi/SpatialStress", "max_stars_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2015-06-12T14:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-04T21:16:40.000Z", "max_issues_repo_path": "R/musselbed.r", "max_issues_repo_name": "skefi/SpatialStress", "max_issues_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2015-06-12T08:03:31.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-25T08:35:31.000Z", "max_forks_repo_path": "R/musselbed.r", "max_forks_repo_name": "skefi/SpatialStress", "max_forks_repo_head_hexsha": "86727b5081dbbe64d0434baf6724e5955125ce59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-12-30T01:18:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T01:18:03.000Z", "avg_line_length": 42.5113636364, "max_line_length": 174, "alphanum_fraction": 0.6672012831, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42395062427725666}}
{"text": "[[[[[\n Given an expr to enumerate (program output) pairs,\n we simulate the Turing machine defined this way.\n We assume this r.e. set of programs is prefix free,\n i.e., no extension of a valid program is a valid\n program. If so, we will carry out this simulation\n in a self-delimiting way, i.e., we won't read any\n unnecessary bits of the program.\n]]]]]\n\ndefine pi\n\n[this is the prefix to put in front of the expr to\nenumerate the infinite set of (program output) pairs]\n\n [graph is an unending expression for (p o) pairs]\n let graph read-exp \n\n [program read so far; initialize to empty bit string]\n let p nil \n\n let (look-for p [in] pairs)\n if atom pairs false\n [(add new macro caar -> car car to interpreter?)]\n if = p car car pairs [does first pair start with p?]\n car pairs [if so, return first pair]\n [otherwise, keep looking]\n (look-for p [in] cdr pairs)\n\n let (look-for-extension-of p [in] pairs)\n if atom pairs false\n if (is-prefix? p car car pairs)\n true\n (look-for-extension-of p [in] cdr pairs)\n\n let (is-prefix? p q) [is p a prefix of q?]\n if atom p true\n if atom q false\n if = car p car q\n (is-prefix? cdr p cdr q)\n false\n\n let (loop t)\n [run for time t expr to generate (program output) pairs]\n [pairs are displayed by graph]\n let pairs debug caddr try debug t graph nil \n let found-it? (look-for p pairs) [found pair with program p?]\n if found-it? cadr found-it? [if so, we have output for p!]\n [(if found-it? isn't false, then it's considered true)]\n [is an extension of p in there?]\n if (look-for-extension-of p [in] pairs) \n [if so, read another bit of p]\n [then] let p debug append p cons read-bit nil\n (loop + t 1) [and generate more pairs]\n [don't read more of p, just generate more pairs]\n [else] (loop + t 1) \n\n [initialize time t to 0]\n (loop 0)\n\ndefine pi\nvalue ((' (lambda (graph) ((' (lambda (p) ((' (lambda (l\n ook-for) ((' (lambda (look-for-extension-of) ((' (\n lambda (is-prefix?) ((' (lambda (loop) (loop 0))) \n (' (lambda (t) ((' (lambda (pairs) ((' (lambda (fo\n und-it?) (if found-it? (car (cdr found-it?)) (if (\n look-for-extension-of p pairs) ((' (lambda (p) (lo\n op (+ t 1)))) (debug (append p (cons (read-bit) ni\n l)))) (loop (+ t 1)))))) (look-for p pairs)))) (de\n bug (car (cdr (cdr (try (debug t) graph nil)))))))\n )))) (' (lambda (p q) (if (atom p) true (if (atom \n q) false (if (= (car p) (car q)) (is-prefix? (cdr \n p) (cdr q)) false)))))))) (' (lambda (p pairs) (if\n (atom pairs) false (if (is-prefix? p (car (car pa\n irs))) true (look-for-extension-of p (cdr pairs)))\n )))))) (' (lambda (p pairs) (if (atom pairs) false\n (if (= p (car (car pairs))) (car pairs) (look-for\n p (cdr pairs))))))))) nil))) (read-exp))\n\n[graph = (1 0) (01 1) (001 2) (0001 3) (00001 4) etc.]\ndefine graph \n let (loop p n)\n [do!] cons display cons p cons n nil\n (loop cons 0 p + 1 n)\n (loop '(1) 0)\n\ndefine graph\nvalue ((' (lambda (loop) (loop (' (1)) 0))) (' (lambda (\n p n) (cons (display (cons p (cons n nil))) (loop (\n cons 0 p) (+ 1 n))))))\n\n[test it!]\n\ntry 10 graph nil\n\nexpression (try 10 graph nil)\nvalue (failure out-of-time (((1) 0) ((0 1) 1) ((0 0 1) 2\n ) ((0 0 0 1) 3) ((0 0 0 0 1) 4) ((0 0 0 0 0 1) 5) \n ((0 0 0 0 0 0 1) 6) ((0 0 0 0 0 0 0 1) 7) ((0 0 0 \n 0 0 0 0 0 1) 8)))\n\nrun-utm-on\n\nappend\n\n bits pi\n\nappend\n\n bits graph\n\n '(0 0 0 1)\n\nexpression (car (cdr (try no-time-limit (' (eval (read-exp)))\n (append (bits pi) (append (bits graph) (' (0 0 0 \n 1)))))))\ndebug 0\ndebug ()\ndebug 1\ndebug ()\ndebug 2\ndebug (((1) 0))\ndebug (0)\ndebug 3\ndebug (((1) 0) ((0 1) 1))\ndebug (0 0)\ndebug 4\ndebug (((1) 0) ((0 1) 1) ((0 0 1) 2))\ndebug (0 0 0)\ndebug 5\ndebug (((1) 0) ((0 1) 1) ((0 0 1) 2) ((0 0 0 1) 3))\ndebug (0 0 0 1)\ndebug 6\ndebug (((1) 0) ((0 1) 1) ((0 0 1) 2) ((0 0 0 1) 3) ((0 0\n 0 0 1) 4))\nvalue 3\n", "meta": {"hexsha": "ccbbb4000c14829e817e56a8cad33ffbd63f1352", "size": 4459, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/exec.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/exec.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/exec.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": 32.5474452555, "max_line_length": 68, "alphanum_fraction": 0.5097555506, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4236039578479139}}
{"text": "### ivmodel: Generates an instance of ivmodel\n### In this package, our IV model is\n### Y_i = beta_0 + D_i * beta_1 + X_i^T * gamma + epsilon_i\n### E(epsilon_i | Z_i, X_i) = 0\n### INPUT: Y, outcome (n * 1 vector)\n### D, exposure (n * 1 vector)\n### Z, instruments (n * L matrix)\n### X, baseline and exogenous covariates (n * p matrix)\n### intercept, should we include the intercept term?\n### beta0: null value for beta\n### alpha: 1 - alpha confidence interval\n### k: values for the k-class estimator\n### heteroSE: heteroskedastic SE?\n### clusterSE: clustered SE?\n### clusterID, if clusterSE is TRUE, then one must 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### deltarange: for sensitivity analysis.\n### OUTPUT: ivmodel object which contains a clean-up version of Y,D,Z,X (if available)\nivmodel <- function(Y,D,Z,X,intercept=TRUE,\n beta0=0,alpha=0.05,k=c(0,1),\n manyweakSE = FALSE, heteroSE = FALSE, clusterID = NULL,\n deltarange = NULL, na.action = na.omit) {\n\n # Error checking: check to see if necessary inputs are there!\n if(missing(Y)) stop(\"Y is missing!\")\n if(missing(D)) stop(\"D is missing!\")\n if(missing(Z)) stop(\"Z is missing!\")\n\n # Error checking: check Y and D\n if( (!is.vector(Y) && !is.matrix(Y) && !is.data.frame(Y)) || (is.matrix(Y) && ncol(Y) != 1) || (is.data.frame(Y) && ncol(Y) != 1) || (!is.numeric(Y))) stop(\"Y is not a numeric vector.\")\n if( (!is.vector(D) && !is.matrix(D) && !is.data.frame(Y)) || (is.matrix(D) && ncol(D) != 1) || (is.data.frame(D) && ncol(D) != 1) || (!is.numeric(D))) stop(\"D is not a numeric vector.\")\n Y = as.numeric(Y); D = as.numeric(D)\n if(length(Y) != length(D)) stop(\"Dimension of Y and D are not the same!\")\n\n # Error checking: check Z and convert \"strings\" into factors\n Z = data.frame(Z); stringIndex = sapply(Z,is.character); Z[stringIndex] = lapply(Z[stringIndex],as.factor)\n if(nrow(Z) != length(Y)) stop(\"Row dimension of Z and Y are not equal!\")\n colnames(Z) = paste(\"Z\",colnames(Z),sep=\"\")\n\n # Add intercept as X\n if(intercept && !missing(X)) X = data.frame(X,1)\n if(intercept && missing(X)) X = data.frame(rep(1,length(Y)))\n\n # Error checking: check X and convert \"strings\" into factors\n if(!missing(X)) {\n X = data.frame(X); stringIndex = sapply(X,is.character); X[stringIndex] = lapply(X[stringIndex],as.factor)\n\tif(nrow(X) != length(Y)) stop(\"Row dimension of X and Y are not equal!\")\n\tcolnames(X) = paste(\"X\",colnames(X),sep=\"\")\n }\n\n # Coalesce all data into one data.frame\n if(!missing(X)) {\n allDataOrig = cbind(Y,D,Z,X)\n } else {\n allDataOrig = cbind(Y,D,Z)\n }\n\n # NA handling\n if(identical(na.action, na.fail) | identical(na.action, na.omit) | identical(na.action, na.pass)){\n allDataOrig = na.action(allDataOrig)\n naindex = rep(TRUE, nrow(allDataOrig))\n\tnaindex[apply(is.na(allDataOrig), 1, any)] = NA\n }else if(identical(na.action, na.exclude)){\n naindex = rep(TRUE, nrow(allDataOrig))\n\tnaindex[apply(is.na(allDataOrig), 1, any)] = NA\n\tallDataOrig = na.action(allDataOrig)\n }else{\n stop(\"Wrong input of NA handling!\")\n }\n\n # Fit adjustment model\n ff = terms(Y ~ D + . -1,data=allDataOrig)\n mf = model.frame(ff,allDataOrig)\n\n # Declare Y and D\n Y = as.matrix(mf$Y); colnames(Y) = \"Y\"\n D = as.matrix(mf$D); colnames(D) = \"D\"\n\n # Extract Z and X\n allData = sparse.model.matrix(ff,allDataOrig); attr(allData,\"assign\") = NULL; attr(allData,\"contrasts\") = NULL\n Zindex = grep(paste(\"^\",colnames(Z),sep=\"\",collapse=\"|\"),colnames(allData))\n Z = allData[,Zindex,drop=FALSE]; colnames(Z) = sub(\"^Z\",\"\",colnames(Z))\n if(!missing(X)) {\n Xindex = grep(paste(\"^\",colnames(X),sep=\"\",collapse=\"|\"),colnames(allData)); X = allData[,Xindex,drop=FALSE]; colnames(X) = sub(\"^X\",\"\",colnames(X))\n }\n # Check to see if there's enough data points after removing missing values\n if(nrow(Y) <= 1) stop(\"Too much missing data!\")\n\n n = length(Y)\n if(!missing(X)){\n ### clean X and project Y, D, Z\n qrX<-qr(X)\n p = qrrank(qrX)\n if(p==0)\n stop(\"vector in X are all 0\")\n #if(p 1){\n Zadj<-qr.Q(ZadjQR)[, 1:L]%*%qrRM(ZadjQR)[1:L, 1:L] ### shall we update the Z by doing qr(X, Z)?\n #qrXZ<-qr(cbind(X, Z))\n #Z<-(qr.Q(qrXZ)[, 1:(p+L)]%*%qrRM(qrXZ)[1:(p+L), 1:(p+L)])[,(p+1):(p+L)]\n }\n ivmodelObject = list(call = match.call(),n=n,L=L,p=p,Y=Y,D=D,Z=Z,X=X,Yadj=Yadj,Dadj=Dadj,Zadj=Zadj, ZadjQR = ZadjQR)\n\n }else{\n p = 0\n Yadj = Y; Dadj = D; Zadj = as.matrix(Z)\n ### only need to clean Z\n ZadjQR = qr(Zadj)\n L = qrrank(ZadjQR)\n if(L==0)\n stop(\"No useful instrumental variables\")\n if(L == 1) {\n Z <- Zadj <-qr.Q(ZadjQR)[, 1:L] * as.numeric(qrRM(ZadjQR)[1:L, 1:L])\n }\n if(L 1)\n Z<-Zadj<-qr.Q(ZadjQR)[, 1:L]%*%qrRM(ZadjQR)[1:L, 1:L]\n\n ivmodelObject = list(call = match.call(),n=n,L=L,p=p,Y=Y,D=D,Z=Z,X=NA,Yadj=Yadj,Dadj=Dadj,Zadj=Zadj, ZadjQR = ZadjQR)\n }\n\n class(ivmodelObject) = \"ivmodel\"\n\n ivmodelObject$naindex = naindex\n ivmodelObject$alpha = alpha\n ivmodelObject$beta0 = beta0\n ivmodelObject$deltarange = deltarange\n\n ivmodelObject$AR = AR.test(ivmodelObject,beta0=beta0,alpha=alpha)\n ivmodelObject$ARsens = ARsens.test(ivmodelObject,beta0=beta0,alpha=alpha,deltarange=deltarange)\n ivmodelObject$kClass = KClass(ivmodelObject,beta0=beta0,alpha=alpha,k=k,heteroSE=heteroSE,clusterID=clusterID) ## Don't use many weak IV asymptotics for OLS and TSLS\n ivmodelObject$LIML = LIML(ivmodelObject,beta0=beta0,alpha=alpha,manyweakSE=manyweakSE,heteroSE=heteroSE,clusterID=clusterID)\n ivmodelObject$Fuller = Fuller(ivmodelObject,beta0=beta0,alpha=alpha,manyweakSE=manyweakSE,heteroSE=heteroSE,clusterID=clusterID)\n ivmodelObject$CLR = CLR(ivmodelObject,beta0=beta0,alpha=alpha)\n\n return(ivmodelObject)\n}\n", "meta": {"hexsha": "8230a6cf213a1484625c8e05b361064a0f54b6a4", "size": 6687, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ivmodel.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/ivmodel.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/ivmodel.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": 43.9934210526, "max_line_length": 187, "alphanum_fraction": 0.6198594287, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42317437836222604}}
{"text": "model_preciprec <- function (Sdry_t1 = 0.0,\n Sdry = 0.0,\n Swet = 0.0,\n Swet_t1 = 0.0,\n Sdepth_t1 = 0.0,\n Sdepth = 0.0,\n Mrf = 0.0,\n precip = 0.0,\n Snowaccu = 0.0,\n rho = 100.0){\n #'- Name: Preciprec -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Precipitation ReCalculation\n #' * Author: STICS\n #' * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002\n #' * Institution: INRA\n #' * Abstract: recalculation of precipitation\n #'- inputs:\n #' * name: Sdry_t1\n #' ** description : water in solid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Sdry\n #' ** description : water in solid state in the snow cover \n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Swet\n #' ** description : water in liquid state in the snow cover\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Swet_t1\n #' ** description : water in liquid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Sdepth_t1\n #' ** description : snow cover depth Calculation in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : m\n #' ** uri : \n #' * name: Sdepth\n #' ** description : snow cover depth Calculation\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : m\n #' ** uri : \n #' * name: Mrf\n #' ** description : liquid water in the snow cover in the process of refreezing\n #' ** inputtype : variable\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: precip\n #' ** description : current precipitation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Snowaccu\n #' ** description : snowfall accumulation\n #' ** inputtype : variable\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mmW/d\n #' ** uri : \n #' * name: rho\n #' ** description : The density of the new snow fixed by the user\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 100\n #' ** min : \n #' ** max : \n #' ** unit : kg/m**3\n #' ** uri : \n #'- outputs:\n #' * name: preciprec\n #' ** description : recalculated precipitation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n preciprec <- precip\n if (Sdry + Swet < Sdry_t1 + Swet_t1)\n {\n preciprec <- preciprec + ((Sdepth_t1 - Sdepth) * rho) - Mrf\n }\n preciprec <- preciprec - Snowaccu\n return (list('preciprec' = preciprec))\n}", "meta": {"hexsha": "bcca48b2faf99cbeb2197c0d2374f57b644c441b", "size": 6464, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/Preciprec.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/Preciprec.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/Preciprec.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": 47.8814814815, "max_line_length": 108, "alphanum_fraction": 0.2948638614, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4228917207774412}}
{"text": "#######################################################################################################################\n## Calibrating SIRX Poper Source Code\n## Author: Michael Halem (c) 2020\n## This code is released, as to the user's choice: either under the BSD License, the GPL License, or the LGPL License.\n## The intention is to give the code users full freedom to incorporate some or all of the code within their modeling work.\n## Note: The R packages incorporated may be under different licenses, so that it is the user's responsibility\n## to decide which license can be correctly used when incorporating the code in your project.\n##\n## If this code should be found useful, the author would appreciate a small citation.\n##\n## A DOI Link to the paper will be here: [DOI Link]\n## The first version of this paper is being released on Medrxiv and is entitled\n## \"Calibrating an Epidemic Compartment Model to Seroprevalence Survey Data\"\n## You may communicate to the author any issues or questions on the code at the contact address in the medrxiv paper.\n########################################################################################################################\n\n\n#####################################################################################################\n## genFiguresAndTables()\n## Generate the charts and tables for the medrxiv paper.\n## This also serves as an example of how to run runSIRX3 from the command line.\n## This also shows how the runSIRX3 can be run from the command line.\n#####################################################################################################\n\ngenFiguresAndTables<-function(\n nItem=NA ## 1 = generate Figures 1,2,3, and data for Tables 1, 7, 8, and 9\n ) ## 2 = generate Figure 4 and Table 5.\n{\n if (is.na(nItem)) return()\n\n if (nItem == 1)\n makeAntiBodyCurve() ## Make the antibody curves for figures 1, 2 and 3.\n\n if (nItem == 2) ##Make Figure 4 and Table 5\n {\n runSIRX3('NYC',nProject=10, nWindow=70,dataSource=nyc,Qprob=0.05, bAuto=T,\n betaChgFact=0.2,betaAuto=T,tABcal=116,tMax=137,tChg=16,bSolveXDX='XDX', ABtarg=0.199, ABweight=1e5) \n }\n}\n \n\n################################\n## A few items the author finds convenient\n\noptions(width=160, digits=5)\n##C like printf\nprintf <- function(...) cat(sprintf(...))\n\n################################\n## External packages that are needed\n## Fetch these before running from CPAN using your R system, i.e. R-Studio\n\nlibrary(deSolve)\nlibrary('minpack.lm')\n\n\n##Constants used \n\nDateRefPosix = as.POSIXct('2019-12-31 OO:OO', tz='EST')\nDateRefDate = as.Date('2019-12-31', tz='EST')\nEST='EST'\n\n##Convenience names for function parameters\nnyc=2\nnycold=3\nnys=4\neuro=5\nszDataSource=c('Unused','NYC','NYC-OLD','NYS','EuroCDC')\n\n#######################################################################################################################\n## Read in some antibody tables\n\nnyAB1 = read.csv(\"data/nyab1.csv\")\nperfectAB = read.csv(\"data/perfectAB.csv\")\nexampleAB=read.csv(\"data/exampleAB.csv\")\n\n\n########################################################################################################################\n##Read in population tables from the data subdirectory\n \ngetPopTable<-function(\n datasource=euro ##the Euro CDC data has different naming nomenclatures and no states than JHU data\n )\n{\n worldPop = read.csv('data/worldPop.csv', as.is=T, stringsAsFactors=F)\n usPop = read.csv('data/usPop.csv', as.is=T, stringsAsFactors=F)\n colnames(worldPop)[1] = 'CountryState'\n colnames(usPop)[1] = 'CountryState'\n\n if (datasource==euro) ##Has spaces\n {\n pop = worldPop ##return country names as is -- EuroCDC data has no states so not needed here\n ##aliases\n rownames(pop) = pop$CountryState\n pop=rbind(pop, c(CountryState = 'US', pop = pop['United States',2]))\n pop=rbind(pop, c(CountryState = 'UK', pop = pop['United Kingdom',2])) \n pop=rbind(pop, c(CountryState = 'United_Kingdom', pop = pop['United Kingdom',2]))\n pop=rbind(pop, c(CountryState = 'South_Korea', pop = pop['South Korea',2]))\n }\n else ##\"Has Dots\"\n {\n worldPop$CountryState = gsub(' ','.', worldPop$CountryState)\n worldPop$CountryState = gsub(',','.', worldPop$CountryState)\n usPop$CountryState = gsub(' ','.', usPop$CountryState)\n usPop$CountryState = gsub(',','.', usPop$CountryState)\n usPop$CountryState = sprintf(\"US.%s\", usPop$CountryState)\n \n pop = rbind(worldPop, usPop)\n rownames(pop) = pop$CountryState\n pop=rbind(pop, c(CountryState = 'US', pop = pop['United.States',2]))\n pop=rbind(pop, c(CountryState = 'UK', pop = pop['United.Kingdom',2]))\n }\n\n ##browser()\n vPop = as.numeric(pop[,2])\n names(vPop) = pop[,1]\n\n ##aliases \n\n \n return(vPop)\n}\n\n\n#############################################################################################\n## SIRX3 based on simple integration based on past value\n## Run a SIRX (version 3) Integration based on input parameters\n## Note: This is a deterministic run that provides extrapolated results based on the parameters.\n## The least squares type fitting is included later in the paper.\n##\n## SIRX3 Uses either a simple Euler Integration (for debugging comparison), or a Faster Runge-Kutta rk() method\n## Originaly based on SIR-X model after Maier and Brockmann https://doi.org/10.1101/2020.02.18.20024414\n## Descretized in integer time steps using simple linear approximation. (a Runge-Kutta method would converge faster)\n## The names variables are defined as in Maier et al.\n## Note: in Maier et al the alpha is https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology beta.\n## Maier's beta is wikipedia's gamma.\n## If you use the code I would appreciate a small citation in your work in addition to Ben Maier's (who invented the concept).\n## The below initial values are from Maier et al's ex-Hubei. I have a few suggestions on modifications to fit better the\n## underlying physics (i.e. reality) of the epidemic. You may email me at my public email address: consult@rocketpwr.com\n## t = Days since start of simulation\n## Compartments:\n## S = Succeptible\n## I = Infected\n## R = Recovered (or died)\n## X = Cumulative Reported Cases\n## Additional outputs are:\n## RfromS = Removed directly from susceptible compartment without infection\n## RfromI = Removed from Infected Compartment without passing thru Confirmed Cases \n## This version adds to X15 two more inputs: beta0 and tChg\n## tChg: time (relative to 0) when public health authorities change social distancing\n## beta0: the beta before the modification in social distancing\n## beta: the beta after the modification in social distancing\n#############################################################################################\n\nsirX3<-function(N = 10000, #population\n X0 = 5, #initial cases\n dX0 = 1, #initial change in cases per day\n kIX = 0.03125, #rate from I compartment to X compartment\n beta = 0.375, #Initial rate from S compartment to I compartment on and after the social distancing changeover\n betaChgFact = 1, #The factor that beta changes AFTER the change over at tChg \n gamma = 0.125, #rate from I compartment to R compartment\n Tmax=30, #days to extend the simulation\n tChg = 0, #day to change over from beta0 to beta -- setting to zero defaults to old sirX15 model\n dt = 0.002, #integration steps\n useRK4=T, ##F = use Halem's version of Euler Method, T=use R's Runge-Kutta rk45dp7 method\n bLinear=T, #if false, use a step function. If true linear up to tChg\n retX=NA, #if either retX or retDX set return only dot product of (isX,isDX)*(X,DX)\n retDX=NA, #NOTE: IF running Antibody test, make extra space in 1st cell for result!!\n tABtest=NA, ##return the antibody test result to this time in cell #1 \n ABcurve=perfectAB, ##a supplied antibody curve\n errorRetVal=NA ##a value so that nls doesn't croak if would return a zero or negative\n )\n{\n ##printf(\"running sirX3 beta=%6f X0=%6f kIX=%6f betaChgFact=%6f\\n\",\n ## beta, X0, kIX, betaChgFact)\n \n nObs = round(Tmax/dt)\n nStep = round(1/dt)\n R0 = X0 * gamma/kIX\n I0 = dX0/kIX\n S0 = N - I0 - X0 - R0\n if (is.na(betaChgFact)) betaChgFact=1\n \n ##browser()\n \n t = 0\n dat = data.frame(t, S=S0, I=I0, X=X0, R=R0)\n \n if (!useRK4)\n {\n ##descrete time steps with no correction for integer step sizes (Euler Method)\n for (i in 2:(nObs+1))\n {\n i0 = i - 1\n t = i0 * dt\n betaUse = beta\n if (!bLinear || tChg<=0)\n {if (t>=tChg) betaUse = beta*betaChgFact}\n else\n ##bLinear\n {\n wt1 = min(t/tChg, 1)\n wt0 = 1 - wt1\n betaUse = beta * (wt0 + betaChgFact * wt1)\n }\n S = S0 - betaUse * S0/N * I0 * dt\n I= I0 + (betaUse * S0 * I0/N - gamma * I0 - kIX * I0) * dt\n X = X0 + kIX * I0 * dt\n R = R0 + (gamma * I0) * dt \n if (i0 %% nStep == 0)\n {\n dat = rbind(dat, c(t, S, I, X, R))\n }\n S0 = S\n I0 = I\n R0 = R\n X0 = X \n }\n }\n else\n {\n ##Adapted from R example in man rk Runge-Kutta Method\n ##Have to back to back the RK models in first and second half\n ##browser()\n betaUse<-function(t, beta, betaChgFact, tChg, bLinear)\n {\n if (tChg <= 0) return(beta)\n if(!bLinear) { if (t>=tChg) return(beta*betaChgFact) else return(beta) }\n ##else bLinear\n wt1 = min(t/tChg, 1)\n wt0 = 1 - wt1\n return(beta * (wt0 + betaChgFact * wt1))\n }\n sirxModel<-function(t, x, parms) {\n with(as.list(c(parms, x)), {\n dS = -betaUse(t, beta, betaChgFact, tChg, bLinear=bLinear) * S * I/ N\n dI = betaUse(t, beta, betaChgFact, tChg, bLinear=bLinear) * S * I/N - gamma * I - kIX * I\n dX = kIX * I\n dR = gamma * I\n res = c(dS, dI, dX, dR)\n list(res)\n })\n }\n\n ## The parameters\n parms = c(beta=beta, gamma=gamma, kIX = kIX)\n ## vector of time steps\n if (length(Tmax) > 1)\n times = Tmax\n else\n times = seq(0, Tmax, length=abs(Tmax+1))\n ##times = seq(0, Tmax*nStep, length=nStep*Tmax+1)/nStep\n xstart = c(S=S0, I=I0, X=X0, R=R0)\n\tnames(xstart) = c('S','I','X','R')\n\t##atol = c(C=0.01, I=0.01, X=0.01, R=0.01)\n dat = rk(xstart, times, sirxModel, parms, method='rk45dp7', maxsteps=1000) ##Dormond-Prince Runge-Kutta adaptive stepsize \n dat = as.data.frame(dat)\n }\n\n cumI = N - dat$X - dat$S ##This is cumulative current and past tense infected, not current infected\n dat = cbind(dat, cumI)\n\n X = dat$X\n dX = c(dX0, X[-1] - X[-length(X)]) ##set first dX point to dX0\n dat = cbind(dat, dX)\n\n\n if (!is.na(tABtest))\n { ##Then calculate an antibody test result\n dCumI = c(dat$cumI[1], dat$cumI[-1] - dat$cumI[-dim(dat)[1]])\n i = which(dat$time <= tABtest)\n NtestPop = N - dat$X[tABtest == dat$time]\n if (length(NtestPop) == 0)\n {\n printf(\"Error in sirX3() NtestPop failure to calc because of bad dat$time\\n\")\n browser()\n }\n ABtestResult = testPctFromNumInfected(dCumI[i], tABtest - dat$time[i], nPop = NtestPop, curve=ABcurve)\n }\n\n dat0=dat\n \n if (!is.na(retX) || !is.na(retDX)) ##a vector of 1s and 0s if needed\n {\n if (!is.na(retX) && is.na(retDX)) retDX = rep(0, length(retX))\n if (!is.na(retDX) && is.na(retX)) retX = rep(0, length(retDX))\n if (length(retDX) != length(retX))\n {\n printf(\"Error in sirX3() length(retX) != length(retDX))\\n\");\n return(NA);\n }\n \n X = dat$X\n dX = dat$dX\n nX = length(X)\n remainder = length(retX) %% nX\n\n if (remainder == 0) \n dat = X*retX + dX*retDX ##This recycles X and dX if shorter than retDX.\n if (remainder == 1)\n {\n ABtestResult = exp(ABtestResult) #Result is exponentiated so when logged pct relative difference is significant\n dat = c(ABtestResult, X*retX[-1] + dX*retDX[-1]) ##stick the AB test in first place\n }\n if (remainder>1)\n {\n printf(\"Error in sirX3() length(retDX) not multiple of length(X) [optional +1]\\n\");\n return(NA);\n } \n iError = is.na(dat) | dat<=0\n if (length(errorRetVal) == length(dat)) dat[iError] = errorRetVal[iError]\n if (length(errorRetVal) == length(dat)) dat[iError] = 1 ##If it pops an error, need to return erroneous value\n \n }\n\n ##debugging print...\n ##if (!is.list(dat)) printf(\"called sirX3(retX[1,end]=%.0f %.0f retDX[1, end]=%.0f %.0f len=%d %d dat[1:3] %f %f %f)\\n\",\n ## retX[1], retDX[1], retX[length(retX)], retDX[length(retDX)], length(retX), length(retDX), dat[1], dat[2], dat[3])\n ##print(dat)\n ##if (!is.list(dat))\n ## browser()\n return(dat)\n}\n\n\n#############################################################################################\n## Get the nyc data\n## The file nyc.csv is included in the paper's data\n\ngetNYC<-function()\n{ \n dat = read.csv('data/nyc.csv', stringsAsFactors=F)\n colnames(dat) = gsub('_','.', colnames(dat))\n if (any(colnames(dat) == 'DATE.OF.INTEREST'))\n Date = as.Date(dat$DATE.OF.INTEREST, '%m/%d/%y')\n else\n Date = as.Date(rownames(dat), '%m/%d/%y')\n nDat = dim(dat)[1]\n dC = dat$CASE.COUNT \n dD = dat$DEATH.COUNT\n C = D = 0\n for (i in 1:nDat)\n {\n C[i] = sum(na.rm=T, dC[1:i])\n D[i] = sum(na.rm=T, dD[1:i])\n }\n if (dC[nDat] < 0.1*dC[nDat-1])\n { ## bad last day filter\n dC = dC[-nDat]\n dD = dD[-nDat]\n C = C[-nDat]\n D = D[-nDat]\n Date = Date[-nDat]\n nDat = nDat - 1\n }\n\n if (dC[nDat] < 0.6 * dC[nDat - 1] && dC[nDat]>0.4 * dC[nDat - 1])\n { ##second of last day 1/2 day adjustment\n dChalf = dC[nDat]\n dC[nDat] = dC[nDat] + dChalf\n C[nDat] = C[nDat] + dChalf\n \n }\n\n X = rep(NA, nDat)\n R = rep(NA, nDat)\n\n t = as.numeric(Date - DateRefDate)\n\n dat = cbind(Date,t,C,D,R,X)\n dat = as.data.frame(dat, stringsAsFactors=F)\n dat$Date = Date\n dat = dat[order(Date),]\n rownames(dat)=1:dim(dat)[1]\n return(dat)\n}\n\n\n\n#############################################################################################\n## Generalized csv fetcher for case time series\n\ngetCsvData<-function(fnamePath, bIsCum=T)\n{ \n dat = read.csv(fnamePath, stringsAsFactors=F)\n dat$Date = as.Date(dat$Date)\n \n nDat = length(dat$Date)\n \n Date = dat$Date\n \n C = dat$Cases \n D = rep(NA, nDat)\n R = rep(NA, nDat)\n X = rep(NA, nDat)\n t = as.numeric(Date - DateRefDate)\n\n if (!bIsCum)\n {\n dC = C\n for (i in 1:length(C))\n {\n C[i] = sum(na.rm=T, dC[1:i])\n } \n \n }\n\n dat = cbind(Date,t,C,D,R,X)\n dat = as.data.frame(dat, stringsAsFactors=F)\n dat$Date = Date\n dat = dat[order(Date),]\n rownames(dat)=1:dim(dat)[1]\n return(dat)\n}\n\n\n\n\n#############################################################################################\n## Read the NYS county based data to return a data frame used for the\n\ngetNysData<-function(county)\n{ \n county = toupper(county)\n if (county == \"NYC\")\n {\n dat1 = getNysData(\"New.York\")\n dat2 = getNysData(\"Queens\") \n dat3 = getNysData(\"Kings\")\n dat4 = getNysData(\"Bronx\")\n dat5 = getNysData(\"Richmond\")\n\n tt = c(dat1$t, dat2$t, dat3$t, dat4$t, dat5$t)\n tt = sort(unique(tt))\n\n dat = dat1[1,] ##clone new data frame\n dat = dat[-1,] ##empty\n for (t in tt)\n {\n Date = dat1$Date[dat1$t == t]\n C = sum(dat1$C[dat1$t == t],\n dat2$C[dat2$t == t],\n dat3$C[dat3$t == t],\n dat4$C[dat4$t == t],\n dat5$C[dat5$t == t])\n nTst = sum(dat1$nTst[dat1$t == t],\n dat2$nTst[dat2$t == t],\n dat3$nTst[dat3$t == t],\n dat4$nTst[dat4$t == t],\n dat5$nTst[dat5$t == t])\n newRow = as.data.frame(cbind(Date, t, C, nTst))\n newRow$Date = Date\n dat = rbind(dat, newRow)\n dat$Date = as.Date(dat$Date)\n }\n return(dat) \n }\n \n county = gsub(' ','.',x=county)\n \n dat = read.csv('data/countyNY.csv', stringsAsFactors=F)\n colnames(dat) = gsub(' ', '.', x=colnames(dat))\n ##Date = as.Date(dat$Test.Date)\n dat$County = toupper(gsub(' ','.',x=dat$County))\n \n counties = sort(unique(dat$County))\n ##browser() \n \n iCounty = which(county == dat$County)\n \n nDat = length(iCounty)\n Date = as.Date(dat$Test.Date[iCounty], format=\"%m/%d/%Y\")\n C = dat$Cumulative.Number.of.Positives[iCounty] \n ##D = dat$death[iCountry]\n nTst = dat$Cumulative.Number.of.Tests.Performed[iCounty]\n ##R = dat$recovered[iCountry]\n ##X = rowSums(cbind(D,R), na.rm=T)\n t = as.numeric(Date - DateRefDate)\n\n ##browser()\n dat = cbind(Date,t,C,nTst)\n dat = as.data.frame(dat, stringsAsFactors=F)\n dat$Date = Date\n dat = dat[order(Date),]\n dat = unique(dat)\n rownames(dat)=1:dim(dat)[1]\n return(dat)\n}\n\n\n\n\n#############################################################################################\n##Pick the better of the multple models\n## In the runSIRX3 curve fitting on bootstrap, a number of initial non-linear closed form models\n## are initially fitting, approaching the fit from, for example, r=positive growth or\n## r= negative growth. (modelNls1a and modelNls1b respectively.)\n## It was found that sometimes approaching from the wrong side\n## would fail to converge, so both sides are run.\n## Similarly, the model can be formulated in different ways depending on where the\n## constants multiplied through, as seen in modelNls1c and modelNls1d \n## After the 4 modelNls1[a,b,c,d] are run, this function picks the one with the best fit\n## and then returns the boot strap parameters, r0, Io, Xo, and dXo\n## within the structure so that the runSIRX2 can use this to seed the\n## SIRX least square fit.\n#############################################################################################\n\npickBetterModel<-function(kIX=NA, model1, model2, model3, model4)\n{\n modelNls = NA\n model = list(model1, model2, model3, model4)\n\n good = rep(NA, 4)\n sigma = rep(NA, 4)\n for (i in 1:4)\n {\n good[i] = !(class(model[[i]]) == 'try-error')\n if (good[i]) sigma[i] = summary(model[[i]])$sigma\n }\n\n if (!any(good)) ##then all bad, return first bad one\n return(model1)\n\n\n minSigma = min(na.rm=T, sigma)\n\n iMin = min(which(sigma == minSigma))\n\n modelNls = model[[iMin]]\n\n coefs = modelNls$m$getPars()\n\n Xo = NA\n r0 = NA\n Io = NA\n\n if (names(coefs)[3] == 'A')\n { ##older model: log(C)~ logOrNA(A * sign(r) * exp(r * (t - tMin))+Co )\n r0 = coefs[1]\n Io = coefs[3] * abs(coefs[1])/kIX \n Xo = coefs[2] + sign(r0)*coefs[3]\n dXo = abs(coefs[3] * r0) \n }\n \n if (names(coefs)[3] == 'Apct')\n { ##newer pct model: log(C)~ logOrNA(Co * (1 + Apct * sign(r) * exp(r * (t - tMin))))\n r0 = coefs[1]\n Xo = coefs[2] * (1 + sign(r0)*coefs[3])\n Io = Xo/kIX\n dXo = abs(coefs[2] * coefs[3] * coefs[1])\n }\n \n modPars = list(r0=unname(r0), Xo=unname(Xo), Io=unname(Io), dXo = unname(dXo))\n modelNls$modPars = modPars\n \n return(modelNls)\n}\n\n#############################################################################################\n## logOrNA() return the log unless R's log() returned a NaN, in which case it returns an NA.\n## This is because NAs are handled better by the regression algorithms, while NaNs terminate\n## with an error code\n#############################################################################################\n\nlogOrNA<-function(x) {\n y=rep(NA, length(x))\n i=x>=0\n y[i] = log(x[i])\n return(y)\n}\n\n\n#############################################################################################\n## runSIRX3 -- This contains the algorithms that fit least squares to calibrate against the\n## seroprevalence data.\n## Note that 3 indicates this is roughly the 3rd version of this model (for the medrxiv paper).\n## The author will explain in greater detail any thing within.\n## If there is was a need, this code could be modularized and made into an R package.\n## It could also the basis of a small Github project. \n## If you have further interest or questions, please contact michael.halem@becare.net\n#############################################################################################\n\n\nrunSIRX3<-function(country, nWindow=7, tMin=NA, tMax=NA, nProject=2, Cnew=NA,\n dataSource=euro,\n N=NA,\n gamma=0.125, kIX = NA,\n Qprob=0.2, ##probability of detection and quarantine to X compartment before recovery to R compartment\n bAuto=F,\n tChg=NA, ##change over time (after Tmin) from beta0 to beta (final). tChg=0 is equivalent to single beta\n betaChgFact=1,\n betaAuto=F,\n bPlotExtra=F,\n bPrintOutOfContext=F, ##Print extra internal debugging information -- READ THE CODE!!! for documentation\n bTrace=F,\n bRetxdat=F,\n scale=1,\n bYtotInterval=NULL,\n tABcal=NA,\n ABcurve=nyAB1,\n bSolveXDX = 'X', #X = cases, DX=change in cases, XDX=both cases and change in cases\n ABweight=100, ##The weight, relative to 1, of the AntiBody log target miss: NOT LOG\n ABtarg=NA\n )\n{\n if (bPrintOutOfContext)\n printf(\"WARNING: PRINTING OUT OF CONTEXT EXTRA DEBUGGING INFORMATION ON -- READ THE CODE TO UNDERSTAND!!!\")\n if (is.na(tChg)) tChg = nWindow\n ##betaChgFact0 = betaChgFact\n ##rm(betaChgFact)\n \n ##Note: Qprob = kIX/(kIX + gamma) (From Ben Meier's paper)\n ##thus: Qk + Qg = k => Qk - k = -Qg => k(Q - 1) = -Qg\n ##thus: k = Qg/(1 - Q)\n Reff = NA; RinfPct=NA; Xinf=NA ##variables to put NA if can't calculate so printing won't crash\n if (is.na(kIX))\n kIX = Qprob * gamma/(1 - Qprob)\n Qprob = kIX/(kIX + gamma) ##a doublecheck\n \n ##six=makeplotSix(country, nWindow=0, nProj=0, dTexit=7); \n if (dataSource==nyc) xdata=getNYC()\n if (dataSource==nys) xdata=getNysData(country)\n if (dataSource==nycold) xdata=getCsvData('data/nycold.csv', bIsCum=T)\n xdata$C=scale*xdata$C \n\n if (is.na(N))\n { ##fetch N from population lookup if available\n pop = getPopTable(dataSource)\n N = pop[country]\n if (dataSource==nys) N=pop[sprintf(\"US.NY.%s\", country)]\n if (length(N) == 0) N = NA\n if (length(N) > 1) N = N[1]\n }\n \n xdata = xdata[(!is.na(xdata$C)),]\n\n\n if (!is.na(Cnew)) #if have today's newest data\n {\n ##browser()\n newData = xdata[dim(xdata)[1],]\n newData$Date = newData$Date + 1\n newData$t = newData$t+1\n newData$C = Cnew\n newData[,4:(dim(newData)[2])]=NA\n xdata = rbind(xdata,newData)\n }\n\n \n nData = dim(xdata)[1]\n six=xdata\n ##six = cbind(six, dD = c(NA, six$D[-1] - six$D[-nData]))\n if (any(colnames(six) == 'nTst')) six = cbind(six, dTst = c(NA, six$nTst[-1] - six$nTst[-nData]))\n six = cbind(six, dC = c(NA, six$C[-1] - six$C[-nData]))\n if (any(colnames(six) == 'nTst')) six = cbind(six, yTot = six$dC/six$dTst)\n\n if (!is.null(bYtotInterval))\n {\n interval = match(bYtotInterval, six$t)\n six = cbind(six, Cold = six$C)\n six = cbind(six, dCold = six$dC)\n modYtot = lm(log(yTot)~t, six[interval,])\n meanTst = mean(six$dTst[interval])\n six$dC[interval] = exp(predict(modYtot))*meanTst\n for (i in interval) six$C[i] = six$C[i-1] + six$dC[i] \n }\n \n ##browser()\n \n Cmax = max(na.rm=T, six$C)\n \n\n if (is.na(tMax)) tMax = max(na.rm=T, six$t)\n if (is.na(tMin)) tMin = tMin = max(tMax - nWindow, min(na.rm=T, six$t))\n \n iData = six$t>=tMin & six$t<=tMax\n\n ##double lm method -- first find r, then find A and C\n nDC = sum(na.rm=T, iData & six$dC>0)\n\n if (nDC <= 1)\n {\n printf(\"Warning: Flatline Cases -- nothing to predict\\n\")\n rDC = 0; Aref = 0; Tref = tMin\n Cdc = mean(na.rm=T, six$C[iData])\n modelDC = NULL\n modelDC3 = NULL\n }\n if (nDC > 1)\n {\n \n modelDC = lm(log(dC)~t, data=six[iData & six$dC>0,])\n rDC = modelDC$coefficients[2]\n names(modelDC$coefficients) = c('Intercept ', 'r from dC ')\n modelDC3 = lm(C ~ I(sign(rDC)*exp(rDC*(t-tMin))), data=six[iData,])\n ##modelDC4 = lm((C) ~ I(sign(rDC)*exp(rDC*(t-tMin))), data=six[iData,])\n Cdc = modelDC3$coefficients[1]\n names(modelDC3$coefficients) = c('Co from dC ', 'A from dC ')\n ##Aref = abs(modelDC3$coefficients[2]/modelDC3$coefficients[1])\n Aref = modelDC3$coefficients[2]\n Tref = -log(Aref)/rDC+tMin\n ##Aref = exp(rDC * tMin)\n }\n\n mySummary<-function(model)\n {\n if (is.null(model) || class(model) == 'try-error')\n {\n if (is.null(model))\n printf(\"No model\\n\")\n else\n {\n printf(\"Note: nls model not used due to:\\t\")\n print(attributes(model)$condition)\n printf(\"\\n\")\n printf(\"\\tInitial Parameter Estimates: r=%g Cdc=%g Aref=%g\\n\", rDC, Cdc, Aref)\n printf(\"Possible Fix: re-read source-code i.e. source('makeplot.r')\\n\")\n }\n }\n else\n {\n szOutput = capture.output(print(width=100, digits=5, summary(model)))\n iBlank = (nchar(szOutput) == 0)\n szOutput = szOutput[!iBlank]\n iResidual = szOutput == \"Residuals:\" | szOutput == \"Call:\" | szOutput == \"Coefficients:\" | szOutput == \"Parameters:\"\n szOutput = szOutput[!iResidual]\n iClutter = grepl('Signif. codes', szOutput)\n szOutput = szOutput[!iClutter] \n printf(\"%s\\n\", szOutput[c(1:length(szOutput))])\n }\n }\n \n\n ##browser()\n ##Aref = min(abs(Aref/Cdc)) ##New for May 12\n if (bPrintOutOfContext) printf(\"Aref=%g Cdc=%g rDC=%g To=%f\\n\", Aref, Cdc, rDC, Tref)\n\n \n Cdc = abs(Cdc) ##consider when flipping sign on Cdc also fipping sign on A and r\n printf(\"Running 4 nlsLM bootstraps...\\n\")\n if (bTrace) printf(\"Running nlsLM #1a\\n\")\n modelNls1a = try(silent=T,\n nlsLM(log(C)~ logOrNA(Co * (1 + Apct * sign(r) * exp(r * (t - tMin)))), data=six[iData,],\n## start=list(r=rDC, Co=-sign(rDC)*(Cdc), A=abs(Cdc)),\n start=list(r=unname(rDC), Co=unname(Cdc), Apct=0.5),\n lower=c(r=-10, Co=-1e10, Apct=-1),\n upper=c(r=10, Co=1e10, Apct=.9999999), \n algorithm='LM', trace=bTrace, control=c(warnOnly=T, maxiter=1000, maxfev=1000)))\n\n ##Try from the other side\n if (bTrace) printf(\"Running nlsLM #1b\\n\")\n\n modelNls1b = try(silent=T,\n nlsLM(log(C)~ logOrNA(Co * (1 + Apct * sign(r) * exp(r * (t - tMin)))), data=six[iData,],\n ## start=list(r=rDC, Co=-sign(rDC)*(Cdc), A=abs(Cdc)),\n start=list(r=unname(-rDC), Co=unname(Cdc), Apct=0.5),\n lower=c(r=-10, Co=-1e10, Apct=-1),\n upper=c(r=10, Co=1e10, Apct=.9999999), \n algorithm='LM', trace=bTrace, control=c(warnOnly=T, maxiter=1000, maxfev=1000)))\n\n if (bTrace) printf(\"Finished Running nlsLM #1a/b\\n\")\n\n\n if (bTrace) printf(\"Running nlsLM #1c\\n\")\n modelNls1c = try(silent=T,\n nlsLM(log(C)~ logOrNA(A * sign(r) * exp(r * (t - tMin))+Co ), data=six[iData,],\n ## start=list(r=rDC, Co=-sign(rDC)*(Cdc), A=abs(Cdc)),\n start=list(r=unname(rDC), Co=unname(Cdc), A=unname(Aref)),\n lower=c(r=-10, Co=-1e10, A=0),\n upper=c(r=10, Co=1e10, A=1e10), \n algorithm='LM', trace=bTrace, control=c(warnOnly=T, maxiter=1000, maxfev=1000)))\n\n ## changing sign to approach from other side\n if (bTrace) printf(\"Running nlsLM #1d\\n\")\n modelNls1d = try(silent=T,\n nlsLM(log(C)~ logOrNA(A * sign(r) * exp(r * (t - tMin))+Co ), data=six[iData,],\n start=list(r=-unname(rDC), Co=unname(Cdc), A=unname(Aref)),\n lower=c(r=-10, Co=-1e10, A=0),\n upper=c(r=10, Co=1e10, A=1e10), \n algorithm='LM', trace=bTrace, control=c(warnOnly=T, maxiter=1000, maxfev=1000))) \n if (bTrace) printf(\"Finished nlsLM #1c/d\\n\")\n\n ##printf(\"...Finished Running 4 nlsLM boostraps, Up to 3 Failures are OK as long as 1 is Good\\n\")\n\n \n \n modelNls = pickBetterModel(kIX, modelNls1a, modelNls1b, modelNls1c, modelNls1d)\n\n nlsErr = class(modelNls) == 'try-error' \n \n xdat = six\n if (any(colnames(xdat) == 'X')) xdat=xdat[,-which(colnames(xdat) == 'X')]\n\n ##Add rows for forward projection\n for (i in 1:nProject)\n {\n newData = xdat[dim(xdat)[1],]\n newData$Date = newData$Date + 1\n newData$t = newData$t+1\n newData[,3:(dim(xdat)[2])]=NA\n xdat = rbind(xdat,newData)\n }\n rownames(xdat)=1:(dim(xdat)[1])\n \n \n nSim = dim(xdat)[1]\n if (!is.null(modelDC3))\n xdat=cbind(xdat, Csim= predict(modelDC3, newdata=data.frame(t=xdat$t)))\n else\n xdat = cbind(xdat, Csim=rep(NA, nSim))\n xdat=cbind(xdat, dCsim=c(NA, (xdat$Csim[-1] - xdat$Csim[-nSim]) ))\n\n ##FOR comparison -- full nls model\n ##Note: the columns for the full nls model are named Cnlm and dCnlm\n if (nlsErr)\n xdat = cbind(xdat, Cnlm = rep(NA, length(xdat$t)))\n else\n xdat=cbind(xdat, Cnlm= exp(predict(modelNls, newdata=data.frame(t=xdat$t))))\n xdat=cbind(xdat, dCnlm=c(NA, (xdat$Cnlm[-1] - xdat$Cnlm[-nSim])))\n rownames(xdat) = 1:(dim(xdat)[1])\n\n havFwd = F\n modelSIRXerr=T\n modelSIRX=NULL\n modelSIRXauto = NULL\n kIXauto=NA\n modPars=modelNls$modPars\n if (!is.na(N) && !nlsErr)\n {\n ##coefs = modelNls$m$getPars()\n gammaEff = gamma + kIX\n Reff = 1 + modPars$r0/gammaEff\n\n if (T) ##simplistic reduction of r\n {\n SIRinf<-function(x) {abs(x - (1-exp(-Reff * x)))}\n root = optimize(interval=c(0,1), f=SIRinf, tol=1e-6)\n ##method='Brent', lower=c(x=0), upper=c(x=1), control=c(trace=9))\n RinfPct = NA\n if (root$objective<1e-6)\n RinfPct = root$minimum\n Rinf = N * RinfPct\n Xinf = Rinf * kIX/(gamma + kIX)\n }\n\n r0 = modPars$r0\n Xo = modPars$Xo\n Io = modPars$Io\n dXo = modPars$dXo\n \n ##browser()\n \n ##xdat = cbind(xdat, Cfwd, dCfwd) \n if (r0>0) havFwd = 1\n\n iMin = which(xdat$t == tMin)\n if (any(iMin))\n {\n R0 = Xo * gamma/kIX #This is recovered R[t=0] is X times the ratio of the drain factors (gamma/kIX)\n S0 = N - Io - Xo - R0 ##this is susceptibles S[t=0]\n ##beta00 = (r0 + gamma + kIX)*N/S0\n beta00 = (r0 + gamma + kIX)\n\n ##Ro = 1 + r0/gamma\n ##beta00 = gamma * Ro\n ##Calculate an xdat matrix using the simplistic model above\n ###Now calculated in modPars dXo = r0 * Xo\n xdat15nlm = sirX3(N=N,\n X0 = Xo,\n ##dX0 = abs(r0) * coefs[3],\n dX0 = dXo,\n kIX = kIX,\n gamma = gamma,\n beta = beta00,\n Tmax = nProject + (tMax - tMin), \n )\n if (bPrintOutOfContext) printf(\"R0=%f Io=%f r0=%f Xo=%f beta00=%f\\n\", R0, Io, r0, Xo, beta00)\n ##if (Xo<0) Xo=1\n ##if (Xo<0) = Xo=0.01\n \n dTmax = tMax - tMin\n dTABcal = tABcal - tMin\n\n dXmax = 0.5*N\n dXmin = 0\n ##NB: dX0 is used to calculate Io. \n \n start=c(X0=Xo, dX0 = dXo, beta=beta00, betaChgFact=betaChgFact)\n \n lower=c(X0=0, dX0=dXmin, beta=0, betaChgFact=0.0)\n upper=c(X0=+N, dX0=dXmax, beta=Inf, betaChgFact=1) \n names(start) = names(lower) = names(upper) = c('X0', 'dX0', 'beta', 'betaChgFact')\n \n \n if (tChg <= 0)\n {\n tChg = 0\n betaChgFact = 1\n }\n\n if (!betaAuto)\n {\n ##betaChgFact = betaChgFact\n start = start[1:3]\n lower = lower[1:3]\n upper = upper[1:3] \n }\n ##browser()\n printf(\"running modelSIRX\\n\")\n ##try\n\n six2 = six[iData,]\n six2 = cbind(six2, isC=rep(0, dim(six2)[1]) , isDC=rep(0, dim(six2)[1]))\n if (bSolveXDX == 'X') six2$isC = 1\n if (bSolveXDX == 'DX') six2$isDC = 1\n if (bSolveXDX == 'XDX')\n {\n six2C = six2DC = six2\n six2C$isC = 1\n six2DC$isDC = 1\n six2 = rbind(six2C, six2DC)\n }\n iDataNoNeg = (six2$isC & six2$C>0) | (six2$isDC & six2$dC>0)\n six2 = six2[iDataNoNeg,]\n\n if (!is.na(ABtarg) && !is.na(tABcal))\n {\n six2 = rbind(rep(NA, dim(six2)[2]), six2)\n six2$C[1] = exp(ABtarg)\n six2$isC[1]=1\n six2$isDC[1]=0\n six2$Date[1]=as.Date('1900-01-01') ##Because I have na.omit on regression, must fill in stub data\n six2$t[1]=-99\n six2$nTst[1]= six2$dTst[1]=0\n six2$dC[1]=0\n six2$yTot[1]=0\n ##printf('here!!\\n')\n ##browser()\n \n }\n\n ##browser()\n if (bTrace) printf(\"Running nlsLM #3\\n\")\n modelSIRX = try(nlsLM(log(C*isC + dC*isDC) ~ log(sirX3( \n retX=isC,\n retDX=isDC,\n tABtest=dTABcal,\n ABcurve=ABcurve,\n Tmax=dTmax,\n kIX = kIX,\n N=N,\n errorRetVal=(isC*C + isDC*dC),\n tChg = tChg, ##Note: couldn't get it to autosolve for tChg\n gamma=gamma, ##gamma and above are known\n ##betaChgFact = betaChgFact0,\n ##beta0=beta00, tChg=0, \n X0=X0, dX0=dX0, beta=beta, betaChgFact=betaChgFact ##this is being solved for\n )),\n data=six2,\n start=start,\n lower=lower,\n upper=upper,\n weights = c(ABweight, rep(1, dim(six2)[1]-1)),\n algorithm='LM', trace=bTrace, control=list(warnOnly=T, maxiter=1000, maxfev=1000),\n na.action = na.omit\n ))\n ##browser()\n if (bTrace) printf(\"Finished running nlsLM #3\\n\")\n ##SIRX with automatic minimization to find kIX\n modelSIRXerr = class(modelSIRX) == 'try-error'\n if (!modelSIRXerr)\n {\n ##rm(beta0)\n coefsX2 = modelSIRX$m$getPars()\n start=c(X0=coefsX2[1], dX0 = coefsX2[2], beta=coefsX2[3], kIX=kIX, betaChgFact=betaChgFact)\n lower=c(X0=0, dX0=0,beta = 0, kIX=0.000001, betaChgFact=0.00)\n upper=c(X0=+N, dX0=0.5*N, beta=Inf, kIX=0.999, betaChgFact=1.0)\n \n names(start) = names(lower) = names(upper) = c('X0', 'dX0', 'beta', 'kIX', 'betaChgFact')\n if (tChg<=0) \n {\n tChg = 0\n betaChgFact = 1\n }\n if (!betaAuto)\n {\n start = start[c(1:4)]\n lower = lower[c(1:4)]\n upper = upper[c(1:4)]\n ##betaChgFact = 1\n }\n\n ##betaChgFact00 = betaChgFact\n \n\n ##browser()\n if (bAuto) printf(\"running modelSIRXauto\\n\")\n if (bTrace && bAuto) printf(\"Running nlsLM #4\\n\")\n if (bAuto) modelSIRXauto =\n try(nlsLM(log(C*isC + dC*isDC)~ log(sirX3(\n retX=isC,\n retDX=isDC,\n tABtest=dTABcal,\n ABcurve=ABcurve,\n Tmax=dTmax,\n N=N,\n errorRetVal=(isC*C + isDC*dC),\n tChg = tChg,\n gamma=gamma, ##gamma and above are known\n ##betaChgFact = betaChgFact0,\n ##X0=X0, dX0=dX0, beta=beta, beta0=beta0, kIX=kIX\n X0=X0, dX0=dX0, beta=beta, kIX=kIX, betaChgFact=betaChgFact\n ##,beta0=beta0, tChg=tChg ##this is being solved for\n )),\n data=six2,\n start=start,\n lower=lower,\n upper=upper,\n weights = c(ABweight, rep(1, dim(six2)[1]-1)),\n algorithm='LM', trace=bTrace, control=list(warnOnly=T, maxiter=200, maxfev=500)\n ))\n if (bTrace && bAuto) printf(\"Finished nlsLM #4\\n\")\n\n ##browser()\n modelSIRXautoerr = class(modelSIRXauto) == 'try-error'\n ##THERE IS A BUG HERE - found it...tChg wasn't being set on the below sirX3 call\n if (!bAuto || modelSIRXautoerr)\n {\n ##browser()\n if (length(coefsX2) == 3)\n {\n if (bPrintOutOfContext)\n printf(\"Drawing4param: tChg=%d X0=%f dX0=%f kIX=%f beta=%f betaChgFactIn=%f\\n\",\n tChg, coefsX2[1], coefsX2[2], kIX, coefsX2[3], betaChgFact)\n xdat15rk = sirX3(N=N, X0=coefsX2[1], dX0=coefsX2[2], kIX=kIX,\n gamma=gamma, beta=coefsX2[3], Tmax=nProject+tMax-tMin, tChg=tChg,\n betaChgFact=betaChgFact)\n }\n else\n {\n if (bPrintOutOfContext)\n printf(\"Drawing5param: tChg=%d X0=%f dX0=%f kIX=%f beta=%f betaChgFact=%f\\n\",\n tChg, coefsX2[1], coefsX2[2], kIX, coefsX2[3], coefsX2[4])\n xdat15rk = sirX3(N=N, X0=coefsX2[1], dX0=coefsX2[2], kIX=kIX,\n gamma=gamma, beta=coefsX2[3], betaChgFact=coefsX2[4], Tmax=nProject+tMax-tMin, tChg=tChg)\n }\n }\n else\n {\n coefsX2a = modelSIRXauto$m$getPars()\n ##browser()\n if (length(coefsX2a) == 4)\n {\n kIXauto=coefsX2a[4]\n if (bPrintOutOfContext)\n printf(\"Drawing4autoKIXparam: tChg=%d X0=%f dX0=%f kIX=%f beta=%f betaChgFactIn=%f\\n\",\n tChg, coefsX2a[1], coefsX2a[2], kIXauto, coefsX2a[3], betaChgFact)\n xdat15rk = sirX3(N=N, X0=coefsX2a[1], dX0=coefsX2a[2], kIX=kIXauto,\n gamma=gamma, beta=coefsX2a[3], Tmax=nProject+tMax-tMin, tChg=tChg, betaChgFact=betaChgFact)\n }\n else\n {\n kIXauto=coefsX2a[4]\n if (bPrintOutOfContext)\n printf(\"Drawing5autoKIXparam: tChg=%d, X0=%f dX0=%f kIX=%f beta=%f betaChgFact=%f\\n\",\n tChg, coefsX2a[1], coefsX2a[2], kIXauto, coefsX2a[3], coefsX2a[5])\n ##browser()\n xdat15rk = sirX3(N=N, X0=coefsX2a[1], dX0=coefsX2a[2], kIX=kIXauto,\n gamma=gamma, beta=coefsX2a[3], betaChgFact=coefsX2a[5], Tmax=nProject+tMax-tMin, tChg=tChg)\n } \n \n }\n }\n \n nMissing0 = dim(xdat)[1] - dim(xdat15nlm)[1]\n nMissing = nMissing0\n if (nMissing0<0) nMissing = 0\n ##xdat=cbind(xdat, Spct=rep(NA, dim(xdat)[1]))\n xdat=cbind(xdat, Ix2=rep(NA, dim(xdat)[1]))\n xdat=cbind(xdat, Cx2=rep(NA, dim(xdat)[1]))\n xdat=cbind(xdat, dCx2=rep(NA, dim(xdat)[1]))\n xdat=cbind(xdat, Spct2=rep(NA, dim(xdat)[1]))\n ##dCsir = c(NA, xdat15nlm$X[-1] - xdat15nlm$X[-length(xdat15nlm$X)])\n dCsir = xdat15nlm$dX\n ##browser()\n ##if (nMissing>0)\n infected=xdat[,1:2]\n infected=cbind(infected, I=rep(NA, dim(infected)[1]))\n infected=cbind(infected, dI=rep(NA, dim(infected)[1]))\n for (i in 1:length(xdat$t))\n {\n it = xdat$t[i]\n ixdat15 = which(it == xdat15nlm$t + tMin)\n if (!modelSIRXerr) ixdat2 = which(it == xdat15rk$t + tMin)\n if (length(ixdat15 == 1) &&\n FALSE) ##comment out for the Isir model\n {\n xdat$Isir[i] = xdat15nlm$I[ixdat15]\n xdat$Csir[i] = xdat15nlm$X[ixdat15]\n xdat$dCsir[i] = dCsir[ixdat15]\n ##xdat$Spct[i] = xdat15nlm$S[ixdat15]/N\n ##xdat$Spct = round(xdat$Spct,4)\n xdat$Isir = round(xdat$Isir,1)\n xdat$Csir = round(xdat$Csir,1)\n xdat$dCsir = round(xdat$dCsir,1)\n## xdat$pct2 = round(xdat$Spct, 2)\n }\n if (!modelSIRXerr && length(ixdat2 == 1))\n {\n ##browser()\n xdat$Ix2[i] = xdat15rk$I[ixdat2]\n xdat$Cx2[i] = xdat15rk$X[ixdat2]\n xdat$dCx2[i] = xdat15rk$dX[ixdat2]\n infected$I[i] = N - xdat15rk$X[ixdat2] - xdat15rk$S[ixdat2]\n xdat$Spct2[i] = xdat15rk$S[ixdat2]/N\n xdat$Spct2= round(xdat$Spct2,4)\n }\n }\n ##if (!modelSIRXerr)\n ## xdat$dCx2 = c(NA, xdat$Cx2[-1] - xdat$Cx2[-length(xdat$Cx2)])\n\n ##xdat$Spct = 100*xdat$Spct\n xdat$Spct2 = 100*xdat$Spct2\n \n }\n } \n \n \n rownames(xdat) = 1:nSim\n iData = xdat$t>=tMin & xdat$t<=tMax\n yrange = c(1, 2*max(na.rm=T, xdat$C, xdat$Csim, xdat$Cnlm))\n if (!is.na(N)) yrange[2] = min(N, yrange[2])\n\n yText = 10^(0:10)\n iyText = yText>=yrange[1] & yText<=yrange[2]\n yText = yText[iyText]\n par(xaxs = 'i', yaxs='i',oma=c(2,2,2,2.5))\n xticks = 5*(floor(min(na.rm=T,xdat$t)/5):ceiling(max(na.rm=T, xdat$t)/5))\n xdat$C[xdat$C<=0]=NA\n with(xdat, plot(C~t, log='y', type='o', pch='o', ylim=yrange, yaxt='n',\n ylab = NA, xlab=NA,\n xaxt='n', lab=c(8,30,20), main=country))\n text(x=min(xdat$t, na.rm=T), y=yText, labels=yText, pos=2, xpd=T) ##label y axis by hand\n xticksEven = xticks[xticks %% 2 == 0]\n xticksEven = xticksEven[xticksEven<=max(na.rm=T, xdat$t)]\n text(y=1, x=xticksEven,\n sprintf(\"%d\\n%s\", xticksEven, format(xdat$Date[1] + xticksEven - xdat$t[1], \"%m-%d\")),\n pos=1, xpd=T) ##label y axis by hand\n\n mtext(\"O's Cases, X's Daily Change (Black=data Blue=Calibration)\",\n side = 2, line = -1, outer = T,\n adj = NA, padj = NA, cex = 1.2, col = 'black')\n\n \n mtext(\"t (Days past 12/31/19) and Date\",\n side = 1, line = -2, outer = T,\n adj = NA, padj = NA, cex = 1.2, col = 'black')\n\n mtext(\"% Susceptible Population (Red)\", side = 4, line = -1.75, outer = T, at = 0.33,\n adj = NA, padj = NA, cex = 1.2, col = 'darkred')\n\n \n \n ## labels = ytick, srt = 45, pos = 2, xpd = TRUE)\n\n ##v=5*(floor(min(na.rm=T,xdat$t)/5):ceiling(min(na.rm=T, xdat$t)/5))\n if (any(xticks == tMin)) xticks = xticks[-which(xticks == tMin)]\n if (any(xticks == tMax)) xticks = xticks[-which(xticks == tMax)]\n\n lightticks = rgb(0.5,0.5,0.5)\n darkticks = rgb(0.3,0.3,0.3)\n \n abline(col=lightticks, v= xticks )\n abline(col=lightticks, h=c(10^(0:10), 2*10^(0:9), 4*10^(0:9), 6*10^(0:9), 8*10^(0:9) ) )\n abline(col=darkticks, h=c(10^(0:10)) )\n ##draw region of interest and tChg\n abline(col=rgb(0,0,1), v = c(tMin, tMax))\n if (tChg != 0) abline(col=rgb(0,0.5,0), v = tMin + tChg)\n if (!is.na(tABcal)) abline(col=rgb(0.25,0.25, 0.25), v = tABcal) \n \n\n nticks = round(log10(max(yrange)/min(yrange))*2)\n ##grid(col=1, ny = nticks, equilogs=F)\n \n if (bPlotExtra)\n { ##For the paper can do without the non-linear model -- make chart less busy\n with(xdat, points(Cnlm~t, type='o', pch='+', col='darkgreen'))\n with(xdat, points(dCnlm~t, type='o', pch='+', col='darkgreen'))\n }\n\n if (bPlotExtra) with(xdat[iData,], points(Csim~t, type='l', pch=0, col='darkred'))\n if (bPlotExtra) with(xdat[xdat$t<=tMin,], points(Csim~t, type='l', pch=0, col='darkblue'))\n if (bPlotExtra) with(xdat[xdat$t>=tMax,], points(Csim~t, type='l', pch=0, col='darkblue'))\n \n \n\n with(xdat, points(dC~t, type='o', pch='x'))\n if (bPlotExtra) with(xdat[iData,], points(dCsim~t, type='l', pch='+', col='darkred'))\n if (bPlotExtra) with(xdat[xdat$t<=tMin,], points(dCsim~t, type='l', col='darkblue'))\n if (bPlotExtra) with(xdat[xdat$t>=tMax,], points(dCsim~t, type='l', col='darkblue'))\n\n if(!is.null(bYtotInterval))\n {\n interval = match(bYtotInterval, six$t)\n with(xdat[interval,], points(dCold~t, type='o', pch='x', col=rgb(0.4,0.4,0.2)))\n with(xdat[interval,], points(Cold~t, type='l', pch='o', col=rgb(0.4,0.4,0.2)))\n }\n \n ##browser()\n\n## if (havFwd && any(colnames(xdat) == 'Csir'))\n if (any(colnames(xdat) == 'Csir'))\n {\n \n ##with(xdat, lines(Cfwd~t, col='purple'))\n ##with(xdat, lines(dCfwd~t, col='purple'))\n\n ##browser()\n if (bPlotExtra) with(xdat, points(Csir~t, col='red', type='l',pch='S'))\n if (bPlotExtra) with(xdat, points(dCsir~t, col='red', type='l', pch='S'))\n }\n\n if (!modelSIRXerr)\n {\n with(xdat, points(Cx2~t, col=rgb(0,0,1), pch='x', cex=0.7, type='o'))\n with(xdat, points(dCx2~t, col=rgb(0,0,1), pch='x', cex=0.7, type='o'))\n }\n\n ##to stop excessive digit printing and useless scientific notation\n xdat$Csim = round(xdat$Csim, 1)\n xdat$dCsim = round(xdat$dCsim, 1)\n xdat$Cnlm = round(xdat$Cnlm, 1)\n xdat$dCnlm = round(xdat$dCnlm, 1)\n\n xdat$Csim[xdat$Csim < -99999] = NA\n xdat$dCsim[is.na(xdat$Csim)] = NA\n xdat$Cnlm[xdat$Cnlm < -99999] = NA\n xdat$dCnlm[is.na(xdat$Cnlm)] = NA\n\n ##browser()\n if (!is.null(xdat$Spct2))\n with(xdat, points(Spct2~t, type='l', col='darkred', lwd=2)) ##if available plot percent remaining susceptibles\n \n ##printf(\"nticks=%d\\n\", nticks)\n\n xdat$C = round(xdat$C)\n xdat$dC = round(xdat$dC)\n ##browser()\n datagaps = which(xdat$t[-1] - xdat$t[-nSim] > 1)\n datagaps = datagaps[xdat$t[datagaps]>=tMin]\n\n xdat=xdat[xdat$t<=(tMax+nProject),]\n\n if (!bPrintOutOfContext) ##Simplify the table for the reader\n {\n xdatSimp = xdat[,c('Date','t','C','dC','Ix2','Cx2','dCx2','Spct2')]\n xdatSimp$Ix2 = round(xdatSimp$Ix2, 1)\n xdatSimp$Cx2 = round(xdatSimp$Cx2, 1)\n xdatSimp$dCx2 = round(xdatSimp$dCx2, 1)\n colnames(xdatSimp) = c('Date','t','C','dC','I(Model)','C(Model)','dC(Model)','S%(Model)')\n print(xdatSimp)\n }\n else\n print(digits=5, xdat)\n \n\n\n QprobAuto = kIXauto/(kIXauto + gamma) ##a doublecheck\n\n printf(\"-------------\\n\")\n printf(\"Country/State: %s\\tData Source: %s\\n\", country, szDataSource[dataSource])\n if (bPrintOutOfContext)\n {\n printf(\"N=%.4g Aref=%g Cdc=%g rDC=%g To=%f Tmin=%d gamma=%f betaChgFact=%f\\n\", N, Aref, Cdc, rDC, Tref, tMin, gamma, betaChgFact)\n ##if (havFwd)\n printf(\"Reff=%f RinfPct=%f Xinf=%7.0f Io=%f kIX=%f Qprob=%f kIXauto=%g QprobAuto=%f\\n\",\n Reff, RinfPct, Xinf, Io, kIX, Qprob, kIXauto, QprobAuto)\n }\n \n printf(\"---------------Log-Linear Bootstrap Model DC----------------\\n\")\n mySummary(modelDC)\n printf(\"---------------Log-Linear Bootstrap Model DC3---------------\\n\")\n mySummary(modelDC3)\n printf(\"---------------Closed Form Solution Exponential Model-------\\n\")\n mySummary(modelNls)\n printf(\"---------------SIRX Model Bootstrap W/Preset Qprob-----------\\n\")\n mySummary(modelSIRX)\n if (bAuto)\n {\n printf(\"---------------SIRX Model Calibration Run-----------\\n\") \n mySummary(modelSIRXauto)\n }\n if (!is.null(bYtotInterval)) mySummary(modYtot)\n\n if (any(datagaps))\n printf(\"Note! -- data gap causes non-linear dC after t=%d\\n\",\n xdat$t[datagaps] )\n\n\n if (!bPrintOutOfContext) ##Show the _final_ results -- make easy for readers\n {\n printf(\"------------------------\\n\")\n printf(\"Calibration Run Summary:\\n\")\n printf(\"Location=%s N=%.4g tMin=%d tMax=%d tBetaChange=%d tSeroTest=%d CasesDataSource=%s\\n\",\n country, N, tMin, tMax, tChg + tMin, tABcal, szDataSource[dataSource])\n\n coefsFinal=modelSIRXauto$m$getPars()\n printf(\"Gamma=%f Beta0=%f BetaChgFactor=%f Beta1=%f kIX=%f Qprob=%f\\n\",\n gamma, coefsFinal['beta'], coefsFinal['betaChgFact'],\n coefsFinal['beta']*coefsFinal['betaChgFact'],\n coefsFinal['kIX'], coefsFinal['kIX']/( coefsFinal['kIX'] + gamma)\n )\n }\n if (!is.na(tABcal))\n {\n infected$I[is.na(infected$I)] = 0 \n infected$dI = c(NA, infected$I[-1] - infected$I[-dim(infected)[1]])\n i = which(infected$t<=tABcal)\n if (bTrace) print(infected[i,])\n NtestPop = N - xdat$Cx2[tABcal == xdat$t] ##This is correction for N as per Eq 12 of paper\n predictedTest = testPctFromNumInfected(infected$dI[i], tABcal - infected$t[i], nPop = NtestPop , curve=ABcurve)\n perfectTest = testPctFromNumInfected(infected$dI[i], tABcal - infected$t[i], nPop = NtestPop, curve=perfectAB)\n printf(\"Perfect/Predicted Test Results = %f / %f vs Calibration Target=%f\\n\", perfectTest, predictedTest, ABtarg) \n }\n\n if (bPrintOutOfContext)\n printf(\"WARNING: PRINTING OUT OF CONTEXT EXTRA DEBUGGING INFORMATION ON -- READ THE CODE TO UNDERSTAND!!!\")\n ##return(NULL)\n if (bRetxdat) return(xdat)\n}\n\n \n\n#####################################################################\n## testPctFromNumInfected\n## Given the true number of seropositive time series and the population\n## return the percentage that would be tested positive by an antibody test\n## with a known input curve\n\ntestPctFromNumInfected<-function(nSeroPos, t, nPop = NA, curve=perfectAB)\n{\n nTestPos = 0\n nFalsePos = 0\n\n if (length(t) <= 0) return(NA)\n if (length(t) != length(nSeroPos)) return(NA)\n\n nSeroPos[is.na(nSeroPos)] = 0\n for (j in 1:length(t))\n {\n i = max(which(t[j] >= curve$t0)) ##Note: can fit a curve, but beyond scope of current analysis, i.e. p = 1 - exp(r*t) curve\n p = curve$sens[i]\n q = curve$spec[i]\n nTestPos = nTestPos + nSeroPos[j] * (p + q - 1)\n nFalsePos = nTestPos * (1 - q) ##just making a weighted average of some kind\n }\n \n ##browser()\n \n pctPos = nTestPos/nPop + nFalsePos/nTestPos\n \n return(pctPos)\n\n\n}\n\n######################################################################\n## Make the antibody surve plots for the paper\n\nmakeAntiBodyCurve<-function(abcurve=exampleAB)\n{\n N = 10000 ##Note R Language doesn't like the naked N as is shared with the next command\n t0 = 40\n t = 0:t0\n dt = t0 - t\n r = log(2)/3\n Iexp = pmin(N,floor(exp(t*r)))\n dIexp = c(Iexp[1], Iexp[-1] - Iexp[-(t0+1)])\n dIdecay = dIexp[(t0+1):1]\n Idecay = rep(NA, t0+1)\n Idecay[1] = dIdecay[1]\n for (i in 2:(t0+1)) Idecay[i] = Idecay[i-1]+dIdecay[i]\n Iflat = dIflat = rep(NA, t0+1)\n dIflat[1:(t0+1)] = ceiling(N/(t0+1))\n ##browser()\n dIflat[t0+1] = N - sum(dIflat[1:t0])\n Iflat[1] = dIflat[1]\n for (i in 2:(t0+1)) Iflat[i] = Iflat[i-1]+dIflat[i]\n\n p = approx(x=abcurve$t0, y=abcurve$sens, xout=dt, method='constant', rule=2)$y\n q = approx(x=abcurve$t0, y=abcurve$spec, xout=dt, method='constant', rule=2)$y\n q = mean(q)\n \n \n TleftExp = (p + q - 1)*dIexp\n TleftFlat = (p + q - 1)*dIflat\n TleftDecay = (p + q - 1)*dIdecay\n \n\n results = cbind(t,dt,Iexp, dIexp, TleftExp, Iflat, dIflat, TleftFlat, Idecay, dIdecay, TleftDecay)\n rownames(results) = 1:dim(results)[1]\n\n thetaExp = sum(TleftExp)/N + 1 - q\n thetaFlat = sum(TleftFlat)/N + 1 - q\n thetaDecay = sum(TleftDecay)/N + 1 - q\n\n results = as.data.frame(results, stringsAsFactors=F)\n print(results)\n\n printf(\"thetaExp=%.3f%%, thetaFlat=%.3f%%, thetaDecay=%.3f%%\\n\", 100*thetaExp, 100*thetaFlat, 100*thetaDecay)\n\n ##with(results, plot(y=dIexp, x=t, log='y',ylim=c(yMin,150), xlim=c(0,40), col='black', type='S'))\n\n \n plotIt(y=results$Iexp, dy=results$dIexp, t=results$t, N=N, theta=thetaExp, filename=\"expPlot.pdf\",\n name=\"Figure 1 - Exponential Increase of New Infected Time Series\")\n dev.new()\n \n plotIt(y=results$Iflat, dy=results$dIflat, t=results$t, N=N, theta=thetaFlat, filename=\"flatPlot.pdf\",\n name=\"Figure 2 - Flat New Infected Time Series\")\n \n dev.new()\n \n plotIt(y=results$Idecay, dy=results$dIdecay, t=results$t, N=N, theta=thetaDecay, filename=\"decayPlot.pdf\",\n name=\"Figure 3 - Exponential Decrease of New Infected Time Series\")\n\n \n}\n \n####################################################################################################\n## Plot barchart and change chart for paper\n\n\nplotIt<-function(y, dy, t, N, theta, name=\"???\", filename=\"theFile\", dir=\"~/Downloads\")\n {\n yMin = 0.0080\n yMax = 150\n yTicks = c(0.01, 0.1, 1, 10, 100)\n\n ##convert to percent\n y = 100 * y/N\n dy = 100 * dy/N\n pdf(sprintf(\"%s/%s\", dir, filename))\n \n plot(1, type='n', xlab='t (Time in Days)', main=name,\n ylab=\"X's = New True Positives, Bars = Cumulative True Positives \",\n log='y',ylim=c(yMin,150), xlim=c(0,40), yaxt='n', xaxs='i', yaxs='i')\n axis(2, at=yTicks, lab=sprintf(\"%.2f%%\",yTicks))\n for (i in 2:length(y))\n polygon(y=c(yMin,yMin,y[i],y[i],yMin), x=c(t[i-1], t[i], t[i], t[i-1], t[i-1]), col='white' )\n points(y=dy, x=t, col='black', type='o', pch='X')\n abline(h=100*theta, col='darkred')\n abline(h=100, col='darkblue')\n graphics.off() \n }\n\n", "meta": {"hexsha": "e3e78432b2af2304d87fb54f8399ea2199ae4223", "size": 58194, "ext": "r", "lang": "R", "max_stars_repo_path": "calibratingSIRX-v200527.r", "max_stars_repo_name": "becare-rocket/calibratingSIRX", "max_stars_repo_head_hexsha": "8f9376fa805c08e261819e99e4d36b67abf4faee", "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": "calibratingSIRX-v200527.r", "max_issues_repo_name": "becare-rocket/calibratingSIRX", "max_issues_repo_head_hexsha": "8f9376fa805c08e261819e99e4d36b67abf4faee", "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": "calibratingSIRX-v200527.r", "max_forks_repo_name": "becare-rocket/calibratingSIRX", "max_forks_repo_head_hexsha": "8f9376fa805c08e261819e99e4d36b67abf4faee", "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": 39.9409746054, "max_line_length": 146, "alphanum_fraction": 0.4987455751, "num_tokens": 17357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4223284998879599}}
{"text": "# ==============================================================================\r\n# ==============================================================================\r\n# Data Science Modelling Exercise for Lending Club Data\r\n# January 2018\r\n# Objective: Build a logistic regression model on previously unseen data using R.\r\n# by Combiz Khozoie, Ph.D.\r\n# ==============================================================================\r\n\r\n# ____________________________________________________________________________\r\n# Load packages and data ####\r\n\r\n## ............................................................................\r\n## Load packages ####\r\n\r\nrequire(readr)\r\nrequire(data.table)\r\nrequire(ggplot2)\r\nrequire(pROC)\r\nrequire(gmodels)\r\nrequire(InformationValue)\r\nrequire(caret)\r\nrequire(rpart)\r\nrequire(glmulti)\r\nrequire(ROSE)\r\nrequire(MLmetrics)\r\nrequire(caret)\r\nrequire(ROSE)\r\nrequire(broom)\r\nrequire(InformationValue)\r\nlibrary(plotly)\r\nrequire(hmeasure)\r\nlibrary(ggplot2)\r\nlibrary(extrafont)\r\nfont_import()\r\nloadfonts(device = \"win\")\r\n\r\n## ............................................................................\r\n## Load data ####\r\n\r\n# A dataset derived from the Lending Club (https://www.lendingclub.com/).\r\n# The data contains rows of customers, with each column showing the features\r\n# for loan applications that have been approved, together with outcomes of the\r\n# loans (in the final column). The outcomes show that each customer has either\r\n# defaulted or completed their loan.\r\nlc <- data.table(read_csv(\"LendingClub.csv\"))\r\ntidy.names <- make.names(names(lc), unique=TRUE) \r\nnames(lc) <- tidy.names # remove spaces from column names etc\r\n\r\n# Data attribute definitions were obtained from \r\n# the Data Dictionary (https://resources.lendingclub.com/LCDataDictionary.xlsx)\r\n\r\n## ............................................................................\r\n## Preliminary data preparation ####\r\n\r\n#count NAs\r\ncolSums(is.na(lc))\r\n\r\n# the number of NAs is miniscule relative to sample size, ok to drop\r\nlc <- lc[complete.cases(lc), ]\r\n\r\n# create unique id to facilitate some wrangling operations\r\nlc[, id := .I]\r\nsetkey(lc, key = id)\r\n\r\n# create new bClass as binary 0 / 1 of Class (default = 0)\r\nlc$bClass <- 0\r\nlc[Class == 'Creditworthy', bClass := 1]\r\nlc$Class <- NULL # drop the original Class\r\nstr(lc)\r\n\r\n# ____________________________________________________________________________\r\n# Data Cleanup and Preparation ####\r\n\r\n## ............................................................................\r\n## Categorical numbers to numeric ####\r\n\r\n## Some text based numbers are suitable for numeric encoding\r\n\r\n# create a lookup table\r\nlookupDT = data.table(oldNumber = c(\"None\", \"One\", \"Two\", \"Three\", \r\n \"Four\", \"Five\", \"Six\", \"Seven\", \r\n \"Eight\", \"Nine\", \"Ten\"), \r\n newNumber = c(0:10))\r\n\r\n# create a new column 'delinq_2yrs' with numeric conversions\r\nlc[lookupDT, on=.('No..Delinquencies.In.Last.2.Years' = oldNumber), \r\n delinq_2yrs := newNumber]\r\n\r\n# check the conversion worked\r\ntable(lc$delinq_2yrs)\r\ntable(lc$'No..Delinquencies.In.Last.2.Years')\r\n\r\n# create a new column 'pub_rec' with numeric conversions\r\nlc[lookupDT, on=.('No..Adverse.Public.Records' = oldNumber), \r\n pub_rec := newNumber]\r\n\r\n# create a new column 'pub_rec_bankruptcies' with numeric conversions\r\nlc[lookupDT, on=.('No..Of.Public.Record.Bankruptcies' = oldNumber), \r\n pub_rec_bankruptcies := newNumber]\r\n\r\n# All looks good so drop the original string-based columns\r\nlc[, c('No..Delinquencies.In.Last.2.Years', \r\n 'No..Adverse.Public.Records', \r\n 'No..Of.Public.Record.Bankruptcies') := NULL]\r\n\r\n## ............................................................................\r\n## Engineer datetime variables ####\r\n\r\n# The 'Earliest.Credit.Line.Opened' variable is in Excel date format \r\n# (date origin in excel is 30 dec 1899)) create a new column 'earliest_cr_line' \r\n# with a date formatted from the original excel date\r\nexcel.date.to.date <- function(x){as.Date(x, origin = \"1899-12-30\")}\r\nlc[, earliest_cr_line := lapply(.SD, excel.date.to.date), \r\n .SDcols = 'Earliest.Credit.Line.Opened']\r\n\r\n# the date format is not useful for glm in this format, so engineer \r\n# a 'credit_age' feature to represent 'months ago'\r\n# for reproducibility use 2018-01-01 as the current date instead of Sys.Date()\r\n# NOTE: in practice, the 'credit_age' metric would be determined at time of loan\r\n# consideration not an unknown no of months later.\r\nlc$credit_age <- as.numeric(difftime(\"2018-01-01\", lc$earliest_cr_line, \r\n units = \"days\")) / 30\r\n\r\n# Drop the two now-redundant columns with earliest credit line data\r\nlc[, c('Earliest.Credit.Line.Opened', 'earliest_cr_line') := NULL]\r\n\r\n## ............................................................................\r\n## Categorize numeric variables ####\r\n\r\n### . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..\r\n### Categorize loan application description ####\r\n\r\n# NLP would likely yield useful insights into this data, \r\n# but here we can generate some basic categories of length\r\nhist(lc$Loan.Application.Description, breaks = 100) \r\n\r\n# large # of applicants enter no description, 1000+ words, or a single word, \r\n# so these will require their own categories. The others we can split into \r\n# categories according to length\r\nlc$descr_cat <- \"Undetermined\" # initialize\r\nlc[Loan.Application.Description == 0, descr_cat := \"Blank\"]\r\nlc[Loan.Application.Description == 1, descr_cat := \"Word\"] # W for 1-word\r\nlc[Loan.Application.Description == 1000, descr_cat := \"LS\"] #LS for life-story\r\nlc[Loan.Application.Description >= 2 & Loan.Application.Description <= 15, \r\n descr_cat := \"Short\"] #S for short / one-sentence\r\nlc[Loan.Application.Description >= 16 & Loan.Application.Description <= 350, \r\n descr_cat := \"Medium\"] #M for medium\r\nlc[Loan.Application.Description >= 351 & Loan.Application.Description <= 999, \r\n descr_cat := \"Long\"] #L for long\r\n\r\n# drop original\r\nlc$Loan.Application.Description <- NULL\r\n\r\n### . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..\r\n### Binarize variables ####\r\n\r\n# the delinq_2yrs can be binarized for simplicity\r\nlc[delinq_2yrs > 0, delinq_2yrs := 1] # simple yes or no for two year delinqs\r\n\r\n# binarize home ownership\r\nlc$Home.Owner <- 0\r\nlc[Home.Ownership == \"MORTGAGE\" | Home.Ownership == \"OWN\", \r\n Home.Owner := 1] # simple yes or no for home ownership\r\nlc$Home.Ownership <- NULL # drop original\r\n\r\n# binarize bankruptcies (tiny number >1)\r\nlc$bankruptcies <- 0\r\nlc[pub_rec_bankruptcies >= 1, bankruptcies := 1]\r\nlc$pub_rec_bankruptcies <- NULL # drop original\r\n\r\n# binarize derogatory public records\r\nlc$derog_pr <- 0\r\nlc[pub_rec >= 1, derog_pr := 1]\r\nlc$pub_rec <- NULL # drop original\r\n\r\n# annual income simplify (thresholds defined by entropy / dt)\r\nlc$salary <- \"Unknown\" # initialize\r\nlc[Annual.Income <= 36000, salary := \"Low\"]\r\nlc[Annual.Income > 36000 & Annual.Income <= 76000, salary := \"Mid\"]\r\nlc[Annual.Income > 76000, salary := \"High\"]\r\nlc$Annual.Income <- NULL # drop original\r\n\r\n# address states -- some states have low sample size\r\n# to avoid generalization from small sample sizes, these states are\r\n# grouped under 'Other'\r\nstate.counts <- data.table(table(lc$Address.State))\r\ncolnames(state.counts) <- c('State', 'Count')\r\n# use a cutoff of n > 75 for now, revisit later\r\nlc[Address.State %in% state.counts[Count < 75, State], Address.State := 'Other']\r\n\r\n# identify a State to use as the reference state for log reg\r\nprop.table(table(train$Address.State, train$bClass),1)\r\n\r\n# Pick KS (Kansas as the reference level as defaults approx 50/50)\r\nlc$Address.State <- as.factor(lc$Address.State)\r\nlc$Address.State <- relevel(lc$Address.State, ref = \"KS\")\r\nlevels(lc$Address.State) # KS is now first / reference\r\n\r\n\r\n# ____________________________________________________________________________\r\n# Split data for model training ####\r\n\r\n# prepare train/test split (70/30) using stratified random sampling\r\nset.seed(95)\r\nsample <- createDataPartition(lc$bClass, p = .7, list = FALSE)\r\ntrain.imba <- lc[sample, ]\r\ntest <- data.table(lc[-sample, ])\r\n\r\n# examine class balance\r\nprop.table(table(train.imba$bClass))\r\nprop.table(table(test$bClass))\r\nprop.table(table(lc$bClass))\r\n\r\n# Note: class imbalance (0.18 / 0.82) is likely to lead to poor modelling\r\n# of the minority (uncreditworthy) class, and an increase in type I errors\r\n# (i.e. incorrectly predicting uncreditworthy individuals as creditworthy)\r\n\r\n## ............................................................................\r\n## Oversampling to address class imbalance ####\r\n\r\n# oversampling is performed on train data to prevent contamination of unseen\r\n\r\ntrain <- data.table(ovun.sample(bClass ~ ., data = train.imba, \r\n p = 0.5, seed = 95, method = \"over\")$data)\r\n\r\n\r\n# quick checks to ensure that: -\r\n# the training data set has a 50/50 class balance\r\n# the train / test split is 70/30\r\n# the test data is unseen (i.e. unique entries absent in train set)\r\n\r\ndim(train)\r\ndim(train.imba)\r\ntable(train$bClass)\r\n\r\n# examine unique cases\r\n#aggregate(id ~ bClass, train, function(x) length(unique(x)))\r\n#aggregate(id ~ bClass, train.imba, function(x) length(unique(x)))\r\n#aggregate(id ~ bClass, test, function(x) length(unique(x)))\r\n\r\n# all test data is unseen\r\nsum(test$id %in% train$id)\r\n\r\n\r\n# ____________________________________________________________________________\r\n# Model training ####\r\n\r\n\r\n## ............................................................................\r\n## Full logistic regression model ####\r\n\r\n#model <- glm(bClass ~ . -id, family=binomial, data = train) # drop id\r\n\r\n# count the number of non-redundant models\r\n#model <- glmulti(bClass ~ . -id, family=binomial, method = \"d\", \r\n# data = train, level = 1) # drop id\r\n\r\n\r\n## ............................................................................\r\n## Automated Model Selection with glmulti ####\r\n\r\n### . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..\r\n### Fit all non-redundant candidate models with glmulti ####\r\n\r\n#m.model <- glmulti(bClass ~ . -id, family=binomial, \r\n# data = train, level = 1, method = \"h\") # drop id\r\n\r\n### . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..\r\n### Fit models with Genetic Algorithm ####\r\n\r\n#g.model <- glmulti(bClass ~ . -id, family=binomial, \r\n# data = train, level = 1, method = \"g\") # drop id\r\n\r\n# After 1200 generations:\r\n# this is the optimal model after examining 1200 generations (Genetic Algo)\r\n# on the balanced classes (via oversampling) data\r\nmodel <- glm(bClass ~ 1 + Loan.Amount + Loan.Term + salary + \r\n Loan.Purpose + Address.State + Debt.To.Income.Ratio + \r\n FICO.Credit.Score + No..Inquiries.In.Last.6.Months + \r\n Months.Since.Last.Delinquency + Use.Of.Credit.Line +\r\n Total.Number.Of.Credit.Lines + delinq_2yrs + derog_pr +\r\n bankruptcies + credit_age + descr_cat + Home.Owner - id,\r\n family = binomial, data = train)\r\n\r\n\r\nsummary(model)\r\n\r\n\r\n# retrieve model coefficients\r\n\r\nmodel.tidy <- data.table(tidy(model))\r\n# calculate odd ratio with 95% CI \r\nmodel.tidy$odd.ratio <- exp(model.tidy$estimate)\r\nmodel.tidy$OR.upperCI <- exp(model.tidy$estimate + \r\n qnorm(0.975) * model.tidy$std.error)\r\nmodel.tidy$OR.lowerCI <- exp(model.tidy$estimate - \r\n qnorm(0.975) * model.tidy$std.error)\r\n#model.tidy\r\n\r\n# ____________________________________________________________________________\r\n# Evaluate model ####\r\n\r\n# anova(model, test = \"Chisq\")\r\n\r\n\r\n## ............................................................................\r\n## Predict classes on test data set ####\r\n\r\ny_pred <- plogis(predict(model, newdata = test))\r\n\r\n# determine the optimal cutoff for binarization of prediction values\r\n# optimize for misclassificationerrors by default\r\noptCutOff <- optimalCutoff(test$bClass, y_pred, \r\n optimiseFor = \"Both\")[1]\r\noptCutOff\r\n\r\n\r\n#y_pred_bClass <- ifelse(y_pred > 0.7, 1, 0) # binarize\r\ny_pred_bClass <- ifelse(y_pred > optCutOff, 1, 0) # binarize\r\n\r\n\r\n\r\n## ............................................................................\r\n## Evaluation metrics and plots ####\r\n\r\n#calculate accuracy of model\r\nmcerror <- mean(y_pred_bClass != test$bClass) # misclassification error\r\nprint(paste('Accuracy: ', 1 - mcerror))\r\n\r\nGini(y_pred, test$bClass)\r\nyoudensIndex(actuals = test$bClass, predictedScores = y_pred_bClass)\r\nmisClassError(actuals = test$bClass, predictedScores = y_pred_bClass)\r\nkappaCohen(actuals = test$bClass, predictedScores = y_pred_bClass)\r\nConcordance(actuals = test$bClass, predictedScores = y_pred)\r\n\r\n \r\n#confusion matrix\r\n\r\nrequire(caret)\r\nCrossTable(test$bClass, y_pred_bClass, prop.chisq = FALSE, prop.c = FALSE, \r\n prop.r = FALSE, dnn = c('actual', 'predicted'))\r\ncaret::confusionMatrix(y_pred_bClass, test$bClass, positive = \"1\") # better\r\n\r\n\r\n# ROC curve with AUC\r\nrocCurve = roc(response = test$bClass, \r\n predictor = y_pred)\r\n\r\nauc_curve = auc(rocCurve)\r\n\r\nplot(rocCurve, legacy.axes = TRUE, print.auc = TRUE, col=\"red\", main=\"ROC\")\r\n\r\n# KS stat\r\nks_stat(actuals = test$bClass, predictedScores = y_pred_bClass)\r\nks_plot(actuals = test$bClass, predictedScores = y_pred_bClass)\r\n\r\nks_stat(actuals = test$bClass, predictedScores = y_pred)\r\nks_plot(actuals = test$bClass, predictedScores = y_pred)\r\n\r\n# hmeasure (prof Hand)\r\nmisclassCounts(predicted.class = y_pred_bClass, true.class = test$bClass)\r\nsummary(HMeasure(test$bClass, y_pred, threshold = optCutOff))\r\nplotROC(HMeasure(test$bClass, y_pred, threshold = optCutOff))\r\n\r\n\r\n# ____________________________________________________________________________\r\n# Plots ####\r\n\r\n\r\n# Word counts for loan description\r\ntable(lc$descr_cat)\r\nprop.table(table(lc$descr_cat, lc$bClass), 1)\r\nplot(prop.table(table(lc$descr_cat, lc$bClass), 1))\r\n\r\n\r\n\r\n## ............................................................................\r\n## Coefficients / Odd-ratios ####\r\n\r\n# Plot odd.ratio for each coefficient in the model\r\ncoefficient.subset <- model.tidy[term != \"(Intercept)\"]\r\n\r\n# plot \r\nggplot(data = coefficient.subset, aes(x = odd.ratio, y = term))+\r\n geom_errorbarh(aes(xmax = OR.upperCI, xmin = OR.lowerCI), \r\n size = .5, color = \"gray50\") +\r\n geom_point(size = 3, colour = \"orange\") +\r\n geom_vline(aes(xintercept = 1), size = .25, linetype = \"dashed\") + \r\n theme_bw() +\r\n theme(panel.grid.minor = element_blank()) +\r\n ylab(\"Predictor\") +\r\n xlab(\"Odds Ratio (log scale)\") +\r\n coord_trans(x = \"log10\") +\r\n #ggtitle(\"Creditworthiness of Loan Applicants\")+\r\n theme(axis.text.x = element_text(angle = 90, hjust = 1))\r\n\r\n# Plot non-geographic odds ratios\r\ncoefficient.subset <- model.tidy[term != \"(Intercept)\" & \r\n !(term %like% \"Address.State\")]\r\n\r\nggplot(data = coefficient.subset, aes(x = odd.ratio, y = term))+\r\n geom_errorbarh(aes(xmax = OR.upperCI, xmin = OR.lowerCI), \r\n size = .5, color = \"gray50\") +\r\n geom_point(size = 3, colour = \"orange\") +\r\n geom_vline(aes(xintercept = 1), size = .25, linetype = \"dashed\") + \r\n theme_bw() +\r\n theme(panel.grid.minor = element_blank()) +\r\n ylab(\"Predictor\") +\r\n xlab(\"Odds Ratio (log scale)\") +\r\n coord_trans(x = \"log10\") +\r\n #ggtitle(\"Creditworthiness of Loan Applicants\")+\r\n theme(axis.text.x = element_text(angle = 90, hjust = 1))\r\n \r\n# Plot of word length descrption\r\n\r\n## ............................................................................\r\n## Odd ratios by US State ####\r\n\r\n# retrieve model properties relating to State\r\nstate.odds <- model.tidy[term %like% \"Address.State\",]\r\nstate.odds$state <- sapply(strsplit(state.odds$term, split='Address.State', \r\n fixed=TRUE), \r\n function(x) (x[2])) # retrieve state code\r\n\r\n# keep only the stats needed for the plot\r\nstate.odds <- state.odds[, .(state, odd.ratio)]\r\n\r\n# prepare additional columns to plot a map\r\n\r\n# Define the text label shown when cursor hovers over the State\r\nstate.odds$hover <- with(state.odds, paste(state, '
', \"Odd.Ratio:\", \r\n odd.ratio))\r\n\r\n\r\n# convert odd.ratio < 1 to fc to linearize for plotting\r\nstate.odds$odd.ratio.fc <- state.odds$odd.ratio\r\nstate.odds[odd.ratio < 1, odd.ratio.fc := -(1/odd.ratio)] \r\n\r\n# Create a Chloropleth map with plot.ly\r\n\r\n# give state boundaries a black border\r\nl <- list(color = toRGB(\"black\"), width = 1)\r\n\r\n# specify some map projection/options\r\ng <- list(\r\n scope = 'usa',\r\n projection = list(type = 'albers usa'),\r\n showlakes = TRUE,\r\n lakecolor = toRGB('white')\r\n)\r\n\r\np <- plot_geo(state.odds[state != \"Other\",], locationmode = 'USA-states') %>%\r\n add_trace(\r\n z = ~odd.ratio.fc, text = ~hover, locations = ~state,\r\n color = ~odd.ratio.fc, \r\n colors = \"RdBu\",\r\n zmin = -2,\r\n zmax = 2,\r\n marker = list(line = l)\r\n ) %>%\r\n colorbar(title = \"Relative Risk\") %>%\r\n layout(\r\n title = 'LendingClub - Lending Risk by State \\n (Logistic Regression Model)',\r\n geo = g\r\n )\r\n\r\nSys.setenv(\"plotly_username\"=\"Combo9\")\r\nSys.setenv(\"plotly_api_key\"=\"G7Tk9Q3kgRuRq0NWjwv4\")\r\n\r\nchart_link = api_create(p, filename=\"lgmap\")\r\nchart_link\r\n\r\n# ____________________________________________________________________________\r\n# Scrapbook / Junk ####\r\n\r\n# The following code is scrap that may come in handy in a future analysis.\r\n# some ideas include changepoint analysis and entropy calculations for\r\n# categorization of numeric variables, and the use of ML techniques to\r\n# inform selection of variables for logistic regression and to identify\r\n# conjunctive/disjunctive features that may inform introduction of\r\n# interaction terms into the model\r\n\r\n# Classification Tree with rpart\r\n\r\nrequire(rattle)\r\nmodel <- rpart(as.factor(bClass) ~ . -id, data = lc,\r\n control = rpart.control(minbucket = 50, \r\n minsplit = 50, cp = 0.003))\r\n\r\nfancyRpartPlot(model)\r\n\r\n# entropy / changepoint scrapbook\r\n\r\nrequire(entropy)\r\nrequire(changepoint)\r\n\r\ncdplot(as.factor(bClass) ~ FICO.Credit.Score, data = train, ylevels = 2:1)\r\n\r\ncdplot(as.factor(bClass) ~ as.factor(salary), data = train, ylevels = 2:1)\r\n\r\nmvalue = cpt.mean(e.df$ent, method=\"PELT\") #mean changepoints using PELT\r\nmvalue = cpt.mean(e.df$ent, method = \"AMOC\", Q = 1) #mean changepoints\r\nmvalue\r\ncpts(mvalue)\r\nplot(mvalue)\r\n\r\n# conditional density plots to reveal relationship between numeric \r\n# predictor variables and output. Can inform categorization decisions\r\n# and cutoffs.\r\n\r\ncdplot(as.factor(bClass) ~ Annual.Income, data = train, ylevels = 2:1, \r\n bw = \"nrd0\")\r\n\r\ncdplot(as.factor(bClass) ~ Annual.Income, data = lc, ylevels = 2:1, \r\n bw = 5, yaxlabels = \"n\")\r\naxis(4)\r\n\r\ncdplot(as.factor(bClass) ~ FICO.Credit.Score, data = lc, ylevels = 2:1, bw = 2)\r\n\r\n\r\ncdplot(as.factor(bClass) ~ Loan.Application.Description, data = train, \r\n ylevels = 2:1, bw = 1)\r\ncdplot(as.factor(bClass) ~ Loan.Application.Description, \r\n data = train[Loan.Application.Description <= 100,], ylevels = 2:1, bw = 1)\r\ncdplot(as.factor(bClass) ~ Annual.Income, data = train[Annual.Income <= 200000,], \r\n ylevels = 2:1)\r\n\r\ncdplot(as.factor(bClass) ~ Loan.Amount, data = train, ylevels = 2:1)\r\ncdplot(as.factor(bClass) ~ FICO.Credit.Score, data = train, ylevels = 2:1)\r\n\r\n\r\ncdplot(as.factor(bClass) ~ FICO.Credit.Score, data = train, ylevels = 2:1)\r\ncdplot(as.factor(bClass) ~ FICO.Credit.Score, data = train, ylevels = 2:1, bw = 2)\r\n\r\n\r\n# plots for report\r\nggplot(data=lc, aes(lc$Loan.Application.Description)) + geom_histogram()+theme_bw()\r\n\r\nggplot(data=data.table(y_pred), aes(y_pred)) + geom_histogram()+theme_bw()\r\n\r\n\r\n\r\n#### EOF\r\n", "meta": {"hexsha": "cf88d5e91d882cbf6e891347c194ddf8d8a91930", "size": 21178, "ext": "r", "lang": "R", "max_stars_repo_path": "r-code/ck_lendingclub.r", "max_stars_repo_name": "thecombiz/Lending_Club", "max_stars_repo_head_hexsha": "0c5927b395a1026c95eb212b1194ff9e100bbe9c", "max_stars_repo_licenses": ["MIT"], "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/ck_lendingclub.r", "max_issues_repo_name": "thecombiz/Lending_Club", "max_issues_repo_head_hexsha": "0c5927b395a1026c95eb212b1194ff9e100bbe9c", "max_issues_repo_licenses": ["MIT"], "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/ck_lendingclub.r", "max_forks_repo_name": "thecombiz/Lending_Club", "max_forks_repo_head_hexsha": "0c5927b395a1026c95eb212b1194ff9e100bbe9c", "max_forks_repo_licenses": ["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.9301470588, "max_line_length": 84, "alphanum_fraction": 0.5865993012, "num_tokens": 5110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6513548578981939, "lm_q1q2_score": 0.42194651620090007}}
{"text": "#' svd\n#' \n#' Singular value decomposition.\n#' \n#' @details\n#' The factorization works by first forming the crossproduct \\eqn{X^T X} for\n#' shaqs (\\eqn{XX^T} for tshaqs) and then taking its eigenvalue decomposition.\n#' In this case, the square root of the eigenvalues are the singular values.\n#' \n#' For shaqs, if the left/right singular vectors \\eqn{U} or \\eqn{V} are desired,\n#' then in either case, \\eqn{V} is computed (the eigenvectors). From these,\n#' \\eqn{U} can be reconstructed, since if \\eqn{X = U\\Sigma V^T}, then \\eqn{U =\n#' XV\\Sigma^{-1}}. For tshaqs, a similar game can be played, noting that the\n#' left singular vectors \\eqn{U} map to the eigenvectors of \\eqn{XX^T}.\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\nutils::globalVariables(c(\"n\", \"p\"))\n\n\n\nsvd.shaq = function(x, retu=FALSE, retv=FALSE)\n{\n only.values = !retu && !retv\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#' @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\n\n\nsvd.tshaq = function(x, retu=FALSE, retv=FALSE)\n{\n only.values = !retu && !retv\n \n cp = tcp.shaq(x)\n \n ev = eigen(cp, only.values=only.values, symmetric=TRUE)\n \n d = sqrt(ev$values)\n \n if (retu)\n u = ev$vectors\n else\n u = NULL\n \n if (retv)\n {\n v.local = sweep(ev$vectors, STATS=1/d, MARGIN=2, FUN=\"*\")\n v.local = crossprod(DATA(x), v.local)\n v = shaq(v.local, ncol(x), nrow(x), checks=FALSE)\n }\n else\n v = NULL\n \n list(d=d, u=u, v=v)\n}\n\n#' @rdname svd\n#' @export\nsetMethod(\"svd\", signature(x=\"tshaq\"),\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.tshaq(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\n\n\n#' @rdname svd\n#' @export\nsetMethod(\"La.svd\", signature(x=\"shaq\"),\n function(x, nu = min(n, p), nv = min(n, p))\n {\n n = nrow(x)\n p = ncol(x)\n \n ret = svd(x, nu, nv)\n if (nv)\n {\n ret$vt = t(ret$v)\n ret$v = NULL\n }\n \n ret\n }\n)\n\n\n\nLa.svd.tshaq = function(x, retu=FALSE, retv=FALSE)\n{\n only.values = !retu && !retv\n \n cp = tcp.shaq(x)\n \n ev = eigen(cp, only.values=only.values, symmetric=TRUE)\n \n d = sqrt(ev$values)\n \n if (retu)\n u = ev$vectors\n else\n u = NULL\n \n if (retv)\n {\n vt.local = sweep(ev$vectors, STATS=1/d, MARGIN=2, FUN=\"*\")\n vt.local = crossprod(vt.local, DATA(x))\n vt = tshaq(vt.local, nrow(x), ncol(x), checks=FALSE)\n }\n else\n vt = NULL\n \n list(d=d, u=u, vt=vt)\n}\n\n#' @rdname svd\n#' @export\nsetMethod(\"La.svd\", signature(x=\"tshaq\"),\n function(x, nu = min(n, p), nv = min(n, p))\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 = La.svd.tshaq(x, retu, retv)\n \n if (nu && NCOL(ret$u) > nu)\n ret$u = ret$u[, 1:nu]\n\n if (nv && NROW(ret$vt) > nv)\n DATA(ret$vt) = DATA(ret$vt)[1:nv, ]\n \n ret\n }\n)\n", "meta": {"hexsha": "91465bd33de134e723e4ce574f79c247cdbe760f", "size": 4611, "ext": "r", "lang": "R", "max_stars_repo_path": "R/svd.r", "max_stars_repo_name": "snoweye/kazaam", "max_stars_repo_head_hexsha": "0b6f290516f1a6e505ced665b6f2730ba9bc45d4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-07-16T19:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-24T13:07:08.000Z", "max_issues_repo_path": "R/svd.r", "max_issues_repo_name": "snoweye/kazaam", "max_issues_repo_head_hexsha": "0b6f290516f1a6e505ced665b6f2730ba9bc45d4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2017-06-24T21:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-07T03:33:48.000Z", "max_forks_repo_path": "R/svd.r", "max_forks_repo_name": "snoweye/kazaam", "max_forks_repo_head_hexsha": "0b6f290516f1a6e505ced665b6f2730ba9bc45d4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-06-24T21:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-24T21:22:10.000Z", "avg_line_length": 19.132780083, "max_line_length": 80, "alphanum_fraction": 0.5564953372, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4217903227167157}}
{"text": "# 4. faza: Analiza podatkov\n\n# Uvozimo funkcijo za uvoz spletne strani.\n# source(\"lib/xml.r\")\n\n# # Preberemo spletno stran v razpredelnico.\n# cat(\"Uvažam spletno stran...\\n\")\n# tabela <- preuredi(uvozi.obcine(), obcine)\n# \n# # Narišemo graf v datoteko PDF.\n# cat(\"Rišem graf...\\n\")\n# pdf(\"slike/naselja.pdf\", width=6, height=4)\n# plot(tabela[[1]], tabela[[4]],\n# main = \"Število naselij glede na površino občine\",\n# xlab = \"Površina (km^2)\",\n# ylab = \"Št. naselij\")\n# dev.off()\n\npodatki <- nutrition[, -c(6, 7, 8, 9, 11, 13, 15, 16, 17, 24)]\n\npodatki <- podatki[-(48:54),]\nrow.names(podatki) <- podatki$Jed\npodatki <- podatki[, -1]\n\nskalar1 <- scale(podatki)\n\nk <- kmeans(skalar1, 6, nstart=1000)\nkat <- k$cluster\nbarve <- c(\"red\", \"green\", \"blue\", \"yellow\", \"gold\", \"black\")\n\n\n# Uporabimo pairs\npdf(\"slike/pairs1.pdf\")\npairs(skalar1, col = barve[kat])\ndev.off()\n# Vidimo, da imamo osamelec, ki ga lahko dobimo z naslednjo funkcijo\nos_st <- as.integer(row.names(table(k$cluster))[table(k$cluster) == 1]) # Vrne grupo osamelca v tem primeru\nos <- row.names(skalar1)[kat %in% os_st] # Ime osamelca\n# Pogledamo pairs brez le-tega\npdf(\"slike/pairs2.pdf\")\npairs(skalar1[!(kat %in% os_st), ], col = barve[kat[!(kat %in% os_st)]])\ndev.off()\n# Osamelcev več ni v podatkih, ki jih bomo uporabili\n# Prvotni osamelec nato odstranimo iz podatkov\n\npodatki <- podatki[!(kat %in% os_st), ]\nkat <- kat[!(kat %in% os_st)]\n\ncat(\"Rišem grafa grupiranj...\\n\")\npdf(\"slike/grupiranje1.pdf\")\n\nplot(podatki[, \"Serving.Size..g.\"], podatki[, \"Calories\"],\n col = barve[kat],\n xlab = \"Masa jedi v gramih\",\n ylab = \"Kalorije\",\n main = \"Razmerje med velikostjo porcije ter kalorijami le-te\")\n\ndev.off()\n\npdf(\"slike/grupiranje2.pdf\")\n\nplot(podatki$Calories, podatki$Calories.From.Fat,\n col = barve[kat],\n xlab = \"Kalorije\",\n ylab = \"Kalorije iz maščob\",\n main = \"Razmerje med celotnimi kalorijami in kalorijami iz maščob\")\n\ndev.off()\n\n# Poizkusimo poizkati najboljše prileganje in napovedovanje proteinov v jedi ob znani količini natrija.\n\nattach(podatki)\n\ncat(\"Rišem graf napovedi...\\n\")\npdf(\"slike/napoved.pdf\")\nplot(Calories, Calories.From.Fat, xlab = \"Kalorije\", ylab = \"Kalorije iz maščob\")\nlin <- lm(Calories.From.Fat ~ Calories)\nkv <- lm(Calories.From.Fat ~ I(Calories^2) + Calories)\n# z <- lowess(Calories, Calories.From.Fat)\nmls <- loess(Calories.From.Fat ~ Calories)\nabline(lin, col = \"blue\")\ncurve(predict(kv, data.frame(Calories=x)), add = TRUE, col = \"red\")\n# lines(z, col = \"green\")\ncurve(predict(mls, data.frame(Calories=x)), add = TRUE, col = \"green\")\n\nlegend(\"bottomright\",\n legend = c(\"Kvadratni\", \"Linearni\", \"Loess\"),\n col = c(\"red\", \"blue\", \"green\"),\n lty = c(\"solid\", \"solid\", \"solid\"),\n bg = \"white\")\ndev.off()\n\n# Ocenimo napako\nvs_kvadratov <- sapply(list(lin, kv, mls), function(x) sum(x$residuals^2))\n# Vidimo, da je najnatančnejši mls model, sledi mu kvadratni\n\n# Sestavimo sedaj tabelo, ki bo napovedala za število kalorij pripadajočo vrednost kalorij iz maščob\n\nkv_napoved1 <- predict(kv, data.frame(Calories=seq(40, 140, 50)))\nmls_napoved <- predict(mls, data.frame(Calories=seq(min(Calories), max(Calories), 50)))\nkv_napoved2 <- predict(kv, data.frame(Calories=seq(max(Calories)+50, 1500, 50)))\nnapoved <- c(kv_napoved1, mls_napoved, kv_napoved2)\n\ntabela_napovedi <- data.frame(Kalorije = seq(40, 1500, 50), Kalorije.iz.mascob = napoved)\na <- c(540, 240, 290, 340, 440, 590, 390, 190)\nb <- c(225, 70, 100, 400/3, 200, 230, 170, 110)\nb <- b[order(a)]\na <- sort(a)\nattach(tabela_napovedi)\ntabela_napovedi$tocna.vrednost <- \"ni podatka\"\ntabela_napovedi$tocna.vrednost[Kalorije %in% a] <- b\ndetach(tabela_napovedi)\n\ndetach(podatki)\n", "meta": {"hexsha": "f0dce7baf07cece4b5412371b4823c293df0a67e", "size": 3699, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "SamoFMF/APPR-2014-15", "max_stars_repo_head_hexsha": "ca84f36fbce361d9cd1f902f7d9d2d6f86ed3962", "max_stars_repo_licenses": ["MIT"], "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": "SamoFMF/APPR-2014-15", "max_issues_repo_head_hexsha": "ca84f36fbce361d9cd1f902f7d9d2d6f86ed3962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2015-01-10T19:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2015-01-11T22:53:00.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "SamoFMF/APPR-2014-15", "max_forks_repo_head_hexsha": "ca84f36fbce361d9cd1f902f7d9d2d6f86ed3962", "max_forks_repo_licenses": ["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.1652173913, "max_line_length": 107, "alphanum_fraction": 0.6742362801, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4214290359973996}}
{"text": "#' Network Topology Metrics\n#'\n#' Calculates stream network topology metrics\n#'\n#' Requires /NHDPlusAttributes directory (see \\code{\\link{net_nhdplus}})\n#'\n#' Length and area measures are scaled by M values\n#'\n#' @param netdelin output from \\code{net_delin}\n#' @param vpu NHDPlusV2 Vector Processing Unit\n#' @param nhdplus_path Directory for NHDPlusV2 files (\\code{\\link{net_nhdplus}})\n#'\n#' @return \\code{data.frame}: \\code{$group.comid} stream network root COMID;\n#' \\code{$vpu} NHDPlusV2 vector processing unit;\\code{M} Position of sampling\n#' point on COMID, as proportion of COMID from upstream end; \\code{WS.ord}\n#' strahler order for root node;\\code{$head.h2o} number of headwater reaches;\n#' \\code{$trib.jun} number of tributary junctions; \\code{reach.cnt} number of\n#' reaches in network; \\code{diver.cnt} count of divergent flow paths;\n#' \\code{$AREASQKM} drainage area (km^2); \\code{$LENGTHKM} total lenght of\n#' network flowlines (km); \\code{drain.den} drainage density (\\code{LENGTHKM}\n#' / \\code{AREASQKM})\n#'\n#' @examples\n#' # identify NHDPlusV2 COMID\n#' a <- net_sample(nhdplus_path = getwd(), vpu = \"01\", ws_order = 6, n = 5)\n#' # delineate stream network\n#' b <- net_delin(group_comid = as.character(a[,\"COMID\"]), nhdplus_path = getwd(), vpu = \"01\")\n#' calculate topology summary\n#' c <- net_calc(netdelin = b, vpu = \"01\", nhdplus_path = getwd())\n#' @export\n\nnet_calc <- function(netdelin, vpu, nhdplus_path){\n directory <- grep(paste(vpu, \"/NHDPlusAttributes\", sep = \"\"),\n list.dirs(nhdplus_path, full.names = T),\n value = T)\n Vaa <- grep(\"PlusFlowlineVAA.dbf\",\n list.files(directory[1], full.names = T),\n value = T)\n slope <- grep(\"elevslope.dbf\",\n list.files(directory, full.names = T),\n value = T)\n flow.files <- grep(\"PlusFlow.dbf\",\n list.files(directory[1], full.names = T),\n value = T)\n\n flow <- foreign::read.dbf(flow.files)\n vaa <- foreign::read.dbf(Vaa)\n slope <- foreign::read.dbf(slope)\n names(slope) <- toupper(names(slope))\n names(vaa) <- toupper(names(vaa))\n\n full.net <- unique(netdelin$Network)\n\n reach.data <- Reduce(function(x, y)\n merge(x, y, by.x = \"net.comid\", by.y = \"COMID\", all.x = T),\n list(full.net, vaa, slope))\n\n #calculate network order\n WS.ord <- reach.data[as.character(reach.data[,\"group.comid\"]) ==\n as.character(reach.data[,\"net.comid\"]),\n c(\"net.id\",\"M\", \"STREAMORDE\")]\n\n names(WS.ord) <- c(\"net.id\", \"M\", \"WS.ord\")\n\n #catchemnts catchment area\n #group by, substract, multiply\n #value at end of flowline\n cat.area <- aggregate(reach.data[, c(\"AREASQKM\", \"LENGTHKM\")],\n by = list(net.id = reach.data[, \"net.id\"],\n group.comid = reach.data[,\"group.comid\"]),\n sum)\n incr <- reach.data[as.character(reach.data[,\"group.comid\"]) ==\n as.character(reach.data[,\"net.comid\"]),\n c(\"net.id\", \"AREASQKM\",\"LENGTHKM\", \"M\")]\n\n incr <- merge(incr, cat.area, by = \"net.id\")\n area <- (incr[,\"AREASQKM.y\"] - incr[,\"AREASQKM.x\"]) + incr[,\"AREASQKM.x\"]*incr[,\"M\"]\n len <- (incr[,\"LENGTHKM.y\"] - incr[,\"LENGTHKM.x\"]) + incr[,\"LENGTHKM.x\"]*incr[,\"M\"]\n\n #scaled length and catchment vlaues\n cat.area <- data.frame(net.id = incr[,\"net.id\"],\n AreaSQKM = area, LengthKM = len)\n\n drain.den <- cat.area[ ,\"LengthKM\"] / cat.area[ ,\"AreaSQKM\"]\n cat.area <- data.frame(cat.area, drain.den)\n\n #diversion feature count\n #counts minor flow paths of divergences\n if (any(reach.data[,c(\"STREAMORDE\")] !=\n reach.data[,\"STREAMCALC\"] &\n reach.data[,\"DIVERGENCE\"]==2)){\n\n div.rm <- reach.data[reach.data[,c(\"STREAMORDE\")] !=\n reach.data[,\"STREAMCALC\"] &\n reach.data[, \"DIVERGENCE\"] == 2,\n c(\"net.id\", \"net.comid\", \"group.comid\")]\n\n diver.cnt <- aggregate(div.rm[, \"group.comid\"],\n by = list(div.rm[,\"net.id\"]),\n length)\n\n names(diver.cnt) <- c(\"net.id\", \"diver.cnt\")\n\n } else {\n diver.cnt <- data.frame(net.id = 99999, diver.cnt = 999999)\n }\n\n #headwaters & Tribs\n head.h2o <- aggregate(reach.data[\n reach.data[,\"STARTFLAG\"] == 1, \"STREAMORDE\"],\n by = list(reach.data[reach.data[,\"STARTFLAG\"] == 1, \"net.id\"]),\n length)\n\n names(head.h2o) <- c(\"net.id\", \"head.h2o\")\n\n trib.jun <- as.numeric(as.character(head.h2o[, \"head.h2o\"])) - 1\n head.h2o <- data.frame(head.h2o, trib.jun)\n\n #edge count\n edges <- head.h2o[,\"head.h2o\"] + head.h2o[,\"trib.jun\"]\n reach.cnt <- data.frame(net.id = head.h2o[,\"net.id\"], reach.cnt = edges)\n\n #relief - at outlet; I want to move this to basin metric\n #maxelev <- aggregate(reach.data[,\"MAXELEVSMO\"],\n # by = list(reach.data[,\"group.comid\"]),\n # max)\n #minelev <- aggregate(reach.data[, \"MINELEVSMO\"],\n # by = list(reach.data[, \"group.comid\"]),\n # min)\n #relief <- maxelev[,\"x\"]-minelev[,\"x\"]\n #relief <- data.frame(COMID = maxelev[,\"Group.1\"],\n # maxelev = maxelev[,\"x\"],\n # minelev = minelev[,\"x\"],\n # releif = relief)\n\n #aggregate table for summaries of group comid\n data.out <- unique(full.net[, c(\"net.id\",\"group.comid\", \"vpu\")])\n\n names(data.out)[2] <- \"COMID\"\n\n data.out <- Reduce(function(x, y)\n merge(x, y, by = \"net.id\", all.x = T),\n list(data.out, WS.ord,head.h2o, reach.cnt, diver.cnt, cat.area))#, relief))\n\n names(data.out)[2] <- \"group.comid\"\n\n return(data.out)\n}\n", "meta": {"hexsha": "5f1b2ce856c09a032043363173cb32f4d8c95eac", "size": 5725, "ext": "r", "lang": "R", "max_stars_repo_path": "StreamNetworkTools/R/net_calc.r", "max_stars_repo_name": "dkopp3/StreamNetworkTools_git", "max_stars_repo_head_hexsha": "b249a38544eda1a756bfce54e0d78a4668925c2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-10-26T14:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-21T22:26:54.000Z", "max_issues_repo_path": "StreamNetworkTools/R/net_calc.r", "max_issues_repo_name": "dkopp3/StreamNetworkTools_git", "max_issues_repo_head_hexsha": "b249a38544eda1a756bfce54e0d78a4668925c2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-01-22T18:58:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T18:58:49.000Z", "max_forks_repo_path": "StreamNetworkTools/R/net_calc.r", "max_forks_repo_name": "dkopp3/StreamNetworkTools_git", "max_forks_repo_head_hexsha": "b249a38544eda1a756bfce54e0d78a4668925c2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-22T18:42:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-22T18:42:49.000Z", "avg_line_length": 38.4228187919, "max_line_length": 94, "alphanum_fraction": 0.5739737991, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42136933876782473}}
{"text": "#' @details\r\n#' This package contains functions to fit joint probability distributions to bivariate wave data (wave height and \r\n#' wave period), estimate environmental contours based on the fitted distribution or directly on a given sample \r\n#' data, output the coordinates of the vertices of the contours, and generate a plot of the contours.\r\n#' \r\n#' The choices for the joint probability distributions include the Heffernan-Tawn model \\code{\\link{fit_ht}} and\r\n#' the Weibull-log-normal distribution \\code{\\link{fit_wln}}. The choices for the environmental contours are the\r\n#' direct sampling contours \\code{\\link{estimate_dsc}}, IFORM\r\n#' contours \\code{\\link{estimate_iform}}, generalised joint exceedance contours \\code{\\link{estimate_gje}}, and the\r\n#' isodensity contours \\code{\\link{estimate_iso}}.\r\n#' \r\n#' This package has been developed as part of the\r\n#' \\href{https://www.dnvgl.com/technology-innovation/sri/maritime-transport/ecsades-project.html}{ECSADES} project\r\n#' and is free to use. The\r\n#' statistical models and contour estimation methods included in this package are discussed in detail in the project\r\n#' paper Ross et al. (2018).\r\n#' \r\n#' @examples\r\n#' # Load sample data from NOAA's WaveWatch III project\r\n#' data(ww3_pk)\r\n#' \r\n#' # Fit the Heffernan-Tawn model to the data\r\n#' ht = fit_ht(\r\n#' data = ww3_pk,\r\n#' npy = nrow(ww3_pk)/10,\r\n#' margin_thresh_count = 100,\r\n#' dep_thresh_count = 500)\r\n#' \r\n#' # Estimate the DSC contours using the Hs return levels as \r\n#' dsc = estimate_dsc(object = ht, output_rp = c(1,10,100))\r\n#' \r\n#' # Plot output and save to a file\r\n#' plot_ec(\r\n#' ec = dsc, raw_data = ww3_pk, hs_x = FALSE, save_to_file = \"dsc_ht.png\",\r\n#' width = 8, height = 6, units = \"in\")\r\n#' \r\n#' @references\r\n#' Ross, E., Astrup, O.C., Bitner-Gregersen, E.M., Bunn, N., Feld, G., Gouldby, B., Huseby, A.B., Liu, Y.,\r\n#' Randell, D., Vanem, E., & Jonathan, P. (2019). On environmental contours for marine and coastal design.\r\n\r\n\"_PACKAGE\"\r\n.limit_inf = 1e7\r\n.limit_zero = 1e-7\r\n.seed_sampling = 121110\r\n.knn = 200\r\n.hs_res = .5\r\n.target_rp_lb = .1 # Ratio to the target RP as a threhsold for importance sampling Huseby et al (2014)\r\n.target_rp_ub = 1000 # Ratio to the target RP as an equivalent number of years to simulate from\r\n", "meta": {"hexsha": "94107a633dc254a0aa67c4443d5c0326f012e56a", "size": 2283, "ext": "r", "lang": "R", "max_stars_repo_path": "ecsades/R/ecsades.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/ecsades.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/ecsades.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": 46.5918367347, "max_line_length": 117, "alphanum_fraction": 0.7012702584, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4211485277461269}}
{"text": "penGAM <- function(x, y, lambda.pen, lambda.curv, knots,\n model = LinReg(), save.x = TRUE,\n control = grpl.control()){\n ## Purpose:\n ## ----------------------------------------------------------------------\n ## Arguments:\n ## ----------------------------------------------------------------------\n ## Author: Lukas Meier, Date: 13 Mar 2008, 11:30\n\n if(any(lambda.pen > 1))\n stop(\"lambda.pen is on a *relative* scale with respect to lambda.max\")\n\n n <- NROW(x)\n p <- NCOL(x)\n\n ## Construct the design matrix and the penalty matrices\n d <- getDesign(x, knots = knots)\n\n ## Extract the necessary information\n m.orig <- d$m ## list of p design matrices\n pen <- d$pen ## list of p penalty matrices\n index <- d$index ## index vector (without intercept)\n\n ## Coefficients for all combinations of lambda.pen * lambda.curv * coef\n coefficients <- array(0,\n dim = c(length(lambda.pen),\n length(lambda.curv),\n length(index) + 1))\n\n lambda.max.all <- numeric(length(lambda.curv))\n\n for(u in 1:length(lambda.curv)){\n if(control@trace >= 1)\n cat(\"\\n*** lambda.curv\", lambda.curv[u], \"***\\n\")\n\n lcurv <- lambda.curv[u]\n\n ## m contains the whole design matrix but *without* intercept column\n m <- matrix(0, nrow = n, ncol = length(index))\n colnames(m) <- unlist(lapply(m.orig, colnames))\n\n ## We have to calculate the penalty matrix for each value of lambda.curv\n ## Transform each predictor group such that we can work with an\n ## \"ordinary\" Group Lasso model\n\n chol.decomp <- list(); length(chol.decomp) <- p\n\n for(j in 1:p){\n ## This will be the penalty matrix for each block\n penmat <- lcurv * pen[[j]] + crossprod(m.orig[[j]])\n\n ## Now calculate the cholesky decomposition\n chol.decomp[[j]] <- chol(penmat)\n m[,index == j] <-\n t(forwardsolve(t(chol.decomp[[j]]), t(m.orig[[j]])))\n }\n\n ## Now we are ready to get the estimates using the grplasso function\n ## for *all* values of lambda.pen\n\n ## We do *not* have to rescale the penalty\n mypenscale <- function(x) rep(1, length(x))\n\n ## Calculate lambda.max\n lambda.max <- lambdamax(x = cbind(1, m), y = y, index = c(NA, index),\n penscale = mypenscale, model = model,\n standardize = FALSE)\n\n lambda.max.all[u] <- lambda.max\n\n ## Actual lambda values\n lambda.use <- lambda.max * lambda.pen\n\n coef.init <- rep(0, NCOL(m) + 1)\n coef.init[1] <- model@link(mean(y))\n\n ## Call now group lasso algorithm on the *transformed* data\n fit.grp <- grplasso(x = cbind(1, m), y = y, index = c(NA, index),\n lambda = lambda.use, model = model,\n coef.init = coef.init,\n standardize = FALSE, penscale = mypenscale,\n control = control)\n\n ## Transform the estimates back to the original scale using backsolve\n coef.pre <- coef(fit.grp)[-1,,drop = FALSE] ## without intercept\n coef.out <- matrix(0, nrow = NROW(coef.pre), ncol = NCOL(coef.pre))\n for(j in 1:p){\n sel <- index == j\n coef.out[sel,] <- backsolve(chol.decomp[[j]], coef.pre[sel,])\n }\n ## Now transform the values back to the original spline-basis and\n ## add intercept.\n ## Put everything into the \"coefficients\" array.\n coefficients[,u,] <- t(rbind(coef(fit.grp)[1,], coef.out))\n } ## end for(u in 1:length(lambda.curv))\n\n dimnames(coefficients) <- list(lambda.pen,\n lambda.curv,\n c(\"(Intercept)\", colnames(m)))\n\n if(is.null(colnames(x))){\n colnam <- 1:NCOL(x)\n }else{\n colnam <- colnames(x)\n }\n\n rownam <- rownames(x)\n\n if(!save.x)\n x <- NULL\n\n out <- list(coefficients = coefficients,\n x = x,\n colnames = colnam,\n rownames = rownam,\n splineobj = list(basis = d$basis, index = d$index),\n lambda.max = lambda.max.all,\n lambda.pen = lambda.pen,\n lambda.curv = lambda.curv,\n model = model)\n structure(out, class = \"penGAM\")\n}\n\n\n\n\n\npredict.penGAM <- function(object, newdata, type = c(\"link\", \"response\"), ...)\n{\n ## Purpose: Predict fitted object on a new data set\n ## ----------------------------------------------------------------------\n ## Arguments: fit object\n ## ----------------------------------------------------------------------\n ## Author: Lukas Meier, Date: 13 Mar 2008, 12:09\n\n type <- match.arg(type)\n\n nr.lambda.pen <- length(object$lambda.pen)\n nr.lambda.curv <- length(object$lambda.curv)\n\n if(missing(newdata) || is.null(newdata)){ ## if we don't have new data object\n if(is.null(object$x))\n stop(\"No x matrix found in 'object'. Set save.x = TRUE or provide newdata!\")\n\n ## Create the whole design matrix (*all* components)\n ## Re-create the design matrix using the given spline basis\n m.list <- list()\n for(j in 1:NCOL(object$x))\n m.list[[j]] <- eval.basis(x[,j], basisobj = object$splineobj$basis[[j]])\n\n n <- NROW(m.list[[1]])\n pred <- array(0, dim = c(nr.lambda.pen, nr.lambda.curv, n))\n\n ## Create predictions\n m <- matrix(unlist(m.list), nrow = n)\n for(l in 1:nr.lambda.pen){\n for(u in 1:nr.lambda.curv){\n pred[l,u,] <- cbind(1, m) %*% coef(object)[l,u,]\n }\n }\n dimnames(pred) <- list(object$lambda.pen, object$lambda.curv,\n object$rownames)\n }else{ ## if we have *new* data object (!!!add some test-functions later!!!)\n x <- newdata\n n <- NROW(x); p <- NCOL(x)\n\n pred <- array(0, dim = c(nr.lambda.pen, nr.lambda.curv, n))\n dimnames(pred) <- list(object$lambda.pen, object$lambda.curv, rownames(x))\n lowdiff <- highdiff <- outrange <-\n matrix(FALSE, nrow = NROW(newdata), ncol = p)\n\n ## Perform *linear* extrapolation\n\n ## Create the 'cut' design matrix: Sets values of x which exceed the\n ## training range to their corresponding boundaries (given by the range\n ## of the training data)\n x.cut <- matrix(0, nrow = n, ncol = p)\n m.list <- m.deriv.list <- list()\n length(m.list) <- length(m.deriv.list) <- p\n\n lower.slopes <- upper.slopes <- list()\n\n for(j in 1:p){\n ## Extract current predictor\n x.current <- x[,j]\n x.cut[,j] <- x.current\n\n ## Current basis matrix (B-spline basis)\n bas <- object$splineobj$basis[[j]]\n\n ## Get the smallest and largest knots (=boundaries)\n lower.end <- bas$rangeval[1]\n upper.end <- bas$rangeval[2]\n\n ## Which observations are exceeding the boundary-values?\n ind.lower <- x.current < lower.end\n ind.upper <- x.current > upper.end\n\n lowdiff[ind.lower,j] <- (x.current - lower.end)[ind.lower]\n highdiff[ind.upper,j] <- (x.current - upper.end)[ind.upper]\n\n x.cut[ind.lower,j] <- lower.end\n x.cut[ind.upper,j] <- upper.end\n\n ## Get the slopes at the boundaries\n m.list[[j]] <- eval.basis(x.cut[,j], bas)\n deriv.info <- eval.basis(c(lower.end, upper.end), bas, Lfdobj = 1)\n\n lower.slopes[[j]] <- deriv.info[1,]\n upper.slopes[[j]] <- deriv.info[2,]\n }\n m <- matrix(unlist(m.list), nrow = n) ## Gets filled *columnwise*\n index <- object$splineobj$index ## without intercept\n\n for(l in 1:nr.lambda.pen){\n ##cat(l, \"\\n\")\n for(u in 1:nr.lambda.curv){\n beta <- coef(object)[l,u,]\n\n pred.pre <- cbind(1, m) %*% coef(object)[l,u,]\n\n ## Put the design matrix of the first derivates (lower.slopes,\n ## upper.slopes) into one long vector each (same length as index) and\n ## multiply with beta vector and take the sum. I.e. perform the matrix\n ## operation in a bit a special form.\n ## The result are the derivatives at the left- and the right-hand side\n ## boundaries of the training range (of the fitted object with the\n ## current coefficients)\n slopes.left <- rowsum(unlist(lower.slopes) * beta[-1],\n group = index)\n slopes.right <- rowsum(unlist(upper.slopes) * beta[-1],\n group = index)\n\n ## Now we have to multiply the derivatives with the difference\n ## in the x-values (contained in lowdiff and highdiff)\n ## lowdiff and highdiff are matrices with dimensions n x p, i.e. the\n ## dimension of the newdata object.\n ## Each column of lowdiff and highdiff is multiplied with the slope\n ## value. The result will be what we have to add beyond the boundaries.\n ## add.left and add.right will also have dimension n x p.\n\n ## 'as.array' is here to force a warning message if recycling would\n ## take place (see help file of sweep)\n add.left <- sweep(lowdiff, MARGIN = 2, STATS = as.array(slopes.left),\n FUN = \"*\")\n add.right <- sweep(highdiff, MARGIN = 2, STATS = as.array(slopes.right),\n FUN = \"*\")\n\n ## Calculate the final prediction:\n ## Take the prediction of the 'cut-down' matrix and add the linear\n ## extrapolation part (add.left + add.right). We have to take the sum\n ## in each row of the linear extrapolation part (add.left + add.right)\n pred[l,u,] <- pred.pre + rowSums(add.left + add.right)\n }\n }\n }\n\n ## Transform to original scale if necessary\n pred <- switch(type,\n link = pred,\n response = object$model@invlink(pred))\n\n dims <- dim(pred)\n\n ## If we have only one combination of lpen/lcurv we allow drop = TRUE.\n ## In all other cases\n if(dims[1] == 1 & dims[2] == 1)\n pred <- pred[1,1,,drop = TRUE]\n\n attr(pred, \"lambda.pen\") <- object$lambda.pen\n attr(pred, \"lambda.curv\") <- object$lambda.curv\n\n pred\n ##out <- list(pred = pred,\n ## lambda.pen = object$lambda.pen,\n ## lambda.curv = object$lambda.curv)\n ##out\n}\n\nplot.penGAM <- function(x, which = NULL, ask = TRUE && dev.interactive(),\n nrgrid = 100, ...)\n{\n ## Purpose:\n ## ----------------------------------------------------------------------\n ## Arguments:\n ## ----------------------------------------------------------------------\n ## Author: Lukas Meier, Date: 6 May 2008, 12:08\n\n n <- NROW(x$splineobj$m[[1]])\n index <- x$splineobj$index\n\n p <- index[length(index)]\n\n dims <- dim(coef(x))\n if(dims[1] > 1 | dims[2] > 1)\n stop(\"Use plot(fit[i,j]) to select the desired penalty parameters\")\n\n coefs <- coef(x)[1, 1,][-1] ## without intercept!\n\n if(is.null(which))\n which <- 1:p\n if(ask){\n op <- par(ask = TRUE)\n on.exit(par(op)) ## use original settings when we leave the function\n }\n\n for(j in 1:length(which)){\n bas <- x$splineobj$basis[[j]]\n rng <- bas$range\n x.current <- seq(rng[1], rng[2], length = nrgrid)\n m.current <- eval.basis(x.current, basisobj = bas)\n ind <- index == which[j]\n fn <- scale(m.current %*% coefs[ind], scale = FALSE)\n plot(sort(x.current), fn[order(x.current)], type = \"l\",\n xlab = x$colnames[which[j]], ylab = bquote(f[.(which[j])]), ...)\n }\n}\n\n\"[.penGAM\" <- function(x, i, j){\n ## Purpose:\n ## ----------------------------------------------------------------------\n ## Arguments:\n ## ----------------------------------------------------------------------\n ## Author: Lukas Meier, Date: 6 May 2008, 12:08\n\n ## First get dimensions of the original object x\n dim <- dim(coef(x))\n nrlambda.pen <- dim[1]\n nrlambda.curv <- dim[2]\n\n if(missing(i))\n i <- 1:nrlambda.pen\n if(missing(j))\n j <- 1:nrlambda.curv\n\n ## Subset the object\n fit.red <- x\n\n fit.red$coefficients <- coef(x)[i,j,,drop = FALSE]\n\n ## We do not allow the situation where everything is removed\n if(length(fit.red$coefficients) == 0)\n stop(\"Not allowed to remove everything!\")\n\n fit.red$lambda.max <- x$lambda.max[j]\n fit.red$lambda.pen <- x$lambda.pen[i]\n fit.red$lambda.curv <- x$lambda.curv[j]\n\n fit.red\n}\n\ngetDesign <- function(x, knots = 10, norder = 4)\n{\n ## Purpose: Get design matrix and penalty matrix in the basis of\n ## B-splines\n ## ----------------------------------------------------------------------\n ## Arguments: x: Design matrix, *without* intercept column\n ## nrknots: Number of quantiles at which to put knots\n ## (these will be evenly spaced on the quantile scale\n ## between 0 and 1)\n ## norder: Set norder = 4 for piecewise cubic polynomials\n ## ----------------------------------------------------------------------\n ## Author: Lukas Meier, Date: 4 Mar 2008, 14:49\n\n p <- NCOL(x)\n\n if(is.null(colnames(x)))\n colnames(x) <- paste(\"x\", 1:p, sep = \"\")\n\n ## If knots is only a number, we have to create the knots first for each\n ## predictor\n if(is.numeric(knots)){\n knots.use <- list()\n for(j in 1:p){\n x.current <- x[,j]\n ## Make sure that we do not place multiple knots at the same\n ## x value (if we have replicates etc.)\n ux.current <- unique(x.current)\n\n if(knots > length(ux.current)){\n nrknots.use <- length(ux.current)\n cat(\"Too many knots in predictor\", j, \"...\\n\")\n cat(\"Using as many knots as there are unique predictor values.\\n\")\n }else{\n nrknots.use <- knots\n }\n knots.use[[j]] <- quantile(ux.current, seq(0, 1, length = nrknots.use))\n }\n }else if(is.list(knots)){\n if(length(list) != p)\n stop(\"knots has wrong length\")\n\n knots.use <- knots\n }\n\n ## Create the design and the penalty matrix\n m <- list()\n pen <- list()\n basis <- list()\n length(m) <- length(pen) <- length(basis) <- p\n\n df <- numeric(p)\n\n for(j in 1:p){\n x.current <- x[,j]\n\n ## Create knot sequence\n breaks <- knots.use[[j]]\n stopifnot(all.equal(range(breaks), range(x.current)))\n\n ## Get basis-object for the j-th spline\n basis[[j]] <- create.bspline.basis(rangeval = range(breaks),\n breaks = breaks, norder = norder)\n ## removed range(x.current)\n\n ## Get the design matrix for the j-th spline (with the basis of above)\n m[[j]] <- eval.basis(x.current, basis[[j]])\n\n ## Get the degrees of freedom for the current predictor\n df[j] <- NCOL(m[[j]])\n\n colnames(m[[j]]) <- paste(colnames(x)[j], \".\", 1:df[j], sep = \"\")\n\n ## Get penalty matrix ## !!! DOUBLE-CHECK THIS !!!\n pen[[j]] <- getbasispenalty(basis[[j]], Lfdobj = 2)\n }\n list(m = m, pen = pen, basis = basis, index = rep(1:p, times = df))\n}\n\n.onAttach <- function(libname, pkgname){\n cat(\"----------------------------------------------------------------------\",\n \"Please note that this is an early test release of package 'penGAM'.\",\n \"It should only be used for experimental reasons. Use at your own risk!\",\n \"----------------------------------------------------------------------\",\n sep = \"\\n\")\n}\n", "meta": {"hexsha": "fb0953cd2e745f0c2f9c70cf43043df34a26d068", "size": 15191, "ext": "r", "lang": "R", "max_stars_repo_path": "penGAMfuns.r", "max_stars_repo_name": "statcodes/NIS", "max_stars_repo_head_hexsha": "73521a69eb0b390b9bc4d7ab8effea0d8709c5d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-09-09T13:41:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T12:50:36.000Z", "max_issues_repo_path": "penGAMfuns.r", "max_issues_repo_name": "statcodes/NIS", "max_issues_repo_head_hexsha": "73521a69eb0b390b9bc4d7ab8effea0d8709c5d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "penGAMfuns.r", "max_forks_repo_name": "statcodes/NIS", "max_forks_repo_head_hexsha": "73521a69eb0b390b9bc4d7ab8effea0d8709c5d1", "max_forks_repo_licenses": ["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.76201373, "max_line_length": 82, "alphanum_fraction": 0.5390033573, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4208970766451963}}
{"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# Optimization 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# Solve LP problem, handling negative x\n###############################################################################\n# Tradional LP problem : http://lpsolve.sourceforge.net/5.5/LPBasics.htm\n# maximize C x\n# subject to A x <= B\n# x >= 0 - NOTE LP assumes all x >= 0\n###############################################################################\n# http://r.789695.n4.nabble.com/help-using-R-s-linprog-for-LP-td906987.html\n# NOTE: Linear Programming (LP) assumes x >= 0\n#\n# The constraints x >= 0 are used in most linear programming realizations.\n# Some bounds from below are needed. The trick to circumvent the restriction\n# is as follows:\n#\n# Assume you know x >= d where some or all of the d_i can be negative.\n# Replace x with y = x - d >= 0 and minimize c'y with Ay <= b - A d !\n# Your solution is then x = y + d , that is\n#\n# solveLP(cvec, bvec - Amat %*% dvec, Amat)$solution + dvec\n#\n# For portfolio weights, it is safe to assume that x.i >= -100\n#' @export \n###############################################################################\nsolve.LP.bounds <- function\n(\n\tdirection, \t\t# lp parameters\n\tobjective.in, \t# lp parameters\n\tconst.mat, \t\t# lp parameters\n\tconst.dir,\t\t# lp parameters\n\tconst.rhs, \t\t# lp parameters\n\tbinary.vec = 0,\t# lp parameters\t\n\tlb = 0,\t\t\t# vector with lower bounds\n\tub = +Inf,\t\t# vector with upper bounds\n\tdefault.lb = -100\t# the smallest possible value for any variable\n)\n{\n\t# number variables\n\tn = len(objective.in)\n\t\n\tif( len(lb) == 1 ) lb = rep(lb, n)\n\tif( len(ub) == 1 ) ub = rep(ub, n)\n\t\n\tlb = ifna(lb, default.lb)\n\tub = ifna(ub, +Inf)\n\t\n\tlb[ lb < default.lb ] = default.lb\n\tdvec = lb\n\t\n\t# add ub constraints\n\tindex = which( ub < +Inf )\t\n\tif( len(index) > 0 ) {\n\t\tconst.rhs = c(const.rhs, ub[index])\n\t\tconst.dir = c(const.dir, rep('<=', len(index)))\t\t\n\t\tconst.mat = rbind(const.mat, diag(n)[index, ])\t\t\n\t}\n\t\n\t# main logic\n\tif ( binary.vec[1] == 0 ) {\t\n\t\tsol = lp( direction, objective.in, const.mat, const.dir, \n\t\t\t\tconst.rhs - const.mat %*% dvec )\n\t} else {\n\t\tdvec[binary.vec] = 0\n\t\tsol = lp( direction, objective.in, const.mat, const.dir, \n\t\t\t\tconst.rhs - const.mat %*% dvec, binary.vec = binary.vec )\n\t\n\t}\n\t\n\t# update solution\n\tsol$solution = sol$solution + dvec\t\t\n\tsol$value = objective.in %*% sol$solution \t\n\t\n\treturn( sol )\t\n}\n\n\n###############################################################################\n# Solve QP problem, handling binary variables using Binary Branch and Bound\n#' @export \n###############################################################################\nsolve.QP.bounds <- function\n(\n\tDmat,\t\t\t\t# solve.QP parameters\n\tdvec, \t\t\t\t# solve.QP parameters\n\tAmat, \t\t\t\t# solve.QP parameters\n\tbvec, \t\t\t\t# solve.QP parameters\n\tmeq=0, \t\t\t\t# solve.QP parameters\n\tfactorized=FALSE, \t# solve.QP parameters\n\tbinary.vec = 0,\t\t# vector with indices of binary variables\n\tlb = -Inf,\t\t\t# vector with lower bounds\n\tub = +Inf\t\t\t# vector with upper bounds\n)\n{\n\tAmat1 = Amat\n\tbvec1 = bvec\n\n\t# number variables\n\tn = len(dvec)\n\t\n\tif( len(lb) == 1 ) lb = rep(lb, n)\n\tif( len(ub) == 1 ) ub = rep(ub, n)\n\t\n\tlb = ifna(lb, -Inf)\n\tub = ifna(ub, +Inf)\n\t\n\t\n\t# add ub constraints, A^T b >= b_0\n\tindex = which( ub < +Inf )\t\n\tif( len(index) > 0 ) {\t\n\t\tbvec = c(bvec, -ub[index])\n\t\tAmat = cbind(Amat, -diag(n)[, index])\t\t\n\t}\n\t\n\t# add lb constraints, A^T b >= b_0\n\tindex = which( lb > -Inf )\t\n\tif( len(index) > 0 ) {\t\n\t\tbvec = c(bvec, lb[index])\n\t\tAmat = cbind(Amat, diag(n)[, index])\t\t\n\t}\n\t\t\n\t# main logic\n\tif ( binary.vec[1] == 0 ) {\t\n\t\t# logic to check for constant variables\t\n\t\tqp.data.final = solve.QP.remove.equality.constraints(Dmat, dvec, Amat, bvec, meq)\t\n\t\t\tDmat = qp.data.final$Dmat\n\t\t\tdvec = qp.data.final$dvec\n\t\t\tAmat = qp.data.final$Amat\n\t\t\tbvec = qp.data.final$bvec\n\t\t\tmeq = qp.data.final$meq\n\n\t\t# solve.QP: min(-d^T w.i + 1/2 w.i^T D w.i) subject to A^T w.i >= b_0\t\t\t\n\t\tsol = try(solve.QP(Dmat, dvec, Amat, bvec, meq, factorized),TRUE)\n\t\t\n\t\t# lot's of errors take place because covariance matrix is not positive defined\n\t\tif(inherits(sol, 'try-error')) {\n#cat('solve.QP error\\n')\t\n#print(sol)\n\t\t\tok = F\n\t\t\tsol = list()\t\t\t\t\n\t\t} else {\n\t\t\t# check that solve.QP solution satisfies constraints\t\t\n\t\t\ttol = 1e-3\n\t\t\tok = T\n\t\t\t\t\t\n\t\t\tcheck = sol$solution %*% Amat - bvec\n\t\t\tif(meq > 0) ok = ok & all(abs(check[1:meq]) <= tol)\n\t\t\tok = ok & all(check[-c(1:meq)] > -tol)\n#if(!ok) cat('solve.QP violates constraints\\n')\t\n#if(!ok) print(sol$solution)\t\t\t\t\t\n\t\t} \n\t\t\n\t\t# try to solve problem one more time using ipop function from kernlab package\n\t\tif(!ok) {\n\t\t\trequire(kernlab)\n#cat('kernlab\\n')\t\n\t\t\tindex.constant.variables = which(!is.na(qp.data.final$solution))\n\t\t\tif( len(index.constant.variables) > 0 ) {\n\t\t\t\t# Amat1 and bvec1 might be incorrect\n\t\t\t\tAmat1 = Amat[,1:ncol(Amat1)]\n\t\t\t\tbvec1 = bvec[1:ncol(Amat1)]\n\t\t\t\tlb = lb[-index.constant.variables]\n\t\t\t\tub = ub[-index.constant.variables]\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t# ipop: min(c'*x + 1/2 * x' * H * x) subject to b <= A * x <= b + r and l <= x <= u\n\t\t\tsv = ipop(c = matrix(-dvec), H = Dmat, A = t(Amat1),\n\t\t\t\t\tb = bvec1, l = ifna(lb,-100), u = ifna(ub,100),\n\t\t\t\t\tr = c(rep(0,meq), rep(100, len(bvec1) - meq))\n\t\t\t\t)\n\t\t\tsol$solution = primal(sv)\n\t\t}\n\n\t\t# logic to check for constant variables\t\n\t\tx = qp.data.final$solution\n\t\tx[qp.data.final$var.index] = sol$solution\n\t\tsol$solution = x\n\t\t\n\t} else {\n\t\t# use Binary Branch and Bound\n\t\tqp_data = qp_new(binary.vec, Dmat = Dmat, dvec = dvec, \n\t\t\t\t\t\tAmat=Amat, bvec=bvec, meq=meq, factorized=factorized)\n\t\n\t\tsol = binary_branch_bound(binary.vec, qp_data, qp_solve, \n\t\t\t\tcontrol = bbb_control(silent=T, branchvar='max', searchdir='best' ))\n\t\t\t\t\n\t\tqp_delete(qp_data)\t\t\n\t\t\n\t\tsol$value = sol$fmin\n\t\tsol$solution = sol$xmin\n\t}\n\t\n\treturn(sol)\n}\n\n\n###############################################################################\n# QP interface for Binary Branch and Bound algorithm\n###############################################################################\n# control list for binary_branch_bound\t\t\t\t\n#' @export \n###############################################################################\nbbb_control <- function\n(\n\titermax = 200, \t\t\t# maximum number of iterations \n\tdepthmax = Inf, \t\t# maximum search depth\n\tbineps = 1e-4, \t\t\t# eps to determine whether a solution is 0/1\n\tprecisioneps = 0, \t\t# stop condition for incremental improvement in best solution\n\tsilent = T,\t\t\t\t# quite or verbose\n\tbranchvar = c('first', 'max','min'),\n\t\t\t\t\t\t\t# first = first free variable\n\t\t\t\t\t\t\t# max = variable with max frac part\n\t\t\t\t\t\t\t# min = variable with min frac part\n\tproborder = c('0', '1', 'mindiff'),\n\t\t\t\t\t\t\t# 0 = problems are put onto the stack '0' first, '1' next\n\t\t\t\t\t\t\t# 1 = problems are put onto the stack '1' first, '0' next\n\t\t\t\t\t\t\t# mindiff = problems are put onto the stack closest to '0' or '1' first\t\n\tsearchdir = c('depth', 'breadth', 'best', 'normbest')\n\t\t\t\t\t\t\t# depth = depth first\n\t\t\t\t\t\t\t# breadth = breadth first\n\t\t\t\t\t\t\t# best = best first\n\t\t\t\t\t\t\t# normbest = best first with normalized cost\t\n)\n{\n\t# parse default arguments\t\t\t\t\n\tbranchvar = switch(branchvar[1],\n\t\t\t\t\t\t'first' = 0,\n\t\t\t\t\t\t'max' = 1,\n\t\t\t\t\t\t'min' = 2,\n\t\t\t\t\t\t0)\n\tbranchvar = iif( is.null(branchvar),0, branchvar)\n\t\t\t\t\t\n\tproborder = switch(proborder[1],\n\t\t\t\t\t\t'0' = 0,\n\t\t\t\t\t\t'1' = 1,\n\t\t\t\t\t\t'mindiff' = 2,\n\t\t\t\t\t\t0)\n\tproborder = iif( is.null(proborder),0, proborder)\n\t\t\t\t\n\tsearchdir = switch(searchdir[1],\n\t\t\t\t\t\t'depth' = 0,\n\t\t\t\t\t\t'breadth' = 1,\n\t\t\t\t\t\t'best' = 2,\n\t\t\t\t\t\t'normbest' = 2,\n\t\t\t\t\t\t0)\n\tsearchdir = iif( is.null(searchdir),0, searchdir)\t\n\t\n\tcontrol = list(itermax = itermax, depthmax = depthmax, bineps = bineps, precisioneps = precisioneps, silent = silent,\n\t\t\t\tbranchvar = branchvar,\n\t\t\t\tproborder = proborder,\n\t\t\t\tsearchdir = searchdir)\n\treturn(control)\n}\n\n###############################################################################\n# Initialize QP\n###############################################################################\nqp_new <- function\n(\n\tindex_binvar, \t# index of binary variables\n\tDmat, \t\t\t# paramters from solve.QP from quaprog library\n\tdvec, \n\tAmat, \n\tbvec, \n\tmeq = 0, \n\tfactorized = FALSE\n)\n{\t\n\t# add 0,1 bounds for the binary variables\n\t\tnbinvar = length(index_binvar)\n\t\tnx = nrow(Dmat)\t\n\t\tnbvec = length(bvec)\n\t\t\n\t# Note 0, -1 bounds 0 to 1\t\t\t\n\tAmat = cbind( Amat, diag(nx)[,index_binvar], -diag(nx)[,index_binvar] )\t\t\t\n\tbvec = c(bvec, rep(0,nx)[index_binvar], rep(1,nx)[index_binvar] )\n\t\tlb_bin_index = (1:nbinvar) + nbvec\n\t\tub_bin_index = (1:nbinvar) + nbvec + nbinvar\n\t\t\n\t# create output\n\tqp_data = new.env()\n\t\tqp_data$Dmat = Dmat\n\t\tqp_data$dvec = dvec\n\t\tqp_data$Amat = Amat\n\t\tqp_data$bvec = bvec\n\t\tqp_data$meq = meq\n\t\tqp_data$factorized = factorized\n\t\tqp_data$x0 = rep(0,nx)\n\t\t\n\t\tqp_data$lb_bin_index = lb_bin_index\n\t\tqp_data$ub_bin_index = ub_bin_index\n\t\tqp_data$lb = bvec[lb_bin_index]\t\t\n\t\tqp_data$ub = bvec[ub_bin_index]\t\t\n\t\t\n\treturn(qp_data)\n}\n\n###############################################################################\n# Delete QP\n###############################################################################\nqp_delete <- function(qp_data)\n{\n\trm(list = ls(qp_data,all=TRUE), envir = qp_data)\n}\n\n###############################################################################\n# Solve QP problem\n###############################################################################\nqp_solve <- function\n(\n\tqp_data, \n\tlb, \n\tub\n)\n{\n\tbvec = qp_data$bvec\n\tbvec[qp_data$lb_bin_index] = lb\n\t# Note 0, -1 bounds 0 to 1\t\t\t\n\tbvec[qp_data$ub_bin_index] = -ub\n\t\n\n\t# NEW logic to remove reduandant equality constraints in QP problem\n\tqp.data.final = solve.QP.remove.equality.constraints(qp_data$Dmat, qp_data$dvec, \n\t\t\t\t\t\t\tqp_data$Amat, bvec, qp_data$meq)\t\t\n\t# end of NEW logic\n\t\t\n\t\n\tsol = tryCatch( solve.QP(Dmat=qp.data.final$Dmat, dvec=qp.data.final$dvec, Amat=qp.data.final$Amat, \n\t\t\t\t\t\tbvec=qp.data.final$bvec, meq=qp.data.final$meq, factorized=qp_data$factorized),\n\t\terror=function( err ) FALSE,\n\t warning=function( warn ) FALSE )\n\t\t\t\n\t \n\tif( !is.logical( sol ) ) { \n\t\tx = qp.data.final$solution\n\t\tx[qp.data.final$var.index] = sol$solution\n\n\t\treturn(list( ok = TRUE, x = x, fval = sol$value )) \n\t} else {\n\t\treturn(list( ok = FALSE )) \n\t} \t \n}\n\n\n\n\n\n\n\n\n###############################################################################\n# Test QP interface to Binary Branch and Bound algorithm\n###############################################################################\nmbqp.test <- function()\n{\n\tload.packages('quadprog')\n\n\t\n\t# Test problem\n\t# min 0.5*x'Q x + b' x\n\t# subject to Cx <= d\t\n\tQ = diag(4)\n\tb\t= c( 2, -3, -2, -3)\n\tC\t= matrix(c(-1, -1, -1, -1,\n \t\t\t\t10,\t5, 3,\t4,\n \t\t\t\t-1,\t0, 0,\t0),\n \t\t3,4,byrow = TRUE)\n\td = c(-2, 10, 0)\n\n\tvlb = c(-1e10, 0, 0, 0);\n\tvub = c( 1e10, 1, 1, 1);\n\n\tindex_binvar = c(2, 3, 4);\n\n\t# Solve.QP\n\t# min(-d^T b + 1/2 b^T D b) : A^T b >= b_0\n\t# meq the first meq constraints are treated as equality constraints, all further as inequality constraints (defaults to 0). \n\tDmat = Q\n\tdvec = -b\n\tAmat = -t(C)\n\tbvec = -d\n\n\t# add vlb / vub\n\tn = nrow(Dmat)\n\tAmat = cbind( Amat, diag(n), -diag(n) )\n\tbvec = c( bvec, vlb, -vub )\n\n\tsol = solve.QP(Dmat=Dmat, dvec=dvec, Amat=Amat, bvec=bvec, meq=0) \n\t\txsol = sol$solution\n\t\tfsol = sol$value\n\t\n\tcat('QP.solve fsol =', fsol, 'xsol =', xsol, '\\n')\n\n\t# Start Branch and Bound \n\tsol = solve.QP.bounds(Dmat=Dmat, dvec=dvec, Amat=Amat, bvec=bvec, meq=0, binary.vec = index_binvar) \n\t\txsol = sol$solution\n\t\tfsol = sol$value\n\n\tcat('QP.solve Binary Branch and Bound fsol =', fsol, 'xsol =', xsol, '\\n')\n\n}\n\n###############################################################################\n# Oriingal version is too slow working on a new faster version\n###############################################################################\n# Logic to remove reduandant equality constraints in QP problem, based on qp_solve\nsolve.QP.remove.equality.constraints <- function\n(\n\tDmat,\t\t\t\t# solve.QP parameters\n\tdvec, \t\t\t\t# solve.QP parameters\n\tAmat, \t\t\t\t# solve.QP parameters\n\tbvec, \t\t\t\t# solve.QP parameters\n\tmeq=0 \t\t\t\t# solve.QP parameters\n)\n{\n\tqp.data = list()\t\n\t\tqp.data$Amat = Amat\n\t\tqp.data$bvec = bvec\n\t\tqp.data$Dmat = Dmat\n\t\tqp.data$dvec = dvec\n\t\tqp.data$meq = meq\t\n\t\n\t\t\n\tAmat1 = t(qp.data$Amat)\n\tbvec1 = qp.data$bvec\n\tDmat1 = qp.data$Dmat\n\tdvec1 = qp.data$dvec\n\tmeq1 = qp.data$meq\n\t\t\n\t\n#Amat - var are rows, constr are columns\t\n#Amat1 - constr are rows, var are columns\n# \tAmat = matrix(1:20,nr=4) \n#\tAmat1 = t(Amat)\n#\t(1+0*Amat1[2:4,])/ c(1,2,3)\n\n\t# default\n\tqp.data$solution = rep(NA, ncol(Amat1))\n\tqp.data$var.index = 1:ncol(Amat1)\n\t\n\nwhile(T) {\n\n\n\t# 1. find columns with just one non-zero element\n\tone.non.zero.index = which( rowSums(Amat1!=0) == 1 )\n\n\tif( len(one.non.zero.index) == 0 ) break\n\t\n\t# 2. divide these columns, and corresponding bvec by column's abs value\t\n\ttemp0 = rowSums(Amat1[one.non.zero.index,])\n\ttemp = abs( temp0 )\n\tbvec1[one.non.zero.index] = bvec1[one.non.zero.index] / temp\n\tAmat1[one.non.zero.index,] = Amat1[one.non.zero.index,] / temp\n\t\t\n\t\n\t\n\ttemp0.index = matrix(1:ncol(Amat1), nr=ncol(Amat1), nc=len(one.non.zero.index))[t(Amat1[one.non.zero.index,]!=0)]\n\t\n\n#Amat - var are rows, constr are columns\t\n#Amat1 - constr are rows, var are columns\t\n\t\n\t\n\t# 3. look for pairs among one.non.zero.index colums\n\t# x >= value , -x>= -value => x = value\n\tequality.constraints = rep(NA, ncol(Amat1))\n\tlb = ub = rep(NA, ncol(Amat1))\n\t\n\t\n\t# Make sure if there are multiple matches only keep max for lb and min for ub\n\t\n\tindex = temp0 > 0\n\t#lb[temp0.index[index]] = bvec1[one.non.zero.index[index]]\n\t##temp = tapply(bvec1[one.non.zero.index[index]], temp0.index[index], max)\n\t##lb[ as.double(names(temp)) ] = temp\n\ttemp = order(bvec1[one.non.zero.index[index]], decreasing = FALSE)\n\tlb[temp0.index[index][temp]] = bvec1[one.non.zero.index[index]][temp]\n\t\n\tindex = temp0 < 0\n\t#ub[temp0.index[index]] = -bvec1[one.non.zero.index[index]]\n\t##temp = tapply(-bvec1[one.non.zero.index[index]], temp0.index[index], min)\n\t##ub[ as.double(names(temp)) ] = temp\t\n\ttemp = order(-bvec1[one.non.zero.index[index]], decreasing = TRUE)\n\tub[temp0.index[index][temp]] = -bvec1[one.non.zero.index[index]][temp]\n\t\n#a = rep(0,5)\n#a[c(2,2,2)] = c(2,1,0)\n\n\t\n\t# 4. remove variables\n\tremove.index = which(lb == ub)\n\tif( len(remove.index) > 0 ) {\n\t\tequality.constraints[remove.index] = lb[remove.index]\n\t\t\n\t\t# remove variables\n\t\tDmat1 = Dmat1[-remove.index, -remove.index,drop=F]\n\t\tdvec1 = dvec1[-remove.index]\n\t\tbvec1 = bvec1 - Amat1[,remove.index,drop=F] %*% equality.constraints[remove.index]\n\t\tAmat1 = Amat1[,-remove.index,drop=F]\n\t\t\n\t\tqp.data$solution[ qp.data$var.index[remove.index] ] = lb[remove.index]\n\t\tqp.data$var.index = which(is.na(qp.data$solution))\t\t\t\t\n\n\t\t# check if there are variables left\t\t\n\t\tif( ncol(Amat1) > 0 ) {\n\t\t\t\t\n\t\t\t# remove constraints\n\t\t\tremove.index = which( rowSums(Amat1!=0) == 0 & bvec1 == 0 )\n\t\t\tif(len(remove.index)>0) {\n\t\t\t\tbvec1 = bvec1[-remove.index]\n\t\t\t\tAmat1 = Amat1[-remove.index,,drop=F]\n\t\t\t\t\t\n\t\t\t\t# handle euality constraints\n\t\t\t\tif( meq1 > 0 ) meq1 = meq1 - len(intersect((1:meq1), remove.index))\n\t\t\t}\n\t\t} else break\n\t\t\t\t\n\t\t\t\t\t\t\n\t} else break\n\t\n\t}\t# while(T)\n\n\t# prepare return object\n\tqp.data$Amat = t(Amat1)\n\tqp.data$bvec = bvec1\n\tqp.data$Dmat = Dmat1\n\tqp.data$dvec = dvec1\n\tqp.data$meq = meq1\n\t\n\treturn(qp.data)\n}\n\n\t\n###############################################################################\n# Find and remove equality constraints in QP problem (slow)\n###############################################################################\n# Logic to remove reduandant equality constraints in QP problem, based on qp_solve\nsolve.QP.remove.equality.constraints12 <- function\n(\n\tDmat,\t\t\t\t# solve.QP parameters\n\tdvec, \t\t\t\t# solve.QP parameters\n\tAmat, \t\t\t\t# solve.QP parameters\n\tbvec, \t\t\t\t# solve.QP parameters\n\tmeq=0 \t\t\t\t# solve.QP parameters\n)\n{\n\tqp.data.temp = list()\t\n\t\tqp.data.temp$Amat = Amat\n\t\tqp.data.temp$bvec = bvec\n\t\tqp.data.temp$Dmat = Dmat\n\t\tqp.data.temp$dvec = dvec\n\t\tqp.data.temp$meq = meq\t\n\t\n\t\t\n\tqp.data.temp = remove.equality.constraints.old(qp.data.temp)\n\t# if no equality constraints found go to optimization\n\tif( len(qp.data.temp$var.index) == len(qp.data.temp$solution) ) {\n\t\tqp.data.final = qp.data.temp\n\t} else {\n\t\t# test for equality constraints one more time\n\t\tqp.data.final = remove.equality.constraints.old(qp.data.temp)\t\t\n\t\t\tqp.data.temp$solution[qp.data.temp$var.index] = qp.data.final$solution\t\t\t\n\t\t\t\tqp.data.final$solution = qp.data.temp$solution\t\t\t\n\t\t\tqp.data.final$var.index = qp.data.temp$var.index[qp.data.final$var.index]\n\t}\n\t\t\n\treturn(qp.data.final)\n}\n\n\nremove.equality.constraints.old <- function(qp.data)\n{\n\t#qp.data1 = qp.data.temp\n\tAmat1 = qp.data$Amat\n\tbvec1 = qp.data$bvec\n\tDmat1 = qp.data$Dmat\n\tdvec1 = qp.data$dvec\n\tmeq1 = qp.data$meq\n\t\t\n\t# 1. find columns with just one non-zero element\n\tone.non.zero.index = which( colSums(Amat1!=0) == 1 )\n\t\n\tif( len(one.non.zero.index) == 0 ) {\t\n\t\tequality.constraints = rep(NA, nrow(Amat1))\n\t\tqp.data$solution = equality.constraints\t\t\n\t\tqp.data$var.index = which(is.na(equality.constraints))\n\t\treturn(qp.data)\n\t}\n\t\n\t# 2. divide these columns, and corresponding bvec by column's abs value\t\n\tbvec1[one.non.zero.index] = bvec1[one.non.zero.index] / abs( colSums(Amat1[,one.non.zero.index]) )\n\tAmat1[,one.non.zero.index] = Amat1[,one.non.zero.index] / abs( Amat1[,one.non.zero.index] )\n\tAmat1[is.na(Amat1)] = 0\t\n\n\t\n\t# 3. look for pairs among one.non.zero.index colums\n\t# x >= value , -x>= -value => x = value\n\tequality.constraints = rep(NA, nrow(Amat1))\n\tremove.constraints = rep(NA, ncol(Amat1))\n\t\t\n\t#for( r in 1:nrow(Amat1) ) {\n\tfor( r in which(rowSums(Amat1[,one.non.zero.index]!=0) > 1) ) {\t\n\t\ttemp.index = which( Amat1[,one.non.zero.index][r,] != 0 )\n\t\t\n\t\tfor( r1 in temp.index[-1] ) {\n\t\t\ttemp.index1 = colSums(abs(\n\t\t\trbind(Amat1,bvec1)[,one.non.zero.index[temp.index]] + \n\t\t\trbind(Amat1,bvec1)[,one.non.zero.index[r1]])\n\t\t\t)\n\t\t\t\n\t\t\tif( any(temp.index1 == 0 ) ) {\n\t\t\t\tequality.constraints[r] = \n\t\t\t\t\tbvec1[one.non.zero.index[r1]] / Amat1[r,one.non.zero.index[r1]]\n\t\t\t\t\t\n\t\t\t\tremove.constraints[ one.non.zero.index[r1] ] = 1\t\t\t\t\n\t\t\t\tremove.constraints[ one.non.zero.index[ temp.index[ temp.index1 == 0]]] = 1\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\t# 4. remove variables\n\tremove.index = which(!is.na(equality.constraints))\n\tif(len(remove.index)>0) {\n\t\t# remove variables\n\t\tDmat1 = Dmat1[-remove.index, -remove.index,drop=F]\n\t\tdvec1 = dvec1[-remove.index]\n\t\tbvec1 = bvec1 - equality.constraints[remove.index] %*% Amat1[remove.index,,drop=F]\n\t\tAmat1 = Amat1[-remove.index,,drop=F]\n\t\n\t\t# remove constraints\n\t\t#remove.index1 = which( colSums(abs(Amat1)) == 0 & bvec1 == 0)\t\t\n\t\tremove.index1 = which(remove.constraints==1)\n\t\tif(len(remove.index1)>0) {\n\t\t\tbvec1 = bvec1[-remove.index1]\n\t\t\tAmat1 = Amat1[,-remove.index1,drop=F]\n\t\t\t\t\n\t\t\t# handle euality constraints\n\t\t\tif( meq1 > 0 ) meq1 = meq1 - len(intersect((1:meq1), remove.index1))\n\t\t}\n\t}\n\t\n\t# prepare return object\n\tqp.data$Amat = Amat1\n\tqp.data$bvec = bvec1\n\tqp.data$Dmat = Dmat1\n\tqp.data$dvec = dvec1\n\tqp.data$meq = meq1\n\n\tqp.data$solution = equality.constraints\t\t\n\tqp.data$var.index = which(is.na(equality.constraints))\n\t\n\treturn(qp.data)\n}\n\n\n\t\n###############################################################################\n# Run linear least squares regression with constraints\n#' @export \n###############################################################################\nlm.constraint <- function\n(\n\tx,\n\ty,\n\tconstraints = NULL\n)\n{\n\tif( is.null(constraints) ) {\n\t\tfit = lm.fit(x, y)\n\t\treturn( ols.summary(x, y, fit$coefficients) )\n\t} else {\n \ttemp = cov(cbind(y, x))\n\t\tDmat = temp[-1,-1] \n\t\tdvec = temp[-1,1]\n\t\n\t\tsol = solve.QP.bounds(Dmat = Dmat, dvec = dvec , \n\t\t\t\tAmat=constraints$A, bvec=constraints$b, constraints$meq,\n\t\t\t\tlb = constraints$lb, ub = constraints$ub)\n\t\treturn( ols.summary(x, y, sol$solution) )\n\t}\n}\n\n\n###############################################################################\n# Run linear least squares regression\n#' @export \n###############################################################################\nols <- function\n(\n\tx,\n\ty,\n\tcomputeSummary=F\n)\n{\n\txx = t(x) %*% x\n\t\n\tif(is.null(ncol(xx))) { xinv = inv1(xx) \n\t} else if(ncol(xx) == 1) { xinv = inv1(xx) \n\t} else if(ncol(xx) == 2) { xinv = inv2(xx) \n\t} else if(ncol(xx) == 3) { xinv = inv3(xx) \n\t} else { xinv = inv(xx) }\n\t\n\tcoefficients = xinv %*% t(x) %*% y\n\tif(computeSummary) {\n\t\treturn( ols.summary(x, y, coefficients, xinv) )\n\t} else {\n\t\treturn(list(coefficients = coefficients))\n\t}\n}\n\n\n#' @export \t\nols.summary <- function\n(\n\tx,\n\ty,\n\tcoefficients,\n\txinv = NULL\n)\n{\n\tn = length(y) \n\tp = length(coefficients) \n\trdf = n-p\n\n\t# error\t\t\n \te = y - x %*% coefficients \n ess=sum(e^2)\n\tmss = sum((y - sum(y)/n)^2)\n\tr.squared = 1 - ess/mss\n\t#r.squared = 1 - (var(e)/var(y))\n\t#adj.r.squared = 1 - (1 - r.squared)*(n - 1)/(n - p - 1)\n \n\tif( !is.null(xinv) ) {\n\t\ts2=ess/(rdf)\n\t\tseb=sqrt(diag(s2*xinv))\t\n\t\ttratio=coefficients/seb\t\n\t\t\n\t\treturn(list(coefficients = coefficients, seb = seb,tratio = tratio, r.squared = r.squared))\n\t} else {\n\t\treturn(list(coefficients = coefficients, r.squared = r.squared))\n\t}\n}\n\nols.test <- function() {\n\tx = matrix( rnorm(4*10), ncol=4)\n\ty = rnorm(10)\n\n\tsummary(lm(y ~ x+0))\n\tols(x, y, T)\n}\n\n\n###############################################################################\n# Compute matrix inverse\n###############################################################################\n#' @export \ninv <- function(x) { solve(x) }\n\n#' @export \ninv1 <- function(x) { 1/x }\n\n#http://www.mathwords.com/i/inverse_of_a_matrix.htm\n#' @export \ninv2 <- function(x) \n{ \n\tmatrix(c(x[2,2],-x[1,2],-x[2,1],x[1,1]),nrow=2,byrow=T) / (x[1,1]*x[2,2] - x[1,2]*x[2,1]) \n}\n\n#http://www.dr-lex.be/random/matrix_inv.html\n#' @export \ninv3 <- function(x) \n{ \n\tmatrix(c(x[3,3]*x[2,2]-x[3,2]*x[2,3],-(x[3,3]*x[1,2]-x[3,2]*x[1,3]),x[2,3]*x[1,2]-x[2,2]*x[1,3],\n\t-(x[3,3]*x[2,1]-x[3,1]*x[2,3]),x[3,3]*x[1,1]-x[3,1]*x[1,3],-(x[2,3]*x[1,1]-x[2,1]*x[1,3]),\n\tx[3,2]*x[2,1]-x[3,1]*x[2,2],-(x[3,2]*x[1,1]-x[3,1]*x[1,2]),x[2,2]*x[1,1]-x[2,1]*x[1,2]),nrow=3,byrow=T) / \n\t(x[1,1]*(x[3,3]*x[2,2]-x[3,2]*x[2,3])-x[2,1]*(x[3,3]*x[1,2]-x[3,2]*x[1,3])+x[3,1]*(x[2,3]*x[1,2]-x[2,2]*x[1,3])) \n}\n \ninv.test <- function() {\n\tm=matrix(c(4,3,3,2),nrow=2,byrow=T)\n\tinv2(m) %*% m\n\tinv(m) %*% m\n\n\tm = matrix(c(1,2,3,4,5,6,7,8,8),ncol=3,byrow=T)\n\tinv3(m) %*% m\n\tm %*% inv3(m)\n\tinv(m) %*% m\n\t\t\n}\n\n\n###############################################################################\n# Maximum Distance Point on the curve\n# http://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve\t\t\n#' @export \n###############################################################################\nfind.maximum.distance.point <- function\n(\n\ty, \n\tx=1:len(y)\n)\n{\t\t\n\tallCoord = rbind(vec(y), vec(x))\n\t\t\n\tfirstPoint = allCoord[,1]\n\tlineVec = allCoord[,len(y)] - firstPoint\n\tlineVecN = lineVec / sqrt(sum(lineVec^2))\n\t\t\n\tvecFromFirst = allCoord - firstPoint\n\tscalarProduct = lineVecN %*% vecFromFirst\n\t\t\n\tvecFromFirstParallel = t(scalarProduct) %*% lineVecN\n\tvecToLine = t(vecFromFirst) - vecFromFirstParallel\n\tdistToLine = sqrt(rowSums(vecToLine^2,2))\n\twhich.max(distToLine)\n}\n\t", "meta": {"hexsha": "022155851cbadacdcbdc7b9176c7a190472a2d88", "size": 24211, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/optimization.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/optimization.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/optimization.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": 28.7541567696, "max_line_length": 126, "alphanum_fraction": 0.5658997976, "num_tokens": 7709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.42063597347102044}}
{"text": "subroutine qtest(h,i,j,k,shdswp,x,y,ntot,eps,nerror)\n\n# Test whether the LOP is satisified; i.e. whether vertex j\n# is outside the circumcircle of vertices h, i, and k of the\n# quadrilateral. Vertex h is the vertex being added; i and k are\n# the vertices of the quadrilateral which are currently joined;\n# j is the vertex which is ``opposite'' the vertex being added.\n# If the LOP is not satisfied, then shdswp (\"should-swap\") is true,\n# i.e. h and j should be joined, rather than i and k. I.e. if j\n# is outside the circumcircle of h, i, and k then all is well as-is;\n# *don't* swap ik for hj. If j is inside the circumcircle of h,\n# i, and k then change is needed so swap ik for hj.\n# Called by swap.\n\nimplicit double precision(a-h,o-z)\ndimension x(-3:ntot), y(-3:ntot)\ninteger h\nlogical shdswp\n\nnerror = -1\n\n# Look for ideal points.\nif(i<=0) ii = 1\nelse ii = 0\nif(j<=0) jj = 1\nelse jj = 0\nif(k<=0) kk = 1\nelse kk = 0\nijk = ii*4+jj*2+kk\n\n# All three corners other than h (the point currently being\n# added) are ideal --- so h, i, and k are co-linear; so \n# i and k shouldn't be joined, and h should be joined to j.\n# So swap. (But this can't happen, anyway!!!)\n# case 7:\nif(ijk==7) {\n\tshdswp = .true.\n\treturn\n}\n\n# If i and j are ideal, find out which of h and k is closer to the\n# intersection point of the two diagonals, and choose the diagonal\n# emanating from that vertex. (I.e. if h is closer, swap.)\n# Unless swapping yields a non-convex quadrilateral!!!\n# case 6:\nif(ijk==6) {\n\txh = x(h)\n\tyh = y(h)\n\txk = x(k)\n\tyk = y(k)\n\tss = 1 - 2*mod(-j,2)\n\ttest = (xh*yk+xk*yh-xh*yh-xk*yk)*ss\n\tif(test>0.d0) shdswp = .true.\n\telse shdswp = .false.\n# Check for convexity:\n\tif(shdswp) call acchk(j,k,h,shdswp,x,y,ntot,eps)\n\treturn\n}\n\n# Vertices i and k are ideal --- can't happen, but if it did, we'd\n# increase the minimum angle ``from 0 to more than 2*0'' by swapping ...\n#\n# 24/7/2011 --- I now think that the forgoing comment is misleading,\n# although it doesn't matter since it can't happen anyway. The\n# ``2*0'' is wrong. The ``new minimum angle would be min{alpha,beta}\n# where alpha and beta are the angles made by the line joining h\n# to j with (any) line with slope = -1. This will be greater than\n# 0 unless the line from h to j has slope = - 1. In this case h,\n# i, j, and k are all co-linear, so i and k should not be joined\n# (and h and j should be) so swapping is called for. If h, i,\n# j and j are not co-linear then the quadrilateral is definitely\n# convex whence swapping is OK. So let's say swap.\n# case 5:\nif(ijk==5) {\n\tshdswp = .true.\n\treturn\n}\n\n# If i is ideal we'd increase the minimum angle ``from 0 to more than\n# 2*0'' by swapping, so just check for convexity:\n# case 4:\nif(ijk==4) {\n\tcall acchk(j,k,h,shdswp,x,y,ntot,eps)\n\treturn\n}\n\n# If j and k are ideal, this is like unto case 6.\n# case 3:\nif(ijk==3) {\n\txi = x(i)\n\tyi = y(i)\n\txh = x(h)\n\tyh = y(h)\n\tss = 1 - 2*mod(-j,2)\n\ttest = (xh*yi+xi*yh-xh*yh-xi*yi)*ss\n\tif(test>0.d0) shdswp = .true.\n\telse shdswp = .false.\n# Check for convexity:\n\tif(shdswp) call acchk(h,i,j,shdswp,x,y,ntot,eps)\n\treturn\n}\n\n# If j is ideal we'd decrease the minimum angle ``from more than 2*0\n# to 0'', by swapping; so don't swap.\n# case 2:\nif(ijk==2) {\n\tshdswp = .false.\n\treturn\n}\n\n# If k is ideal, this is like unto case 4.\n# case 1:\nif(ijk==1) {\n\tcall acchk(h,i,j,shdswp,x,y,ntot,eps) # This checks\n # for convexity.\n # (Was i,j,h,...)\n\treturn\n}\n\n# If none of the `other' three corners are ideal, do the Lee-Schacter\n# test for the LOP.\n# case 0:\nif(ijk==0) {\n\tcall qtest1(h,i,j,k,x,y,ntot,eps,shdswp,nerror)\n\treturn\n}\n\n# default: # This CAN'T happen.\nnerror = 7\nreturn\n\nend\n", "meta": {"hexsha": "319f73f173316040cdd433fba2c6ac8638edd51b", "size": 3722, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/qtest.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/qtest.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/qtest.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": 27.984962406, "max_line_length": 72, "alphanum_fraction": 0.6480386889, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4202173876200336}}
{"text": "################################################################################\r\n# Part of the R/EpiILM package\r\n#\r\n# AUTHORS:\r\n# Waleed Almutiry ,\r\n# Vineetha Warriyar. K. V. and\r\n# Rob Deardon \r\n#\r\n# Based on:\r\n# Deardon R, Brooks, S. P., Grenfell, B. T., Keeling, M. J., Tildesley,\r\n# M. J., Savill, N. J., Shaw, D. J., Woolhouse, M. E. (2010).Inference\r\n# for individual level models of infectious diseases in large\r\n# populations. Statistica Sinica, 20, 239-261.\r\n#\r\n#\r\n# Free software under the terms of the GNU General Public License, version 2,\r\n# a copy of which is available at http://www.r-project.org/Licenses/.\r\n################################################################################\r\n\r\nepimcmc <- function (object, tmin = NULL, tmax, niter,\r\n sus.par.ini, trans.par.ini = NULL, beta.ini = NULL, spark.ini = NULL,\r\n Sformula = NULL, Tformula = NULL,\r\n pro.sus.var, pro.trans.var = NULL, pro.beta.var = NULL, pro.spark.var = NULL,\r\n prior.sus.dist, prior.trans.dist = NULL, prior.beta.dist = NULL, prior.spark.dist = NULL,\r\n prior.sus.par, prior.trans.par = NULL, prior.beta.par = NULL, prior.spark.par = NULL,\r\n adapt = FALSE, acc.rate = NULL) {\r\n \r\n if (!is(object, \"epidata\")) {\r\n stop(\"The object must be in a class of \\\"epidata\\\"\", call. = FALSE)\r\n } else {\r\n \r\n # error checks for input arguments\r\n \r\n if (any(is.null(object$type) | !(object$type %in% c(\"SI\", \"SIR\"))) == TRUE) {\r\n stop(\"epimcmc: Specify type as \\\"SI\\\" or \\\"SIR\\\" \", call. = FALSE)\r\n }\r\n \r\n if (!is.vector(object$inftime)) {\r\n stop('epimcmc: inftime is not a vector')\r\n }\r\n \r\n n <- length(object$inftime)\r\n \r\n if (object$type == \"SIR\") {\r\n infperiod = object$remtime - object$inftime\r\n }\r\n \r\n if (all(is.null(object$contact) & is.null(object$XYcoordinates)) == TRUE) {\r\n stop(\"epimcmc: Specify contact network or x, y coordinates\")\r\n }\r\n \r\n if (is.null(tmin)) {\r\n tmin <- 1\r\n }\r\n \r\n \r\n # susceptibility parameters:\r\n \r\n ns <- length(sus.par.ini)\r\n \r\n # formula for susceptibility function\r\n if (!is.null(Sformula)) {\r\n covmat.sus <- model.matrix(Sformula)\r\n if (all((ncol(covmat.sus) == length(all.vars(Sformula))) & (ns != length(all.vars(Sformula)))) == TRUE) {\r\n stop(\"epimcmc: Check Sformula (no intercept term) and the dimension of susceptibility parameters\", call. = FALSE)\r\n } else if (all((ncol(covmat.sus) > length(all.vars(Sformula))) & (ns != ncol(covmat.sus))) == TRUE) {\r\n stop(\"epimcmc: Check Sformula (intercept term) and the dimension of susceptibility parameters\", call. = FALSE)\r\n }\r\n } else {\r\n if (ns == 1) {\r\n covmat.sus <- matrix(1.0, nrow = n, ncol = ns)\r\n }\r\n }\r\n \r\n if (any(is.null(prior.sus.dist) | !(all(prior.sus.dist %in% c(\"halfnormal\", \"gamma\",\"uniform\")))) == TRUE) {\r\n stop(\"epimcmc: Specify prior for susceptibility parameters as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n \r\n prostda <- vector(mode = \"numeric\", length = ns)\r\n if (ns == 1) {\r\n prostda <- pro.sus.var\r\n } else if (ns > 1) {\r\n if (length(pro.sus.var) != ns) {\r\n stop('epimcmc: Specify proposal variance for each susceptibility parameter')\r\n }\r\n for (i in 1:ns) {\r\n prostda[i] <- pro.sus.var[i]\r\n }\r\n }\r\n \r\n alphapar <- list(NULL)\r\n len.alphapar <- ns - sum(prostda == 0)\r\n if (len.alphapar != 0){\r\n j <- 1\r\n for (i in 1:ns) {\r\n if (prostda[i] != 0){\r\n alphapar[[j]] <- list(NULL)\r\n alphapar[[j]][[1]] <- prior.sus.dist[i]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n } else {\r\n alphapar[[1]] <- list(NULL)\r\n alphapar[[1]][[1]] <- \"uniform\" # just to fill the list and it is not being used at all.\r\n }\r\n \r\n if (all(ns == 1 & len.alphapar != 0) == TRUE) {\r\n if (any((prior.sus.dist == \"gamma\") | (prior.sus.dist == \"uniform\")) == TRUE) {\r\n if (is.null(prior.sus.par)) {\r\n stop('epimcmc: Specify prior.sus.par as a vector or a 1 by 2 matrix.')\r\n } else {\r\n alphapar[[1]][[2]] <- prior.sus.par\r\n }\r\n } else if (prior.sus.dist == \"halfnormal\") {\r\n if (is.null(prior.sus.par)) {\r\n stop('epimcmc: Specify the variance of the half normal prior distribution for prior.sus.par.')\r\n } else {\r\n alphapar[[1]][[2]] <- c(prior.sus.par[1], 0)\r\n }\r\n }\r\n } else if (all(ns == 1 & len.alphapar == 0) == TRUE) {\r\n alphapar[[1]][[2]] <- c(0, 0)\r\n } else if (all(ns > 1 & len.alphapar != 0) == TRUE) {\r\n if (any(is.null(prior.sus.par) | !is.matrix(prior.sus.par)) == TRUE) {\r\n stop('epimcmc: Specify prior.sus.par as a matrix with each row corresponds to each susceptibility parameter')\r\n } else {\r\n j <- 1\r\n for (i in 1:ns) {\r\n if (prostda[i] != 0){\r\n alphapar[[j]][[2]] <- prior.sus.par[i,]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n }\r\n } else if (all(ns > 1 & len.alphapar == 0) == TRUE) {\r\n alphapar[[1]][[2]] <- c(0, 0)\r\n }# end if - ns\r\n \r\n # transmissibility parameters:\r\n \r\n if (!is.null(trans.par.ini)) {\r\n nt <- length(trans.par.ini)\r\n flag.trans <- 1\r\n } else {\r\n nt <- 1\r\n flag.trans <- 0\r\n phipar <- 1\r\n }\r\n \r\n # formula for transmissibility function\r\n if (flag.trans == 1) {\r\n if (is.null(Tformula)) {\r\n stop(\"epimcmc: Tformula is missing. It has to be specified with no intercept term and number of columns equal to the length of trans.par\", call. = FALSE)\r\n } else if (!is.null(Tformula)) {\r\n covmat.trans <- model.matrix(Tformula)\r\n if (all((ncol(covmat.trans) == length(all.vars(Tformula))) & (nt != length(all.vars(Tformula)))) == TRUE) {\r\n stop(\"epimcmc: Check Tformula. It has to be with no intercept term and number of columns equal to the length of trans.par\", call. = FALSE)\r\n }\r\n }\r\n } else if (flag.trans == 0) {\r\n covmat.trans <- matrix(1.0, nrow = n, ncol = nt)\r\n }\r\n \r\n if (all(!is.null(prior.trans.dist) & !(all(prior.trans.dist %in% c(\"halfnormal\", \"gamma\",\"uniform\")))) == TRUE) {\r\n stop(\"epimcmc: Specify prior for transmissibility parameters as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n \r\n if (all(is.null(prior.trans.dist) & flag.trans == 1) == TRUE) {\r\n stop(\"epimcmc: Specify prior for transmissibility parameters as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n \r\n # proposal variance for transmissibility parameters\r\n prostdt <- vector(mode = \"numeric\", length = nt)\r\n if (all(flag.trans == 1 & nt == 1) == TRUE) {\r\n if (is.null(pro.trans.var)) {\r\n stop('epimcmc: Specify proposal variance for the transmissibility parameter')\r\n }\r\n prostdt <- pro.trans.var\r\n } else if (all(flag.trans == 1 & nt > 1) == TRUE) {\r\n if (is.null(pro.trans.var)) {\r\n stop('epimcmc: Specify proposal variance for each transmissibility parameter')\r\n }\r\n if (length(pro.trans.var) != nt) {\r\n stop('epimcmc: Specify proposal variance for each transmissibility parameter')\r\n }\r\n for (i in 1:nt) {\r\n prostdt[i] <- pro.trans.var[i]\r\n }\r\n } else {\r\n prostdt <- NULL\r\n }\r\n \r\n if (flag.trans == 1){\r\n phipar <- list(NULL)\r\n len.phipar <- nt - sum(prostdt == 0)\r\n if (len.phipar != 0){\r\n j <- 1\r\n for (i in 1:nt) {\r\n if (prostdt[i] != 0){\r\n phipar[[j]] <- list(NULL)\r\n phipar[[j]][[1]] <- prior.trans.dist[i]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n } else {\r\n phipar[[1]] <- list(NULL)\r\n phipar[[1]][[1]] <- \"uniform\" # just to fill the list and it is not being used at all.\r\n }\r\n } else {\r\n phipar <- 1\r\n }\r\n \r\n # prior selection for transmissibility parameters\r\n if (flag.trans == 1) {\r\n \r\n if (nt == 1 & len.phipar != 0) {\r\n if (any((prior.trans.dist == \"gamma\") | (prior.trans.dist == \"uniform\")) == TRUE) {\r\n if (is.null(prior.trans.par)) {\r\n stop('epimcmc: Specify prior.trans.par as a vector or a 1 by 2 matrix.')\r\n } else {\r\n phipar[[1]][[2]] <- prior.trans.par\r\n }\r\n } else if (prior.trans.dist == \"halfnormal\") {\r\n if (is.null(prior.trans.par)) {\r\n stop('epimcmc: Specify the variance of the half normal prior distribution for prior.trans.par.')\r\n } else {\r\n phipar[[1]][[2]] <- c(prior.trans.par[1], 0)\r\n }\r\n }\r\n } else if (all(nt == 1 & len.phipar == 0) == TRUE) {\r\n phipar[[1]][[2]] <- c(0, 0)\r\n } else if (all(nt > 1 & len.phipar != 0) == TRUE) {\r\n if (any(is.null(prior.trans.par) | !is.matrix(prior.trans.par)) == TRUE) {\r\n stop('epimcmc: Specify prior.trans.par as a matrix with each row corresponds to each transmissibility parameter')\r\n } else {\r\n j <- 1\r\n for (i in 1:nt) {\r\n if (prostdt[i] != 0){\r\n phipar[[j]][[2]] <- prior.trans.par[i,]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n }\r\n } else if (all(nt > 1 & len.phipar == 0) == TRUE) {\r\n phipar[[1]][[2]] <- c(0, 0)\r\n }# end if - nt\r\n }# end if - flag.trans\r\n \r\n # BETA:\r\n \r\n if (!is.null(object$contact)) {\r\n if (length(object$contact)/(n * n) == 1) {\r\n ni <- 1\r\n \r\n if (any(!is.null(beta.ini) | !is.null(prior.beta.dist) | !is.null(pro.beta.var) | !is.null(prior.beta.par)) == TRUE) {\r\n stop(\"As the model has only one contact network, The model does not have a network parameter beta, beta.ini, prior.dist.beta, prior.beta.var, and pro.beta.var must be assigned to their default values = NULL\", .call = FALSE)\r\n }\r\n \r\n flag.beta <- 0\r\n \r\n betapar <- list(NULL)\r\n betapar[[1]] <- \"uniform\" # just to fill the list and it is not being used at all.\r\n betapar[[2]] <- c(0, 0)\r\n\r\n } else if (length(object$contact)/(n * n) > 1) {\r\n \r\n if (is.null(beta.ini)) {\r\n stop(\"epimcmc: The initial values beta.ini of the network parameters has to specified\", call. = FALSE)\r\n }\r\n ni <- length(beta.ini)\r\n \r\n if (length(object$contact)/(n * n) != ni) {\r\n stop('epimcmc: Dimension of beta and the number of contact networks are not matching')\r\n }\r\n \r\n flag.beta <- 1\r\n \r\n if (any(is.null(prior.beta.dist) | !(all(prior.beta.dist %in% c(\"halfnormal\", \"gamma\",\"uniform\")))) == TRUE) {\r\n stop(\"epimcmc: Specify prior for beta as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n \r\n \r\n if (length(prior.beta.dist) != ni) {\r\n stop('epimcmc: Specify prior distributions for each of the network parameters beta, prior.beta.dist')\r\n }\r\n \r\n # proposal variance for beta\r\n prostdb <- vector(mode = \"numeric\", length = ni)\r\n if (length(pro.beta.var) != ni) {\r\n stop('epimcmc: Specify proposal variance for each beta parameter')\r\n }\r\n for (i in 1:ni) {\r\n prostdb[i] <- pro.beta.var[i]\r\n }\r\n \r\n \r\n betapar <- list(NULL)\r\n if (flag.beta == 0) {\r\n len.betapar <- 0\r\n } else {\r\n len.betapar <- ni - sum(prostdb == 0)\r\n }\r\n \r\n if (len.betapar != 0){\r\n j <- 1\r\n for (i in 1:ni) {\r\n if (prostdb[i] != 0){\r\n betapar[[j]] <- list(NULL)\r\n betapar[[j]][[1]] <- prior.beta.dist[i]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n } else {\r\n betapar[[1]] <- list(NULL)\r\n betapar[[1]][[1]] <- \"uniform\" # just to fill the list and it is not being used at all.\r\n }\r\n # prior selection for kernel parameters\r\n if (len.betapar != 0) {\r\n if (any(is.null(prior.beta.par) | !is.matrix(prior.beta.par)) == TRUE) {\r\n stop('epimcmc: Specify prior.beta.par as a matrix with each row corresponds to each beta parameter')\r\n } else {\r\n j <- 1\r\n for (i in 1:ni) {\r\n if (prostdb[i] != 0){\r\n betapar[[j]][[2]] <- prior.beta.par[i,]\r\n j <- j + 1\r\n } else {\r\n j <- j\r\n }\r\n }\r\n }\r\n } else if (len.betapar == 0) {\r\n betapar[[1]][[2]] <- c(0, 0)\r\n }# end if - ni\r\n }\r\n \r\n } else if (is.null(object$contact)) {\r\n \r\n if (is.null(object$XYcoordinates)) {\r\n stop(\"epimcmc: Specify contact network or x, y coordinates\")\r\n }\r\n \r\n ni <- length(beta.ini)\r\n \r\n if (ni > 1) {\r\n stop(\"epimcmc: The input of beta.ini has more than one value while the considered distance-based ILM needs only one spatial parameter, beta.\")\r\n }\r\n \r\n if (any(is.null(prior.beta.dist) | !(all(prior.beta.dist %in% c(\"halfnormal\", \"gamma\",\"uniform\")))) == TRUE) {\r\n stop(\"epimcmc: Specify prior for beta as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n \r\n if (length(pro.beta.var) != ni) {\r\n stop('epimcmc: Specify only one proposal variance for the spatial parameter beta, pro.beta.var')\r\n }\r\n \r\n if (length(prior.beta.dist) != ni) {\r\n stop('epimcmc: Specify only one prior distribution for the spatial parameter beta, prior.beta.dist')\r\n }\r\n \r\n flag.beta <- 1\r\n \r\n prostdb <- pro.beta.var\r\n \r\n betapar <- list(NULL)\r\n len.betapar <- ni - sum(prostdb == 0)\r\n betapar[[1]] <- list(NULL)\r\n if (len.betapar != 0){\r\n betapar[[1]][[1]] <- prior.beta.dist\r\n } else {\r\n betapar[[1]][[1]] <- \"uniform\" # just to fill the list and it is not being used at all.\r\n }\r\n # prior selection for kernel parameters\r\n if (len.betapar != 0) {\r\n if (any((prior.beta.dist == \"gamma\") | (prior.beta.dist == \"uniform\")) == TRUE) {\r\n if (is.null(prior.beta.par)) {\r\n stop('epimcmc: Specify prior.beta.par as a vector or a 1 by 2 matrix.')\r\n } else {\r\n betapar[[1]][[2]] <- prior.beta.par\r\n }\r\n } else if (prior.beta.dist == \"halfnormal\") {\r\n if (is.null(prior.beta.par)) {\r\n stop('epimcmc: Specify the variance of the half normal prior distribution for prior.beta.par.')\r\n } else {\r\n betapar[[1]][[2]] <- c(prior.beta.par[1], 0)\r\n }\r\n }\r\n \r\n } else if (len.betapar == 0) {\r\n betapar[[1]][[2]] <- c(0, 0)\r\n }\r\n }\r\n \r\n # SPARK parameter:\r\n \r\n if (!is.null(spark.ini)) {\r\n flag <- 1\r\n if (is.null(pro.spark.var)) {\r\n stop(\"epimcmc: Specify proposal variance for spark\", call. = FALSE)\r\n }\r\n if (is.null(prior.spark.dist)) {\r\n stop(\"epimcmc22: Specify prior for spark\", call. = FALSE)\r\n }\r\n if (any(is.null(prior.spark.dist) | !(prior.spark.dist %in% c(\"halfnormal\", \"gamma\",\"uniform\"))) == TRUE) {\r\n stop(\"epimcmc2: Specify prior for spark term as \\\"halfnormal\\\" , \\\"gamma\\\" or \\\"uniform\\\" \", call. = FALSE)\r\n }\r\n sparkpar <- list(NULL)\r\n length(sparkpar) <- 2\r\n sparkpar[[1]] <- prior.spark.dist\r\n if (any((prior.spark.dist == \"gamma\") | (prior.spark.dist == \"uniform\")) == TRUE) {\r\n if (is.null(prior.spark.par)) {\r\n stop('epimcmc: Specify prior.spark.par as a vector or a 1 by 2 matrix.')\r\n } else {\r\n sparkpar[[2]] <- c(prior.spark.par)\r\n }\r\n } else if (prior.spark.dist == \"halfnormal\") {\r\n if (is.null(prior.spark.par)) {\r\n stop('epimcmc: Specify the variance of the half normal prior distribution for prior.spark.par.')\r\n } else {\r\n sparkpar[[2]] <- c(prior.spark.par[1], 0)\r\n }\r\n }\r\n \r\n } else if (is.null(spark.ini)) {\r\n flag <- 0\r\n sparkpar <- list(NULL)\r\n sparkpar[[2]] <- c(0, 0)\r\n }\r\n \r\n # proposal variance for spark\r\n \r\n if (flag == 1) {\r\n prostdsp <- pro.spark.var\r\n } else {\r\n prostdsp <- 0.0\r\n }\r\n \r\n \r\n \r\n if (all(flag == 0 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n mcmcscale <- c(prostda)\r\n } else if (all(flag == 0 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n mcmcscale <- c(prostda, prostdb)\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n mcmcscale <- c(prostda, prostdt)\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n mcmcscale <- c(prostda, prostdt, prostdb)\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n mcmcscale <- c(prostda, prostdsp)\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n mcmcscale <- c(prostda, prostdb, prostdsp)\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n mcmcscale <- c(prostda, prostdt, prostdsp)\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n mcmcscale <- c(prostda, prostdt, prostdb, prostdsp)\r\n }\r\n \r\n scalemc <- mcmcscale[mcmcscale !=0]\r\n \r\n \r\n if (all(flag == 0 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n mcmcinit <- c(sus.par.ini)\r\n } else if (all(flag == 0 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, beta.ini)\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, trans.par.ini)\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, trans.par.ini, beta.ini)\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, spark.ini)\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, beta.ini, spark.ini)\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, trans.par.ini, spark.ini)\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n mcmcinit <- c(sus.par.ini, trans.par.ini, beta.ini, spark.ini)\r\n }\r\n \r\n \r\n initmc <- mcmcinit[mcmcscale!=0]\r\n \r\n p <- function(xx) {\r\n \r\n ms <- which(mcmcscale[1: ns] == 0)\r\n nns <- ns - length(ms)\r\n if (length(ms) != 0) {\r\n xs <- vector(\"double\", length = ns)\r\n xs[ms] <- mcmcinit[ms]\r\n xs[-ms] <- xx[1: nns]\r\n } else {\r\n xs <- xx[1: nns]\r\n }\r\n \r\n if (flag.trans == 1) {\r\n mt <- which(mcmcscale[(1+ns): (ns+nt)] == 0)\r\n nnt <- nt - length(mt)\r\n if (length(mt) != 0) {\r\n xt <- vector(\"double\", length = nt)\r\n xt[mt] <- mcmcinit[mt+ns]\r\n xt[-mt] <- xx[(1+nns): (nns+nnt)]\r\n } else {\r\n xt <- xx[(1+nns): (nns+nnt)]\r\n }\r\n } else {\r\n nnt <- 0\r\n xt <- NULL\r\n }\r\n \r\n if (flag.beta == 1) {\r\n if (flag.trans == 1) {\r\n mi <- which(mcmcscale[(1+ns+nt): (ns+nt+ni)] == 0)\r\n } else {\r\n mi <- which(mcmcscale[(1+ns): (ns+ni)] == 0)\r\n }\r\n nni <- ni - length(mi)\r\n \r\n if (flag.trans == 1) {\r\n if (length(mi) != 0) {\r\n xi <- vector(\"double\", length = ni)\r\n xi[mi] <- mcmcinit[mi+ns+nt]\r\n xi[-mi] <- xx[(1+nns+nnt): (nns+nnt+nni)]\r\n } else {\r\n xi <- xx[(1+nns+nnt): (nns+nnt+nni)]\r\n }\r\n } else {\r\n if (length(mi) != 0) {\r\n xi <- vector(\"double\", length = ni)\r\n xi[mi] <- mcmcinit[mi+ns+nnt]\r\n xi[-mi] <- xx[(1+nns+nnt): (nns+nnt+nni)]\r\n } else {\r\n xi <- xx[(1+nns+nnt): (nns+nnt+nni)]\r\n }\r\n }\r\n } else {\r\n nni <- 0\r\n xi <- NULL\r\n }\r\n \r\n if (flag == 1) {\r\n if(length(xx) > nns+nnt+nni) {\r\n xsp <- xx[nns+nnt+nni+1]\r\n } else if (all(length(xx) == nns+nnt+nni & mcmcscale[ns+nt+ni+1] == 0) == TRUE) {\r\n xsp <- mcmcinit[ns+nt+ni+1]\r\n }\r\n } else {\r\n xsp <- NULL\r\n }\r\n \r\n \r\n loglikeILM <- epilike(object = object, tmin = tmin, tmax = tmax, sus.par = xs,\r\n trans.par = xt, beta = xi, spark = xsp,\r\n Sformula = Sformula, Tformula = Tformula)\r\n \r\n if (nns != 0) {\r\n palpha = 0\r\n for (i in 1:nns) {\r\n if (alphapar[[i]][[1]] == \"uniform\") {\r\n palpha <- palpha + dunif(xx[i], min = alphapar[[i]][[2]][1],\r\n max = alphapar[[i]][[2]][2], log = TRUE)\r\n } else if (alphapar[[i]][[1]] == \"gamma\") {\r\n palpha <- palpha + dgamma(xx[i], shape = alphapar[[i]][[2]][1],\r\n rate = alphapar[[i]][[2]][2], log = TRUE)\r\n } else if (alphapar[[i]][[1]] == \"halfnormal\") {\r\n palpha <- palpha + dhalfnorm(xx[i], scale = alphapar[[i]][[2]][1], log = TRUE)\r\n }\r\n }\r\n } else {\r\n palpha = 0\r\n }\r\n \r\n if (all(flag.trans == 1 & nnt != 0) == TRUE) {\r\n pphi = 0\r\n for (i in 1:nnt) {\r\n if (phipar[[i]][[1]] == \"uniform\") {\r\n pphi <- pphi + dunif(xx[i+nns], min = phipar[[i]][[2]][1],\r\n max = phipar[[i]][[2]][2], log = TRUE)\r\n } else if (phipar[[i]][[1]] == \"gamma\") {\r\n pphi <- pphi + dgamma(xx[i+nns], shape = phipar[[i]][[2]][1],\r\n rate = phipar[[i]][[2]][2], log = TRUE)\r\n } else if (phipar[[i]][[1]] == \"halfnormal\") {\r\n pphi <- pphi + dhalfnorm(xx[i+nns], scale = phipar[[i]][[2]][1], log = TRUE)\r\n }\r\n }\r\n } else {\r\n pphi = 0\r\n }\r\n \r\n if (nni != 0) {\r\n pbeta = 0\r\n for (i in 1:nni) {\r\n if (betapar[[i]][[1]] == \"uniform\") {\r\n pbeta <- pbeta + dunif(xx[i+nns+nnt], min = betapar[[i]][[2]][1],\r\n max = betapar[[i]][[2]][2], log = TRUE)\r\n } else if (betapar[[i]][[1]] == \"gamma\") {\r\n pbeta <- pbeta + dgamma(xx[i+nns+nnt], shape = betapar[[i]][[2]][1],\r\n rate = betapar[[i]][[2]][2], log = TRUE)\r\n } else if (betapar[[i]][[1]] == \"halfnormal\") {\r\n pbeta <- pbeta + dhalfnorm(xx[i+nns+nnt], scale = betapar[[i]][[2]][1], log = TRUE)\r\n }\r\n }\r\n } else {\r\n pbeta = 0\r\n }\r\n \r\n \r\n if (flag == 1) {\r\n if (sparkpar[[1]] == \"uniform\") {\r\n pspark <- dunif(xx[nns+nnt+nni+1], min = sparkpar[[2]][1],\r\n max = sparkpar[[2]][2], log = TRUE)\r\n } else if (sparkpar[[1]] == \"gamma\") {\r\n pspark <- dgamma(xx[nns+nnt+nni+1], shape = sparkpar[[2]][1],\r\n rate = sparkpar[[2]][2], log = TRUE)\r\n } else if (sparkpar[[1]] == \"halfnormal\") {\r\n pspark <- pspark + dhalfnorm(xx[nns+nnt+nni+1], scale = sparkpar[[2]][1], log = TRUE)\r\n }\r\n } else {\r\n pspark = 0.0\r\n }\r\n \r\n return(loglikeILM + palpha + pphi + pbeta + pspark)\r\n }\r\n \r\n if (is.null(object$contact)) {\r\n kernel.type <- \"distance-based discrete-time ILM\"\r\n result <- MCMC(p = p, n = niter, init = initmc, scale = scalemc,\r\n adapt = adapt, acc.rate = acc.rate)\r\n } else if (!is.null(object$contact)) {\r\n kernel.type <- \"network-based discrete-time ILM\"\r\n result <- MCMC(p = p, n = niter, init = initmc, scale = scalemc,\r\n adapt = adapt, acc.rate = acc.rate)\r\n }\r\n \r\n alphanames <- c()\r\n for (i in 1:ns) {\r\n alphanames <- c(alphanames, paste(\"alpha.\", i, sep = \"\"))\r\n }\r\n \r\n if (flag.trans == 1) {\r\n phinames <- c()\r\n for (i in 1:nt) {\r\n phinames <- c(phinames, paste(\"phi.\", i, sep = \"\"))\r\n }\r\n }\r\n \r\n if (flag.beta == 1) {\r\n betanames <- c()\r\n for (i in 1:ni) {\r\n betanames <- c(betanames, paste(\"beta.\", i, sep = \"\"))\r\n }\r\n }\r\n \r\n if (all(flag == 0 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n nnames <- c(alphanames)\r\n } else if (all(flag == 0 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n nnames <- c(alphanames, betanames)\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 0) == TRUE) {\r\n nnames <- c(alphanames, \"spark\")\r\n } else if (all(flag == 1 & flag.trans == 0 & flag.beta == 1) == TRUE) {\r\n nnames <- c(alphanames, betanames, \"spark\")\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n nnames <- c(alphanames, phinames)\r\n } else if (all(flag == 0 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n nnames <- c(alphanames, phinames, betanames)\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 0) == TRUE) {\r\n nnames <- c(alphanames, phinames, \"spark\")\r\n } else if (all(flag == 1 & flag.trans == 1 & flag.beta == 1) == TRUE) {\r\n nnames <- c(alphanames, phinames, betanames, \"spark\")\r\n }\r\n \r\n finalnames <- nnames[mcmcscale!=0]\r\n \r\n Estimates <- data.frame(result$samples)\r\n colnames(Estimates) <- finalnames\r\n \r\n Loglikelihood <- c(result$log.p)\r\n # colnames(Loglikelihood) <- \"Loglikelihood\"\r\n \r\n ki <- match(nnames,finalnames)\r\n \r\n nki <- which(nnames %in% finalnames)\r\n \r\n fullsamples <- matrix(0, ncol = length(nnames), nrow = niter)\r\n fullsamples[,nki] <- result$samples\r\n nnki <- which(is.na(ki))\r\n \r\n if (length(nnki) == 1) {\r\n fullsamples[,nnki] <- rep(mcmcinit[nnki], niter)\r\n } else if (length(nnki) > 1){\r\n for (i in 1:length(nnki)) {\r\n fullsamples[,nnki[i]] <- rep(mcmcinit[nnki[i]], niter)\r\n }\r\n }\r\n }\r\n \r\n # mcmc result as a coda object\r\n \r\n if (flag.trans == 1) {\r\n n.trans.par <- nt\r\n } else {\r\n n.trans.par <- 0\r\n }\r\n if (flag.beta == 1) {\r\n n.ker.par <- ni\r\n } else {\r\n n.ker.par <- 0\r\n }\r\n \r\n output <- list(type = object$type, kernel.type = kernel.type, Estimates = Estimates,\r\n Loglikelihood = Loglikelihood, Fullsample = fullsamples,\r\n n.sus.par = ns, n.trans.par = n.trans.par, n.ker.par = n.ker.par)\r\n \r\n \r\n class(output) <- \"epimcmc\"\r\n output\r\n \r\n} # End of function\r\n\r\nsummary.epimcmc <- function(object, ...) {\r\n if (!is(object, \"epimcmc\")) {\r\n stop(\"The object has to be of \\\"epimcmc\\\" class\", call. = FALSE)\r\n }\r\n if (object$type == \"SI\") {\r\n cat(paste(\"Model:\", object$type, object$kernel.type,\"\\n\"))\r\n cat(paste(\"Method: Markov chain Monte Carlo (MCMC) \\n\"))\r\n summary(window(mcmc(object$Estimates), ...))\r\n } else if (object$type == \"SIR\") {\r\n cat(paste(\"Model:\", object$type, object$kernel.type,\"\\n\"))\r\n cat(paste(\"Method: Markov chain Monte Carlo (MCMC) \\n\"))\r\n summary(window(mcmc(object$Estimates), ...))\r\n }\r\n}\r\n\r\n\r\nplot.epimcmc <- function(x, partype, start = 1, end = NULL, thin = 1, ...) {\r\n if (is.null(end)) {\r\n end = nrow(x$Estimates)\r\n }\r\n if (!is(x, \"epimcmc\")) {\r\n stop(\"The object x has to be of \\\"epimcmc\\\" class\", call. = FALSE)\r\n }\r\n if (partype == \"parameter\") {\r\n plot(window(as.mcmc(x$Estimates), start = start, end = end, thin = thin), ...)\r\n } else if (partype == \"loglik\") {\r\n plot(window(as.mcmc(x$Loglikelihood), start = start, end = end, thin = thin), ...)\r\n }\r\n}\r\n", "meta": {"hexsha": "8cf72f0cc8d56754e8bf7e527e020dfa81637ec7", "size": 28193, "ext": "r", "lang": "R", "max_stars_repo_path": "R/epimcmc.r", "max_stars_repo_name": "waleedalmutiry/EpiILM", "max_stars_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_stars_repo_licenses": ["Intel"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-30T03:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:15:25.000Z", "max_issues_repo_path": "R/epimcmc.r", "max_issues_repo_name": "waleedalmutiry/EpiILM", "max_issues_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/epimcmc.r", "max_forks_repo_name": "waleedalmutiry/EpiILM", "max_forks_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-01T20:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T17:44:20.000Z", "avg_line_length": 37.2430647292, "max_line_length": 234, "alphanum_fraction": 0.4813606214, "num_tokens": 8251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4193925144200281}}
{"text": "#dod方法下的射出频率与参数之间的关系\r\n#########说明########\r\n#乙二醇液体\r\n#voltage_pluse,说明高峰电压和基准电压下的射出时间ms\r\n#duty_pluse,随着fv电压频率上升,占空比不同时的射出时间\r\n#height,不同占空比下,随fv上升,弯月面高度的变化\r\n#angle,同上,弯月面锥角的变化\r\n#flowrate_pulse,不同占空比下,随流量变化的射出时间\r\n#flowrate_height,此时的弯月面高度\r\n#flowrate_angle,弯月面角度的变化\r\n#setduty_pulse, 固定占空比为50%时,不同电压频率下,不同流量下的射出时间\r\n#setduty_height,同上,弯月面高度\r\n#setduty_angle,同上,弯月面锥角\r\n\r\n#####第一组:随电压频率上升,不同占空比下的射出时间和弯月面信息#####\r\n#####第二组:固定电压频率下,不同流量,不同占空比下的射出时间和弯月面信息####\r\n#####第三组:固定占空比下,不同流量,不同电压频率的射出时间和弯月面信息####\r\n\r\n#设定工作区间\r\nsetwd(\"D:/data\")\r\nlibrary(xlsx)\r\n\r\nsetp<-read.xlsx(\"dod_v_pulse.xls\", sheetName = \"setduty_pulse\", header = TRUE)\r\nseth<-read.xlsx(\"dod_v_pulse.xls\", sheetName = \"setduty_height\", header = TRUE)\r\nseta<-read.xlsx(\"dod_v_pulse.xls\", sheetName = \"setduty_angle\", header = TRUE)\r\n#规划区域\r\npar(mfrow=c(2,2), mar=c(4,4,2,2), oma=c(2,1,1,1))\r\n\r\n#保存pdf\r\n#pdf(\"dod_frequency.pdf\")\r\n\r\n#固定占空比为20%\r\n\r\n################################画图-流量与pulse射出时间的关系###########################\r\nplot(setp$flowrate, setp$X10, col=0, xaxs=\"i\", xlim=c(0, 0.001), ylim=c(0.2, 0.5), \r\nxlab=\"Flow rate (ml/min)\", cex.lab=1.2, ylab=\"Pulse time (ms)\", main=\"Pulse time in various fv\", cex.main = 1.5)\r\n\r\nmodel1 = loess(setp$X10~setp$flowrate)\r\nlines(setp$flowrate, model1$fit, col=\"#458B74\", pch=21, lwd=2.5, type=\"b\", lty=2)\r\n\r\nmodel2 = loess(setp$X25~setp$flowrate)\r\nlines(setp$flowrate, model2$fit, col=\"#FF00FF\", pch=22, lwd=2.5, type=\"b\", lty=2)\r\n\r\nmodel3 = loess(setp$X50~setp$flowrate)\r\nlines(setp$flowrate, model3$fit, col=\"#EE0000\", pch=23, lwd=2.5, type=\"b\", lty=2)\r\n\r\nmodel4 = loess(setp$X75~setp$flowrate)\r\nlines(setp$flowrate, model4$fit, col=\"#EEAD0E\", pch=24, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlegend(\"bottomright\", c(\"10Hz\", \"25Hz\", \"50Hz\", \"75Hz\"), inset=.05, col=c(\"#458B74\", \"#FF00FF\", \"#EE0000\", \"#EEAD0E\"), pch=c(21,22,23, 24), lwd=1.5, lty=2, cex=1.2, bty=\"n\")\r\n\r\n################################画图-信息###########################\r\n\r\nplot(setp$flowrate, setp$X10, yaxt=\"n\", xaxt= \"n\", col=0, xlab=\"\", ylab=\"\", xlim=c(0,0.001), ylim=c(1, 3), main=\"Information\", cex.main = 1.5)\r\ntext(0.00025, 2.8, \"Liquids - Ethylene glycol\", col=\"black\", adj=0, cex=1.5)\r\ntext(0.00025, 2.5, \"Distance - 1mm\", col=\"black\", adj=0, cex=1.5)\r\ntext(0.00025, 2.2, \"Nozzle - 24G - 0.55mm\", col=\"black\", adj=0, cex=1.5)\r\ntext(0.00025, 1.9, \"Flowrate - 0.0002ml/min\", col=\"black\", adj=0, cex=1.5)\r\ntext(0.00025, 1.6, \"Voltage frequency - 20Hz\", col=\"black\", adj=0, cex=1.5)\r\ntext(0.00025, 1.3, \"Duty cycle - 20%\", col=\"black\", adj=0, cex=1.5)\r\n\r\n\r\n#legend(\"bottomleft\", c(\"k=0.1\", \"k=0.2\", \"k=0.3\", \"k=0.5\", \"k=0.8\"), inset=.05, col=c(\"#458B74\", \"#FF00FF\", \"#EE0000\", \"#EEAD0E\", \"#27408B\"), pch=c(21,22,23,24,25), lwd=1.5, lty=2, cex=1.2, bty=\"n\")\r\n\r\n#################################画图--弯月面高度#############################\r\nplot(seth$flowrate, seth$X10, col=0, xaxs=\"i\", xlim=c(0, 0.001), ylim=c(0.3, 0.4), \r\nxlab=\"Flow rate (ml/min)\", cex.lab=1.2, ylab=\"Height of Meniscus (mm)\", main=\"Meniscus height in various fv\", cex.main = 1.5)\r\n\r\nlines(lowess(seth$flowrate, seth$X10), col=\"#458B74\", pch=21, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seth$flowrate, seth$X25), col=\"#FF00FF\", pch=22, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seth$flowrate, seth$X50), col=\"#EE0000\", pch=23, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seth$flowrate, seth$X75), col=\"#EEAD0E\", pch=24, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlegend(\"bottomright\", c(\"10Hz\", \"25Hz\", \"50Hz\", \"75Hz\"), inset=.05, col=c(\"#458B74\", \"#FF00FF\", \"#EE0000\", \"#EEAD0E\"), pch=c(21,22,23,24), lwd=1.5, lty=2, cex=1.2, bty=\"n\")\r\n\r\n###############################画图--弯月面角度#############################\r\nplot(seta$flowrate, seta$X10, col=0, xaxs=\"i\",xlim=c(0, 0.001), ylim=c(65, 90), \r\nxlab=\"Flow rate (ml/min)\", cex.lab=1.2, ylab=\"Taylor fale (°)\", main=\"Meniscus Angle in various fv\", cex.main = 1.5)\r\n\r\nlines(lowess(seta$flowrate, seta$X10), col=\"#458B74\", pch=21, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seta$flowrate, seta$X25), col=\"#FF00FF\", pch=22, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seta$flowrate, seta$X50), col=\"#EE0000\", pch=23, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlines(lowess(seta$flowrate, seta$X75), col=\"#EEAD0E\", pch=24, lwd=2.5, type=\"b\", lty=2)\r\n\r\nlegend(\"topright\", c(\"10Hz\", \"25Hz\", \"50Hz\", \"75Hz\"), inset=.05, col=c(\"#458B74\", \"#FF00FF\", \"#EE0000\", \"#EEAD0E\"), pch=c(21,22,23,24), lwd=1.5, lty=2, cex=1.2, bty=\"n\")\r\n\r\n#mtext(\"乙二醇 | H = 1mm | Nozzle 24G | Q = 0.0002ml/min | Fv = 20Hz | Duty = 20%\", 1, line=1, col=\"black\", cex=1.3, font=2, outer=TRUE)\r\n\r\n#dev.off()", "meta": {"hexsha": "e80d790a7c6d8368bfc775e251bed2b9e1a89b56", "size": 4497, "ext": "r", "lang": "R", "max_stars_repo_path": "Liquids/DOD/dod_frequency.r", "max_stars_repo_name": "shuaimeng/r", "max_stars_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Liquids/DOD/dod_frequency.r", "max_issues_repo_name": "shuaimeng/r", "max_issues_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Liquids/DOD/dod_frequency.r", "max_forks_repo_name": "shuaimeng/r", "max_forks_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_forks_repo_licenses": ["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.3368421053, "max_line_length": 200, "alphanum_fraction": 0.599510785, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4192687433265391}}
{"text": "model_soilevaporation <- function (diffusionLimitedEvaporation = 6605.505,\n energyLimitedEvaporation = 448.24){\n #'- Name: SoilEvaporation -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: SoilEvaporation 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: Starting from a soil at field capacity, soil evaporation is assumed to\n #' be energy limited during the first phase of evaporation and diffusion limited thereafter.\n #' Hence, the soil evaporation model considers these two processes taking the minimum between\n #' the energy limited evaporation (PtSoil) and the diffused limited\n #' evaporation \n #' * ShortDescription: Starting from a soil at field capacity, soil evaporation is assumed to\n #' be energy limited during the first phase of evaporation and diffusion limited thereafter.\n #' Hence, the soil evaporation model considers these two processes taking the minimum between\n #' the energy limited evaporation (PtSoil) and the diffused limited\n #' evaporation\n #'- inputs:\n #' * name: diffusionLimitedEvaporation\n #' ** description : diffusion Limited Evaporation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 6605.505\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: energyLimitedEvaporation\n #' ** description : energy Limited Evaporation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 448.240\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 #'- outputs:\n #' * name: soilEvaporation\n #' ** description : soil 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 soilEvaporation <- min(diffusionLimitedEvaporation, energyLimitedEvaporation)\n return (list('soilEvaporation' = soilEvaporation))\n}", "meta": {"hexsha": "043fa7c62dae3e1fa403fbbfb132ef5d2a0e489d", "size": 3235, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Energy_Balance/Soilevaporation.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/Soilevaporation.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/Soilevaporation.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": 62.2115384615, "max_line_length": 112, "alphanum_fraction": 0.4918083462, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4189524017027944}}
{"text": "\"\nFit Nicolas's model to the Colombia data.\n\"\nlibrary(RJSONIO)\nsource(\"contagious_infected/model.r\")\nsource(\"visualization.r\")\n\nparams = list(\n \"alpha\" = 2 ^ 40,\n \"beta_min\" = 0,\n \"beta_max\" = 2,\n \"gamma_min\" = 1/3,\n \"gamma_max\" = 1/3,\n \"lambda_min\" = 1/40,\n \"lambda_max\" = 1/4,\n \"N0_min\" = 0,\n \"N0_max\" = 2000,\n \"C0_min\" = 0,\n \"C0_max\" = 2000,\n \"t0\" = 1\n)\nbootstrap_params = list(\n \"number_samples\" = 500,\n \"window_size\" = 10,\n \"confidence\" = 0.95\n)\n# load data and initialize parameters\nload(\"CasosAjustados_Diagnostico.Rda\")\nobserved_I = data$`Estimados Totales`\nobserved_I = c(observed_I[1], 0, tail(observed_I, -1))\nobserved_I = observed_I[params$t0:length(observed_I)]\nfor (i in 1:100) {\n # params$beta0 = read.table(\"BetaInitials.txt\", quote=\"\\\"\", comment.char=\"\")$V1\n params$beta0 = runif(length(observed_I), params$beta_min, params$beta_max)\n params$gamma0 = runif(1, params$gamma_min, params$gamma_max)\n params$lambda0 = runif(1, params$lambda_min, params$lambda_max)\n params$N00 = runif(1, params$N0_min, params$N0_max)\n params$C00 = runif(1, params$C0_min, params$C0_max)\n params$observed_I = observed_I\n # fit Nicolas's model\n model = fit(observed_I=observed_I, beta0=params$beta0, beta_min=params$beta_min,\n beta_max=params$beta_max, gamma0=params$gamma0,\n gamma_min=params$gamma_min, gamma_max=params$gamma_max,\n lambda0=params$lambda0, lambda_min=params$lambda_min,\n lambda_max=params$lambda_max, N00=params$N00, N0_min=params$N0_min,\n N0_max=params$N0_max, C00=params$C00, C0_min=params$C0_min,\n C0_max=params$C0_max, alpha=params$alpha, ignore_beta_diff=27)\n # save fitted model and parameters\n timestamp = format(Sys.time(), \"%Y%m%d%H%M\")\n out_dir = paste(\"contagious_infected\", \"tuned\", timestamp, sep=\"/\")\n dir.create(out_dir, recursive=TRUE)\n write(toJSON(params), paste(out_dir, \"params.json\", sep=\"/\"))\n write(toJSON(model), paste(out_dir, \"model.json\", sep=\"/\"))\n # plot reproduction number series\n R = model$beta / model$lambda\n png(paste(out_dir, \"R(t).png\", sep=\"/\"))\n plot(R, xlab=\"t\", ylab=\"R(t)\", type=\"l\")\n dev.off()\n # plot expected new cases with confidence intervals\n expected_I = get_expected_I(model$N0, model$C0, model$beta, model$gamma, model$lambda)\n png(paste(out_dir, \"I(t).png\", sep=\"/\"))\n plot(1:length(expected_I), expected_I, type=\"l\")\n lines(1:length(observed_I), observed_I, col=\"red\")\n dev.off()\n}\n", "meta": {"hexsha": "d0eedaa4c1d3569759099401a23575484bdaa30f", "size": 2466, "ext": "r", "lang": "R", "max_stars_repo_path": "contagious_infected/Colombia.r", "max_stars_repo_name": "secg95/INS_COVID", "max_stars_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contagious_infected/Colombia.r", "max_issues_repo_name": "secg95/INS_COVID", "max_issues_repo_head_hexsha": "d3e1e9b2d83de9bbfb246c9be93624ffb4df88a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contagious_infected/Colombia.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": 37.3636363636, "max_line_length": 88, "alphanum_fraction": 0.6820762368, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4185780576594144}}
{"text": "#' Simulate data to test tryx\n#' \n#' # Create data using model here: https://www.draw.io/#G1VqjTd4iH2de7sXI4PhUrxazBnYLduH_w. Create summary data for all necessary traits, then perform tryx scan\n#' x = exposure\n#' y = outcome\n#' u1 = confounder of x and y\n#' u2 = mediator of horizontal pleiotropy from gx to y. One for each gx\n#' u3 = mediator between x and y\n#'\n#' @param nid = 10000 Number of samples\n#' @param ngx = 30 Number of direct instruments to x\n#' @param ngu1 = 30 Number of instruments influencing confounder of x and y\n#' @param ngu2 = 30 Number of instruments per mediating\n#' @param nu2 = 2 Number of gx that are pleiotropic\n#' @param ngu3 = 30 Number of instruments for u3 mediator\n#' @param vgx = 0.2 Variance explained by gx instruments\n#' @param vgu1 = 0.6 Variance explained by u1 instruments\n#' @param vgu2 = 0.2 Variance explained by u2 instruments\n#' @param vgu3 = 0.2 Variance explained by u3 instruments\n#' @param bxy = 0 Causal effect of x on y\n#' @param bu1x = 0.6 Effect of u1 on x\n#' @param bu1y = 0.4 Effect of u1 on y\n#' @param bxu3 = 0.3 Effect of x on u3\n#' @param bu3y = 0 Effect of u3 on y\n#' @param vgxu2 = 0.2 Variance explained by each gx instrument on each u2 mediator\n#' @param vu2y = 0.2 Variance explained by all u2 mediators on y\n#' @param ngxu3 = 0 Number of gx instruments that pleiotropically associate with u3 mediator\n#' @param vgxu3y = 0 Variance explained by all gx variants directly on u3 mediator\n#' @param mininum_instruments = 10 Minimum number of instruments required to have been detected to run simulation\n#' @param instrument_threshold = \"bonferroni\" Threshold, either numeric or 'bonferroni'\n#' @param outlier_threshold = \"bonferroni\" Threshold, either numeric or 'bonferroni'\n#' @param outliers_known = \"detected\" Either detected = using radial mr to find heterogeneity outliers; known = adjust for all known invalid instruments; all = adjust for all instruments\n#' @param directional_bias = FALSE Is the pleiotropic effect randomly centered around 0 (FALSE) or does it have a non-0 mean (TRUE)\n#'\n#' @export\n#' @return list for tryx.analyse\ntryx.simulate <- function(nid = 10000, ngx = 30, ngu1 = 30, ngu2 = 30, nu2 = 2, ngu3 = 30, vgx = 0.2, vgu1 = 0.6, vgu2 = 0.2, vgu3 = 0.2, bxy = 0, bu1x = 0.6, bu1y = 0.4, bxu3 = 0.3, bu3y = 0, vgxu2 = 0.2, vu2y = 0.2, ngxu3 = 0, vgxu3=0, mininum_instruments = 10, instrument_threshold = \"bonferroni\", outlier_threshold = \"bonferroni\", outliers_known = \"detected\", directional_bias = FALSE)\n{\n\tout <- list()\n\n\tmessage(\"Generating genetic effects\")\n\n\tgx <- make_geno(nid, ngx, 0.5)\n\tgu1 <- make_geno(nid, ngu1, 0.5)\n\tgu2 <- make_geno(nid, ngu2 * nu2, 0.5)\n\tgu3 <- make_geno(nid, ngu3, 0.5)\n\tu1 <- make_phen(choose_effects(ngu1, vgu1), gu1)\n\tx <- make_phen(c(abs(choose_effects(ngx, vgx)), bu1x), cbind(gx, u1))\n\tif(ngxu3 > 0)\n\t{\n\t\tu3 <- make_phen(c(choose_effects(ngu3, vgu3), bxu3, choose_effects(ngxu3, vgxu3)), cbind(gu3, x, gx[,sample(1:ngx, ngxu3)]))\n\t} else {\n\t\tu3 <- make_phen(c(choose_effects(ngu3, vgu3), bxu3), cbind(gu3, x))\n\t}\n\n\n\t# Some number of the direct gx SNPs also influence the outcome via a mediator\n\t# This is mediated pleiotropy\n\n\tmessage(\"Creating potential pleiotropy paths\")\n\n\tu2 <- matrix(rnorm(nid * nu2), nid, nu2)\n\tfor(i in 1:nu2)\n\t{\n\t\tmessage(\"SNP \", i, \" is pleiotropic\")\n\t\tu2[,i] <- make_phen(\n\t\t\tc(choose_effects(ngu2, vgu2), abs(choose_effects(1, vgxu2))),\n\t\t\tcbind(gu2[,((i-1) * ngu2 + 1):(ngu2 * i)], gx[,i])\n\t\t)\n\t}\n\n\tmessage(\"Creating outcome\")\n\n\tbu2y <- choose_effects(nu2, vu2y)\n\n\tif(directional_bias) \n\t{\n\t\tmessage(\"U2 bias is directional\")\n\t\tbu2y <- abs(bu2y)\n\t}\n\ty <- make_phen(\n\t\tc(bxy, bu3y, bu1y, bu2y),\n\t\tcbind(x, u3, u1, u2)\n\t)\n\n\t# Single genotype data source for simplicity\n\n\tG <- cbind(gx, gu1, gu2, gu3)\n\tG_annotation <- tibble(\n\t\tsnp=1:ncol(G),\n\t\torigin1=c(\n\t\t\trep(\"x\", ngx),\n\t\t\trep(\"u1\", ngu1),\n\t\t\trep(paste0(\"u2_\",1:nu2), each=ngu2),\n\t\t\trep(\"u3\", ngu3)\n\t\t),\n\t\torigin2=c(\n\t\t\trep(\"x\", ngx),\n\t\t\trep(\"u1\", ngu1),\n\t\t\trep(\"u2\", each=ngu2*nu2),\n\t\t\trep(\"u3\", ngu3)\n\t\t)\n\t)\n\n\t# How do we select instruments?\n\n\tif(instrument_threshold == \"bonferroni\")\n\t{\n\t\tinstrument_threshold <- 0.05 / ncol(G)\n\t} else {\n\t\tstopifnot(is.numeric(instrument_threshold))\n\t}\n\tmessage(\"instrument_threshold = \", instrument_threshold)\n\n\n\t# Get summary set\n\n\tmessage(\"Getting instruments\")\n\n\tout$dat_all <- get_effs(x, y, G, \"X\", \"Y\")\n\tout$dat <- subset(out$dat_all, pval.exposure < instrument_threshold)\n\tstopifnot(nrow(out$dat) > mininum_instruments)\n\tout$dat$mr_keep <- TRUE\n\tG_annotation$detected <- G_annotation$snp %in% out$dat$SNP\n\tmessage(\"Detected \", nrow(out$dat), \" associations for x\")\n\n\t## Determine valid instruments\n\n\tif(vu2y == 0)\n\t{\n\t\tvalid <- 1:ngx\n\t} else {\n\t\tvalid <- (1:ngx)[! (1:ngx %in% 1:nu2)]\n\t}\n\n\tif(bu1y == 0)\n\t{\n\t\tvalid <- c(valid, (ngx+1):(ngx+ngu1))\n\t}\n\tmessage(\"Valid instruments: \", paste(valid, collapse=\",\"))\n\tG_annotation$valid <- G_annotation$snp %in% valid\n\n\t## known invalid instruments\n\tinvalid <- which(! 1:ncol(G) %in% valid)\n\n\tout$valid <- valid\n\tout$invalid <- invalid\n\n\n\n\t# Get outliers\n\n\tno_outlier_flag <- FALSE\n\tif(outliers_known == \"known\")\n\t{\n\t\tmessage(\"Assuming knowledge of all outliers\")\n\t\toutliers <- out$dat$SNP[out$dat$SNP %in% invalid]\n\t} else if(outliers_known %in% c(\"detected\", \"all\")) {\n\t\tmessage(\"Detecting outliers\")\n\t\tradial <- RadialMR::ivw_radial(RadialMR::format_radial(out$dat$beta.exposure, out$dat$beta.outcome, out$dat$se.exposure, out$dat$se.outcome, out$dat$SNP), ifelse(outlier_threshold == \"bonferroni\", 0.05/nrow(out$dat), outlier_threshold), weights=3)\n\t\tif(radial$outliers[1] == \"No significant outliers\")\n\t\t{\n\t\t\tmessage(\"No significant outliers detected\")\n\t\t\toutliers <- as.character(out$dat$SNP[out$dat$SNP %in% invalid])\n\t\t\tif(length(outliers) == 0) outliers <- 1\n\t\t\tno_outlier_flag <- TRUE\n\t\t} else {\n\t\t\toutliers <- as.character(sort(radial$outliers$SNP))\n\t\t\tmessage(\"Number of outliers: \", length(outliers))\n\t\t}\n\t} else {\n\t\tstop(\"outliers_known must be 'known', 'detected' or 'all'\")\n\t}\n\n\tnout <- length(outliers)\n\toutliers <- subset(out$dat, SNP %in% outliers)$SNP\n\tout$outliers <- outliers\n\tif(outliers_known == \"all\")\n\t{\n\t\tmessage(\"Treating all variants as outliers\")\n\t\toutliers <- out$dat$SNP\n\t}\n\t# out$id_list <- c(paste0(\"U1_\", 1:nu1), paste0(\"U2_\", 1:nu2))\n\tmessage(\"Outliers to be analysed: \", paste(outliers, collapse=\",\"))\n\n\tmessage(\"Perform outlier scan\")\n\n\tU <- cbind(u1, u2, u3)\n\tcolnames(U) <- c(\"U1\", paste0(\"U2_\", 1:ncol(u2)), \"U3\")\n\toutlier_scan <- list()\n\tfor(i in 1:ncol(U))\n\t{\n\t\toutlier_scan[[colnames(U)[i]]] <- gwas(U[,i], G[,outliers, drop=FALSE])\n\t\toutlier_scan[[colnames(U)[i]]]$SNP <- outliers\n\t\toutlier_scan[[colnames(U)[i]]]$outcome <- colnames(U)[i]\n\t}\n\toutlier_scan <- bind_rows(outlier_scan)\n\tout$search <- tibble::tibble(\n\t\tSNP=outlier_scan$SNP, \n\t\tbeta.outcome=outlier_scan$bhat, \n\t\tse.outcome=outlier_scan$se, \n\t\tpval.outcome=outlier_scan$pval, \n\t\tid.outcome=outlier_scan$outcome, \n\t\toutcome=outlier_scan$outcome, \n\t\tmr_keep=TRUE, \n\t\teffect_allele.outcome=\"A\", \n\t\tother_allele.outcome=\"G\", \n\t\teaf.outcome=0.5\n\t)\n\tout$search$sig <- out$search$pval.outcome < 5e-8\n\tmessage(\"Found the following candidate traits: \", paste(unique(subset(out$search, sig)$id.outcome), collapse=\",\"))\n\n\n\tmessage(\"Organise data for mvmr\")\n\n\ttraitlist <- as.character(unique(subset(out$search, sig)$id.outcome))\n\tPHEN <- cbind(x, U[,traitlist])\n\tPHEN <- lapply(seq_len(ncol(PHEN)), function(i) PHEN[,i])\n\tnames(PHEN) <- c(\"x\", traitlist)\n\tmessage(\"Analysing \", length(PHEN), \" traits: \", paste(names(PHEN), collapse=\",\"))\n\n\tsnplist <- sapply(1:length(PHEN), function(x) {\n\t\tsubset(gwas(PHEN[[x]], G), pval < instrument_threshold)$snp\n\t}) %>% unlist() %>% sort %>% unique\n\tmessage(\"Found \", length(snplist), \" unique instruments\")\n\n\tmessage(\"Perform mvmr\")\n\tout$mvres <- try({\n\t\tmvdat <- make_mvdat(PHEN, y, G[,snplist])\n\t\tmvres <- mv_multiple(mvdat)\n\t\tmvres$result$exposure <- c(\"x\", traitlist)\n\t\tmvres\n\t})\n\n\n\tmessage(\"Building effects for \", length(traitlist), \" trait(s)\")\n\n\t## get effects\n\tux <- list()\n\tuy <- list()\n\tfor(i in traitlist)\n\t{\n\t\tmessage(i)\n\t\tux[[i]] <- get_effs(U[,i], x, G, i, \"X\") %>% subset(pval.exposure < instrument_threshold)\n\t\tuy[[i]] <- get_effs(U[,i], y, G, i, \"Y\") %>% subset(pval.exposure < instrument_threshold)\n\t\tif(nrow(ux[[i]]) > 0)\n\t\t{\n\t\t\tux[[i]]$effect_allele.exposure <- \"A\"\n\t\t\tux[[i]]$other_allele.exposure <- \"G\"\n\t\t\tux[[i]]$effect_allele.outcome <- \"A\"\n\t\t\tux[[i]]$other_allele.outcome <- \"G\"\n\t\t\tux[[i]]$eaf.exposure <- 0.5\n\t\t\tux[[i]]$eaf.outcome <- 0.5\n\t\t}\n\n\t\tif(nrow(uy[[i]]) > 0)\n\t\t{\n\t\t\tuy[[i]]$effect_allele.exposure <- \"A\"\n\t\t\tuy[[i]]$other_allele.exposure <- \"G\"\n\t\t\tuy[[i]]$effect_allele.outcome <- \"A\"\n\t\t\tuy[[i]]$other_allele.outcome <- \"G\"\n\t\t\tuy[[i]]$eaf.exposure <- 0.5\n\t\t\tuy[[i]]$eaf.outcome <- 0.5\t\t\n\t\t}\n\t}\n\n\tout$candidate_instruments <- subset(bind_rows(ux), select=c(\n\t\tSNP, beta.exposure, se.exposure, id.exposure, exposure, effect_allele.exposure, other_allele.exposure, eaf.exposure, pval.exposure\n\t))\n\n\tmessage(\"Removing known outliers from candidate instruments\")\n\n\tout2 <- subset(out$search, sig)\n\tout$candidate_instruments <- group_by(out$candidate_instruments, id.exposure) %>%\n\t\tdo({\n\t\t\tx <- .\n\t\t\ty <- subset(out2, id.outcome == x$id.exposure[1])\n\t\t\tx <- subset(x, !SNP %in% y$SNP)\n\t\t\tx\n\t\t})\n\n\tmessage(\"MR of candidates on outcome\")\n\n\tout$candidate_outcome <- subset(bind_rows(uy), select=c(\n\t\tSNP, beta.outcome, se.outcome, id.outcome, outcome, effect_allele.outcome, other_allele.outcome, eaf.outcome, pval.outcome\n\t))\n\n\t# out$candidate_outcome_dat <- suppressMessages(harmonise_data(out$candidate_instruments, out$candidate_outcome))\n\tout$candidate_outcome_dat <- harmonise_data(out$candidate_instruments, out$candidate_outcome)\n\tout$candidate_outcome_mr <- suppressMessages(mr(out$candidate_outcome_dat, method_list=\"mr_ivw\"))\n\n\n\tmessage(\"MR of candidates on exposure\")\n\n\tout$candidate_exposure <- subset(bind_rows(ux), select=c(\n\t\tSNP, beta.outcome, se.outcome, id.outcome, outcome, effect_allele.outcome, other_allele.outcome, eaf.outcome, pval.outcome\n\t))\n\n\t# out$candidate_exposure_dat <- suppressMessages(harmonise_data(out$candidate_instruments, out$candidate_exposure))\n\tout$candidate_exposure_dat <- harmonise_data(out$candidate_instruments, out$candidate_exposure)\n\tout$candidate_exposure_mr <- suppressMessages(mr(out$candidate_exposure_dat, method_list=\"mr_ivw\"))\n\n\tmessage(\"Finalising\")\n\tout$G_annotation <- G_annotation\n\tout$simulation <- list()\n\tout$simulation$no_outlier_flag <- no_outlier_flag\n\tout$simulation$nid <- nid\n\tout$simulation$ngx <- ngx\n\tout$simulation$ngu1 <- ngu1\n\tout$simulation$ngu2 <- ngu2\n\tout$simulation$nu2 <- nu2\n\tout$simulation$ngu3 <- ngu3\n\tout$simulation$vgx <- vgx\n\tout$simulation$vgu1 <- vgu1\n\tout$simulation$vgu2 <- vgu2\n\tout$simulation$vgu3 <- vgu3\n\tout$simulation$bxy <- bxy\n\tout$simulation$bu1x <- bu1x\n\tout$simulation$bu1y <- bu1y\n\tout$simulation$bxu3 <- bxu3\n\tout$simulation$bu3y <- bu3y\n\tout$simulation$vgxu2 <- vgxu2\n\tout$simulation$vu2y <- vu2y\n\tout$simulation$ngxu3 <- ngxu3\n\tout$simulation$vgxu3 <- vgxu3\n\tout$simulation$mininum_instruments <- mininum_instruments\n\tout$simulation$instrument_threshold <- instrument_threshold\n\tout$simulation$outlier_threshold <- outlier_threshold\n\tout$simulation$outliers_known <- outliers_known\n\tout$simulation$directional_bias = directional_bias\n\tout$simulation$n_instruments <- sum(G_annotation$detected)\n\tout$simulation$n_valid_instruments <- sum(G_annotation$detected * G_annotation$valid)\n\n\nreturn(out)\n}\n\n\n\n\n\n\n\n\n\n# #' Simulate data to test tryx\n# #' \n# #' Choose a sample size, number of horizontal pleiotropy paths, and number of confounders. Create summary data for all necessary traits, then perform tryx scan\n# #' \n# #' @param nid Sample size to simulate\n# #' @param nu1 Number of traits which influence both X and Y\n# #' @param nu2 Number of traits which influence Y\n# #' @param bxu3 Effect of x on mediator\n# #' @param bu3y Effect of mediator on y\n# #' @param bxy Causal effect of X on Y\n# #' @param outliers_known Assume that all outliers are detected (default = 'known'). But can also be 'detected', where we use heterogeneity based outlier detection, or 'all' where we try to adjust for every outlier regardless of heterogeneity\n# #' @param directional_bias Is the outlier typically in one direction (i.e. unbalanced pleiotropy?)\n# #' @param outlier_threshold Either 'nominal' or 'bonferroni'\n# #' @param single_pleiotropy_trait = FALSE\n# #' \n# #' @export\n# #' @return Results from simulations and tryx scan\n# tryx.simulate <- function(nid, nu1, nu2, bxu3=0, bu3y=0, bxy=3, outliers_known=c(\"known\", \"detected\", \"all\")[1], directional_bias=FALSE, outlier_threshold = 'nominal', single_pleiotropy_trait = FALSE, debug=FALSE, ngu4=10, ngx=30, bu4x=0, bu4y=0)\n# {\n# \t# scenario 1 - confounder g -> u; u -> x; u -> y\n# \t# scenario 2 - pleiotropy g -> u -> y\n# \t# scenario 3 - mediator\n# \t# scenario 4 - \n\n# \tout <- list()\n\n# \tcpg <- require(simulateGP)\n# \tif(!cpg)\n# \t{\n# \t\tstop(\"Please install the simulateGP package\\ndevtools::install_github('explodecomputer/simulateGP')\")\n# \t}\n\n# \tngu1 <- 30\n# \tngu2 <- 30\n# \tngu3 <- 30\n# \tnu3 <- 1\n# \tnu4 <- 1\n# \tnu <- nu1 + nu2 + nu3\n# \tstopifnot(ngx >= nu)\n\n# \tgx <- make_geno(nid, ngx, 0.5)\n# \tout$true_outliers <- 1:nu\n\n# \t# Effect sizes\n# \tbgu1 <- lapply(1:nu1, function(x) runif(ngu1))\n# \tbgu2 <- lapply(1:nu2, function(x) runif(ngu2))\n# \tbgu3 <- runif(ngu3)\n# \tbgx <- runif(ngx)\n\n# \tbu1x <- out$bu1x <- rnorm(nu1)\n# \tbu1y <- out$bu1y <- rnorm(nu1)\n# \tbu2y <- out$bu2y <- rnorm(nu2)\n# \tif(directional_bias)\n# \t{\n# \t\tbu1x <- out$bu1x <- abs(bu1x)\n# \t\tbu1y <- out$bu1y <- abs(bu1y)\n# \t\tbu2y <- out$bu2y <- abs(bu2y)\n# \t}\n# \tout$bxu3 <- bxu3\n# \tbu3y <- out$bu3y <- bu3y\n# \tbxy <- out$bxy <- bxy\n\n# \t# create outlier traits\n# \tgu1 <- list()\n# \tu1 <- matrix(rnorm(nid * ngx), nid, ngx)\n# \tif(nu1 > 0)\n# \t{\n# \t\tfor(i in 1:nu1)\n# \t\t{\n# \t\t\tgu1[[i]] <- cbind(gx[,i], make_geno(nid, ngu1-1, 0.5))\n# \t\t\tif(single_pleiotropy_trait)\n# \t\t\t{\n# \t\t\t\tu1[,1] <- u1[,1] + gu1[[i]] %*% bgu1[[i]]\n# \t\t\t} else {\n# \t\t\t\tu1[,i] <- gu1[[i]] %*% bgu1[[i]] + rnorm(nid)\n# \t\t\t}\n# \t\t}\n# \t}\n\n# \tgu2 <- list()\n# \tu2 <- matrix(rnorm(nid * ngx), nid, ngx)\n# \tif(nu2 > 0)\n# \t{\n# \t\tfor(j in 1:nu2)\n# \t\t{\n# \t\t\tgu2[[j]] <- cbind(gx[,i+j], make_geno(nid, ngu1-1, 0.5))\n# \t\t\tif(single_pleiotropy_trait)\n# \t\t\t{\n# \t\t\t\tu2[,1] <- u2[,1] + gu2[[j]] %*% bgu2[[j]]\n# \t\t\t} else {\n# \t\t\t\tu2[,j] <- gu2[[j]] %*% bgu2[[j]] + rnorm(nid)\n# \t\t\t}\n# \t\t}\n# \t}\n\n# \tu4 <- rnorm(nid)\n# \tif(ngu4 > 0)\n# \t{\n# \t\tu4 <- u4 + gx[,1:ngu4] %*% runif(ngu4)\n# \t}\n# \tx <- drop(gx[,c((ngu4+1):ngx)] %*% bgx[c((ngu4+1):ngx)] + u4 %*% bu4x + u1 %*% bu1x + rnorm(nid))\n\t\n# \tgu3 <- list(make_geno(nid, ngu3, 0.5))\n# \tu3 <- matrix(gu3[[1]] %*% bgu3 + x * bxu3 + rnorm(nid), nid, 1)\n\n# \ty <- drop(x * bxy + u1 %*% bu1y + u2 %*% bu2y + u3 * bu3y + u4 %*% bu4y + rnorm(nid))\n\n# \tout$dat <- get_effs(x, y, gx, \"X\", \"Y\")\n# \tout$dat$mr_keep <- TRUE\n# \tno_outlier_flag <- FALSE\n\n# \tif(outliers_known == \"known\")\n# \t{\n# \t\tmessage(\"Assuming knowledge of all outliers\")\n# \t\toutliers <- as.character(c(1:nu))\n# \t} else if(outliers_known %in% c(\"detected\", \"all\")) {\n# \t\tmessage(\"Detecting outliers\")\n# \t\tradial <- RadialMR::ivw_radial(RadialMR::format_radial(out$dat$beta.exposure, out$dat$beta.outcome, out$dat$se.exposure, out$dat$se.outcome, out$dat$SNP), ifelse(outlier_threshold == \"nominal\", 0.05, 0.05/nrow(out$dat)))\n# \t\tif(radial$outliers[1] == \"No significant outliers\")\n# \t\t{\n# \t\t\tmessage(\"No significant outliers detected\")\n# \t\t\toutliers <- as.character(c(1:nu))\n# \t\t\tno_outlier_flag <- TRUE\n# \t\t} else {\n# \t\t\toutliers <- as.character(sort(radial$outliers$SNP))\n# \t\t\tmessage(\"Number of outliers: \", length(outliers))\n# \t\t}\n# \t} else {\n# \t\tstop(\"outliers_known must be known, detected or all\")\n# \t}\n# \t# output$radialmr <- radial\n# \tnout <- length(outliers)\n# \toutliers <- subset(out$dat, SNP %in% outliers)$SNP\n# \tout$outliers <- outliers\n# \tif(outliers_known == \"all\")\n# \t{\n# \t\tmessage(\"Treating all variants as outliers\")\n# \t\toutliers <- 1:ngx\n# \t}\n# \tout$id_list <- c(paste0(\"U1_\", 1:nu1), paste0(\"U2_\", 1:nu2))\n\n# \t# temp1 <- gwas(u1, gx[,1:2])\n\n# \ttemp <- list()\n# \tfor(i in 1:nu1)\n# \t{\n# \t\ttemp[[i]] <- gwas(u1[,i], gx[,outliers, drop=FALSE])\n# \t\ttemp[[i]]$SNP <- outliers\n# \t\ttemp[[i]]$outcome <- paste0(\"U1_\", i)\n# \t}\n# \tfor(i in 1:nu2)\n# \t{\n# \t\ttemp[[i + nu1]] <- gwas(u2[,i], gx[,outliers, drop=FALSE])\n# \t\ttemp[[i + nu1]]$SNP <- outliers\n# \t\ttemp[[i + nu1]]$outcome <- paste0(\"U2_\", i)\n# \t}\n# \tfor(i in 1:nu3)\n# \t{\t\n# \t\ttemp[[i + nu1 + nu2]] <- gwas(u3[,i], gx[,outliers, drop=FALSE])\n# \t\ttemp[[i + nu1 + nu2]]$SNP <- outliers\n# \t\ttemp[[i + nu1 + nu2]]$outcome <- paste0(\"U3_\", i)\n# \t}\n# \tfor(i in 1:nu4)\n# \t{\t\n# \t\ttemp[[i + nu1 + nu2 + nu3]] <- gwas(u4[,i], gx[,outliers, drop=FALSE])\n# \t\ttemp[[i + nu1 + nu2 + nu3]]$SNP <- outliers\n# \t\ttemp[[i + nu1 + nu2 + nu3]]$outcome <- paste0(\"U4_\", i)\n# \t}\n\n# \ttemp <- bind_rows(temp)\n\n# \tout$search <- tibble::data_frame(SNP=temp$SNP, beta.outcome=temp$bhat, se.outcome=temp$se, pval.outcome=temp$pval, id.outcome=temp$outcome, outcome=temp$outcome, mr_keep=TRUE, effect_allele.outcome=\"A\", other_allele.outcome=\"G\", eaf.outcome=0.5)\n# \tout$search$sig <- out$search$pval.outcome < 5e-8\n\n# \t## Multivariable MR\n# \t# Do mvmr with just the outlier detected traits\n\n# \ttraitlist <- as.character(unique(subset(out$search, sig)$id.outcome))\n# \tG <- list()\n# \tPHEN <- list(x)\n# \tj <- 2\n# \tif(any(grepl(\"U1\", traitlist)))\n# \t{\n# \t\tu1traits <- gsub(\"U1_\", \"\", traitlist[grepl(\"U1\", traitlist)]) %>% as.numeric()\n# \t\tmessage(\"U1 traits: \", paste(u1traits, collapse=\",\"))\n# \t\tG[[1]] <- lapply(u1traits, function(x) {\n# \t\t\treturn(gu1[[x]][,-1])\n# \t\t}) %>% do.call(cbind, .)\n# \t\tfor(i in u1traits)\n# \t\t{\n# \t\t\tPHEN[[j]] <- u1[,i]\n# \t\t\tj <- j + 1\n# \t\t}\n# \t}\n# \tif(any(grepl(\"U2\", traitlist)))\n# \t{\n# \t\tu2traits <- gsub(\"U2_\", \"\", traitlist[grepl(\"U2\", traitlist)]) %>% as.numeric()\n# \t\tmessage(\"U2 traits: \", paste(u2traits, collapse=\",\"))\n# \t\tG[[2]] <- lapply(u2traits, function(x) {\n# \t\t\treturn(gu2[[x]][,-1])\n# \t\t}) %>% do.call(cbind, .)\n# \t\tfor(i in u2traits)\n# \t\t{\n# \t\t\tPHEN[[j]] <- u2[,i]\n# \t\t\tj <- j + 1\n# \t\t}\n# \t}\n# \tif(any(grepl(\"U3\", traitlist)))\n# \t{\n# \t\tu3traits <- gsub(\"U3_\", \"\", traitlist[grepl(\"U3\", traitlist)]) %>% as.numeric()\n# \t\tmessage(\"U3 traits: \", paste(u3traits, collapse=\",\"))\n# \t\tG[[3]] <- lapply(u3traits, function(x) {\n# \t\t\treturn(gu3[[x]])\n# \t\t}) %>% do.call(cbind, .)\n# \t\tfor(i in u3traits)\n# \t\t{\n# \t\t\tPHEN[[j]] <- u3[,i]\n# \t\t\tj <- j + 1\n# \t\t}\n# \t}\n# \tif(any(grepl(\"U4\", traitlist)))\n# \t{\n# \t\tu4traits <- gsub(\"U4_\", \"\", traitlist[grepl(\"U4\", traitlist)]) %>% as.numeric()\n# \t\tmessage(\"U4 traits: \", paste(u4traits, collapse=\",\"))\n# \t\tG[[4]] <- lapply(u4traits, function(x) {\n# \t\t\treturn(gx)\n# \t\t}) %>% do.call(cbind, .)\n# \t\tfor(i in u4traits)\n# \t\t{\n# \t\t\tPHEN[[j]] <- u4[,i]\n# \t\t\tj <- j + 1\n# \t\t}\n# \t}\n# \tG[[5]] <- gx\n# \tG <- do.call(cbind, G)\n# \ttraitlist <- c(\"X\", traitlist)\n# \tnames(PHEN) <- traitlist\n\n# \tout$mvres <- try({\n# \t\tmvdat <- make_mvdat(PHEN, y, G)\n# \t\tmvres <- mv_multiple(mvdat)\n# \t\tmvres$result$exposure <- traitlist\n# \t\tmvres\n# \t})\n# \t## get effects\n# \tu1x <- list()\n# \tu1y <- list()\n# \tfor(i in 1:nu1)\n# \t{\n# \t\tu1x[[i]] <- get_effs(u1[,i], x, gu1[[i]], paste0(\"U1_\", i), \"X\")\n# \t\tu1y[[i]] <- get_effs(u1[,i], y, gu1[[i]], paste0(\"U1_\", i), \"Y\")\n# \t\tu1x[[i]]$SNP <- u1y[[i]]$SNP <- c(i, paste0(\"u1_\",1:(ngu1-1)))\n# \t\tu1x[[i]]$effect_allele.exposure <- u1y[[i]]$effect_allele.exposure <- \"A\"\n# \t\tu1x[[i]]$other_allele.exposure <- u1y[[i]]$other_allele.exposure <- \"G\"\n# \t\tu1x[[i]]$effect_allele.outcome <- u1y[[i]]$effect_allele.outcome <- \"A\"\n# \t\tu1x[[i]]$other_allele.outcome <- u1y[[i]]$other_allele.outcome <- \"G\"\n# \t\tu1x[[i]]$eaf.exposure <- u1y[[i]]$eaf.exposure <- 0.5\n# \t\tu1x[[i]]$eaf.outcome <- u1y[[i]]$eaf.outcome <- 0.5\n# \t}\n\n# \tu2x <- list()\n# \tu2y <- list()\n# \tfor(i in 1:nu2)\n# \t{\n# \t\tu2x[[i]] <- get_effs(u2[,i], x, gu2[[i]], paste0(\"U2_\", i), \"X\")\n# \t\tu2y[[i]] <- get_effs(u2[,i], y, gu2[[i]], paste0(\"U2_\", i), \"Y\")\n# \t\tu2x[[i]]$SNP <- u2y[[i]]$SNP <- c(i+nu1, paste0(\"u2_\",1:(ngu2-1)))\n# \t\tu2x[[i]]$effect_allele.exposure <- u2y[[i]]$effect_allele.exposure <- \"A\"\n# \t\tu2x[[i]]$other_allele.exposure <- u2y[[i]]$other_allele.exposure <- \"G\"\n# \t\tu2x[[i]]$effect_allele.outcome <- u2y[[i]]$effect_allele.outcome <- \"A\"\n# \t\tu2x[[i]]$other_allele.outcome <- u2y[[i]]$other_allele.outcome <- \"G\"\n# \t\tu2x[[i]]$eaf.exposure <- u2y[[i]]$eaf.exposure <- 0.5\n# \t\tu2x[[i]]$eaf.outcome <- u2y[[i]]$eaf.outcome <- 0.5\n# \t}\n\n# \tu3x <- list()\n# \tu3y <- list()\n# \tfor(i in 1:nu3)\n# \t{\n# \t\tu3x[[i]] <- get_effs(u3[,i], x, gu3[[i]], paste0(\"U3_\", i), \"X\")\n# \t\tu3y[[i]] <- get_effs(u3[,i], y, gu3[[i]], paste0(\"U3_\", i), \"Y\")\n# \t\tu3x[[i]]$SNP <- u3y[[i]]$SNP <- c(i+nu1, paste0(\"u3_\",1:(ngu3-1)))\n# \t\tu3x[[i]]$effect_allele.exposure <- u3y[[i]]$effect_allele.exposure <- \"A\"\n# \t\tu3x[[i]]$other_allele.exposure <- u3y[[i]]$other_allele.exposure <- \"G\"\n# \t\tu3x[[i]]$effect_allele.outcome <- u3y[[i]]$effect_allele.outcome <- \"A\"\n# \t\tu3x[[i]]$other_allele.outcome <- u3y[[i]]$other_allele.outcome <- \"G\"\n# \t\tu3x[[i]]$eaf.exposure <- u3y[[i]]$eaf.exposure <- 0.5\n# \t\tu3x[[i]]$eaf.outcome <- u3y[[i]]$eaf.outcome <- 0.5\n# \t}\n\n# \tu4x <- list()\n# \tu4y <- list()\n# \tfor(i in 1:nu4)\n# \t{\n# \t\tu4x[[i]] <- get_effs(u4[,i], x, gx[,1:ngu4], paste0(\"U4_\", i), \"X\")\n# \t\tu4y[[i]] <- get_effs(u4[,i], y, gx[,1:ngu4], paste0(\"U4_\", i), \"Y\")\n# \t\tu4x[[i]]$SNP <- u4y[[i]]$SNP <- c(i+nu1, paste0(\"u4_\",1:(ngu4-1)))\n# \t\tu4x[[i]]$effect_allele.exposure <- u4y[[i]]$effect_allele.exposure <- \"A\"\n# \t\tu4x[[i]]$other_allele.exposure <- u4y[[i]]$other_allele.exposure <- \"G\"\n# \t\tu4x[[i]]$effect_allele.outcome <- u4y[[i]]$effect_allele.outcome <- \"A\"\n# \t\tu4x[[i]]$other_allele.outcome <- u4y[[i]]$other_allele.outcome <- \"G\"\n# \t\tu4x[[i]]$eaf.exposure <- u4y[[i]]$eaf.exposure <- 0.5\n# \t\tu4x[[i]]$eaf.outcome <- u4y[[i]]$eaf.outcome <- 0.5\n# \t}\n\n\n# \tout$candidate_instruments <- subset(rbind(bind_rows(u1x), bind_rows(u2x), bind_rows(u3x)), select=c(\n# \t\tSNP, beta.exposure, se.exposure, id.exposure, exposure, effect_allele.exposure, other_allele.exposure, eaf.exposure, pval.exposure\n# \t))\n# \tout2 <- subset(out$search, sig)\n# \tout$candidate_instruments <- group_by(out$candidate_instruments, id.exposure) %>%\n# \t\tdo({\n# \t\t\tx <- .\n# \t\t\ty <- subset(out2, id.outcome == x$id.exposure[1])\n# \t\t\tx <- subset(x, !SNP %in% y$SNP)\n# \t\t\tx\n# \t\t})\n\n# \tout$candidate_outcome <- subset(rbind(bind_rows(u1y), bind_rows(u2y), bind_rows(u3y)), select=c(\n# \t\tSNP, beta.outcome, se.outcome, id.outcome, outcome, effect_allele.outcome, other_allele.outcome, eaf.outcome, pval.outcome\n# \t))\n\n# \t# out$candidate_outcome_dat <- suppressMessages(harmonise_data(out$candidate_instruments, out$candidate_outcome))\n# \tout$candidate_outcome_dat <- bind_rows(bind_rows(u1y), bind_rows(u2y), bind_rows(u3y))\n# \tout$candidate_outcome_mr <- suppressMessages(mr(out$candidate_outcome_dat, method_list=\"mr_ivw\"))\n\n\n# \tout$candidate_exposure <- subset(rbind(bind_rows(u1x), bind_rows(u2x), bind_rows(u3x)), select=c(\n# \t\tSNP, beta.outcome, se.outcome, id.outcome, outcome, effect_allele.outcome, other_allele.outcome, eaf.outcome, pval.outcome\n# \t))\n\n# \t# out$candidate_exposure_dat <- suppressMessages(harmonise_data(out$candidate_instruments, out$candidate_exposure))\n# \tout$candidate_exposure_dat <- bind_rows(bind_rows(u1x), bind_rows(u2x), bind_rows(u3x))\n# \tout$candidate_exposure_mr <- suppressMessages(mr(out$candidate_exposure_dat, method_list=\"mr_ivw\"))\n\n\n# \tout$simulation <- list()\n# \tout$simulation$no_outlier_flag <- no_outlier_flag\n# \tout$simulation$nu1 <- nu1\n# \tout$simulation$nu2 <- nu2\n# \tout$simulation$nu3 <- nu3\n# \tout$simulation$bxu3 <- bxu3\n# \tout$simulation$bu3y <- bu3y\n# \tout$simulation$outliers_known <- outliers_known\n# \tout$simulation$bxy <- bxy\n\n# \tif(debug)\n# \t{\n# \t\tout$phen <- list(\n# \t\t\ty=y, x=x, u1=u1, u2=u2, u3=u3, u4=u4\n# \t\t)\n# \t}\n# \treturn(out)\n# }\n\n", "meta": {"hexsha": "cd63ab6b32d067c429c25f3295afa35535d0e0b8", "size": 23854, "ext": "r", "lang": "R", "max_stars_repo_path": "R/simulations.r", "max_stars_repo_name": "explodecomputer/tryx", "max_stars_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-03-14T14:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T15:46:39.000Z", "max_issues_repo_path": "R/simulations.r", "max_issues_repo_name": "explodecomputer/tryx", "max_issues_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-02-17T23:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T07:42:06.000Z", "max_forks_repo_path": "R/simulations.r", "max_forks_repo_name": "explodecomputer/tryx", "max_forks_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-13T13:29:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T13:29:03.000Z", "avg_line_length": 34.0285306705, "max_line_length": 389, "alphanum_fraction": 0.6404795841, "num_tokens": 8880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4182356059384569}}
{"text": "#' Uses an ARTMAP network to classify the given input data.\n#' \n#' This function uses an ARTMAP network to classify the given input data with \n#' the specified vigilance parameter. Each sample of the data is presented to\n#' the network, which classifies each sample. The function returns the \n#' classification of each sample. If the classification of the sample requires\n#' that a new category be created, the class for that sample is set to -1.\n#' @title ARTMAP_Classify\n#' @param artmap_network The trained ARTMAP network. It should be created with ARTMAP_Create_Network() and trained with ARTMAP_Learn()\n#' @param data Classification data to be presented to the network. It is a matrix of size NumFeatures-by-NumSamples.\n#' @return Vector of size NumSamples that holds the class in which the ARTMAP network placed each sample.\n#' @export\nARTMAP_Classify=function(artmap_network, data)\n{\n # Make sure the user specifies the input parameters.\n if(nargs() != 2)\n {\n stop('You must specify both input parameters.');\n }\n \n # Make sure that the data is appropriate for the given network.\n numFeatures = ncol(data);\n numSamples = nrow(data);\n \n if(numFeatures != artmap_network$numFeatures)\n {\n stop('The data does not contain the same number of features as the network.');\n }\n \n # Make sure the vigilance is within the (0, 1] range.\n if((artmap_network$vigilance <= 0) | (artmap_network$vigilance > 1))\n {\n stop('The vigilance must be within the range (0, 1].');\n }\n \n # Set up the return variables.\n classification = matrix(0,numSamples,1);\n \n # Classify and learn on each sample.\n for (sampleNumber in 1:numSamples)\n {\n # Get the current data sample.\n currentData = data[sampleNumber,];\n \n # Activate the categories for this sample.\n bias = artmap_network$bias;\n categoryActivation = ART_Activate_Categories(currentData, artmap_network$weight, bias);\n \n # Rank the activations in order from highest to lowest.\n # This will allow us easier access to step through the categories.\n auxList = sort(-categoryActivation,index.return=TRUE);\n sortedActivations=auxList[[1]];\n sortedCategories=auxList[[2]];\n # Go through each category in the sorted list looking for the best match.\n resonance = 0;\n match = 0;\n numSortedCategories = length(sortedCategories);\n currentSortedIndex = 1;\n while(!resonance)\n {\n \n # If there are no categories, we return a -1.\n if(numSortedCategories == 0)\n {\n classification[sampleNumber,1] = -1;\n resonance = 1;\n break;\n }\n \n # Get the current category based on the sorted index.\n currentCategory = sortedCategories[currentSortedIndex];\n \n # Get the current weight vector from the sorted category list.\n currentWeightVector = artmap_network$weight[currentCategory,];\n \n # Calculate the match given the current data sample and weight vector.\n match = ART_Calculate_Match(currentData, currentWeightVector);\n \n # Check to see if the match is less than the vigilance.\n if(match < artmap_network$vigilance)\n {\n # If so, choose the next category in the sorted category list.\n # If the current category is the last in the list, set the \n # category for the return value as -1 and induce resonance.\n if(currentSortedIndex == numSortedCategories)\n {\n classification[sampleNumber,] = -1;\n resonance = 1;\n }\n else\n {\n currentSortedIndex = currentSortedIndex + 1;\n } \n } \n else\n { \n # Otherwise, the current category codes the input.\n # Therefore, we should induce resonance.\n classification[sampleNumber,] = artmap_network$mapField[currentCategory,];\n resonance = 1; \n }\n } \n }\n return (classification);\n}", "meta": {"hexsha": "66eeecdffb8df2cdb7257d798ad1db138797c196", "size": 3887, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ARTMAP_Classify.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/ARTMAP_Classify.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/ARTMAP_Classify.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.019047619, "max_line_length": 134, "alphanum_fraction": 0.6753280165, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.41770608521530833}}
{"text": "score <- function(input) {\n var0 <- subroutine0(input)\n var1 <- subroutine1(input)\n var2 <- subroutine2(input)\n var3 <- subroutine3(input)\n var4 <- subroutine4(input)\n var5 <- subroutine5(input)\n var6 <- subroutine6(input)\n var7 <- subroutine7(input)\n var8 <- subroutine8(input)\n var9 <- subroutine9(input)\n var10 <- subroutine10(input)\n var11 <- subroutine11(input)\n var12 <- subroutine12(input)\n var13 <- subroutine13(input)\n var14 <- subroutine14(input)\n var15 <- subroutine15(input)\n var16 <- subroutine16(input)\n var17 <- subroutine17(input)\n var18 <- subroutine18(input)\n var19 <- subroutine19(input)\n var20 <- subroutine20(input)\n var21 <- subroutine21(input)\n var22 <- subroutine22(input)\n var23 <- subroutine23(input)\n var24 <- subroutine24(input)\n var25 <- subroutine25(input)\n var26 <- subroutine26(input)\n var27 <- subroutine27(input)\n var28 <- subroutine28(input)\n var29 <- subroutine29(input)\n var30 <- subroutine30(input)\n var31 <- subroutine31(input)\n var32 <- subroutine32(input)\n var33 <- subroutine33(input)\n var34 <- (var21) * (-29.893441720221567)\n return(c((((((((((((((((((((((-0.10040896360166912) + ((var0) * (-0.0))) + ((var1) * (-0.0))) + ((var2) * (-0.41839590533727394))) + ((var3) * (-0.0))) + ((var4) * (-0.04143676373258231))) + ((var5) * (-0.41839590533727394))) + ((var6) * (-0.41839590533727394))) + ((var7) * (-0.0))) + ((var8) * (-0.09370933375375942))) + ((var9) * (-0.021427693031370827))) + ((var10) * (-0.19906272901896646))) + ((var11) * (-0.41839590533727394))) + ((var12) * (0.01790941942476885))) + ((var13) * (0.19838472644676905))) + ((var14) * (0.41839590533727394))) + ((var15) * (0.0))) + ((var16) * (0.41839590533727394))) + ((var17) * (0.13934237366514107))) + ((var18) * (0.0))) + ((var19) * (0.41839590533727394))) + ((var20) * (0.41839590533727394)), ((((((((((((((((((((((-0.18554309515982967) + ((var21) * (-0.06950455855790763))) + ((var22) * (-0.0))) + ((var23) * (-0.04843045931251089))) + ((var24) * (-0.0))) + ((var25) * (-0.3538789357824905))) + ((var26) * (-0.0609756100198299))) + ((var27) * (-0.11288644645628641))) + ((var28) * (-0.3538789357824905))) + ((var29) * (-0.30936738135098624))) + ((var30) * (-0.3538789357824905))) + ((var31) * (-0.0))) + ((var32) * (-0.08889946907833211))) + ((var33) * (-0.0))) + ((var12) * (0.14642472878044094))) + ((var13) * (0.11750372941413528))) + ((var14) * (0.3538789357824905))) + ((var15) * (0.3538789357824905))) + ((var16) * (0.0))) + ((var17) * (0.0722565307987864))) + ((var18) * (0.3538789357824905))) + ((var19) * (0.3538789357824905))) + ((var20) * (0.0)), (((((((((((((((((((((((((0.5039648533253523) + (var34)) + ((var22) * (-29.893441720221567))) + ((var23) * (-0.0))) + ((var24) * (-23.66820011477251))) + ((var25) * (-0.0))) + ((var26) * (-0.0))) + ((var27) * (-0.0))) + ((var28) * (-7.128872495868185))) + ((var29) * (-19.888600728398526))) + ((var30) * (-0.4282859091720985))) + ((var31) * (-5.683580020209366))) + ((var32) * (-0.0))) + ((var33) * (-29.893441720221567))) + ((var0) * (15.40619227503478))) + ((var1) * (11.497905273164342))) + ((var2) * (0.0))) + ((var3) * (29.893441720221567))) + ((var4) * (29.893441720221567))) + ((var5) * (0.0))) + ((var6) * (0.0))) + ((var7) * (29.893441720221567))) + ((var8) * (29.893441720221567))) + ((var9) * (0.0))) + ((var10) * (0.0))) + ((var11) * (0.0))))\n}\nsubroutine0 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.4) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((4.5) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine1 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.2) - (input[1])) ^ (2)) + (((2.2) - (input[2])) ^ (2))) + (((4.5) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine2 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.0) - (input[1])) ^ (2)) + (((2.3) - (input[2])) ^ (2))) + (((3.3) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2)))))\n}\nsubroutine3 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.9) - (input[1])) ^ (2)) + (((3.2) - (input[2])) ^ (2))) + (((4.8) - (input[3])) ^ (2))) + (((1.8) - (input[4])) ^ (2)))))\n}\nsubroutine4 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.7) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((5.0) - (input[3])) ^ (2))) + (((1.7) - (input[4])) ^ (2)))))\n}\nsubroutine5 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((7.0) - (input[1])) ^ (2)) + (((3.2) - (input[2])) ^ (2))) + (((4.7) - (input[3])) ^ (2))) + (((1.4) - (input[4])) ^ (2)))))\n}\nsubroutine6 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.9) - (input[1])) ^ (2)) + (((2.4) - (input[2])) ^ (2))) + (((3.3) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2)))))\n}\nsubroutine7 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.3) - (input[1])) ^ (2)) + (((2.5) - (input[2])) ^ (2))) + (((4.9) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine8 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.0) - (input[1])) ^ (2)) + (((2.7) - (input[2])) ^ (2))) + (((5.1) - (input[3])) ^ (2))) + (((1.6) - (input[4])) ^ (2)))))\n}\nsubroutine9 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.7) - (input[1])) ^ (2)) + (((2.6) - (input[2])) ^ (2))) + (((3.5) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2)))))\n}\nsubroutine10 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.9) - (input[1])) ^ (2)) + (((3.1) - (input[2])) ^ (2))) + (((4.9) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine11 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.1) - (input[1])) ^ (2)) + (((2.5) - (input[2])) ^ (2))) + (((3.0) - (input[3])) ^ (2))) + (((1.1) - (input[4])) ^ (2)))))\n}\nsubroutine12 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.1) - (input[1])) ^ (2)) + (((3.8) - (input[2])) ^ (2))) + (((1.9) - (input[3])) ^ (2))) + (((0.4) - (input[4])) ^ (2)))))\n}\nsubroutine13 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.4) - (input[1])) ^ (2)) + (((2.9) - (input[2])) ^ (2))) + (((1.4) - (input[3])) ^ (2))) + (((0.2) - (input[4])) ^ (2)))))\n}\nsubroutine14 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.7) - (input[1])) ^ (2)) + (((4.4) - (input[2])) ^ (2))) + (((1.5) - (input[3])) ^ (2))) + (((0.4) - (input[4])) ^ (2)))))\n}\nsubroutine15 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.8) - (input[1])) ^ (2)) + (((4.0) - (input[2])) ^ (2))) + (((1.2) - (input[3])) ^ (2))) + (((0.2) - (input[4])) ^ (2)))))\n}\nsubroutine16 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.1) - (input[1])) ^ (2)) + (((3.3) - (input[2])) ^ (2))) + (((1.7) - (input[3])) ^ (2))) + (((0.5) - (input[4])) ^ (2)))))\n}\nsubroutine17 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.7) - (input[1])) ^ (2)) + (((3.8) - (input[2])) ^ (2))) + (((1.7) - (input[3])) ^ (2))) + (((0.3) - (input[4])) ^ (2)))))\n}\nsubroutine18 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.3) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((1.1) - (input[3])) ^ (2))) + (((0.1) - (input[4])) ^ (2)))))\n}\nsubroutine19 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.5) - (input[1])) ^ (2)) + (((2.3) - (input[2])) ^ (2))) + (((1.3) - (input[3])) ^ (2))) + (((0.3) - (input[4])) ^ (2)))))\n}\nsubroutine20 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.8) - (input[1])) ^ (2)) + (((3.4) - (input[2])) ^ (2))) + (((1.9) - (input[3])) ^ (2))) + (((0.2) - (input[4])) ^ (2)))))\n}\nsubroutine21 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.0) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((4.8) - (input[3])) ^ (2))) + (((1.8) - (input[4])) ^ (2)))))\n}\nsubroutine22 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.3) - (input[1])) ^ (2)) + (((2.8) - (input[2])) ^ (2))) + (((5.1) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine23 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((5.8) - (input[1])) ^ (2)) + (((2.8) - (input[2])) ^ (2))) + (((5.1) - (input[3])) ^ (2))) + (((2.4) - (input[4])) ^ (2)))))\n}\nsubroutine24 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.1) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((4.9) - (input[3])) ^ (2))) + (((1.8) - (input[4])) ^ (2)))))\n}\nsubroutine25 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((7.7) - (input[1])) ^ (2)) + (((2.6) - (input[2])) ^ (2))) + (((6.9) - (input[3])) ^ (2))) + (((2.3) - (input[4])) ^ (2)))))\n}\nsubroutine26 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.9) - (input[1])) ^ (2)) + (((3.1) - (input[2])) ^ (2))) + (((5.1) - (input[3])) ^ (2))) + (((2.3) - (input[4])) ^ (2)))))\n}\nsubroutine27 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.3) - (input[1])) ^ (2)) + (((3.3) - (input[2])) ^ (2))) + (((6.0) - (input[3])) ^ (2))) + (((2.5) - (input[4])) ^ (2)))))\n}\nsubroutine28 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((4.9) - (input[1])) ^ (2)) + (((2.5) - (input[2])) ^ (2))) + (((4.5) - (input[3])) ^ (2))) + (((1.7) - (input[4])) ^ (2)))))\n}\nsubroutine29 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.0) - (input[1])) ^ (2)) + (((2.2) - (input[2])) ^ (2))) + (((5.0) - (input[3])) ^ (2))) + (((1.5) - (input[4])) ^ (2)))))\n}\nsubroutine30 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((7.9) - (input[1])) ^ (2)) + (((3.8) - (input[2])) ^ (2))) + (((6.4) - (input[3])) ^ (2))) + (((2.0) - (input[4])) ^ (2)))))\n}\nsubroutine31 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((7.2) - (input[1])) ^ (2)) + (((3.0) - (input[2])) ^ (2))) + (((5.8) - (input[3])) ^ (2))) + (((1.6) - (input[4])) ^ (2)))))\n}\nsubroutine32 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((7.7) - (input[1])) ^ (2)) + (((3.8) - (input[2])) ^ (2))) + (((6.7) - (input[3])) ^ (2))) + (((2.2) - (input[4])) ^ (2)))))\n}\nsubroutine33 <- function(input) {\n var0 <- (0) - (0.25)\n return(exp((var0) * ((((((6.2) - (input[1])) ^ (2)) + (((2.8) - (input[2])) ^ (2))) + (((4.8) - (input[3])) ^ (2))) + (((1.8) - (input[4])) ^ (2)))))\n}\n", "meta": {"hexsha": "3612b823eede768ade1b0e74d8bcce195d305dd2", "size": 10736, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/classification/svm.r", "max_stars_repo_name": "yarix/m2cgen", "max_stars_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:59:21.000Z", "max_issues_repo_path": "generated_code_examples/r/classification/svm.r", "max_issues_repo_name": "yarix/m2cgen", "max_issues_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generated_code_examples/r/classification/svm.r", "max_forks_repo_name": "yarix/m2cgen", "max_forks_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.3485714286, "max_line_length": 2259, "alphanum_fraction": 0.4418777943, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.41737296979268834}}
{"text": "\n\n\n#' Calculate topological indices for ecological networks. The mean trophic level\n#' and Omnivory and the Level of omnivory are calculated with the function [NetIndices::TrophInd()]\n#'\n#' @param ig vector of igraph objects\n#' @param ncores number of cores used to compute in parallel, if 0 sequential processing is used.\n#'\n#' @return a data.frame with the following fields:\n#'\n#' \\item{Size:}{Number of species}\n#' \\item{Top:}{Number of top predator species}\n#' \\item{Basal:}{Number of basal especies}\n#' \\item{Omnivory:}{ Proportion of omnivorous species }\n#' \\item{Links:}{ number of interactions}\n#' \\item{LD:}{ linkage density}\n#' \\item{Connectance:}{ directed Connectance}\n#' \\item{PathLength:}{ average path length}\n#' \\item{Clustering:}{ clustering coeficient}\n#' \\item{Cannib:}{ number of cannibalistic species}\n#' \\item{TLmean:}{ mean trophic level}\n#' \\item{TLmax:}{ maximum trophic level}\n#' \\item{LOmnivory:} { Level of omnivory, quantifies mean of the variety in trophic levels of the preys of a consumer}\n#' \\item{Components:}{ number of weakly connected components}\n#' \\item{Vulnerability:}{ mean of number of consumers per prey}\n#' \\item{VulSD:}{ the standard deviation of normalized Vulnerability}\n#' \\item{Generality:}{ mean number of prey per consumer}\n#' \\item{GenSD:}{ the standard deviation of normalized Generality}\n#'\n#'\n#' @export\n#' @importFrom NetIndices TrophInd\n#' @import igraph\n#' @importFrom foreach foreach %dopar%\n#' @importFrom doFuture registerDoFuture\n#' @importFrom future sequential multiprocess\n#'\n#' @aliases calcTopologicalIndices\n#'\n#' @examples\n#'\n#' calc_topological_indices(netData)\n#'\n#' # Generate a test network\n#'\n#' g <- graph_from_literal( 1 -+ 4 -+ 7,2 -+ 5 -+7, 3-+6-+7, 7-+7, 4+-3, simplify = FALSE)\n#'\n#' calc_topological_indices(g)\n\ncalc_topological_indices <- function(ig,ncores=0){\n\n if(inherits(ig,\"igraph\")) {\n ig <- list(ig)\n } else if(class(ig[[1]])!=\"igraph\") {\n stop(\"parameter ig must be an igraph object\")\n }\n\n registerDoFuture()\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n\n\n df <- foreach(g=ig,.combine='rbind',.inorder=FALSE,.packages=c('igraph','NetIndices')) %dopar%\n {\n\n deg <- degree(igraph::simplify(g), mode=\"out\") # calculate the out-degree: the number of predators\n\n V(g)$outdegree <- deg\n\n nTop <- length(V(g)[outdegree==0]) # Top predators do not have predators\n\n deg <- degree(g, mode=\"in\") # calculate the in-degree: the number of preys\n\n V(g)$indegree <- deg\n\n nBasal <- length(V(g)[indegree==0]) # Basal species do not have preys\n\n #vcount(g)-nTop-nBasal\n\n size <- vcount(g)\n\n links <- ecount(g)\n\n linkDen <- links/size # Linkage density\n\n conn <- links/size^2 # Connectance\n\n pathLength <- mean_distance(g) # Average path length\n\n clusCoef <- transitivity(g, type = \"global\")\n\n cannib <- sum(which_loop(g))\n\n a <- get.adjacency(g,sparse=F)\n\n tl <- TrophInd(a) # Calculate the trophic level\n\n omn <- sum(round(tl$OI,5)>0)/size # Omnivory proportion\n\n lomn <- mean(tl$OI) # Level of omnivory\n\n vulnerability <- links / (size - nTop) # l/(nb + ni)\n generality <- links / (size - nBasal) # l/(nt + ni)\n vulSD <- sd(apply(a, 1, sum)*1/linkDen)\n genSD <- sd(apply(a, 2, sum)*1/linkDen)\n\n data.frame(Size=size,Top=nTop,Basal=nBasal,Omnivory=omn,Links=links, LD=linkDen,Connectance=conn,PathLength=pathLength,\n Clustering=clusCoef, Cannib=cannib, TLmean=mean(tl$TL),TLmax=max(tl$TL),LOmnivory=lomn,Components=components(g)$no,\n Vulnerability=vulnerability,VulSD=vulSD,Generality=generality,GenSD=genSD)\n }\nreturn(df)\n}\n\n#' @export\ncalcTopologicalIndices <- function(ig,ncores=0){\n calc_topological_indices(ig,ncores)\n}\n\n\n#' Calculate the incoherence index of a food web\n#'\n#' The incoherence index is based in how the species fit in discrete trophic levels\n#' when Q is closer to 0 more coherent and stable is a food web, and the less omnivory it has.\n#' It calculates the trophic level using the package NetIndices.\n#'\n#' Based on:\n#'\n#' @references Johnson, S., Domínguez-García, V., Donetti, L., & Muñoz, M. A. (2014). Trophic coherence determines food-web stability. Proceedings of the National Academy of Sciences , 111(50), 17923–17928. https://doi.org/10.1073/pnas.1409077111\n#'\n#' @references Johnson, S., & Jones, N. S. (2017). Looplessness in networks is linked to trophic coherence. Proceedings of the National Academy of Sciences, 114(22), 5618–5623. https://doi.org/10.1073/pnas.1613786114\n#'\n#'\n#' @param ig an igraph object or a list of igraph objects\n#' @param ncores number of cores used to compute in parallel, if 0 sequential processing is used.\n#'\n#' @return a data.frame with the following fields\n#'\n#' \\item{Q}{incoherence (0=coherent)}\n#' \\item{rQ}{ratio of Q with expected Q under null expectation of a random network given N=nodes L=links B=basal nodes Lb=basal links}\n#' \\item{mTI}{mean trophic level}\n#' \\item{rTI}{ratio of mTI with expected TI under the same null model expectation than Q}\n#\n#' @aliases calcIncoherence\n#'\n#' @export\n#'\n#' @examples\n#'\n#' calc_incoherence(netData[[1]])\n#'\n#'\n#' @importFrom NetIndices TrophInd\n#' @importFrom igraph V degree get.adjacency vcount ecount\n#' @importFrom foreach foreach %dopar%\n#' @importFrom doFuture registerDoFuture\n#' @importFrom future sequential multiprocess\n\ncalc_incoherence <- function(ig,ncores=0) {\n\n if(inherits(ig,\"igraph\")) {\n ig <- list(ig)\n } else if(class(ig[[1]])!=\"igraph\") {\n stop(\"parameter ig must be an igraph object\")\n }\n\n registerDoFuture()\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n\n\n # if(!is.null(ncores)) {\n # cn <-parallel::detectCores()\n # if(cn>ncores)\n # cn <- ncores\n # else\n # cn <- cn-1\n #\n # # cl <- makeCluster(cn,outfile=\"foreach.log\") # Logfile to debug\n # cl <- parallel::makeCluster(cn)\n # doParallel::registerDoParallel(cl)\n # on.exit(parallel::stopCluster(cl))\n # } else {\n # foreach::registerDoSEQ()\n # }\n\n df <- foreach(g=ig,.combine='rbind',.inorder=FALSE,.packages=c('igraph','NetIndices')) %dopar%\n {\n ti<-TrophInd(get.adjacency(g,sparse=FALSE))\n v <- ti$TL\n z <- round(outer(v,v,'-'),8);\n A <- get.adjacency(g,sparse = FALSE)\n xx <- A>0\n x <- (A*t(z))[xx]\n Q <- round(sqrt(sum((x-1)^2)/ecount(g) ),8)\n\n basal <- which(round(v,8)==1)\n bedges <- sum(degree(g,basal,mode='out'))\n mTI <- mean(v)\n mK <- mean(degree(g,mode='out'))\n eTI <- 1+(1-length(basal)/vcount(g))*ecount(g)/bedges\n eQ <- sqrt(ecount(g)/bedges-1)\n data.frame(Q=Q,rQ=Q/eQ,mTI=mTI,rTI=mTI/eTI)\n }\n return(df)\n}\n\n#' @export\ncalcIncoherence <- function(ig,ncores=0){\n calc_incoherence(ig,ncores)\n }\n\n#' Calculation of Modularity and Small-world-ness z-scores\n#'\n#' The function calculates modularity, number of groups and small-world-ness z-scores and 99\\% CI intervals\n#' using as null model the list of networks in the nullDist parameters. Modularity is calculated using the [igraph::cluster_spinglass()]\n#' if the parameter weights is NULL the atribute \"weigths\" is used, or if it has the name of an network attribute, that is used as a weigth\n#' to build the modules, when this parameter is NA then no weigth is used.\n#' Only works for one component networks\n#'\n#' @references\n#' Marina, T. I., Saravia, L. A., Cordone, G., Salinas, V., Doyle, S. R., & Momo, F. R. (2018). Architecture of marine food webs: To be or not be a ‘small-world.’ PLoS ONE, 13(5), 1–13. https://doi.org/10.1371/journal.pone.0198217\n#'\n#' @param g igraph object\n#' @param nullDist list of igraph object with the null model simulations\n#' @param sLevel significance level to calculate CI (two tails)\n#' @param ncores number of cores to use paralell computation, if 0 sequential processing is used.\n#' @param weights The weights of the edges. Either a numeric vector or NULL or NA. If it is null and the input graph has a ‘weight’ edge attribute\n#' then that will be used. If NULL and no such attribute is present then the edges will have equal weights.\n#' Set this to NA if the graph was a ‘weight’ edge attribute, but you don't want to use it for community detection.\n#'\n#'\n#' @return a list with two data frames: one with indices z-scores and CI\n#'\n#' \\item{Clustering}{ Clustering coefficient, measures the average fraction of pairs of neighbors of a node that are also neighbors of each other}\n#' \\item{PathLength}{ Mean of the shortest paths between all pair of vertices }\n#' \\item{Modularity}{ modularity measures how separated are different groups from each other, the algorithm \\code{cluster_spinglass} was used to obtain the groups}\n#' \\item{zCC,zCP,zMO}{Z-scores of Clustering,PathLength and Modularity with respect to a random Erdos-Renyi null model}\n#' \\item{CClow,CChigh,CPlow,CPhigh,MOlow,MOhigh}{sLevel confidence intervals}\n#' \\item{SWness,SWnessCI}{ Small-world-ness and it CI value}\n#' \\item{isSW,isSWness}{ Logical variable signalling if the network is Small-world by the method of Marina 2018 or the method of Humprhies & Gurney 2008 }\n#'\n#' Another data.frame with the values calculated for the nullDist.\n#'\n#' @export\n#'\n#' @importFrom igraph transitivity average.path.length cluster_spinglass\n#' @importFrom future.apply future_lapply\n#' @importFrom future sequential multiprocess\n#'\n#' @examples\n#' \\dontrun{\n#' nullg <- generateERbasal(netData[[1]],10)\n#' calcModularitySWnessZScore(netData[[1]],nullg)\n#' }\n#'\ncalc_modularity_swness_zscore<- function(g, nullDist,sLevel=0.01,ncores=0,weights=NA){\n\n if(!is_igraph(g))\n stop(\"Parameter g must be an igraph object\")\n\n t <- calcTopologicalIndices(g)\n\n if(length(nullDist)<5)\n stop(\"nullDist: There has to be more than 5 elements in the list\")\n\n if(any(sapply(nullDist, function(g) components(g)$no>1)))\n stop(\"nullDist: one or more igraph object from nullDist have more than one component\")\n\n # nullDist <- lapply(1:nsim, function (x) {\n # e <- sample_gnm(t$Size, t$Links, directed = TRUE)\n #\n # # Check that the ER networks has only one connected component\n # #\n # while(components(e)$no>1)\n # e <- erdos.renyi.game(t$Size, t$Links, type=\"gnm\",directed = TRUE)\n #\n # return(e) }\n # )\n\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n\n ind <- data.frame()\n\n ind <- future_lapply(1:length(nullDist), function(i)\n {\n m<-cluster_spinglass(nullDist[[i]],weights=weights)\n modl <- m$modularity\n clus.coef <- transitivity(nullDist[[i]], type=\"Global\")\n cha.path <- average.path.length(nullDist[[i]])\n data.frame(modularity=modl,clus.coef=clus.coef,cha.path=cha.path)\n }, future.seed = TRUE)\n ind <- bind_rows(ind)\n\n ind$gamma <- t$Clustering/ind$clus.coef\n ind$lambda <- t$PathLength/ind$cha.path\n ind$SWness <- ind$gamma/ind$lambda\n\n # 99% confidence interval\n #\n sLevel <- sLevel/2\n qSW <- quantile(ind$SWness,c(sLevel,1-sLevel),na.rm = TRUE)\n qmo <- quantile(ind$modularity,c(sLevel,1-sLevel))\n\n mcc <- mean(ind$clus.coef)\n mcp <- mean(ind$cha.path)\n\n zcc <- (t$Clustering-mcc)/sd(ind$clus.coef)\n zcp <- (t$PathLength-mcp)/sd(ind$cha.path)\n qcc <- quantile(ind$clus.coef,c(sLevel,1-sLevel),na.rm = TRUE)\n qcp <- quantile(ind$cha.path,c(sLevel,1-sLevel),na.rm = TRUE)\n\n\n\n m<-cluster_spinglass(g, weights=weights)\n\n zmo <- (m$modularity - mean(ind$modularity))/sd(ind$modularity)\n\n mSW <- mean(t$Clustering/mcc*mcp/t$PathLength)\n mCI <- 1+(qSW[2]-qSW[1])/2\n\n isLowInsideCPL <- t$PathLength<=qcp[2]\n isGreaterCC <- t$Clustering>qcc[2]\n isSW <- (isLowInsideCPL & isGreaterCC)\n isSWness <- (mSW>mCI)\n\n return(list(da=data.frame(Clustering=t$Clustering, PathLength= t$PathLength, Modularity=m$modularity,\n zCC=zcc,zCP=zcp,zMO=zmo,\n CClow=qcc[1],CChigh=qcc[2],CPlow=qcp[1],CPhigh=qcp[2],MOlow=qmo[1],MOhigh=qmo[2],\n SWness=mSW,SWnessCI=mCI,\n isSW=isSW,isSWness=isSWness),sims=ind))\n}\n\n#' @export\ncalcModularitySWnessZScore<- function(g, nullDist,sLevel=0.01,ncores=0){\n calc_modularity_swness_zscore(g, nullDist,sLevel,ncores)\n}\n\n\n#' Calculation Small-world-ness z-scores\n#'\n#' The function calculates small-world-ness z-scores and 99\\% CI intervals,\n#' using as null model the list of networks in the nullDist parameter.\n#'\n#' @references\n#' Marina, T. I., Saravia, L. A., Cordone, G., Salinas, V., Doyle, S. R., & Momo, F. R. (2018). Architecture of marine food webs: To be or not be a ‘small-world.’ PLoS ONE, 13(5), 1–13. https://doi.org/10.1371/journal.pone.0198217\n#'\n#' @param g igraph object\n#' @param nullDist list of igraph object with the null model simulations\n#' @param sLevel significance level to calculate CI (two tails)\n#' @param ncores number of cores to use paralell computation, if 0 sequential processing is used.\n#'\n#'\n#' @return a list with two data frames: one with indices z-scores and CI\n#'\n#' \\item{Clustering}{ Clustering coefficient, measures the average fraction of pairs of neighbors of a node that are also neighbors of each other}\n#' \\item{PathLength}{ Mean of the shortest paths between all pair of vertices }\n#' \\item{Modularity}{ modularity measures how separated are different groups from each other, the algorithm \\code{cluster_spinglass} was used to obtain the groups}\n#' \\item{zCC,zCP,zMO}{Z-scores of Clustering,PathLength and Modularity with respect to a random Erdos-Renyi null model}\n#' \\item{CClow,CChigh,CPlow,CPhigh,MOlow,MOhigh}{sLevel confidence intervals}\n#' \\item{SWness,SWnessCI}{ Small-world-ness and it CI value}\n#' \\item{isSW,isSWness}{ Logical variable signalling if the network is Small-world by the method of Marina 2018 or the method of Humprhies & Gurney 2008 }\n#'\n#' Another data.frame with the values calculated for the nullDist.\n#'\n#' @export\n#'\n#' @importFrom igraph transitivity average.path.length\n#' @importFrom foreach foreach %dopar%\n#' @importFrom doFuture registerDoFuture\n#' @importFrom future sequential multiprocess\n#'\n#' @examples\n#' \\dontrun{\n#' nullg <- generateERbasal(netData[[1]],10)\n#' calc_swness_zscore(netData[[1]],nullg)\n#' }\n#'\ncalc_swness_zscore<- function(g, nullDist,sLevel=0.01,ncores=0,weights=NA){\n\n if(!is_igraph(g))\n stop(\"Parameter g must be an igraph object\")\n\n t <- calcTopologicalIndices(g)\n\n if(length(nullDist)<5)\n stop(\"nullDist: There has to be more than 5 elements in the list\")\n\n registerDoFuture()\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n\n ind <- data.frame()\n\n ind <- foreach(i=1:length(nullDist),.combine='rbind',.inorder=FALSE,.packages='igraph') %dopar%\n {\n clus.coef <- transitivity(nullDist[[i]], type=\"Global\")\n cha.path <- average.path.length(nullDist[[i]])\n data.frame(clus.coef=clus.coef,cha.path=cha.path)\n }\n\n ind$gamma <- t$Clustering/ind$clus.coef\n ind$lambda <- t$PathLength/ind$cha.path\n ind$SWness <- ind$gamma/ind$lambda\n\n # 99% confidence interval\n #\n sLevel <- sLevel/2\n qSW <- quantile(ind$SWness,c(sLevel,1-sLevel),na.rm = TRUE)\n\n mcc <- mean(ind$clus.coef)\n mcp <- mean(ind$cha.path)\n\n zcc <- (t$Clustering-mcc)/sd(ind$clus.coef)\n zcp <- (t$PathLength-mcp)/sd(ind$cha.path)\n qcc <- quantile(ind$clus.coef,c(sLevel,1-sLevel),na.rm = TRUE)\n qcp <- quantile(ind$cha.path,c(sLevel,1-sLevel),na.rm = TRUE)\n\n mSW <- mean(t$Clustering/mcc*mcp/t$PathLength)\n mCI <- 1+(qSW[2]-qSW[1])/2\n\n isLowInsideCPL <- t$PathLength<=qcp[2]\n isGreaterCC <- t$Clustering>qcc[2]\n isSW <- (isLowInsideCPL & isGreaterCC)\n isSWness <- (mSW>mCI)\n\n return(list(da=data.frame(Clustering=t$Clustering, PathLength= t$PathLength,\n zCC=zcc,zCP=zcp,\n CClow=qcc[1],CChigh=qcc[2],CPlow=qcp[1],CPhigh=qcp[2],\n SWness=mSW,SWnessCI=mCI,\n isSW=isSW,isSWness=isSWness),sims=ind))\n}\n\n\n\n\n#' Calc topological roles among network communities/modules\n#'\n#' Topological roles characterize species as its roles between communities or modules, we calculate the modules using\n#' the [igraph::cluster_spinglass()] function.\n#' Topological roles are described by two parameters: the standardized within-module degree \\eqn{dz} and the among-module\n#' connectivity participation coefficient \\eqn{PC}. The within-module degree is a z-score that measures how well a species is\n#' connected to other species within its own module compared with a random graph. The participation coefficient \\eqn{PC}\n#' estimates the distribution of the links of species among modules. As the community algorithm is stochastic we run it several\n#' times and return the repeated runs for both parameters.\n#'\n#' @references\n#'\n#' 1. Guimerà, R. & Nunes Amaral, L.A. (2005). Functional cartography of complex metabolic networks. Nature, 433, 895–900\n#'\n#' 1. Kortsch, S. et al. 2015. Climate change alters the structure of arctic marine food webs due to poleward shifts of boreal generalists. - Proceedings of the Royal Society B: Biological Sciences 282: 20151546. https://doi.org/10.1098/rspb.2015.1546\n\n#'\n#' @param g an Igraph object with the network\n#' @param nsim number of simulations with different community\n#' @param ncores number of cores to use paralell computation, if 0 sequential processing is used.\n#'\n#' @return a data frame with two numeric fields: within_module_degree, among_module_conn\n#'\n#' @export\n#'\n#' @import igraph\n#' @importFrom foreach foreach %dopar%\n#' @importFrom doFuture registerDoFuture\n#' @importFrom future sequential multiprocess\n#'\n#' @examples\n#' #' \\dontrun{\n#'\n#' g <- netData[[2]]\n#'\n#' tp <- calc_topological_roles(g,nsim=10)\n#'\n#' }\n\ncalc_topological_roles <- function(g,nsim=1000,ncores=0)\n{\n if(!is_igraph(g))\n stop(\"Parameter g must be an igraph object\")\n\n\n toRol <- data.frame()\n\n\n registerDoFuture()\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n\n toRol <- foreach(idx=1:nsim,.combine='rbind',.inorder=FALSE,.packages='igraph') %dopar%\n {\n # within-module degree\n #\n # Standarized Within module degree z-score\n #\n m<-cluster_spinglass(g,weights = NA)\n spingB.mem<- m$membership\n\n l<-vector()\n memMod<-vector()\n\n for (i in 1:vcount(g)){\n\n sp.in.deg <- V(g)[nei(i, \"in\")]\n sp.out.deg<- V(g)[nei(i, \"out\")]\n mem.sp<-spingB.mem[i]\n k<- length(which(spingB.mem[c(sp.in.deg, sp.out.deg)]==mem.sp))\n mem<- which(spingB.mem==mem.sp)\n\n for (m in 1:length(mem)){\n mem.in.deg <- V(g)[nei(mem[m], \"in\")]\n mem.out.deg<- V(g)[nei(mem[m], \"out\")]\n memMod.id<- length(which(spingB.mem[c(mem.in.deg, mem.out.deg)]==mem.sp))\n memMod[m]<- memMod.id\n }\n\n k.ave<- mean(memMod)\n k.sd<- sd(memMod)\n l[i]<- (k-k.ave)/k.sd\n }\n\n # among module connectivity\n r<- vector()\n for (i in 1:vcount(g)){\n\n d<-degree(g)[i]\n sp.in.deg <- V(g)[nei(i, \"in\")]\n sp.out.deg<- V(g)[nei(i, \"out\")]\n mod.sp<-table(spingB.mem[c(sp.in.deg, sp.out.deg)])\n mod.no<-as.numeric(names(mod.sp))\n mod<-rep(0, length(unique(spingB.mem)))\n mod[mod.no]<-c(mod.sp)\n r[i]<- 1-(sum((mod/d)^2))\n }\n return(data.frame(node=1:vcount(g),within_module_degree=l, among_module_conn=r))\n\n }\n\n return(toRol)\n}\n\n\n#' Classify and plot topological roles\n#'\n#' We use the topological roles calculated with [calc_topological_roles()] and categorize them following the approach of\n#' Kortsch (2015), that defines species roles based in two thresholds \\eqn{PC=0.625} and \\eqn{dz=2.5}.\n#' If a species had at least 60% of links within its own module then \\eqn{PC<0.625}, and if it also had \\eqn{dz\\ge 2.5}, thus it was\n#' classified as a module hub, labeled **modhub**. If a species had \\eqn{PC<0.625} and \\eqn{dz<2.5}, then it was called a peripheral\n#' or specialist, labeled **modspe**. Species that had \\eqn{PC\\ge0.625} and \\eqn{dz<2.5} were considered module connectors **modcon**.\n#' Finally, if a species had \\eqn{PC\\ge0.625} and \\eqn{dz\\ge 2.5}, then it was classified as a super-generalist or hub-connector **hubcon**.\n#'\n#' @references\n#'\n#'1. Kortsch, S., Primicerio, R., Fossheim, M., Dolgov, A. V & Aschan, M. (2015). Climate change alters the structure of arctic marine food webs due to poleward shifts of boreal generalists. Proc. R. Soc. B Biol. Sci., 282\n#'\n#' 1. Saravia, L.A., Marina, T.I., De Troch, M. & Momo, F.R. (2018). Ecological Network assembly: how the regional meta web influence local food webs. bioRxiv, 340430, doi: https://doi.org/10.1101/340430\n#'\n#' @param tRoles Calculated topological roles with the function [calc_topological_roles()]\n#' @param g Igraph network object\n#' @param spingB Igraph community object\n#' @param plt logical whether a plot is generated\n#'\n#' @return a data.frame with the classified topological roles\n#' @export\n#'\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom dplyr %>% group_by summarise_all inner_join\n#'\n#' @examples\n#' \\dontrun{\n#'\n#' g <- netData[[2]]\n#'\n#' tp <- calc_topological_roles(g,nsim=10)\n#'\n#' classify_topological_roles(tp,g,plt=TRUE)\n#' }\nclassify_topological_roles <- function(tRoles,g,spingB=NULL,plt=FALSE){\n\n if(is.null(spingB))\n spingB <- cluster_spinglass(g,weights=NA)\n\n spingB.mem<- spingB$membership\n tRoles <- tRoles %>% group_by(node) %>% summarise_all(mean)\n l <- tRoles$within_module_degree\n r <- tRoles$among_module_conn\n # Plot\n if(plt){\n\n colbar.FG <- brewer.pal(length(spingB$csize),\"Dark2\")\n\n old_par <- par(mfrow=c(1,1))\n par(oma=c(2.7,1.3,0.7,1)) # change outer figure margins\n par(mai=c(1,1,0.7,0.7)) # size of figure margins\n yran <- range(l,na.rm = TRUE,finite=TRUE)\n xran <- range(r)\n plot(l~r, type=\"n\", axes=T ,tck=F, lwd=2, ann=F, cex.axis=1.2, xlim=xran, ylim=yran)\n lines(c(0.625,0.625), yran, col=\"grey\")\n lines(xran, c(2.5, 2.5), col=\"grey\")\n points(r, l, col=colbar.FG[spingB.mem], pch=20, cex=2)\n mtext(2, text=\"Within module degree\", line=4,font=2, cex=1.2)\n mtext(1, text=\"Among module connectivity\",line=4, font=2, cex=1.2)\n axis(1, tck=0.02, lwd=1,las=2,lty=1, labels=F, xlim=c(0,1))\n axis(2,tck=0.02, labels=FALSE)\n }\n # Which are the module hubs: many links within its own module.\n #\n modhub <- which(l>2.5)\n modhub <- modhub[which(l>2.5) %in% which(r<=0.625)]\n modlbl <- vertex_attr(g, \"name\", index=modhub)\n if(is.null(modlbl))\n modlbl <- modhub\n hub_conn <- data.frame()\n\n if(length(modhub)) {\n if(plt) text(r[modhub],l[modhub],labels = modlbl,cex=0.7,pos=3)\n hub_conn <- data.frame(type=\"modhub\",node=modhub,name=modlbl)\n }\n\n #points(r[modhub], l[modhub], cex=4, col=\"blue\", pch=20)\n\n # Which are the hub connectors: high within and between-module connectivity\n # and are classified super-generalists\n #\n modhub <- which(l>2.5)\n modhub <- modhub[which(l>2.5) %in% which(r>0.625)]\n modlbl <- vertex_attr(g,\"name\",index=modhub)\n if(is.null(modlbl))\n modlbl <- modhub\n if(length(modhub)) {\n if(plt) {\n text(r[modhub],l[modhub],labels = modlbl,cex=0.7,pos=3)\n par(old_par)\n }\n }\n\n #points(r[modhub], l[modhub], cex=4, col=\"blue\", pch=20)\n if(length(modhub)){\n hub_conn <- rbind(hub_conn, data.frame(type=\"hubcon\",node=modhub,name=modlbl))\n }\n\n # Which are the module specialist: Few links and most of them within its own module\n #\n modhub <- which(l<=2.5)\n modhub <- modhub[which(l<=2.5) %in% which(r<=0.625)]\n modlbl <- vertex_attr(g,\"name\",index=modhub)\n if(is.null(modlbl))\n modlbl <- modhub\n\n hub_conn <- rbind(hub_conn, data.frame(type=\"modspe\",node=modhub,name=modlbl))\n\n # Which are the module connectors: Few links and between modules\n #\n modhub <- which(l<=2.5)\n modhub <- modhub[which(l<=2.5) %in% which(r>0.625)]\n modlbl <- vertex_attr(g,\"name\", index=modhub)\n if(is.null(modlbl))\n modlbl <- modhub\n\n hub_conn <- rbind(hub_conn, data.frame(type=\"modcon\",node=modhub,name=modlbl))\n hub_conn <- hub_conn %>% inner_join(tRoles)\n return(hub_conn)\n}\n\n\n#' Calculation of Modularity for a list of igraph objects\n#'\n#' The function calculates modularity of the list of networks in the nullDist parameter.\n#' Modularity is calculated using the [igraph::cluster_spinglass()]\n#' Only works for one component networks.\n#'\n#'\n#' @param ig list of igraph objects to calculate modularity\n#' @param ncores number of cores used to compute in parallel, if 0 sequential processing is used.\n#' @param weights The weights of the edges. Either a numeric vector or NULL or NA. If it is null and the input graph has a ‘weight’ edge attribute\n#' then that will be used. If NULL and no such attribute is present then the edges will have equal weights.\n#' Set this to NA if the graph was a ‘weight’ edge attribute, but you don't want to use it for community detection.\n\n#'\n#' @return a data.frame with the field Modularity\n#'\n#' @export\n#'\n#' @import igraph\n#' @importFrom future.apply future_lapply\n#' @importFrom future sequential multiprocess\n#'\n#'\n#' @examples\n#' \\dontrun{\n#' nullg <- generateERbasal(netData[[1]],10)\n#' calc_modularity(nullg)\n#' }\n#'\ncalc_modularity <- function(ig,ncores=0,weights=NA){\n\n if(inherits(ig,\"igraph\")) {\n ig <- list(ig)\n } else if(class(ig[[1]])!=\"igraph\") {\n stop(\"parameter ig must be an igraph object\")\n }\n\n registerDoFuture()\n if(ncores) {\n cn <- future::availableCores()\n if(ncores>cn)\n ncores <- cn\n future::plan(multiprocess, workers=ncores)\n on.exit(future::plan(sequential))\n } else {\n future::plan(sequential)\n }\n df <- future_lapply(ig, function(g)\n {\n m<-cluster_spinglass(g,weights=weights)\n modl <- m$modularity\n data.frame(Modularity=modl)\n }, future.seed=TRUE)\n return(bind_rows(df))\n}\n", "meta": {"hexsha": "d4d143311b7c7daac7dc17e4c8248470f16d8f3b", "size": 26496, "ext": "r", "lang": "R", "max_stars_repo_path": "R/calcTopologicalIndices.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/calcTopologicalIndices.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/calcTopologicalIndices.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": 35.0476190476, "max_line_length": 251, "alphanum_fraction": 0.6758378623, "num_tokens": 8084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.4172451768821257}}
{"text": "# via Houstonwp\nlibrary(data.table)\n\nq <- c(0.001,\n 0.002,\n 0.003,\n 0.003,\n 0.004,\n 0.004,\n 0.005,\n 0.007,\n 0.009,\n 0.011)\n\nw <- c(0.05,\n 0.07,\n 0.08,\n 0.10,\n 0.14,\n 0.20,\n 0.20,\n 0.20,\n 0.10,\n 0.04)\n\nP <- 100\nS <- 25000\nr <- 0.02\n\ndt <- as.data.table(cbind(q,w))\n\nnpv <- function(cf, r, S, P) {\n cf[, inforce := shift(cumprod(1 - q - w), fill = 1)\n ][, lapses := inforce * w\n ][, deaths := inforce * q\n ][, claims := deaths * S\n ][, premiums := inforce * P\n ][, ncf := premiums - claims\n ][, d := (1/(1+r))^(.I)\n ][, sum(ncf*d)]\n}\n\nnpv(dt,r,S,P)\n#> [1] 50.32483\n\nmicrobenchmark::microbenchmark(npv(dt,r,S,P))", "meta": {"hexsha": "3979d761e16ccc37db6d9455ea45d1324f3b3a27", "size": 725, "ext": "r", "lang": "R", "max_stars_repo_path": "Benchmarks/LifeModelingProblem/r/data.table.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/data.table.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/data.table.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": 15.7608695652, "max_line_length": 53, "alphanum_fraction": 0.44, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4165956693713733}}
{"text": "path <- '/home/maanitou/programming/fsharp/rufc/Samples/schrodinger/'\n\ncontent_f <- read.table(paste(path, 'output_schrodinger_forward.txt', sep=\"\"))\n\nfactor <- 1000000\n\nXf <- sapply(content_f, function(x) as.numeric(x)/factor)\n\npar(mfrow=c(1,1))\n\nplot(1:128, Xf[1,], type='l', xlim=c(0,128), ylim=c(min(Xf),max(Xf)))\nlines(1:128, Xf[2,], type='l')\n\nfor (i in 1:(nrow(Xf)-1)) {\n plot(1:128, Xf[i,], type='l', col='red', xlim=c(0,128), ylim=c(min(Xf),max(Xf)))\n lines(1:128, Xf[i+1,], type='l', col='black')\n \n #Sys.sleep(0.001)\n}", "meta": {"hexsha": "fc61bc421e63e58eb5f8e6b3744afa0434832001", "size": 534, "ext": "r", "lang": "R", "max_stars_repo_path": "Samples/schrodinger/code_forward.r", "max_stars_repo_name": "maanitou/rufc", "max_stars_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Samples/schrodinger/code_forward.r", "max_issues_repo_name": "maanitou/rufc", "max_issues_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-18T14:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T15:14:49.000Z", "max_forks_repo_path": "Samples/schrodinger/code_forward.r", "max_forks_repo_name": "maanitou/rufc", "max_forks_repo_head_hexsha": "d63285aba9a9225f0b15d61f4542a51e8c9b8278", "max_forks_repo_licenses": ["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.1052631579, "max_line_length": 82, "alphanum_fraction": 0.627340824, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.41635075952466033}}
{"text": "##' Create null model forecasts\n##'\n##' Uses a truncated normal distribution fitted to past data points under the\n##' assumption of no change. Contains uk-specific code on truncation at the time\n##' of data availability \n##'\n##' @param forecasts existing forecast data frame\n##' @param data data to create null model\n##' @return data frame with null model forecasts\n##' @importFrom dplyr arrange mutate group_by ungroup filter\n##' @importFrom tidyr complete expand_grid nest unnest\n##' @importFrom purrr map\n##' @author Sebastian Funk\nfit_null_model <- function(forecasts, data) {\n\n creation_dates <- forecasts %>%\n arrange(creation_date) %>%\n .$creation_date %>%\n unique\n\n use_data <- data %>%\n mutate(truncation = if_else(value_type == \"death_inc_line\", 4, 0),\n truncation = if_else(value_type == \"hospital_inc\" &\n geography == \"Wales\", 2, truncation),\n truncation = if_else(value_type == \"hospital_inc\" &\n geography == \"Scotland\", 4, truncation),\n truncation = if_else(value_type == \"hospital_inc\" &\n geography == \"Northern Ireland\", 9, truncation)) %>%\n group_by(geography, value_type, value_desc, truncation) %>%\n tidyr::complete(value_date =\n seq(min(value_date), max(value_date), by = \"day\"),\n fill = list(value = 0)) %>%\n ungroup()\n\n null_model_forecast_df <-\n function(x, creation_date, horizon = 22, truncation = 0)\n {\n quant <-\n null_model_forecast_quantiles(x$value, horizon = horizon,\n truncation = truncation)\n df <- \n bind_rows(replicate(horizon + truncation, quant, simplify = FALSE)) %>%\n mutate(value_date = creation_date - truncation +\n seq(1, horizon + truncation),\n model = \"null\") %>%\n gather(quantile, value, starts_with(\"0\")) %>%\n mutate(value = round(value),\n quantile = as.numeric(quantile))\n }\n\n fc <- use_data %>%\n group_by(geography, value_desc, value_type, truncation) %>%\n complete(value_date = seq(min(value_date), max(value_date), by = \"day\"),\n fill = list(value = 0)) %>%\n ungroup() %>%\n expand_grid(creation_date = creation_dates) %>%\n filter(value_date <= creation_date) %>%\n group_by(creation_date, geography, value_desc, value_type, truncation) %>%\n nest() %>%\n mutate(forecast = map(data, null_model_forecast_df,\n creation_date = creation_date,\n truncation = truncation)) %>%\n unnest(forecast) %>%\n ungroup() %>%\n select(model, geography, value_type, value_desc, creation_date, value_date,\n quantile, value)\n \n return(fc)\n}\n\n##' Makes a null model forecast based on a vector of values\n##'\n##' Null model assumes last value stays\n##' @param values vector of values\n##' @param horizon forecast horizon\n##' @param truncation truncation of data series\n##' @importFrom msm dtnorm qtnorm\n##' @return quantiles of null model predictive distribution\n##' @author Sebastian Funk\nnull_model_forecast_quantiles <- function(values, horizon, truncation = 0)\n{\n if (truncation > 0) {\n values <- head(values, -truncation)\n }\n\n tnorm_unc_fit <- function(x, mean, true) {\n return(-sum(dtnorm(x = true, mean = mean, sd = x, lower = 0, log = TRUE)))\n }\n\n quantiles <- seq(0.05, 0.95, by = 0.05)\n ts <- tail(values, min(horizon, length(values)))\n\n if (length(ts) > 1) {\n ## null model\n null_ts <- rep(last(ts), horizon + truncation)\n\n interval <- c(0, max(abs(diff(ts))))\n\n if (diff(interval) > 0 ) {\n tnorm_sigma <-\n optimise(tnorm_unc_fit, interval = interval,\n mean = head(ts, -1),\n true = tail(ts, -1))\n\n quant <- round(qtnorm(p = quantiles, mean = last(ts),\n sd = tnorm_sigma$minimum, lower = 0))\n } else {\n quant <- rep(last(ts), length(quantiles))\n }\n } else {\n quant <- rep(last(ts), length(quantiles))\n }\n\n names(quant) <- quantiles\n\n return(quant)\n}\n\n", "meta": {"hexsha": "e484a5731eefdaca3283e8d773e35a4964383cdb", "size": 4100, "ext": "r", "lang": "R", "max_stars_repo_path": "R/fit_null_model.r", "max_stars_repo_name": "epiforecasts/covid19.forecasts.uk", "max_stars_repo_head_hexsha": "5bc52a12e2b54b07759acf47af63fb6dd3d7b95f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-13T15:57:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T15:57:27.000Z", "max_issues_repo_path": "R/fit_null_model.r", "max_issues_repo_name": "epiforecasts/covid19.forecasts.uk", "max_issues_repo_head_hexsha": "5bc52a12e2b54b07759acf47af63fb6dd3d7b95f", "max_issues_repo_licenses": ["MIT"], "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/fit_null_model.r", "max_forks_repo_name": "epiforecasts/covid19.forecasts.uk", "max_forks_repo_head_hexsha": "5bc52a12e2b54b07759acf47af63fb6dd3d7b95f", "max_forks_repo_licenses": ["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.4537815126, "max_line_length": 84, "alphanum_fraction": 0.6073170732, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.41601069433215204}}
{"text": "\n### Auditing\n# The Goal: Reduce audit cost (it is currently a 'binding constraint').\n# Making auditing between only a few choices.\n\n\n# #Cleanup\n# rm(list=ls())\n\n# #Load everything\n# tryCatch(expr=setwd(\"~/GitHub/Truthcoin/lib\"), error=function(e) setwd(choose.dir(caption=\"Failed to set working directory automatically. Choose 'Truthcoin/lib' folder:\")) )\n# source(file=\"consensus/ConsensusMechanism.r\")\n# \n# Use <- function(package) { if(suppressWarnings(!require(package,character.only=TRUE))) install.packages(package,repos=\"http://cran.case.edu/\") ; require(package,character.only=TRUE) }\n\n\n\n# Setup\n# \n# Data:\n# \nR <- c(.40, .25, .10, .10, .05, .05, .05)\n\nVM <- matrix( c(1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0), 7,5,byrow=TRUE)\n\nVM2 <- matrix(c(1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0), 7,5,byrow=TRUE)\n\nVM3 <- matrix(c(1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 1, 0, 1, 0,\n 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 1), 7,5,byrow=TRUE)\n\nVM4 <- matrix(c(1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0,\n .5, 0, 0, 0, 0,\n .5, 0, 0, 0, 0,\n 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0), 6,5,byrow=TRUE)\n\nVM5 <- matrix(c(0.0, 1.0, 0.81, 0.20, 0.03,\n 0.0, 1.0, 0.79, 0.20, 0.04, # confused\n 0.0, 1.0, 0.80, 0.20, 0.02,\n 0.0, 1.0, 0.80, 0.20, 0.03,\n 0.0, 1.0, 0.80, 0.98, 0.55, # liars spamming\n 0.0, 1.0, 0.80, 0.97, 0.56, # liars spamming\n 0.0, 1.0, 0.80, 0.99, 0.57), # liars spamming\n 7, 5, byrow=TRUE)\n\n# drawing it out of the binary ballot - cuts everything in half\nVM6 <- matrix(c(0.8, 0.0, 0.0, 0.25, 0.045,\n 0.6, 0.5, 0.5, 0.20, 0.030,\n 0.4, 1.0, 1.0, 0.15, 0.015),\n 3, 5, byrow=TRUE)\n\nR6a <- c(.34,.32,.34)\n\nR2 <- c(.40, .20, .20, .17, .01, .01, .01)\n\n# End Setup\n\n\nGetUniqueBallots <- function(VoteMatrix, Reputation = DemocracyRep(VoteMatrix)) {\n Use('reshape2')\n # Takes a VoteMatrix and Reputation, and returns a minimal set of unique Ballots.\n \n Rep_VM <- matrix(c(Reputation,VoteMatrix), nrow = nrow(VoteMatrix))\n \n # Force Unique Names\n colnames(Rep_VM) <- c( \"Rep\", paste(\"D\",1:(ncol(Rep_VM)-1), sep=\".\") )\n \n # Get the unique ballots (\"unique\"), but ignore non-unique VTC ownership ( \" [,-1]\" ).\n Map1 <- data.frame( unique(Rep_VM[,-1]) ) \n \n # Relabel (for upcoming merge)\n names(Map1) <- colnames(Rep_VM)[-1] # Again, we're dropping \"Rep\"\n \n # Give each Ballot a LETTER label\n Map2 <- cbind( Map1, \"BallotGroup\"= factor(LETTERS[1:nrow(Map1)]) )\n\n # Vote Matrix, with labelled Ballots\n Merg <- merge(Rep_VM,Map2)\n MergSub <- Merg[,c(\"Rep\",\"BallotGroup\")]\n \n # Aggregate Ballots\n Map3 <- dcast(MergSub, formula = BallotGroup~., fun.aggregate = sum, value.var = \"Rep\") #\n names(Map3) <- c(\"BallotGroup\",\"BallotRep\")\n \n Merg2 <- merge(Map3,Map2)\n if( !is.null(colnames(VoteMatrix)) ) names(Merg2) <- c( names(Merg2)[1:2], colnames(VoteMatrix) ) # restore original column names (if the given VM had colnames)\n return(Merg2)\n}\n\n# GetUniqueBallots(VoteMatrix = VM3, R)\n# BallotGroup BallotRep D.1 D.2 D.3 D.4 D.5\n# 1 A 0.65 1 0 0 0 0\n# 2 B 0.10 0 1 0 1 0\n# 3 C 0.20 0 0 0 0 1\n# 4 D 0.05 0 0 0 0 0\n\n\n# GetUniqueBallots(VoteMatrix = VM4)\n# BallotGroup BallotRep D.1 D.2 D.3 D.4 D.5\n# 1 A 0.3333333 1.0 0 0 0 0\n# 2 B 0.3333333 0.5 0 0 0 0\n# 3 C 0.3333333 0.0 0 0 0 0\n\n# GetUniqueBallots(VoteMatrix = VM5)\n# BallotGroup BallotRep D.1 D.2 D.3 D.4 D.5\n# 1 A 0.1428571 0 1 0.81 0.20 0.03\n# 2 B 0.1428571 0 1 0.79 0.20 0.04\n# 3 C 0.1428571 0 1 0.80 0.20 0.02\n# 4 D 0.1428571 0 1 0.80 0.20 0.03\n# 5 E 0.1428571 0 1 0.80 0.98 0.55\n# 6 F 0.1428571 0 1 0.80 0.97 0.56\n# 7 G 0.1428571 0 1 0.80 0.99 0.57\n\n# GetUniqueBallots(VM6,Reputation = R6a)\n# BallotGroup BallotRep D.1 D.2 D.3 D.4 D.5\n# 1 A 0.34 0.8 0.0 0.0 0.25 0.045\n# 2 B 0.32 0.6 0.5 0.5 0.20 0.030\n# 3 C 0.34 0.4 1.0 1.0 0.15 0.015\n\n\n\n# We have succeeded in paritioning the VoteMatrix into selections. Auditors need only choose their favorite Ballot.\n# \n# Can we do better?\n# 1. An attacker will likely distort many Decisions at once, to maximize the Attack Revenue.\n# 2. Double-Factory will already sort out only the contested Decisions.\n# 3. It takes effort for each Auditor to consider each Ballot. Fewer Ballots = Less Effort, Easier Audit.\n# 4. Likely, some attacked-Decisions will be extremely-obviously false (a claim that Romney was elected in 2012).\n# \n# Auditors should be doing MUCH less work than Voters.\n# Reducing to an 0 / 1 Ballot Referendum easily allows reuse of the existing SVD consensus system.\n# \n# Goal: Reduce many unique Ballots to a maximally-representative set of 2 or 3.\n# Strategy: calculated 'Moved Reputation' and minimize it.\n# \n# EasyAuditing\n# ==========================\n\n\n\nGetTravelMatrix <- function(UniqueBallotDf) {\n # Takes the results computed by 'GetUniqueBallots' and uses them to build a matrix describing how different the Ballots are from each other.\n \n nBals <- nrow(UniqueBallotDf)\n \n DistMat <- matrix(0, nBals, nBals,dimnames = list(UniqueBallotDf$BallotGroup, UniqueBallotDf$BallotGroup))\n \n for(i in 1:nBals) { # for each Ballot-Group A, B, C...\n for(j in 1:nBals) { # for each other Ballot-Group A, B, C...\n if(i!=j) { # Diagonals will always be zero\n \n RowDifference <- UniqueBallotDf[i,-1:-2] - UniqueBallotDf[j,-1:-2] # How different are these rows?\n Distance <- sum( abs( RowDifference ) ) # Aggregate distance\n DistMat[i,j] <- Distance\n \n }\n }\n }\n \n DistMat\n \n TravelMat <- diag(UniqueBallotDf$BallotRep) %*% DistMat\n row.names(TravelMat) <- colnames(TravelMat)\n \n return(TravelMat)\n}\n\n\n# GetTravelMatrix( GetUniqueBallots(VoteMatrix = VM3, R) )\n# A B C D\n# A 0.00 1.95 1.30 0.65\n# B 0.30 0.00 0.30 0.20\n# C 0.40 0.60 0.00 0.20\n# D 0.05 0.10 0.05 0.00\n\n# GetTravelMatrix( GetUniqueBallots(VoteMatrix = VM4) )\n# A B C\n# A 0.0000000 0.1666667 0.3333333\n# B 0.1666667 0.0000000 0.1666667\n# C 0.3333333 0.1666667 0.0000000\n\n\n\n### Now, our pooling algorithm\n\n\nGetChosen <- function(TravMat, ExtractN = 2) {\n # Takes a matrix of travel-distances (\"from\" row-Ballot \"to\" column-Ballot) and finds the two nearest destinations (columns)\n \n Use('combinat')\n \n Options <- combn(colnames(TravMat), ExtractN)\n \n # If there is exactly one option, we know will chose it. Also, there will be no columns (as there will be no matrix, just a vector). \n if( is.null(ncol(Options)) ) return(Options)\n \n BallotPairs <- vector(\"numeric\", ncol(Options))\n \n # Get Chosen\n for(i in 1:ncol(Options)) {\n \n ThisDestination <- Options[,i]\n \n # remove rows where the rowname matched the entries in this Option-column\n # \"In a world where these Ballots are staying put (not going from anywhere to anwhere).\"\n \n TravMatTemp <- TravMat[ , colnames(TravMat) %in% ThisDestination ] # everyone must come to these rows\n TravMatTemp <- TravMatTemp[ !( row.names(TravMatTemp) %in% ThisDestination ) ,] # these rows aren't going anywhere\n \n if(class(TravMatTemp) ==\"numeric\") {\n # In this case, we've removed all rows except one.\n BallotPairs[i] <- sum(TravMatTemp) # Total distance\n }\n \n if(class(TravMatTemp) ==\"matrix\") {\n # Normal case\n ColMins <- apply( TravMatTemp, 1, function(x) x[which.min(x)]) # shortest path to a destination\n BallotPairs[i] <- sum(ColMins) # Total distance\n }\n \n # If TravMatTemp is of a different class, it is probably empty (and we can leave the distances at zero).\n }\n \n Chosen <- Options[ , which.min(BallotPairs) ]\n return(Chosen)\n}\n\n# GetChosen( GetTravelMatrix( GetUniqueBallots(VoteMatrix = VM3, R) ) )\n# [1] \"A\" \"C\"\n# \n# GetChosen( GetTravelMatrix( GetUniqueBallots(VoteMatrix = VM4) ) ) \n# [1] \"A\" \"C\"\n\n\nGetAuditChoices <- function(VoteMatrix, Reputation = DemocracyRep(VoteMatrix), Phi = .80) {\n # Putting it all together.\n \n # Call our functions.\n Ballots <- GetUniqueBallots(VoteMatrix, Reputation)\n Distance <- GetTravelMatrix(Ballots)\n \n # Filter small fish / spam Ballots ( because I will be doing combinatorial math next)\n SeriousCandidates <- Distance[, Ballots$BallotRep >= .05 ] # might change \".05\" to the Branch's (1-Phi)\n \n # Grab the most-representative choices, and don't stop grabbing until you have enough\n CumulativeReputation <- 0\n ExtractN <- 2\n while(CumulativeReputation < Phi) { # \".80\" should definitly be Phi\n Chosen <- GetChosen(SeriousCandidates, ExtractN)\n CumulativeReputation <- sum( Ballots[ Ballots$BallotGroup %in% Chosen , \"BallotRep\" ] )\n ExtractN <- ExtractN + 1\n }\n \n # For simplicity\n InChosen <- ( row.names(Distance) %in% Chosen )\n \n # Create two dataframes\n Choices <- Ballots[ InChosen , ]\n NonChoices <- Ballots[ !(InChosen) , ]\n \n # Get some info to tell people which Ballots contain which.\n NonChDist <- as.matrix( Distance[ !(InChosen) , InChosen ] )\n \n NonChoices$SurrogateChoice <- apply( NonChDist, 1, function(x) colnames(NonChDist)[which.min(x)] )\n \n return(list(\"Choices\"=Choices,\"NonChoices\"=NonChoices))\n \n}\n\n# GetAuditChoices(VM4)\n# \n# GetAuditChoices(VM3, R) \n# GetAuditChoices(VM3, R2) \n# \n# GetAuditChoices(VM5)\n# GetAuditChoices(VM5, R2)\n# \n# GetAuditChoices(VM6, R6a) \n# Here, we've succeeded in drawing the 'real' ballot (B) off, using 68% of the votes. However, B still has a surrogate choice (\"C\")\n# B will deterministically have a unique surrogate choice (not a \"Tie\") unless every single Decision was scaled and had a real outcome of exactly \".5\" (which is nearly impossible).\n\n\n\n\n", "meta": {"hexsha": "b8d08dcc0fce51a44c06e9b9cd6359e72baddcd6", "size": 10361, "ext": "r", "lang": "R", "max_stars_repo_path": "lib/consensus/Audit.r", "max_stars_repo_name": "endolith/Truthcoin", "max_stars_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 161, "max_stars_repo_stars_event_min_datetime": "2015-01-11T20:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:44:13.000Z", "max_issues_repo_path": "lib/consensus/Audit.r", "max_issues_repo_name": "endolith/Truthcoin", "max_issues_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2016-04-21T10:17:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T14:38:06.000Z", "max_forks_repo_path": "lib/consensus/Audit.r", "max_forks_repo_name": "endolith/Truthcoin", "max_forks_repo_head_hexsha": "448b35fb94f27e61f5989ead7ef87e03da2e9237", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 40, "max_forks_repo_forks_event_min_datetime": "2015-01-19T16:44:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T14:09:49.000Z", "avg_line_length": 34.1947194719, "max_line_length": 185, "alphanum_fraction": 0.5986873854, "num_tokens": 3785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41599267716509236}}
{"text": "#' Function to detect year transitions and calculate cumulative age of model results\n#' \n#' Takes the result of iterative growth modeling and\n#' transforms data from Julian Day (0 - 365) to cumulative\n#' day of the shell age by detecting where transitions\n#' from one year to the next occur and adding full years\n#' (365 days) to simulations in later years.\n#' @param resultarray Array containing the full results of\n#' the optimized growth model\n#' @param plotyearmarkers Should the location of identified year\n#' transitions be plotted? \\code{TRUE/FALSE}\n#' @param export_peakid Should the result of peak identification\n#' be plotted? \\code{TRUE/FALSE}\n#' @param path Export path (defaults to tempdir())\n#' @return A new version of the Julian Day tab of the resultarray \n#' with Julian Day model estimates replaced by estimates of \n#' cumulative age of the record in days.\n#' @references package dependencies: zoo 1.8.7; scales 1.1.0; graphics\n#' function dependencies: peakid\n#' @importFrom graphics plot\n#' @importFrom stats median\n#' @examples\n#' testarray <- array(NA, dim = c(40, 36, 9)) # Create empty array\n#' # with correct third dimension\n#' windowfill <- seq(50, 500, 50) %% 365 # Create dummy simulation data \n#' # (ages) to copy through the array\n#' for(i in 6:length(testarray[1, , 1])){\n#' testarray[, i, 3] <- c(windowfill, rep(NA, length(testarray[, 1, 3]) - \n#' length(windowfill)))\n#' windowfill <- c(NA, (windowfill + 51) %% 365)\n#' }\n#' # Add dummy /code{D} column.\n#' testarray[, 1, 3] <- seq(1, length(testarray[, 1, 3]), 1)\n#' # Add dummy YEARMARKER column\n#' testarray[, 3, 3] <- c(0, rep(c(0, 0, 0, 0, 0, 0, 1), 5), 0, 0, 0, 0)\n#' # Add dummy d18Oc column\n#' testarray[, 2, 3] <- sin((2 * pi * (testarray[, 1, 3] - 8 + 7 / 4)) / 7)\n#' testarray2 <- suppressWarnings(cumulative_day(testarray, FALSE, FALSE, tempdir()))\n#' # Apply function on array\n#' @export\ncumulative_day <- function(resultarray, # Align Day of year results from modeling in different windows to a common time axis\n plotyearmarkers = TRUE, # Plot peak fitting?\n export_peakid = TRUE, # Export data on how the boundaries between years were found?\n path = tempdir()\n ){\n \n dat <- resultarray[, 1:5, 3] # isolate original data\n \n # Recognition of the boundaries between years.\n # Method one: Apply sinusoidal function to the julian day simulations\n JDdat <- resultarray[, (length(dat[1, ]) + 1):length(resultarray[1, , 1]), 3] # Isolate julian day simulations\n JDdat <- matrix(sin(2 * pi * (JDdat + 365/4) / 365), ncol = ncol(JDdat)) # Convert julian day to sinusoidal value (end and start of year = 1)\n JDends <- data.frame(Depth = dat[, 1],\n Yearmarker = dat[, 3],\n YEsin = scales::rescale(rowSums(JDdat, na.rm = TRUE), c(0, 1)) # Create depth series of positions which most likely represent a year end, rescale to a scale from 0 to 1\n )\n \n # Method two: Give weight to the first and final days in reconstructions\n weightvector <- c(seq(10, 1, -1), rep(0, 346), seq(1, 10, 1)) # Create vector of weights to be given to days near the start and end of the year\n JDdat <- round(resultarray[, (length(dat[1, ]) + 1):length(resultarray[1, , 1]), 3]) # Isolate julian day simulations\n JDdat <- matrix(weightvector[JDdat + 1], ncol = ncol(JDdat)) # Apply weighting to starts and ends of the year\n JDends$YEweight <- scales::rescale(rowSums(JDdat, na.rm = TRUE), c(0, 1)) # Add normalized results to depth series\n\n # Method three: Use instances within the window simulations where the end of year is recorded\n JDdat <- resultarray[, (length(dat[1, ]) + 1):length(resultarray[1, , 1]), 3] # Isolate julian day simulations\n JDdat <- rbind(rep(NA, length(JDdat[1, ])), diff(JDdat) < 0) # Matrix of positions in individual windows where end of year (day 365) is recorded\n YEcount <- rowSums(JDdat, na.rm = TRUE) / max(rowSums(JDdat, na.rm = TRUE), na.rm = TRUE) # Aggregate the counted ends of years in simulations\n smoothfactor <- min(diff(which(JDends[, 2] == 1))) # Define smoothing factor for year end counts based on yearmarkers (take thickness of year with least growth to be conservative)\n YEcount <- c(rep(0, floor(smoothfactor / 2)), zoo::rollmean(YEcount, smoothfactor, align = \"center\"), rep(0, smoothfactor - floor(smoothfactor / 2) - 1)) # Smooth record of year end counts and pad with zeroes \n JDends$YEcount <- scales::rescale(YEcount, c(0, 1)) # Add normalized results to depth series\n\n # Method four: Use maxima in d18Oc in original data\n yearpos <- c(1, which(JDends[, 2] == 1), length(JDends$Depth)) # Extract positions of yearmarkers and include start and end of record\n yearpos <- unique(yearpos) # Remove duplicates in yearpos due to yearmarkers on beginning and/or end of record\n YE18O <- vector() # Create vector for the position of the maximum d18O value\n for(m in 1:(length(yearpos) - 1)){ # Loop through positions of yearmarkers\n if(m %in% 2:(length(yearpos) - 2)){ # central part of the record\n maxpos <- which(dat[yearpos[m] : (yearpos[m + 1] - 1), 2] == max(dat[yearpos[m] : (yearpos[m + 1] - 1), 2])) + yearpos[m] - 1 # Find the position of the maximum value in the d18O data in that year\n if(length(maxpos) > 1){\n maxpos = round(stats::median(maxpos)) # Prevent multiple values in maxpos (gives errors further in the calculations)\n }\n days <- seq(1, yearpos[m + 1] - yearpos[m], 1) * 365 / (yearpos[m + 1] - yearpos[m]) # Define sequence of \"days\" values with length = number of datapoints in the year\n sinusoid <- sin(2 * pi * (days - rep((maxpos - yearpos[m]) / (yearpos[m + 1] - yearpos[m]) * 365 - 365 / 4, length(days))) / 365) # Create sinusoid with peak at peak in d18Oc\n sinusoid[which(days > ((maxpos - yearpos[m]) / (yearpos[m + 1] - yearpos[m]) + 0.5) * 365 | days < ((maxpos - yearpos[m]) / (yearpos[m + 1] - yearpos[m]) - 0.5) * 365)] <- -1 # Assign lowest value (-1) to all datapoints more than 1/2 period away from the maximum to prevent false peaks\n YE18O <- append(YE18O, sinusoid) # add sinusoid values to running vector\n }else if(m == 1){ # beginning of the record\n maxpos <- which(dat[yearpos[m + 1] : (yearpos[m + 2] - 1), 2] == max(dat[yearpos[m + 1] : (yearpos[m + 2] - 1), 2])) + yearpos[m + 1] - 1 # Find the position of the maximum value in the d18O data of the next year (the first year that is complete)\n if(length(maxpos) > 1){\n maxpos = round(stats::median(maxpos)) # Prevent multiple values in maxpos (gives errors further in the calculations)\n }\n days <- seq(yearpos[m] - yearpos[m + 1] + 1, yearpos[m + 2] - yearpos[m + 1], 1) * 365 / (yearpos[m + 2] - yearpos[m + 1]) # Define sequence of \"days\" values\n sinusoid <- sin(2 * pi * (days - rep((maxpos - yearpos[m + 1]) / (yearpos[m + 2] - yearpos[m + 1]) * 365 - 365 / 4, length(days))) / 365) # Create sinusoid with peak at peak in d18Oc\n sinusoid[which(days > ((maxpos - yearpos[m + 1]) / (yearpos[m + 2] - yearpos[m + 1]) + 0.5) * 365 | days < ((maxpos - yearpos[m + 1]) / (yearpos[m + 2] - yearpos[m + 1]) - 0.5) * 365)] <- -1 # Assign lowest value (-1) to all datapoints more than 1/2 period away from the maximum to prevent false peaks\n YE18O <- append(YE18O, sinusoid[1:(yearpos[m + 1] - yearpos[m])]) # Add sinusoid values for first bit of record to the vector\n }else if(m == (length(yearpos) - 1)){ # end of the record\n maxpos <- which(dat[yearpos[m - 1] : (yearpos[m] - 1), 2] == max(dat[yearpos[m - 1] : (yearpos[m] - 1), 2])) + yearpos[m - 1] - 1 # Find the position of the maximum value in the d18O data of the previous year (the last year that is complete)\n if(length(maxpos) > 1){\n maxpos = round(stats::median(maxpos)) # Prevent multiple values in maxpos (gives errors further in the calculations)\n }\n days <- seq(1, yearpos[m + 1] - yearpos[m - 1], 1) * 365 / (yearpos[m] - yearpos[m - 1]) # Define sequence of \"days\" values\n sinusoid <- sin(2 * pi * (days - rep((maxpos - yearpos[m - 1]) / (yearpos[m] - yearpos[m - 1]) * 365 - 365 / 4, length(days))) / 365) # Create sinusoid with peak at peak in d18Oc\n sinusoid[which(days > ((maxpos - yearpos[m - 1]) / (yearpos[m] - yearpos[m - 1]) + 0.5) * 365 | days < ((maxpos - yearpos[m - 1]) / (yearpos[m] - yearpos[m - 1]) - 0.5) * 365)] <- -1 # Assign lowest value (-1) to all datapoints more than 1/2 period away from the maximum to prevent false peaks\n YE18O <- append(YE18O, sinusoid[(yearpos[m] - yearpos[m - 1]):(yearpos[m + 1] - yearpos[m - 1])]) # Add sinusoid values for last bit of record to the vector\n }\n }\n JDends$YE18O <- scales::rescale(YE18O, c(0, 1)) # Add normalized results to depth series\n JDends$YEcombined <- scales::rescale(rowSums(JDends[, -c(1,2)]), c(0, 1)) # Combine all four methods of peak recognition into one vector\n\n # Use peak ID algorhythm to find peaks in the combined vector of year end indicators to use as basis for cumulative day counting in the model results\n wmin <- round(min(diff(which(JDends[,2] == 1))) / 4) # Define starting window for peak recognition as one forth the minimum width of a year\n wmax <- round(min(diff(which(JDends[,2] == 1))) / 2) # Define maximum window for peak recognition as half the minimum width of a year\n YM <- length(which(JDends[,2] == 1)) # Extract number of years in record\n X <- list(w = vector(), p = vector()) # List for storing results\n w <- wmin # Start at minimum window size\n repeat{\n peaks <- peakid(JDends$Depth, JDends$YEcombined, w = w, span = 0.05) # Identify peaks based on current threshold\n if(length(peaks$x) == YM){ # Check if the number of years is correct and break loop if it is\n break\n }else if(w < wmax){ # Check if maximum window is reached\n X$w <- append(X$w, w) # Store window size\n X$p <- append(X$p, length(peaks$x)) # Store peak number\n w <- w + 1 # Increment window size\n }else{\n X$w <- append(X$w, w) # Store window size\n X$p <- append(X$p, length(peaks$x)) # Store peak number\n w <- max(X$w[which(abs(X$p - YM) == min(abs(X$p - YM)))]) # If no windows give the exact number of years, take the window that comes closer (prioritize larger windows in case of a tie)\n peaks <- peakid(JDends$Depth, JDends$YEcombined, w = w, span = 0.05) # Recalculate peak positions with the final chosen window size before breaking the loop\n break\n }\n }\n JDends$peakid <- rep(0, length(JDends[,1])) # Add column for peakid results\n JDends$peakid[peaks$i] <- 1 # Mark the location of peaks found in the time series\n\n if(plotyearmarkers == TRUE){\n dev.new()\n graphics::plot(JDends$Depth,\n JDends$YEcombined,\n type = \"l\",\n main = \"Peak fitting results\",\n xlab = \"Depth\",\n ylab = \"Probability of end of year\") # Plot aggregate of yearmarkers\n points(peaks$x, rep(1, length(peaks$x)), col = \"red\") # Plot location of yearmarkers\n }\n\n if(export_peakid == TRUE){\n write.csv(JDends, file.path(path, \"peakid.csv\"))\n }\n\n # Apply calculation of years in the model on the simulation results\n JDdat <- resultarray[, (length(dat[1, ]) + 1):length(resultarray[1, , 1]), 3] # Isolate julian day simulations\n for(col in 1:length(JDdat[1, ])){ # Loop through all simulation windows\n window <- JDdat[, col] # Isolate simulation window\n peakx <- head(which(peaks$x %in% dat[which(!is.na(window)), 1]), 1) # Find position of the first year end in the window column\n if(length(peakx) == 0){\n if(peaks$x[1] < dat[head(which(!is.na(window)), 1), 1]){ # If no global year transitions fall within the window, check if there are global year transitions before the window and find the last year transition before the first value in the window\n peakx <- max(which(peaks$x < dat[head(which(!is.na(window)), 1), 1])) # Find number of years before start of window\n JDpeak <- window[head(which(!is.na(window)), 1)] # Find the day of year of the first simulated value\n if(JDpeak < 182.5){\n window <- window + peakx * 365 # If first simulated value co-occurs with first half of the year, add all years before the window\n }else{\n window <- window + (peakx - 1) * 365 # If year first simulated value co-occurs with last half of the year, simulated values are assumed to belong to the previous year\n }\n } # If all year transitions happen after the window, no year number needs to be added to the window values\n }else{\n JDpeak <- JDdat[tail(which(dat[, 1] == peaks$x[peakx] & !is.na(window)), 1), col] # Find JD simulation belonging to the first year transition\n if(JDpeak < 182.5){ \n window <- window + peakx * 365 # If year transition co-occurs with first half of the simulated year, all simulated values are assumed to belong to the next year\n }else{\n window <- window + (peakx - 1) * 365 # If year transition co-occurs with last half of the simulated year, all simulated values are assumed to belong to the previous year\n }\n }\n if(length(which(diff(window) < 0)) > 0){ # Check if year transitions occur within the simulation\n for(i in which(diff(window) < 0)){\n if(length(peakx) > 0){ # Check if global year transitions occur within the window\n if(i < which(dat[, 1] == peaks$x[peakx])){\n window[1:i] <- window[1:i] - 365 # If the transition happens before the reference point (peakx), subtract a year's worth of days from the values before to prevent adding a year twice.\n }else{\n window[(i + 1):length(window)] <- window[(i + 1):length(window)] + 365 # If the transition happens on or after the reference point (peakx), add one year's worth of days to simulations after each transition\n }\n }else{\n window[(i + 1):length(window)] <- window[(i + 1):length(window)] + 365 # If no global transitions occur within the window, add one year's worth of days to simulations after each local transition\n }\n }\n }\n JDdat[, col] <- window # Update the julian day data with the new cumulative day simulations\n }\n\n # Screen for extreme outliers in JD due to very bad simulations based on first and last modeled values\n firstval <- apply(JDdat, 2, min, na.rm = TRUE) # find first values of all modeling windows\n lastval <- apply(JDdat, 2, max, na.rm = TRUE) # find last values of all modeling windows\n badwindow <- rep(FALSE, ncol(JDdat)) # Vector indicating if window simulation is bad\n for(i in 2:(ncol(JDdat) - 1)){\n if(((abs(firstval[i] - firstval[i - 1]) > 365) & (abs(firstval[i + 1] - firstval[i])) > 365) | ((abs(lastval[i] - lastval[i - 1]) > 365) & (abs(lastval[i + 1] - lastval[i])))){ # Find windows with large (> 1 year) jumps in either first or last value\n badwindow[i] <- TRUE # Label these windows as bad\n }\n }\n JDdat[, badwindow] <- rep(NA, nrow(JDdat)) # Remove values from bad windows to prevent messing up the age model\n\n result <- resultarray[, , 3]\n result[, 6:length(result[1, ])] <- JDdat # Add the updated cumulative julian day results to the resultarray and export\n return(result)\n}", "meta": {"hexsha": "5fa1642eb97a4781d47ddc8770e3f43a256a074b", "size": 15719, "ext": "r", "lang": "R", "max_stars_repo_path": "R/cumulative_day.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/cumulative_day.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/cumulative_day.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": 77.8168316832, "max_line_length": 313, "alphanum_fraction": 0.6336280934, "num_tokens": 4504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.41595769931924187}}
{"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# number of edges\nnedge<-8\n\n# vector declarations\n# see below for their meaning\nedgelab<-vector(mode=\"character\",length=nedge)\nr<-vector(mode=\"numeric\",length=nedge)\nw<-vector(mode=\"numeric\",length=nedge)\n\n# edge names\n# only relevant if edge states are plotted\n# plotting edge states is currently not implemented\nedgelab[1]<-\"EGF__EGFR\"\nedgelab[2]<-\"HRG__EGFR\"\nedgelab[3]<-\"EGFR__Raf\"\nedgelab[4]<-\"AKT__Raf\"\nedgelab[5]<-\"Raf__ERK\"\nedgelab[6]<-\"EGFR__PI3K\"\nedgelab[7]<-\"ERK__PI3K\"\nedgelab[8]<-\"PI3K__AKT\"\n\n# edge reactivity\n# for each edge and at each iteration of the simulation: the portion of its state which is updated\n# here randomly selected between 0.3 and 0.7 as example\nr[1]<-runif(1,0.3,0.7)# EGF__EGFR\nr[2]<-runif(1,0.3,0.7)# HRG__EGFR\nr[3]<-runif(1,0.3,0.7)# EGFR__Raf\nr[4]<-runif(1,0.3,0.7)# AKT__Raf\nr[5]<-runif(1,0.3,0.7)# Raf__ERK\nr[6]<-runif(1,0.3,0.7)# EGFR__PI3K\nr[7]<-runif(1,0.3,0.7)# ERK__PI3K\nr[8]<-runif(1,0.3,0.7)# PI3K__AKT\n\n# edge weakening\n# for each edge and at each iteration of the simulation: the weakening coefficient applied on the updated portion of its state\n# here randomly selected between 0.7 and 1 as example\nw[1]<-runif(1,0.7,1)# EGF__EGFR\nw[2]<-runif(1,0.7,1)# HRG__EGFR\nw[3]<-runif(1,0.7,1)# EGFR__Raf\nw[4]<-runif(1,0.7,1)# AKT__Raf\nw[5]<-runif(1,0.7,1)# Raf__ERK\nw[6]<-runif(1,0.7,1)# EGFR__PI3K\nw[7]<-runif(1,0.7,1)# ERK__PI3K\nw[8]<-runif(1,0.7,1)# PI3K__AKT\n\n# edge updating function\n# for all edges and at each iteration of the simulation: the function which calculates their updated states\nfedge<-function(node,k,nedge) {\n y<-vector(mode=\"numeric\",length=nedge)\n y[1]<-node[1,k]# EGF__EGFR\n y[2]<-node[2,k]# HRG__EGFR\n y[3]<-node[3,k]# EGFR__Raf\n y[4]<-node[7,k]# AKT__Raf\n y[5]<-node[4,k]# Raf__ERK\n y[6]<-node[3,k]# EGFR__PI3K\n y[7]<-node[5,k]# ERK__PI3K\n y[8]<-node[6,k]# PI3K__AKT\n return(y)\n}\n", "meta": {"hexsha": "a5ca7c42f9ebc79374c8de01909195fb954316e0", "size": 2053, "ext": "r", "lang": "R", "max_stars_repo_path": "edge.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": "edge.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": "edge.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": 32.078125, "max_line_length": 126, "alphanum_fraction": 0.6980029226, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.41593193428626046}}
{"text": "#' Population interpolation annual and single age in MSDem\n#'\n#' This function allows you to calculate population size by sex or by regions using the MSDem output\n#' @param res1 data\n#' @param agel lower limit - default is 0\n#' @param ageu upper limit - default it 'max'\n#' @param period specific periods - default is NULL\n#' @param sex specific sex - default is NULL\n#' @param bysex group by sex - default is FALSE\n#' @param reg specific region(s)\n#' @param byreg group by regions - default is FALSE\n#' @param resi specific residence(s)\n#' @param byresi group by residences - default is FALSE\n#' @return R list with five data.table 1) var_def 2) state_space 3) mig_dom 4) mig_int 5) results\n#' @keywords read\n#' @export\n#' @examples\n\n# 1. The initial data as you have seen are for 5-year periods and 5-year intervals (on 1 july of each year),\n#\n# 2. so the interpolation is done first to create a cross-sectional annual time series of 5-year age groups\n# (1-BeersOInterpol.r and IND_Pop2015B5_1.7.csv as sample input test data for India population both sexes for 2015 WPP revision),\n#\n# 3. and then it gets transformed into single ages (e.g., IND_Pop2015B1x1-step1-sprague.csv),\n#\n# 4. and interpolated by cohort for the pivotal years ending in 0 and 5 for which the estimates/projections are available\n# (2-SpragueSplit.r).\n#\n# At very old ages some alternative method with additional constraint needs to be added\n# to avoid implausible negative populations (e.g., IND_Pop2015B1x1-step2-pchipGE90.csv).\n#\n# A special provision is needed to deal with the youngest age group and oldest age groups which cannot be\n# interpolated by cohort.\n#\n# The cohort interpolation can be done using linear or exponential interpolation.\n# In previous WPP revisions the interpolation used was linear, but exponential interpolation alleviates\n# some of the artifact fluctuations.\n\npopinterpkc <- function(x){\n x<<-x\n head(x)\n # stop()\n #1. The initial data as you have seen are for\n #5-year periods and 5-year intervals (on 1 july of each year),\n\n iage <- sort(unique(x$age))\n iper <- unique(x$period)\n x1<-x%>%select(period,age,pop)%>%spread(period,pop)%>%select(-age)\n\n # xx_8_90 <- x1[-19,8]*(x1[-1,8]/x1[-19,7])\n # xx_age0_4 <- (x1[1,8]/sum(x1[5:8,8]))*sum(xx_8_90[4:7,1])\n # x1[,9] <- rbind(xx_age0_4,xx_8_90)\n #colnames(x1)[6] <- 2036\n x1 <- as.matrix(x1)\n row.names(x1) <- iage\n\n # 2. so the interpolation is done first to create a cross-sectional annual time series of 5-year age groups\n # (1-BeersOInterpol.r and IND_Pop2015B5_1.7.csv as sample input test data for India population both sexes for 2015 WPP revision),\n tp <- t(x1)\n YEAR <- as.numeric(substr(rownames(tp),1,4))\n FYEAR <- min(YEAR) #2011\n LYEAR <- max(YEAR) #2021\n ## dimensions\n NY <- 5 # Number of years in period\n NCOL <- dim(tp)[2] # number of data columns/number of countries/time series\n NYEAR5 <- dim(tp)[1] # number of five year period\n NYEAR1 <- (NYEAR5 - 1) * 5 + 1 # number of single years\n ## Beers Ordinary Interpol\n bc <- c(\n 1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,\n 0.6667, 0.4969, -0.1426, -0.1006, 0.1079, -0.0283,\n 0.4072, 0.8344, -0.2336, -0.0976, 0.1224, -0.0328,\n 0.2148, 1.0204, -0.2456, -0.0536, 0.0884, -0.0244,\n 0.0819, 1.0689, -0.1666, -0.0126, 0.0399, -0.0115,\n 0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 0.0000,\n -0.0404, 0.8404, 0.2344, -0.0216, -0.0196, 0.0068,\n -0.0497, 0.6229, 0.5014, -0.0646, -0.0181, 0.0081,\n -0.0389, 0.3849, 0.7534, -0.1006, -0.0041, 0.0053,\n -0.0191, 0.1659, 0.9354, -0.0906, 0.0069, 0.0015,\n 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000,\n 0.0117, -0.0921, 0.9234, 0.1854, -0.0311, 0.0027,\n 0.0137, -0.1101, 0.7194, 0.4454, -0.0771, 0.0087,\n 0.0087, -0.0771, 0.4454, 0.7194, -0.1101, 0.0137,\n 0.0027, -0.0311, 0.1854, 0.9234, -0.0921, 0.0117,\n 0.0000, 0.0000, 0.0000 , 1.0000, 0.0000, 0.0000,\n 0.0015, 0.0069, -0.0906 , 0.9354, 0.1659, -0.0191,\n 0.0053, -0.0041, -0.1006 , 0.7534, 0.3849, -0.0389,\n 0.0081, -0.0181, -0.0646 , 0.5014, 0.6229, -0.0497,\n 0.0068, -0.0196, -0.0216 , 0.2344, 0.8404, -0.0404,\n 0.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000,\n -0.0115, 0.0399, -0.0126, -0.1666, 1.0689, 0.0819,\n -0.0244, 0.0884, -0.0536, -0.2456, 1.0204, 0.2148,\n -0.0328, 0.1224, -0.0976, -0.2336, 0.8344, 0.4072,\n -0.0283, 0.1079, -0.1006, -0.1426, 0.4969, 0.6667,\n 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000\n )\n\n\n ## Format for Beers ordinary coefficients 26 x 6 fixed\n ##first part is added\n bm <- matrix(bc,26,6,byrow = T)\n\n # number of middle panels\n MP <- NYEAR5 - 5 #Issue, I have NYEARS = 3\n\n ## creating a beers coefficient matrix for single years\n bcm <- array(0, dim = c(NYEAR1,NYEAR5))\n\n ## inserting first two panels\n bcm[1:10,1:6] <- bm[1:10,]\n\n # inserting middle panels\n for (i in (1:MP))\n {\n # calculate the slices and add middle panels accordingly\n bcm[((i + 1)*NY + 1):((i + 2)*NY), i:(i + NY)] <- bm[11:15,]\n }\n ## insert last two panels\n bcm[((NYEAR5 - 3)*NY + 1):(NYEAR1),MP:(MP + NY)]<- bm[16:26,]\n options(max.print = 10000000)\n pop <- bcm %*% as.matrix(tp)\n colnames(pop) <- colnames(tp)\n rownames(pop) <- c(FYEAR:LYEAR)\n\n tp <-t(pop)\n Age5 <- as.numeric(row.names(tp))\n\n return(data.frame(age=Age5,tp))\n\n}\n# At very old ages some alternative method with additional constraint needs to be added\n# to avoid implausible negative populations (e.g., IND_Pop2015B1x1-step2-pchipGE90.csv).\n#\n# A special provision is needed to deal with the youngest age group and oldest age groups which cannot be\n# interpolated by cohort.\n#\n# The cohort interpolation can be done using linear or exponential interpolation.\n# In previous WPP revisions the interpolation used was linear, but exponential interpolation alleviates\n# some of the artifact fluctuations.\n\n\n\n\n# births.interp <-function(x) {\n# ########################################################################\n# ## Interpolation of of event data (five year periods)\n# ## fifth/single years by Beers Modified six-term formula\n# ## (Siegel and Swanson, 2004, p. 729)\n# ## This formula applies some smoothing to the interpolant, which is\n# ## recommended for time series of events with some dynamic\n# ## R implementation by Thomas Buettner (21 Oct. 2015)\n# ########################################################################\n#\n#\n#\n# x <<- x\n# tp <- x$births\n# #stop(\"..\")\n# ## interpolation period\n# YEAR1 <- (x$year)\n# YEAR2 <- (x$year)+5\n# YEAR <- 0.5 + (YEAR1 + YEAR2)/2\n#\n# FYEAR <- min(YEAR1) #1950\n# LYEAR <- max(YEAR2) #2100\n# LYEAR1 <- LYEAR - 1\n#\n# ## dimensions\n# NCOL =1\n# #NCOL <- dim(tp)[2] ## countries or trajectories\n# #NAG5 <- dim(tp)[1] ## age or time\n# NAG5 = length(YEAR1)\n# # number of single year or single age groups\n# NAG1 <- NAG5 * 5\n#\n# ## Beers Modified Split\n# bc <- c(\n# 0.3332, -0.1938, 0.0702, -0.0118, 0.0022 ,\n# 0.2569, -0.0753, 0.0205, -0.0027, 0.0006 ,\n# 0.1903, 0.0216, -0.0146, 0.0032, -0.0005 ,\n# 0.1334, 0.0969, -0.0351, 0.0059, -0.0011 ,\n# 0.0862, 0.1506, -0.0410, 0.0054, -0.0012 ,\n#\n# 0.0486, 0.1831, -0.0329, 0.0021, -0.0009 ,\n# 0.0203, 0.1955, -0.0123, -0.0031, -0.0004 ,\n# 0.0008, 0.1893, 0.0193, -0.0097, 0.0003 ,\n# -0.0108, 0.1677, 0.0577, -0.0153, 0.0007 ,\n# -0.0159, 0.1354, 0.0972, -0.0170, 0.0003 ,\n#\n# -0.0160, 0.0973, 0.1321, -0.0121, -0.0013 ,\n# -0.0129, 0.0590, 0.1564, 0.0018, -0.0043 ,\n# -0.0085, 0.0260, 0.1650, 0.0260, -0.0085 ,\n# -0.0043, 0.0018, 0.1564, 0.0590, -0.0129 ,\n# -0.0013, -0.0121, 0.1321, 0.0973, -0.0160 ,\n#\n# 0.0003, -0.0170, 0.0972, 0.1354, -0.0159 ,\n# 0.0007, -0.0153, 0.0577, 0.1677, -0.0108 ,\n# 0.0003, -0.0097, 0.0193, 0.1893, 0.0008 ,\n# -0.0004, -0.0031, -0.0123, 0.1955, 0.0203 ,\n# -0.0009, 0.0021, -0.0329, 0.1831, 0.0486 ,\n#\n# -0.0012, 0.0054, -0.0410, 0.1506, 0.0862 ,\n# -0.0011, 0.0059, -0.0351, 0.0969, 0.1334 ,\n# -0.0005, 0.0032, -0.0146, 0.0216, 0.1903 ,\n# 0.0006, -0.0027, 0.0205, -0.0753, 0.2569 ,\n# 0.0022, -0.0118, 0.0702, -0.1938, 0.3332\n# )\n# ## standard format for Beers coefficients\n# bm <- matrix(bc,25,5,byrow = T)\n#\n# ## Age vector\n# a <- seq(0, (NAG5 - 1)*5, by = 5)\n#\n# # number of middle panels\n# MP <- NAG5 - 5 + 1\n#\n# ## creating a beers coefficient matrix for 18 5-year age groups\n# bcm <- array(0, dim = c(NAG1,NAG5))\n#\n# ## insert first two panels\n# bcm[1:10,1:5] <- bm[1:10,]\n#\n# for (i in (1:MP))\n# {\n# # calculate the slices and add middle panels accordingly\n# bcm[((i + 1)*5 + 1):((i + 2)*5), i:(i + 4)] <- bm[11:15,]\n# }\n#\n# ## insert last two panels\n# bcm[((NAG5 - 2)*5 + 1):(NAG5*5),MP:(MP + 4)] <- bm[16:25,]\n#\n# options(max.print = 10000000)\n#\n# pop <- bcm %*% as.matrix(tp)\n#\n# ## write un-shifted results\n# ## write.csv(pops, ofn)\n#\n# ## shifting the interpolant by half a year forward\n# ## In general, each interval is halved and the the halves are recombined to form a calendar year.\n# ## The first missing half year is assumed to be equal the half of the first interval.\n# ## This means simply that the first year is equal to the first (shifted) interval\n# ## The implementation used vector arithmetic by constructing a parallel data array\n# ## with the first element equal to the original first interval,\n# ## and filling the rest with the original data up to n-1 elements\n# ## Adding the two data structures and dividing the result by two\n# ## produces the shifted time reference.\n#\n# pop2 <- array(0, dim = c(NAG1,NCOL))\n# pop2[1,] <- pop[1,]\n# pop2[2:NAG1,] <- pop[1:(NAG1 - 1),]\n# pops <- (pop + pop2)*0.5\n#\n# return(data.frame(value=pops)%>%mutate(year=seq(FYEAR,LYEAR-1,by=1)))\n#\n# }\n", "meta": {"hexsha": "93c81633653136ee7d93c362b8b50312161d1aa6", "size": 9957, "ext": "r", "lang": "R", "max_stars_repo_path": "R/popinterpkc.r", "max_stars_repo_name": "kcsamir/mdpop", "max_stars_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-09T11:50:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T11:50:05.000Z", "max_issues_repo_path": "R/popinterpkc.r", "max_issues_repo_name": "kcsamir/mdpop", "max_issues_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-08-20T10:32:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-20T10:53:29.000Z", "max_forks_repo_path": "R/popinterpkc.r", "max_forks_repo_name": "kcsamir/mdpop", "max_forks_repo_head_hexsha": "1d1330b0fbbae8ea1eb893b3f6a3c5d91f48b73f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7431906615, "max_line_length": 131, "alphanum_fraction": 0.6097218038, "num_tokens": 4102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4151277937122631}}
{"text": "# Load the rjags library\nlibrary('rjags')\n\n# Convert to a list\nmake_list <- function(draw)\n{\n\tresults = list()\n\tfor(name in names(draw))\n\t{\n\t\t# Extract \"chain 1\"\n\t\tresults[[name]] = as.array(draw[[name]][,,1])\n\t\t\n\t\t# Transpose 2D arrays\n\t\tif(length(dim(results[[name]])) == 2)\n\t\t\tresults[[name]] = t(results[[name]])\n\t}\n\treturn(results)\n}\n\n# Load data from file\nsource('data.txt')\n\n# Run model 1 and save results\nm = jags.model(file='model1.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=list(N1=data$N1, N2=data$N2))\nupdate(m, 10000)\ndraw = jags.samples(m, 50000, thin=10,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(5000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='prior1.txt', row.names=FALSE, col.names=FALSE)\n\n# Run model 2 and save results\nm = jags.model(file='model2.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=list(N1=data$N1, N2=data$N2))\nupdate(m, 10000)\ndraw = jags.samples(m, 50000, thin=10,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(5000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='prior2.txt', row.names=FALSE, col.names=FALSE)\n\n# Run model 3 and save results\nm = jags.model(file='model3.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=list(N1=data$N1, N2=data$N2))\nupdate(m, 10000)\ndraw = jags.samples(m, 50000, thin=10,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(5000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='prior3.txt', row.names=FALSE, col.names=FALSE)\n\n\n# Run model 1 and save results\nm = jags.model(file='model1.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=data)\nupdate(m, 10000)\ndraw = jags.samples(m, 100000, thin=100,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(1000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='chains1.txt', row.names=FALSE, col.names=FALSE)\nprint(mean(results$mu1 < results$mu2))\nprint(mean(results$mu1 == results$mu2))\nprint(mean(results$mu1 > results$mu2))\n\n# Run model 2 and save results\nm = jags.model(file='model2.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=data)\nupdate(m, 10000)\ndraw = jags.samples(m, 100000, thin=100,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(1000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='chains2.txt', row.names=FALSE, col.names=FALSE)\nprint(mean(results$mu1 < results$mu2))\nprint(mean(results$mu1 == results$mu2))\nprint(mean(results$mu1 > results$mu2))\n\n# Run model 3 and save results\nm = jags.model(file='model3.txt', inits=list(.RNG.seed=42, .RNG.name=\"base::Mersenne-Twister\"), data=data)\nupdate(m, 10000)\ndraw = jags.samples(m, 100000, thin=100,\n\t\tvariable.names = c('mu1', 'mu2', 'sigma'))\nresults = make_list(draw)\nchains = array(NA, dim=c(1000, 3))\nchains[,1] = results$mu1\nchains[,2] = results$mu2\nchains[,3] = results$sigma\nwrite.table(chains, file='chains3.txt', row.names=FALSE, col.names=FALSE)\nprint(mean(results$mu1 < results$mu2))\nprint(mean(results$mu1 == results$mu2))\nprint(mean(results$mu1 > results$mu2))\n\n\n", "meta": {"hexsha": "9f9d77d30f25a1d4f36fbb63457088d4b409e20b", "size": 3525, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/TTest/main.r", "max_stars_repo_name": "xulinpan/stat331", "max_stars_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55, "max_stars_repo_stars_event_min_datetime": "2015-03-09T18:03:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T03:36:54.000Z", "max_issues_repo_path": "Code/TTest/main.r", "max_issues_repo_name": "xulinpan/stat331", "max_issues_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-07-07T05:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-10T08:48:27.000Z", "max_forks_repo_path": "Code/TTest/main.r", "max_forks_repo_name": "xulinpan/stat331", "max_forks_repo_head_hexsha": "7ca22bf3ce2c43d1a3b5fd8ff22842bdeb87ecf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-07-29T14:34:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T20:04:47.000Z", "avg_line_length": 33.2547169811, "max_line_length": 130, "alphanum_fraction": 0.6893617021, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4150259878273743}}
{"text": "# take input from the user\nnum = as.integer(readline(prompt = \"Enter a number: \"))\nif(num < 0) {\nprint(\"Enter a positive number\")\n} else {\nsum = (num * (num + 1)) / 2;\nprint(paste(\"The sum is\", sum))\n}", "meta": {"hexsha": "39d5ce1dcab3daf14dfc640099b417dae73ab1c4", "size": 201, "ext": "r", "lang": "R", "max_stars_repo_path": "find_sum_of_natural_numbers_using_a_formula.r", "max_stars_repo_name": "MarcosFloresta/R_Examples", "max_stars_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "find_sum_of_natural_numbers_using_a_formula.r", "max_issues_repo_name": "MarcosFloresta/R_Examples", "max_issues_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_sum_of_natural_numbers_using_a_formula.r", "max_forks_repo_name": "MarcosFloresta/R_Examples", "max_forks_repo_head_hexsha": "1ca3a7db0c7c82b352653ef70a6c7311f295b212", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.125, "max_line_length": 55, "alphanum_fraction": 0.6218905473, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.41498493464827146}}
{"text": "REBOL\n[\n title: \"Code to implement printf natively\"\n]\n\ndbg: [ here: ( print here ) ]\n\nformat: func [\n fmt [string!] {Format to print}\n data [ block!] {Block of data to put into fmt}\n /local \n\t;o\n][\n o: context [\n\tstr: copy \"\"\n\tchar: none\n\t\n\tval: fills: none\n\n\tfillchar: #\" \"\n\talign-char: none\n\tn-space: 0\n\tn-fracts: 6\n\tfmt-char: none\n\n\n\tdigit: charset [ #\"0\" - #\"9\" ]\n\n\tdata-pattern: [\n\t ( align-char: fillchar: signchar: none )\n\t #\"%\"\n\t opt [\n\t\t[ copy align-char #\"-\" ]\n\t\t|\n\t\t[ copy fillchar #\"0\" ]\n\t\t| copy signchar #\"+\"\n\t ]\n\t copy n-space any digit\n\t opt [\n\t\t#\".\" copy n-fracts any digit\n\t\t]\n\t copy fmt-char [\n\t\t#\"f\"\n\t\t| #\"g\"\n\t\t| #\"e\" \n\t\t| #\"E\" \n\t\t| #\"d\" \n\t\t| #\"i\" \n\t\t| #\"s\"\n\t ]\n\t (\n\t\tn-space: to-integer any [ n-space 0 ]\n\t\tn-fracts: to-integer any [ n-fracts 6 ]\n\n\t\tval: first+ data\n\t\tunless val [\n\t\t make error! \"Not enough data to print, number of specifiers larger than data\"\n\t\t]\n\n\t\tval: switch fmt-char [\n\t\t \"s\"\t\t[ to-string val ]\n\t\t \"d\" \"i\"\t[ num-to-string-d abs val ]\n\t\t \"f\"\t\t[ num-to-string-f abs val n-fracts ]\n\t\t \"e\" \"E\"\t[ num-to-string-e abs val n-fracts fmt-char ]\n\t\t]\n\n\t\tfills: max 0 n-space - length? val\n\t\teither align-char == #\"+\" [\n\t\t insert/dup tail str fillchar fills\n\t\t append str val\n\t\t][\n\t\t append str val\n\t\t insert/dup tail str fillchar fills\n\t\t]\n\t )\n\t]\n\n\tpattern: [\n\t any [ data-pattern | copy char skip ( append str char ) ] \n\t]\n\n\tnum-to-string-d: func [ num [ integer! ] /local str ] [\n\t str: copy \"\"\n\n\t unless num >= 0 [\n\t\tappend str \"-\"\n\t\tstr: next str\n\t\tnum: negate num\n\t ]\n\t until [\n\t\tfrac: mod num 10\n\t\tinsert str round/floor frac\n\t\tnum: num - frac\n\t\tnum: num / 10\n\t\tnum < 1.0\n\t ]\n\t head str\n\t]\n\n\tnum-to-string-f: func [ num n-fracts /local str ][\n\t str: copy \"\"\n\n\t unless num >= 0 [\n\t\tappend str \"-\"\n\t\tstr: next str\n\t\tnum: negate num\n\t ]\n\n\t num: num * ( 10.0 ** n-fracts ) \n\t loop n-fracts [\n\t\tfrac: mod num 10\n\t\tinsert str round/half-ceiling frac\n\t\tnum: num - frac\n\t\tnum: num / 10\n\t ]\n\t insert str #\".\"\n\t until [\n\t\tfrac: mod num 10\n\t\tinsert str round/floor frac\n\t\tnum: num - frac\n\t\tnum: num / 10\n\t\tnum < 1.0\n\t ]\n\t head str\n\t]\n\tnum-to-string-e: func [\n\t num n-fracts modifier\n\t /local str n\n\t] [\n\t str: copy \"\"\n\t n: round/floor log-10 abs num\n\t num: num / (10.0 ** n )\n\t str: num-to-string-f num n-fracts\n\t append str modifier\n\t append str n-fracts\n\t]\n\t \n\n\n\tparse/all/case fmt pattern \n ]\n\n return o/str\n]\n\t\ntest-base: func [ fmt dta] [\n prin my: format fmt dta\n prin std: sprintf join [ fmt ] dta\n either my == std [\n\tprint \"-- OK\"\n ][\n\tprint \"-- Fault\"\n ]\n]\ntest-string: does [\n fmt: \"<%s> <%10s> <%-10s> <%010s> ---\"\n dta: [\"a\" \"b\" \"c\" \"d\"]\n test-base fmt dta\n]\n\ntest-f: does [\n fmt: \"%f %10f %-10f %4.2f %-10.3f %3.8f ---\"\n dta: reduce [ pi pi pi pi pi pi]\n test-base fmt dta\n]\ntest-e: does [\n fmt: \"%E %10e %-10E %4.2E %-10.3e %3.8E ---\"\n dta: reduce [ pi pi pi pi pi pi]\n test-base fmt dta\n]\n\ntest-d: does [\n fmt: \"%d %10d %-10d %2d^/\"\n dta: reduce [ random 1000 random 1000 random 10000 3 ]\n test-base fmt dta\n]\n\ntest-string\ntest-f\ntest-e\ntest-d\n\n", "meta": {"hexsha": "365c77ee2acb2b8780512f93461c543da1423947", "size": 3215, "ext": "r", "lang": "R", "max_stars_repo_path": "printf-experimental.r", "max_stars_repo_name": "ingvast/pdf-export", "max_stars_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-04-19T16:01:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T09:25:22.000Z", "max_issues_repo_path": "printf-experimental.r", "max_issues_repo_name": "ingvast/pdf-export", "max_issues_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "printf-experimental.r", "max_forks_repo_name": "ingvast/pdf-export", "max_forks_repo_head_hexsha": "4b9f29653c7e1e5bc907c9acddcea821ca7cc732", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5683060109, "max_line_length": 83, "alphanum_fraction": 0.5306376361, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4149331065726166}}
{"text": "\n# Load EISMINT1 data \nload_eismint1_moving = function(fldr)\n{\n xHt1 = read.table(file.path(fldr,\"EISMINT1-moving_x-H_type1.txt\"),header=TRUE)\n xHt2 = read.table(file.path(fldr,\"EISMINT1-moving_x-H_type2.txt\"),header=TRUE)\n xHe = read.table(file.path(fldr,\"EISMINT1-moving_x-H_exactmargin.txt\"),header=TRUE)\n \n xuxy = read.table(file.path(fldr,\"EISMINT1-moving_x-uxy_mean.txt\"),header=TRUE)\n xtprime = read.table(file.path(fldr,\"EISMINT1-moving_x-T_prime_base.txt\"),header=TRUE)\n tprime = read.table(file.path(fldr,\"EISMINT1-moving_divide_T_prime.txt\"),header=TRUE)\n uz = read.table(file.path(fldr,\"EISMINT1-moving_divide_uz.txt\"),header=TRUE)\n\n eis1 = list(x=seq(0,750,by=10),s=seq(0,1,by=0.05))\n \n # Variables versus distance from divide x\n eis1$Ht1 = approx(x=xHt1$x,y=xHt1$H, xout=eis1$x,rule=2)$y \n eis1$Ht2 = approx(x=xHt2$x,y=xHt2$H, xout=eis1$x,rule=2)$y \n eis1$He = approx(x=xHe$x, y=xHe$H, xout=eis1$x,rule=2)$y \n eis1$uxy_mean = approx(x=xuxy$x,y=xuxy$uxy_mean,xout=eis1$x,rule=2)$y \n eis1$T_prime_base = approx(x=xtprime$x,y=xtprime$T_prime_base,xout=eis1$x,rule=2)$y \n\n # Variables at divide versus normalized ice thickness sigma \n eis1$T_prime = approx(x=tprime$sigma,y=tprime$T_prime,xout=eis1$s,rule=2)$y \n eis1$uz = approx(x=uz$sigma, y=uz$uz, xout=eis1$s,rule=2)$y \n\n return(eis1)\n}\n\nload_eismint1_fixed = function(fldr)\n{\n xHt1 = read.table(file.path(fldr,\"EISMINT1-fixed_x-H_type1.txt\"),header=TRUE)\n xHt2 = read.table(file.path(fldr,\"EISMINT1-fixed_x-H_type2.txt\"),header=TRUE)\n\n xuxy = read.table(file.path(fldr,\"EISMINT1-fixed_x-uxy_mean_3D.txt\"),header=TRUE)\n # xtprime = read.table(file.path(fldr,\"EISMINT1-fixed_x-T_prime_base.txt\"),header=TRUE)\n\n eis1 = data.frame(x=seq(0,750,by=10))\n eis1$Ht1 = approx(x=xHt1$x,y=xHt1$H, xout=eis1$x,rule=2)$y \n eis1$Ht2 = approx(x=xHt2$x,y=xHt2$H, xout=eis1$x,rule=2)$y \n eis1$uxy_mean = approx(x=xuxy$x,y=xuxy$uxy_mean,xout=eis1$x,rule=2)$y \n # eis1$T_prime_base = approx(x=xtprime$x,y=xtprime$T_prime_base,xout=eis1$x,rule=2)$y \n\n return(eis1)\n}\n\n# Check data\nif (FALSE) {\n\n eis1m = load_eismint1_moving(\"./EISMINT1-moving/\")\n eis1f = load_eismint1_fixed(\"./EISMINT1-fixed/\")\n\n eis1 = eis1f \n\n xlim = c(0,750)\n ylim = c(0,4000)\n\n plot(xlim,ylim,type=\"n\",ann=FALSE,axes=FALSE)\n axis(1)\n axis(2)\n mtext(side=1,line=2.5,las=0,\"Distance from divide [km]\")\n mtext(side=2,line=2.5,las=0,\"Ice thickness [m]\")\n grid()\n\n lines(eis1$x,eis1$Ht1,col=1,lwd=2,lty=1)\n lines(eis1$x,eis1$Ht2,col=1,lwd=2,lty=2)\n # lines(eis1$x,eis1$He, col=1,lwd=2,lty=3)\n \n legend(\"bottomleft\",inset=0.02,bty=\"n\",col=c(1,1,1),lwd=c(2,2,2),lty=c(1,2,3),c(\"type I\",\"type II\",\"exact\"))\n\n box() \n\n}", "meta": {"hexsha": "ab1917196c83362cff6429c24144a787156b4c2f", "size": 2900, "ext": "r", "lang": "R", "max_stars_repo_path": "load_eismint1.r", "max_stars_repo_name": "alex-robinson/ice-benchmarks", "max_stars_repo_head_hexsha": "4ee87f377a596feb5661c1f239166a003c72b94d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "load_eismint1.r", "max_issues_repo_name": "alex-robinson/ice-benchmarks", "max_issues_repo_head_hexsha": "4ee87f377a596feb5661c1f239166a003c72b94d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "load_eismint1.r", "max_forks_repo_name": "alex-robinson/ice-benchmarks", "max_forks_repo_head_hexsha": "4ee87f377a596feb5661c1f239166a003c72b94d", "max_forks_repo_licenses": ["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.7260273973, "max_line_length": 112, "alphanum_fraction": 0.6434482759, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4149331027926744}}
{"text": "model_shootnumber <- function (canopyShootNumber_t1 = 288.0,\n leafNumber = 3.34,\n sowingDensity = 288.0,\n targetFertileShoot = 600.0,\n tilleringProfile_t1 = c(288.0),\n leafTillerNumberArray_t1 = c(1, 1, 1),\n numberTillerCohort_t1 = 1){\n #'- Name: ShootNumber -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: CalculateShootNumber Model\n #' * Author: Pierre MARTRE\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA/LEPSE Montpellier\n #' * Abstract: calculate the shoot number and update the related variables if needed\n #'- inputs:\n #' * name: canopyShootNumber_t1\n #' ** description : shoot number for the whole canopy\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 288.0\n #' ** unit : shoot m-2\n #' ** inputtype : variable\n #' * name: leafNumber\n #' ** description : Leaf number \n #' ** variablecategory : state\n #' ** inputtype : variable\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 3.34\n #' ** unit : leaf\n #' * name: sowingDensity\n #' ** description : number of plant /m²\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 500\n #' ** default : 288.0\n #' ** unit : plant m-2\n #' ** inputtype : parameter\n #' * name: targetFertileShoot\n #' ** description : max value of shoot number for the canopy\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 280\n #' ** max : 1000\n #' ** default : 600.0\n #' ** unit : shoot\n #' ** inputtype : variable\n #' * name: tilleringProfile_t1\n #' ** description : store the amount of new tiller created at each time a new tiller appears\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** default : [288.0]\n #' ** unit : \n #' ** inputtype : variable\n #' * name: leafTillerNumberArray_t1\n #' ** description : store the number of tiller for each leaf layer\n #' ** variablecategory : state\n #' ** datatype : INTLIST\n #' ** unit : leaf\n #' ** default : [1, 1, 1]\n #' ** inputtype : variable\n #' * name: numberTillerCohort_t1\n #' ** description : Number of tiller which appears\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : variable\n #'- outputs:\n #' * name: averageShootNumberPerPlant\n #' ** description : average shoot number per plant in the canopy\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : shoot m-2\n #' * name: canopyShootNumber\n #' ** description : shoot number for the whole canopy\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : shoot m-2\n #' * name: leafTillerNumberArray\n #' ** description : store the number of tiller for each leaf layer\n #' ** variablecategory : state\n #' ** datatype : INTLIST\n #' ** unit : leaf\n #' * name: tilleringProfile\n #' ** description : store the amount of new tiller created at each time a new tiller appears\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** unit : dimensionless\n #' * name: numberTillerCohort\n #' ** description : Number of tiller which appears\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : dimensionless\n leafTillerNumberArray <- vector()\n tilleringProfile <- vector()\n lNumberArray_rate <- vector()\n emergedLeaves <- max(1, ceiling(leafNumber - 1.0))\n shoots <- fibonacci(emergedLeaves)\n canopyShootNumber <- min(shoots * sowingDensity, targetFertileShoot)\n averageShootNumberPerPlant <- canopyShootNumber / sowingDensity\n if (canopyShootNumber != canopyShootNumber_t1)\n {\n tilleringProfile <- c(tilleringProfile_t1, canopyShootNumber - canopyShootNumber_t1)\n }\n numberTillerCohort <- length(tilleringProfile)\n for( i in seq(length(leafTillerNumberArray_t1), ceiling(leafNumber)-1, 1)){\n lNumberArray_rate <- c(lNumberArray_rate, numberTillerCohort)\n }\n leafTillerNumberArray <- c(leafTillerNumberArray_t1, lNumberArray_rate)\n return (list (\"averageShootNumberPerPlant\" = averageShootNumberPerPlant,\"canopyShootNumber\" = canopyShootNumber,\"leafTillerNumberArray\" = leafTillerNumberArray,\"tilleringProfile\" = tilleringProfile,\"numberTillerCohort\" = numberTillerCohort))\n}\n\nfibonacci <- function (n){\n if (n <= 1)\n {\n return( n)\n }\n else\n {\n return( fibonacci(n - 1) + fibonacci(n - 2))\n }\n}\n\ninit_shootnumber <- function (sowingDensity = 288.0,\n targetFertileShoot = 600.0){\n tilleringProfile_t1 <- vector()\n leafTillerNumberArray_t1 <- vector()\n leafTillerNumberArray <- vector()\n tilleringProfile <- vector()\n canopyShootNumber <- sowingDensity\n averageShootNumberPerPlant <- 1.0\n tilleringProfile <- c(tilleringProfile, sowingDensity)\n numberTillerCohort <- 1\n leafTillerNumberArray <- vector()\n return (list (\"averageShootNumberPerPlant\" = averageShootNumberPerPlant,\"canopyShootNumber\" = canopyShootNumber,\"leafTillerNumberArray\" = leafTillerNumberArray,\"tilleringProfile\" = tilleringProfile,\"numberTillerCohort\" = numberTillerCohort))\n}", "meta": {"hexsha": "f49629c356771d8d550cd7fbaaf66189327cedb9", "size": 7795, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Shootnumber.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-06T07:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T16:31:33.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Shootnumber.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-12-06T07:51:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-14T18:03:12.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Shootnumber.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2018-12-10T12:11:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T10:52:03.000Z", "avg_line_length": 51.6225165563, "max_line_length": 245, "alphanum_fraction": 0.4506735087, "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.414847920724877}}
{"text": "#' @title findMax \n#' @description unknown\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\nfindMax <- function(x,y){ \n\t\t\tnp \t= length(x)\n\t\t\tix \t= which.max(y)\n\t\t\tixx = min(np-1,max(2,ix))\n\t\t\ttx \t= x[ixx + c(-1,0,1)]\n\t\t\tty \t= y[ixx + c(-1,0,1)]\n\t\t\tco \t= coef(lm(ty ~ tx + I(tx^2)))\n\t\t\txmax = co[2] /(-2 * co[3])\n\t\t\tymax = co %*% (xmax^(0:2))\n\t\treturn(c(xmax,ymax))\n\t}\n", "meta": {"hexsha": "f60eee6f3446354178b66740220720f7af10f902", "size": 417, "ext": "r", "lang": "R", "max_stars_repo_path": "R/findMax.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/findMax.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/findMax.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": 24.5294117647, "max_line_length": 53, "alphanum_fraction": 0.5323741007, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.414315088153746}}
{"text": "prior <- setClass(\n Class = \"prior\",\n slots = list(\n data = \"list\",\n theta_range = \"numeric\",\n func = \"function\",\n desc = \"character\",\n type = \"character\",\n dist_type = \"character\",\n plot = \"list\",\n parameters = \"list\",\n function_text = \"character\"\n )\n)\n\n\nlikelihood <- setClass(\n Class = \"likelihood\",\n slots = list(\n data = \"list\",\n # theta_range = \"\",\n func = \"function\",\n desc = \"character\",\n observation = \"numeric\",\n # type = \"character\",\n dist_type = \"character\",\n plot = \"list\",\n # parameters = \"\",\n marginal = \"character\"\n )\n)\n\n\n\nproduct <- setClass(\n Class = \"product\",\n slots = list(\n data = \"list\",\n desc = \"character\",\n K = \"numeric\",\n lik = \"function\",\n prior = \"function\",\n theta_range = \"numeric\",\n likelihood_obj = \"likelihood\",\n prior_obj = \"prior\"\n )\n)\n\n\nposterior <- setClass(\n Class = \"posterior\",\n slots = list(\n data = \"list\",\n desc = \"character\",\n K = \"numeric\",\n lik = \"function\",\n prior = \"function\",\n theta_range = \"numeric\",\n likelihood_obj = \"likelihood\",\n prior_obj = \"prior\"\n )\n)\n\nprediction <- setClass(\n Class = \"prediction\",\n slots = list(\n data = \"list\",\n desc = \"character\",\n K = \"numeric\",\n lik = \"function\",\n prior = \"function\",\n theta_range = \"numeric\",\n likelihood_obj = \"likelihood\",\n prior_obj = \"prior\"\n )\n)\n\n\nsetClassUnion(\"bayesplay\", c(\n \"likelihood\",\n \"prior\",\n \"product\",\n \"posterior\",\n \"prediction\"\n))\n\nsetMethod(\n \"show\",\n \"bayesplay\",\n function(object) {\n cat(object@desc, \"\\n\")\n }\n)\n\nshow <- function(x) {\n UseMethod(\"show\")\n}\n\n#' Get fields from data slot\n#' @param x a \\code{bayesplay} object\n#' @param name field name\n#' @return content of the named field from the data slot\nsetMethod(\n \"$\",\n \"bayesplay\",\n function(x, name) {\n returnval <- x@data[[name]]\n return(returnval)\n }\n)\n\n#' Get names from data slot\n#' @param x a \\code{bayesplay} object\n#' @return the field names from the data slot\nsetMethod(\"names\",\n signature = \"bayesplay\",\n function(x) {\n return(names(x@data))\n }\n)\n\n# constants\ntheta <- \"\\u03F4\"\nposterior_labs <- list(x = theta, y = \"Density\")\nlikelihood_labs <- list(x = theta, y = \"Pr(Outcome)\")\n\n\n\nsetClass(\n Class = \"normal\",\n list(\n family = \"character\",\n fun = \"function\",\n default_range = \"numeric\"\n ),\n prototype = list(\n family = \"normal\",\n fun = function(x, mean, sd, ...) {\n dnorm(x = mean, mean = x, sd = sd)\n },\n default_range = c(-Inf, Inf)\n )\n)\n\n\nsetClass(\n Class = \"point\",\n list(\n family = \"character\",\n fun = \"function\",\n default_range = \"numeric\"\n ),\n prototype = list(\n family = \"point\",\n fun = function(x, point, ...) {\n ifelse(x == point, 1, 0)\n },\n default_range = c(-Inf, Inf)\n )\n)\n\n\nsetClass(\n Class = \"uniform\",\n list(\n family = \"character\",\n fun = \"function\",\n default_range = \"numeric\"\n ),\n prototype = list(\n family = \"uniform\",\n fun = function(x, min, max, ...) {\n dunif(x = x, min = min, max = max)\n },\n default_range = c(-Inf, Inf)\n )\n)\n\n\n\n\nsetClass(\n Class = \"student_t\",\n list(family = \"character\", fun = \"function\", default_range = \"numeric\"),\n prototype = list(\n family = \"student_t\",\n fun = function(x, mean, sd, df) {\n dt_scaled(x = mean, mean = x, sd = sd, df = df)\n },\n default_range = c(-Inf, Inf)\n )\n)\n\n\nsetClass(\n Class = \"cauchy\",\n list(family = \"character\", fun = \"function\", default_range = \"numeric\"),\n prototype = list(\n family = \"cauchy\",\n fun = function(x, location = 0, scale) {\n dcauchy(x = x, location = location, scale = scale)\n },\n default_range = c(-Inf, Inf)\n )\n)\n\nsetClass(\n Class = \"beta\",\n list(family = \"character\", fun = \"function\", default_range = \"numeric\"),\n prototype = list(\n family = \"beta\",\n fun = function(x, alpha, beta) {\n dbeta(x = x, shape1 = alpha, shape2 = beta)\n },\n default_range = c(0, 1)\n )\n)\n\nsetClass(\n Class = \"noncentral_t\",\n list(family = \"character\", fun = \"function\"),\n prototype = list(\n family = \"noncentral_t\",\n fun = function(x, t, df) {\n suppressWarnings(dt(x = t, df = df, ncp = x))\n }\n )\n)\n\n\nsetClass(\n Class = \"noncentral_d\",\n list(family = \"character\", fun = \"function\"),\n prototype = list(\n family = \"noncentral_d\",\n fun = function(x, d, n) {\n suppressWarnings(dt(x = d * sqrt(n), df = n - 1, ncp = x * sqrt(n)))\n }\n )\n)\n\nsetClass(\n Class = \"noncentral_d2\",\n list(family = \"character\", fun = \"function\"),\n prototype = list(\n family = \"noncentral_d2\",\n fun = function(x, d, n1, n2) {\n suppressWarnings(dt(\n x = d / sqrt(1 / n1 + 1 / n2),\n df = n1 + n2 - 2,\n ncp = x * sqrt((n1 * n2) / (n1 + n2))\n ))\n }\n )\n)\n\nsetClass(\n Class = \"binomial\",\n list(family = \"character\", fun = \"function\"),\n prototype = list(\n family = \"binomial\",\n fun = function(p, successes, trials) {\n dbinom(prob = p, size = trials, x = successes)\n }\n )\n)\n\n\n\nsetClassUnion(\n \"family\",\n c(\n \"normal\",\n \"student_t\",\n \"noncentral_t\",\n \"noncentral_d\",\n \"noncentral_d2\",\n \"binomial\",\n \"point\",\n \"uniform\",\n \"cauchy\"\n )\n)\n", "meta": {"hexsha": "afab0ed4eba326a7199b1b3275923818ed3b28ec", "size": 5209, "ext": "r", "lang": "R", "max_stars_repo_path": "R/classes.r", "max_stars_repo_name": "bayesplay/bayesplay", "max_stars_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-12-09T16:19:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:15:00.000Z", "max_issues_repo_path": "R/classes.r", "max_issues_repo_name": "bayesplay/bayesplay", "max_issues_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11, "max_issues_repo_issues_event_min_datetime": "2021-07-07T10:39:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T18:30:26.000Z", "max_forks_repo_path": "R/classes.r", "max_forks_repo_name": "bayesplay/bayesplay", "max_forks_repo_head_hexsha": "23284aee9fe7c73f7a5a92efc1a4ce4cdfec6b42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-01T00:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T00:17:37.000Z", "avg_line_length": 18.3415492958, "max_line_length": 74, "alphanum_fraction": 0.5588404684, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41404850004563276}}
{"text": "#' crossprod\n#' \n#' Croddproducts.\n#' \n#' @details\n#' If \\code{y} is a numeric matrix, then \\code{x} will be promoted to a numeric\n#' matrix, and the return will therefore be numeric (not float).\n#' \n#' @param x\n#' A float vector/matrix.\n#' @param y\n#' Either \\code{NULL}, or a numeric/float matrix.\n#' \n#' @return\n#' A float matrix (unless \\code{y} is numeric; see details section).\n#' \n#' @examples\n#' library(float)\n#' \n#' s = flrunif(10, 3)\n#' crossprod(s)\n#' tcrossprod(s)\n#' \n#' @useDynLib float R_crossprod_spm R_crossprod_spmspm R_tcrossprod_spm R_tcrossprod_spmspm\n#' @name crossprod\n#' @rdname crossprod\nNULL\n\n\n\ncp_float32 = function(x, y=NULL)\n{\n if (is.float(x))\n {\n if (is.null(y))\n d = .Call(R_crossprod_spm, DATA(x))\n else if (is.float(y))\n d = .Call(R_crossprod_spmspm, DATA(x), DATA(y))\n else\n return(base::crossprod(dbl(x), y))\n }\n else if (is.matrix(x) && is.float(y))\n return(base::crossprod(x, dbl(y)))\n else\n return(base::crossprod(x, y))\n \n float32(d)\n}\n\ntcp_float32 = function(x, y=NULL)\n{\n if (is.float(x))\n {\n if (is.null(y))\n d = .Call(R_tcrossprod_spm, DATA(x))\n else if (is.float(y))\n d = .Call(R_tcrossprod_spmspm, DATA(x), DATA(y))\n else\n return(base::tcrossprod(dbl(x), y))\n }\n else if (is.matrix(x) && is.float(y))\n return(base::tcrossprod(x, dbl(y)))\n else\n return(base::tcrossprod(x, y))\n \n float32(d)\n}\n\n\n\n#' @rdname crossprod\n#' @export\nsetMethod(\"crossprod\", signature(x=\"Mat\", y=\"ANY\"), cp_float32)\n\n#' @rdname crossprod\n#' @export\nsetMethod(\"tcrossprod\", signature(x=\"Mat\", y=\"ANY\"), tcp_float32)\n", "meta": {"hexsha": "66760bd43af17e3151e0ddbc1281d6cd638b3061", "size": 1611, "ext": "r", "lang": "R", "max_stars_repo_path": "R/crossprod.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/crossprod.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/crossprod.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": 20.6538461538, "max_line_length": 91, "alphanum_fraction": 0.6238361266, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4137120343908656}}
{"text": "# Comparing pictures from literature with those made directly\n\n# libs ----\nlibrary(\"Momocs\")\n\n# input ----\ninNProf <- list.files(\"./Obr/Porovnani/Prof/\", full.names = T)\ninNSide <- list.files(\"./Obr/Porovnani/Side/\", full.names = T)\ninNTop <- list.files(\"./Obr/Porovnani/Top/\", full.names = T)\n\ninProf <- import_jpg(jpg.path = inNProf, auto.notcentered = TRUE, \n threshold = 0.5, verbose = TRUE)\n\ninSide <- import_jpg(jpg.path = inNSide, auto.notcentered = TRUE,\n threshold = 0.5,verbose = TRUE)\n\ninTop <- import_jpg(jpg.path = inNTop, auto.notcentered = TRUE,\n threshold = 0.5, verbose = TRUE)\n\n# fac ----\nfacSlot <- data.frame(factor(c(rep(\"Lit\", 10), rep(\"Orig\", 10))))\nnames(facSlot) <- \"Puv\"\nfacSlot$Nr <- factor(rep(0:9, 2))\n\n# outlines ----\noutProf <- Out(inProf, fac = facSlot)\noutSide <- Out(inSide, fac = facSlot)\noutTop <- Out(inTop, fac = facSlot)\n\npanel(outProf, fac = \"Puv\", names = \"Nr\")\npanel(outSide, fac = \"Puv\", names = \"Nr\")\npanel(outTop, fac = \"Puv\", names = \"Nr\")\n\n# manipulate outlines ----\nmanProf <- outProf %>%\n coo_slidedirection(\"S\") %>% coo_center() %>% coo_scale() %>% \n coo_smooth(50) %>% coo_sample(200)\n\nmanSide <- outSide %>%\n coo_alignxax() %>% coo_slidedirection(\"W\") %>% coo_center() %>%\n coo_smooth(200) %>% coo_sample(200)\n\nmanTop <- outTop %>%\n coo_alignxax() %>% coo_slidedirection(\"W\") %>% coo_center() %>%\n coo_smooth(200) %>% coo_sample(400)\n\npanel(manProf, fac = \"Puv\", names = \"Nr\")\npanel(manTop, fac = \"Puv\", names = \"Nr\")\npanel(manSide, fac = \"Puv\", names = \"Nr\")\n\n\n# stack(filter(manProf, Nr == 5))\n# \n# stack(filter(manTop, Nr == 1))\n# stack(filter(manTop, Nr == 2))\n# stack(filter(manTop, Nr == 3))\n\n# efourier ----\nefProf <- efourier(manProf, nb.h = 10, norm = FALSE, smooth.it = 0,\n start = FALSE, verbose = TRUE)\n\nefSide <- efourier(manSide, nb.h = 11, norm = TRUE, smooth.it = 0,\n start = FALSE, verbose = TRUE)\n\nefTop <- efourier(manTop, nb.h = 12, norm = TRUE, smooth.it = 0,\n start = FALSE, verbose = TRUE)\n\n# centroid size ----\n# coo_centsize(manProf)\n# coo_centsize(manSide)\n# coo_centsize(manTop)\n\n# mean shapes ----\nProf <- mshapes(efProf, 1)\nSide <- mshapes(efSide, 1)\nTop <- mshapes(efTop, 1)\n\n# t-test\n# lit <- filter(manProf, Puv == \"Lit\")\n# orig <- filter(manProf, Puv == \"Orig\")\n# \n# t.test(Prof$shp$Lit, Prof$shp$Orig)\n# t.test(Prof$shp$Lit, Prof$shp$Orig, paired = T)\n# \n# t.test(lit$coo$LitProf0, orig$coo$OrigProf0)\n\n# stack plots of meanshapes ----\n# pdf(file = \"./Obr/prof.pdf\")\n# LitProf <- Prof$shp$Lit %T>% coo_plot(border=\"blue\")\n# KreProf <- Prof$shp$Orig %T>% coo_draw(border=\"red\")\n# dev.off()\n# \n# pdf(file = \"./Obr/side.pdf\")\n# LitSide <- Side$shp$Lit %T>% coo_plot(border=\"blue\")\n# KreSide <- Side$shp$Orig %T>% coo_draw(border=\"red\")\n# dev.off()\n# \n# pdf(file = \"./Obr/top.pdf\")\n# LitTop <- Top$shp$Lit %T>% coo_plot(border=\"blue\")\n# KreTop <- Top$shp$Orig %T>% coo_draw(border=\"red\")\n# dev.off()\n\n# difference plots of meanshapes ----\npdf(file = \"./Obr/panProf.pdf\")\nefProf %>% mshapes(\"Puv\") %>% plot_mshapes(col2=\"#0000FF\")\ndev.off()\n\npdf(file = \"./Obr/panSide.pdf\")\nefSide %>% mshapes(\"Puv\") %>% plot_mshapes(col2=\"#0000FF\")\ndev.off()\n\npdf(file = \"./Obr/panTop.pdf\")\nefTop %>% mshapes(\"Puv\") %>% plot_mshapes(col2=\"#0000FF\")\ndev.off()\n\n# tps plots ----\npdf(file = \"./Obr/isoProf.pdf\", width = 10, height = 10)\ntps_iso(LitProf, KreProf, cont.col = \"gray40\", grid = F, \n shp.border = c(\"black\", \"blue\"), shp.lwd = c(4, 3), shp.lty = c(3, 3),\n legend.text = c(\"Lit\", \"Orig\"))\ndev.off()\n\npdf(file = \"./Obr/isoSide.pdf\", width = 9, height = 3)\ntps_iso(LitSide, KreSide, cont.col = \"gray40\", grid = F, \n shp.border = c(\"black\", \"blue\"), shp.lwd = c(4, 3), shp.lty = c(3, 3),\n legend.text = c(\"Lit\", \"Orig\"))\ndev.off()\n\npdf(file = \"./Obr/isoTop.pdf\", width = 11, height = 4)\ntps_iso(LitTop, KreTop, cont.col = \"gray40\", grid = F, \n shp.border = c(\"black\", \"blue\"), shp.lwd = c(4, 3), shp.lty = c(3, 3),\n legend.text = c(\"Lit\", \"Orig\"))\ndev.off()\n\n# indiv.\ntps_iso(manProf$coo$LitProf1, manProf$coo$OrigProf1)\n\ncoo_lolli(LitProf, KreProf)\ncoo_lolli(LitSide, KreSide)\ncoo_lolli(LitTop, KreTop)\n# or?\ncoo_arrows(LitProf, KreProf)\ncoo_arrows(LitSide, KreSide)\ncoo_arrows(LitTop, KreTop)\n\n# coo_plot(LitProf)\n# coo_ruban(LitProf, edm(LitProf, KreProf), lwd=8)\n# coo_ruban(LitTop, edm(LitTop, KreTop), lwd=8)\n\n# a <- efourier(manTop)\n# ms.Top <- mshapes(a, fac = \"Puv\", nb.pts = 80)$shp\n# fr <- ms.Top$Lit\n# to <- ms.Top$Orig\n# tps_iso(fr, to)\n\n# end\nrm(list = ls())\ngraphics.off()\n", "meta": {"hexsha": "94b5c54f8d8e68061d6440509553eaa2c74cc369", "size": 4630, "ext": "r", "lang": "R", "max_stars_repo_path": "Scripts/Comp.r", "max_stars_repo_name": "PetPaj/DiplomaThesis", "max_stars_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-08T10:02:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T10:02:36.000Z", "max_issues_repo_path": "Scripts/Comp.r", "max_issues_repo_name": "petrpajdla/DiplomaThesis", "max_issues_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "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": "Scripts/Comp.r", "max_forks_repo_name": "petrpajdla/DiplomaThesis", "max_forks_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "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.1194968553, "max_line_length": 78, "alphanum_fraction": 0.6107991361, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.41315030323787594}}
{"text": "\r\n#' @title midg is an abalone tagging data-set from the Actaeons\r\n#'\r\n#' @description midg is a tagging data-set for blacklip abalone\r\n#' (\\emph{Haliotis rubra}) from the middle ground in the Actaeons\r\n#' in Tasmania's Block 13. All individuals were recaptured in 2003,\r\n#' the site number was 478, at Latitude -43.54 longitude 146.99,\r\n#' and there are 347 observations. All Dt = 1 year.\r\n#'\r\n#' @name midg\r\n#'\r\n#' @docType data\r\n#'\r\n#' @format A data.frame of abalone tagging data\r\n#' \\describe{\r\n#' \\item{RecapL}{the length at recapture}\r\n#' \\item{Lt}{the length at tagging}\r\n#' \\item{Dt}{The time interval between tagging and recapture, in this\r\n#' instance they are all listed as 1 year}\r\n#' \\item{DL}{the growth increment in mm}\r\n#' }\r\n#'\r\n#' @section Subjects:\r\n#' \\itemize{\r\n#' \\item growth curves\r\n#' \\item inverse logistic, von Bertalanffy, Gompertz\r\n#' \\item Static model fitting\r\n#' }\r\n#'\r\n#' @source Thanks to the Institute of Marine and Antarctic Science,\r\n#' which is part of the University of Tasmania, and especially to\r\n#' Dr Craig Mundy, leader of the Abalone Group, for permission to use\r\n#' this data collected in 2003.\r\n#'\r\n#' @examples\r\n#' data(midg)\r\n#' head(midg,20)\r\n#' oldpar <- par(no.readonly=TRUE)\r\n#' plot(midg$Lt,midg$DL,type=\"p\",pch=16,cex=1.0,xlim=c(5,180))\r\n#' abline(h=0,col=1)\r\n#' par(oldpar)\r\nNULL\r\n\r\n\r\n\r\n#' @title tasab is a matrix of abalone maturity-at-length data\r\n#'\r\n#' @description tasab is a 715 x 4 matrix of maturity-at-length data\r\n#' for blacklip abalone (\\emph{Haliotis rubra}) from two sites\r\n#' along the Tasmanian west coast. All data was collected in\r\n#' February 1995, but details, such as site name, accurate\r\n#' location, statistical block, year, month, and other\r\n#' details have been omitted for brevity.\r\n#'\r\n#' @name tasab\r\n#'\r\n#' @docType data\r\n#'\r\n#' @format A data.frame of maturity-at-length data\r\n#' \\describe{\r\n#' \\item{site}{an identifier for the two different sites sampled}\r\n#' \\item{sex}{I = immature, M = male, F = female}\r\n#' \\item{length}{the shell length in mm}\r\n#' \\item{mature}{was the animal mature = 1 or not = 0}\r\n#' }\r\n#'\r\n#' @section Subjects:\r\n#' \\itemize{\r\n#' \\item maturity ogives or logistic curves\r\n#' \\item Binomial likelihoods\r\n#' }\r\n#'\r\n#' @source Thanks to the Institute of Marine and Antarctic Science,\r\n#' which is part of the University of Tasmania, and especially to\r\n#' Dr Craig Mundy, leader of the Abalone Group, for permission to use\r\n#' this data collected in February 1995.\r\n#'\r\n#' @examples\r\n#' data(tasab)\r\n#' head(tasab,20)\r\n#' table(tasab$site,tasab$sex)\r\nNULL\r\n\r\n", "meta": {"hexsha": "11ad1273b1a5140538e038ad68d653eb3281a548", "size": 2681, "ext": "r", "lang": "R", "max_stars_repo_path": "R/datasets.r", "max_stars_repo_name": "haddonm/invLogistic", "max_stars_repo_head_hexsha": "368fb503785211f1b86e5897083af2e9debea444", "max_stars_repo_licenses": ["MIT"], "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/datasets.r", "max_issues_repo_name": "haddonm/invLogistic", "max_issues_repo_head_hexsha": "368fb503785211f1b86e5897083af2e9debea444", "max_issues_repo_licenses": ["MIT"], "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/datasets.r", "max_forks_repo_name": "haddonm/invLogistic", "max_forks_repo_head_hexsha": "368fb503785211f1b86e5897083af2e9debea444", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 74, "alphanum_fraction": 0.6512495338, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.4130692627882308}}
{"text": "score <- function(input) {\n var0 <- exp(subroutine0(input))\n var1 <- exp(subroutine1(input))\n var2 <- exp(subroutine2(input))\n var3 <- ((var0) + (var1)) + (var2)\n return(c((var0) / (var3), (var1) / (var3), (var2) / (var3)))\n}\nsubroutine0 <- function(input) {\n return(((0) + (subroutine3(input))) + (subroutine4(input)))\n}\nsubroutine1 <- function(input) {\n return(((0) + (subroutine5(input))) + (subroutine6(input)))\n}\nsubroutine2 <- function(input) {\n return(((0) + (subroutine7(input))) + (subroutine8(input)))\n}\nsubroutine3 <- function(input) {\n if ((input[3]) > (3.1500000000000004)) {\n var0 <- -1.1736122903444903\n } else {\n if ((input[2]) > (3.35)) {\n var0 <- -0.9486122853153485\n } else {\n var0 <- -0.9598622855668056\n }\n }\n return(var0)\n}\nsubroutine4 <- function(input) {\n if ((input[3]) > (3.1500000000000004)) {\n if ((input[3]) > (4.450000000000001)) {\n var0 <- -0.07218200074594171\n } else {\n var0 <- -0.0725391787456957\n }\n } else {\n if ((input[2]) > (3.35)) {\n var0 <- 0.130416969124648\n } else {\n var0 <- 0.12058330491181404\n }\n }\n return(var0)\n}\nsubroutine5 <- function(input) {\n if ((input[3]) > (1.8)) {\n if ((input[4]) > (1.6500000000000001)) {\n var0 <- -1.1840003561812273\n } else {\n var0 <- -0.99234128317334\n }\n } else {\n var0 <- -1.1934739985732523\n }\n return(var0)\n}\nsubroutine6 <- function(input) {\n if ((input[4]) > (0.45000000000000007)) {\n if ((input[4]) > (1.6500000000000001)) {\n var0 <- -0.06203313079859976\n } else {\n var0 <- 0.11141505233015861\n }\n } else {\n if ((input[3]) > (1.4500000000000002)) {\n var0 <- -0.0720353255122301\n } else {\n var0 <- -0.07164473223425313\n }\n }\n return(var0)\n}\nsubroutine7 <- function(input) {\n if ((input[4]) > (1.6500000000000001)) {\n if ((input[3]) > (5.3500000000000005)) {\n var0 <- -0.9314095846701695\n } else {\n var0 <- -0.9536869036452162\n }\n } else {\n if ((input[3]) > (4.450000000000001)) {\n var0 <- -1.115439610985773\n } else {\n var0 <- -1.1541827744206368\n }\n }\n return(var0)\n}\nsubroutine8 <- function(input) {\n if ((input[3]) > (4.750000000000001)) {\n if ((input[3]) > (5.150000000000001)) {\n var0 <- 0.12968922424213622\n } else {\n var0 <- 0.07468384042736965\n }\n } else {\n if ((input[2]) > (2.7500000000000004)) {\n var0 <- -0.07311533184609437\n } else {\n var0 <- -0.06204412771870974\n }\n }\n return(var0)\n}\n", "meta": {"hexsha": "7ea9301b6f52fa9706de78fb6c4fa80e59e6f03a", "size": 2820, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/classification/lightgbm.r", "max_stars_repo_name": "yarix/m2cgen", "max_stars_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:59:21.000Z", "max_issues_repo_path": "generated_code_examples/r/classification/lightgbm.r", "max_issues_repo_name": "yarix/m2cgen", "max_issues_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generated_code_examples/r/classification/lightgbm.r", "max_forks_repo_name": "yarix/m2cgen", "max_forks_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_forks_repo_licenses": ["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.8571428571, "max_line_length": 64, "alphanum_fraction": 0.5007092199, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4130194214963232}}
{"text": "# -*- coding: utf-8 -*-\n\"\"\"ar_hw6.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/18rtZgaq0UI96qYguCIX8fQ6apMYKxQ8W\n\n# Práctico 6 - Modelos de grafos\n\n# 1). Ambientes de trabajo\n\n## 1.a) Ambiente COLAB remoto\n\n1. Abrir en navegador: https://colab.research.google.com/\n2. Abrir el notebook de la tarea:\n File-> Open Notebook -> Github -> https://github.com/prbocca/na101_master -> homework_6_models\n3. Guardar el notebook en su Google Drive:\n File -> Save a Copy in Drive... \n4. Renombrar el archivo `\"cedula ID\"_ar_hw6.ipynb`, por ejemplo *33484022_ar_hw6.ipynb*\n5. Al final usted deberá descargar el notebook. Asegurarse que se están guardando las salidas de ejecución en el notebook: File -> Download .ipynb\n6. Luego estos archivos deberán ser enviados a prbocca@fing.edu.uy \n\n##1.b) Ambiente RSTUDIO local (opcional)\n\nAbrir el .r de la tarea en: https://github.com/prbocca/na101_master/tree/master/homework_6_models\n\n## 1.c) Cargar Librerias\n\nTodas las librerías deben instalarse correctamente, si el proceso se interrumpe o alguna librería da error en la instalación, entonces habrá problemas en el código más adelante. Si tiene este tipo de problemas pruebe hacer `Runtime -> Factory reset runtime`, y volver a intentar.\n\"\"\"\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(\"sand\",\"igraph\") \n\nload_libs(libs)\n\n\"\"\"## 1.d) Descargar funciones auxiliares\"\"\"\n\n#directorio donde se va a trabajar\ndata_path = \"/content/ar/hw6/\"\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\"\"\"# 2). Modelos clásicos de grafos en `R`\n\nSeguir las Secciones 5.1 y 5.2 del libro [SANDR], ejecutando el código fuente incluido.\n\"\"\"\n\n#5.1 Introduction\n#5.2 Classical Random Graph Models\n\n#The function erdos.renyi.game in igraph can be used to simulate classical\n#random graphs of either type. Figure 5.1 shows a realization of a classical random\n#graph, based on the choice of N v = 100 vertices and a probability of p = 0.02 of an\n#edge between any pair of vertices. Using a circular layout, we can see that the edges\n#appear to be scattered between vertex pairs in a fairly uniform manner, as expected.\nset.seed(42)\ng.er <- erdos.renyi.game(100, 0.02)\nplot(g.er, layout=layout.circle, vertex.label=NA)\n\n# Note that random graphs generated in the manner described above need not be connected.\nis.connected(g.er)\n#2 [1] FALSE\n\n#Although this particular realization is not connected, it does nevertheless have a\n# giant component, containing 71 of the 100 vertices. All other components contain\n#between one and four vertices only.\ntable(sapply(decompose.graph(g.er), vcount))\n# 3 1 2 3 4 71\n#4 15 2 2 1 1\n#In general, a classical random graph G will with high probability have a giant com-\n#ponent if p = c/N v for some c > 1.\n\n# Under this same parameterization for p, for c > 0, the degree distribution will\n# be well-approximated by a Poisson distribution, with mean c, for large N v .\n# Indeed, in our simulated random graph, the mean degree is quite close to the\n# expected value of (100 − 1) × 0.02 = 1.98.\nmean(degree(g.er))\n\n# Furthermore, we see that the degree distribution is quite homogeneous.\nhist(degree(g.er), col=\"lightblue\", xlab=\"Degree\", ylab=\"Frequency\", main=\"\")\n\n#Other properties of classical random graphs include that there are relatively few\n#vertices on shortest paths between vertex pairs72\naverage.path.length(g.er)\n#[1] 5.276511\ndiameter(g.er)\n#[1] 14\n#and that there is low clustering.\ntransitivity(g.er)\n#[1] 0.01639344\n# More specifically, under the conditions above, it can be shown that the diameter\n# varies like O(log N v ), and the clustering coefficient, like N v −1.\n\n\"\"\"# 3). Distribución de grado de Erdös-Renyi, $G(n, p)$ , en `R`. \n\nUtilizando la función `erdos.renyi.game()` generar grafos aleatorios de distinto orden.\n\n## 3.a) Crecer la cantidad de vértices\n\nSi fijamos $p = 0.02$, al crecer la cantidad de vértices: \n¿qué sucede con el grado promedio?, y \n¿la distribución de grado se acerca a una Normal o a una Poisson? \n\nVerificar comparando el histograma con la distribución teórica para $n \\in \\{10, 100, 1000, 10000\\}$.\n\"\"\"\n\n# Gnp: efecto de crecer la red, se aproxima a una normal\npar(mfrow=c(3,2))\np=0.02\nfor (i in 1:5){\n n = 10^i\n g.er <- erdos.renyi.game(n, p.or.m=p, type=\"gnp\")\n #hist(degree(g.er), probability = T, col=\"lightblue\", xlab=\"Degree\", ylab=\"Probabilities\", main=\"\")\n g.er.dd = degree_distribution(g.er)\n plot(g.er.dd, xlab=\"Degree\", ylab=\"Probabilities\", main=paste(\"n=\",n))\n x = seq(from=1,to=length(g.er.dd), by=1)\n lines(x, dnorm(x, mean = n*p, sd = sqrt(n*p*(1-p))), type=\"l\",col=\"red\")\n print(paste(\"n =\",n,\", grado promedio =\", mean(degree(g.er))))\n}\n\npar(mfrow=c(1,1))\n\n\"\"\"## 3.b) Crecer la cantidad de vértices y obtener una distribución de Poisson\n\n¿Cómo debemos cambiar el parámetro $p$ del modelo al crecer $n$ para que la distribución tienda a una Poisson? \n\nVerificar comparando el histograma con la distribución de Poisson para $n \\in \\{10, 100, 1000, 10000\\}$ y un grado promedio de $1.8$.\n\nNota: Los parámtros de la distribución teórica fueron vistos en las clases teóricas.\n\"\"\"\n\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: similar a 3.a), los parámtros de la distribución teórica fueron vistos en las clases teóricas.\n#\n#\n#\n##################################################################\n\n\"\"\"# 4). Otros modelos de grafos en `R`.\n\nSeguir las Secciones 5.3 y 5.4 del libro [SANDR], ejecutando el código fuente incluido. En ellas se explican los modelos de configuración, acoplamiento preferencial, Barabási-Albert, y mundo pequeño.\n\"\"\"\n\n# 5.3 Generalized Random Graph Models\n\nset.seed(42)\n\n# The igraph function degree.sequence.game can be used to uniformly\n# sample random graphs with fixed degree sequence. Suppose, for example, that we\n# are interested in graphs of N v = 8 vertices, half of which have degree d = 2, and the\n# other half, degree d = 3. Two examples of such graphs, drawn uniformly from the\n# collection of all such graphs, are shown in Fig. 5.2.\ndegs <- c(2,2,2,2,3,3,3,3)\ng1 <- degree.sequence.game(degs, method=\"vl\")\ng2 <- degree.sequence.game(degs, method=\"vl\")\nplot(g1, vertex.label=NA)\nplot(g2, vertex.label=NA)\n\n#Note that these two graphs do indeed differ, in that they are not isomorphic. \ngraph.isomorphic(g1, g2)\n#[1] FALSE\n\n# For a fixed number of vertices N v , the collection of random graphs with fixed\n# degree sequence all have the same number of edges N e , due to the relation d ̄ =\n# 2N e /N v , where d ̄ is the mean degree of the sequence (d (1) , . . . , d (N v ) ).\nc(ecount(g1), ecount(g2))\n#[1] 10 10\n\n\n# On the other hand, it is important to keep in mind that all other characteristics\n# are free to vary to the extent allowed by the chosen degree sequence. For example,\n# we can generate a graph with the same degree sequence as our network of protein–\n# protein interactions in yeast.\ndata(yeast)\ndegs <- degree(yeast)\nfake.yeast <- degree.sequence.game(degs, method=c(\"vl\"))\nall(degree(yeast) == degree(fake.yeast))\n# [1] TRUE\n\n#But the original network has twice the diameter of the simulated version\ndiameter(yeast)\n# [1] 15\ndiameter(fake.yeast)\n# [1] 8\n\n# and virtually all of the substantial amount of clustering originally present is now gone.\ntransitivity(yeast)\n#[1] 0.4686178\ntransitivity(fake.yeast)\n#[1] 0.0396504\n\n# 5.4 Network Graph Models Based on Mechanisms\n\nset.seed(42)\n\n# 5.4.1 Small-World Models\n# Work on modeling of this type received a good deal of its impetus from the seminal\n# paper of Watts and Strogatz [146] and the ‘small-world’ network model introduced\n# therein. These authors were intrigued by the fact that many networks in the real\n# world display high levels of clustering, but small distances between most nodes.\n#\n# In order to create a network graph with both of these properties, Watts and Strogatz \n# suggested instead beginning with a graph with lattice structure, and then randomly \n# ‘rewiring’ a small percentage of the edges. More specifically, in this model\n# we begin with a set of N v vertices, arranged in a periodic fashion, and join each\n# vertex to r of its neighbors to each side. Then, for each edge, independently and\n# with probability p, one end of that edge will be moved to be incident to another\n# vertex, where that new vertex is chosen uniformly, but with attention to avoid the\n# construction of loops and multi-edges.\n# An example of a small-world network graph of this sort can be generated in\n# igraph using the function watts.strogatz.game.\n\ng.ws <- watts.strogatz.game(1, 25, 5, 0.05)\nplot(g.ws, layout=layout.circle, vertex.label=NA)\n\n# For the lattice alone, which we generate by setting p = 0, there is a substantial amount of clustering.\ng.lat100 <- watts.strogatz.game(1, 100, 5, 0)\nplot(g.lat100, layout=layout.circle, vertex.label=NA)\ntransitivity(g.lat100)\n#[1] 0.6666667\n#But the distance between vertices is non-trivial.\ndiameter(g.lat100)\n#[1] 10\naverage.path.length(g.lat100)\n#[1] 5.454545\n\n#The effect of rewiring a relatively small number of edges in a random fashion is to\n# noticeably reduce the distance between vertices, while still maintaining a similarly\n# high level of clustering.\ng.ws100 <- watts.strogatz.game(1, 100, 5, 0.05)\nplot(g.ws100, layout=layout.circle, vertex.label=NA)\ndiameter(g.ws100)\n#[1] 5\naverage.path.length(g.ws100)\n#[1] 2.793939393\ntransitivity(g.ws100)\n#[1] 0.5121305\n\n\n# This effect may be achieved even with very small p. To illustrate, we simulate ac-\n# cording to a particular Watts-Strogatz small-world network model, with N v = 1, 000\n#and r = 10, and re-wiring probability p, as p varies over a broad range.\nsteps <- seq(-4, -0.5, 0.1)\nlen <- length(steps)\ncl <- numeric(len)\napl <- numeric(len)\nntrials <- 100\nfor (i in (1:len)) {\n cltemp <- numeric(ntrials)\n apltemp <- numeric(ntrials)\n for (j in (1:ntrials)) {\n g <- watts.strogatz.game(1, 1000, 10, 1^steps[i])\n cltemp[j] <- transitivity(g)\n apltemp[j] <- average.path.length(g)\n }\n cl[i] <- mean(cltemp)\n apl[i] <- mean(apltemp)\n}\n# The results shown in Fig. 5.4, where approximate expected values for normalized\n# versions of average path length and clustering coefficient are plotted, indicate that\n# over a substantial range of p the network exhibits small average distance while main-\n# taining a high level of clustering.\nplot(steps, cl/max(cl), ylim=c(0, 1), lwd=3, type=\"l\", col=\"blue\", xlab=expression(log[10](p)),\n ylab=\"Clustering and Average Path Length\")\nlines(steps, apl/max(apl), lwd=3, col=\"red\")\n\n# 5.4.2 Preferential Attachment Models\n\n# Many networks grow or otherwise evolve in time. The World Wide Web and\n# scientific citation networks are two obvious examples. Similarly, many biological\n# networks may be viewed as evolving as well, over appropriately defined time scales.\n# Much energy has been invested in the development of models that mimic network growth.\n# In this arena, typically a simple mechanism(s) is specified for how the network\n# changes at any given point in time, based on concepts like vertex preference, fitness,\n# copying, age, and the like. A celebrated example of such a mechanism is that of\n# preferential attachment, designed to embody the principle that ‘the rich get richer.’\n# ...\n\n# Using the igraph function barabasi.game, we can simulate a BA random\n# graph of, for example, N v = 100 vertices, with m = 1 new edges added for each new vertex.\nset.seed(42)\ng.ba <- barabasi.game(100, directed=FALSE)\n# A visualization of this graph is shown in Fig. 5.5.\nplot(g.ba, layout=layout.circle, vertex.label=NA)\n\n# Note that the edges are spread among vertex pairs in a decidedly less uniform man-\n# ner than in the classical random graph we saw in Fig. 5.1. And, in fact, there appear\n# to be vertices of especially high degree—so-called ‘hub’ vertices.\n# Examination of the degree distribution (also shown in Fig. 5.5)\nhist(degree(g.ba), col=\"lightblue\", xlab=\"Degree\", ylab=\"Frequency\", main=\"\")\n# confirms this suspicion, and indicates, moreover, that the overall distribution is quite\n# heterogeneous. Actually, the vast majority of vertices have degree no more than two\n# in this graph, while, on the other hand, one vertex has a degree of 11.\nsummary(degree(g.ba))\n#Min. 1st Qu. Median Mean 3rd Qu. Max.\n#1.00 1.00 1.00 1.98 2.00 11.00\n\n# On the other hand, network graphs generated according to the BA model will\n# share with their classical counterparts the tendency towards relatively few vertices\n# on shortest paths between vertex pairs\naverage.path.length(g.ba)\n# [1] 5.81555555555556\ndiameter(g.ba)\n# [1] 12\n#and low clustering.\ntransitivity(g.ba)\n# [1] 0\n\n\"\"\"# 5). Distribución de grado de Barabási-Albert en `R`.\n\nVerificar que el modelo de Barabasi-Albert tiende a una distribución power-law de parámetro $\\alpha = 3$ al crecer $n$. \nPara esto graficar la función de distribución acumulada complementaria (CCDF) en conjunto con la recta teórica de la power-law. Usar los $n \\in \\{10, 100, 1000, 10000, 100000, 1000000\\}$. \nPara cada caso, encontrar el $\\hat{\\alpha}$ usando la función de ajuste de igraph, llamada `power.law.fit()`. \nAdemás entender el test de hipótesis que se realiza en el ajuste, e interpretar el p-value del resultado.\n\"\"\"\n\n# BA: efecto de crecer la red\nset.seed(42)\npar(mfrow=c(3,2))\n\nfor (i in 1:6){\n n = 10^i\n g.ba = barabasi.game(n)\n \n # Degree distribution is the cumulative frequency of nodes with a given degree\n # this, like degree() can be specified as \"in\", \"out\", or \"all\"\n g.ba.dd = degree.distribution(g.ba, cumulative=T,mode=\"all\")\n g.ba.d = degree(g.ba,v=V(g.ba),mode=\"all\")\n \n # Using the power.law.fit() function I can fit a power law to the degree distribution\n # Plot degree distribution histogram, and theoretical line\n g.ba.power = NA\n ##################################################################\n # TU CÓDIGO ACÁ \n #\n #\n #\n ##################################################################\n print(paste(\"n =\",n,\", alpha =\", g.ba.power$alpha, \", xmin =\", g.ba.power$xmin))\n}\n\n\"\"\"# 6) Distribución de grado de una red real.\n\nMark Newman en 2006 creó un grafo de routers en Internet, con 22963 vértices y 48436 aristas. \nDescargar el grafo en formato GML desde:\nhttps://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip\n\n## 6.a) Descargar los datos\n\nDescargar los datos en formato `GML` en el siguiente link: \nhttps://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip.\n\nCargar los datos en `R`.\n\"\"\"\n\n# download data\ndownload.file(url=\"https://github.com/prbocca/na101_master/raw/master/homework_6_models/internet_routers-22july06.gml.zip\", destfile=\"internet_routers-22july06.gml.zip\", mode=\"wb\")\nunzip(zipfile=\"internet_routers-22july06.gml.zip\")\nlist.files()\n\n# cargar datos\ng.real = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar funciones de igraph\n#\n#\n#\n##################################################################\nsummary(g.real)\n\n\"\"\"## 6.b) (Opcional) Visualizar el grafo en Gephi\n\nVisualizar los vértices de mayor grado con mayor tamaño,\ny los vértices con mayor PageRank más oscuros.\n\nEl resultado debe ser similar al de la siguiente Figura: \n\n## 6.c) En `R`, graficar la distribución de grado.\n\nTambién graficar con ejes log-log para una mejor visualización.\n\"\"\"\n\n# graficar distribución de grado de g.real\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar funciones de igraph\n#\n#\n#\n##################################################################\n\n\"\"\"## 6.d) Graficar la función de distribución acumulada complementaria (CCDF).\"\"\"\n\n# graficar CCDF de g.real\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar funciones de igraph\n#\n#\n#\n##################################################################\n\n\"\"\"## 6.e) Austar una distribución Power-law\n\nAjustar la distribución a una power-law. \n\n¿Cuál es el $\\hat{\\alpha}$ y el $d_{min}$ del ajuste? \n\n¿Cómo interpretar el $p-value$ del test de hipotesis del resultado del ajuste? \n\nVerificar las conclusiones comparando la CCDF con la recta ajustada. La gráfica debería ser similar a la siguiente: \n\"\"\"\n\n# graficar la CCDF de g.real, y la distribución power-low ajustada\ng.real.power = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar funciones de igraph\n#\n#\n#\n##################################################################\nprint(paste(\"El alpha estimado es =\",g.real.power$alpha))", "meta": {"hexsha": "4dd81023ee935fe5ef743ca55759f0376a831de2", "size": 17618, "ext": "r", "lang": "R", "max_stars_repo_path": "r_deprecated/homework_6_models/ar_hw6.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_6_models/ar_hw6.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_6_models/ar_hw6.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": 39.6801801802, "max_line_length": 279, "alphanum_fraction": 0.6884436372, "num_tokens": 4813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.4127408166893801}}
{"text": "#' kmh2mph\n#'\n#' Conversion kilometer per hour to mile per hour.\n#'\n#' @param numeric kmh Speed in Kilometer per hour.\n#' @return \n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords kmh2mph \n#' \n#' @export\n#'\n#'\n#'\n#'\n\nkmh2mph<-function(kmh)\n{\n return (kmh * 0.621371);\n}", "meta": {"hexsha": "0b7ddc9c1e43dfdf2b14bb9a72e48388778cfcd8", "size": 344, "ext": "r", "lang": "R", "max_stars_repo_path": "R/kmh2mph.r", "max_stars_repo_name": "alfcrisci/biometeoR", "max_stars_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:46.000Z", "max_issues_repo_path": "R/kmh2mph.r", "max_issues_repo_name": "alfcrisci/biometeoR", "max_issues_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/kmh2mph.r", "max_forks_repo_name": "alfcrisci/biometeoR", "max_forks_repo_head_hexsha": "e9ee73da6ecc515ecd471cb9ae059a4370a51493", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.380952381, "max_line_length": 101, "alphanum_fraction": 0.6511627907, "num_tokens": 123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4127118812238993}}
{"text": "ivfastplm.core <- function(y = NULL, ## outcome vector\r\n x = NULL, ## regressor matrix\r\n z = NULL, ## exogenous variables matrix\r\n ind = NULL, ## indicator matrix\r\n se = 0,\r\n robust = FALSE,\r\n cl = NULL,\r\n sfe.index = NULL, ## index for simple fe , a vector of integer\r\n cfe.index = NULL, ## index for complex fe, a list of double, e.g. c(effect, influence)\r\n core.num = 1,\r\n df.use = NULL,\r\n df.cl.use = NULL,\r\n need.fe = FALSE,\r\n iv.test = FALSE,\r\n first = TRUE,\r\n orthog = NULL,\r\n endog = NULL) {\r\n\r\n if(is.null(z)){\r\n stop(\"No exogenous variables.\\n\")\r\n }\r\n \r\n if(is.null(x)){\r\n stop(\"No regressors.\\n\")\r\n }\r\n\r\n data.reduce <- cbind(y, z)\r\n data <- cbind(y, x)\r\n\r\n ## create indicators\r\n inds <- create.indicators(ind) ## an indicator class object\r\n\r\n ## ------ fe ------- ##\r\n fe <- cfes <- sub.cfe.index <- num.cfe.index <- NULL\r\n\r\n ## create complex fe\r\n gcfe <- function(i) {\r\n sub.cfe.index <- cfe.index[[i]]\r\n inf.weight <- as.numeric(inds$levels[[sub.cfe.index[2]]])\r\n cfe.sub <- create.complex.effect(inds, sub.cfe.index[1], \r\n sub.cfe.index[2], t(as.matrix(inf.weight)))\r\n return(cfe.sub)\r\n }\r\n\r\n ## complex fe\r\n if (!is.null(cfe.index)) { \r\n ## length\r\n cfe.length <- length(cfe.index)\r\n cfes <- lapply(1:cfe.length, gcfe)\r\n }\r\n\r\n ## create an fe class object\r\n fe <- create.fixed.effects(inds, sfes = sfe.index, cfes = cfes)\r\n \r\n\r\n ## demean all variables and then recover the fixed effects in ivregression using the coefficients\r\n model <- SolveFixedEffects(data, fe$ptr, core.num)\r\n model <- name.fe.model(model, inds, fe)\r\n model$inds <- inds\r\n model$fe <- fe\r\n\r\n model.reduce <- SolveFixedEffects(data.reduce, fe$ptr, core.num)\r\n model.reduce <- name.fe.model(model.reduce, inds, fe)\r\n model.reduce$inds <- inds\r\n model.reduce$fe <- fe\r\n\r\n dy <- model$demeaned$y\r\n dz <- model.reduce$demeaned$x\r\n dx <- model$demeaned$x\r\n colnames(dy) <- colnames(y)\r\n colnames(dz) <- colnames(z)\r\n colnames(dx) <- colnames(x)\r\n\r\n #inv.x <- solve(t(dx)%*%dx)\r\n #inv.z <- solve(t(dz)%*%dz)\r\n #Pz <- dz%*%inv.z%*%t(dz)\r\n #inv.xPzx <- solve(t(dx)%*%Pz%*%dx)\r\n #inv.z.zx <- inv.z%*%t(dz)%*%dx\r\n #iv.coef <- matrix(inv.xPzx%*%t(dx)%*%Pz%*%dy,ncol=1)\r\n #u.hat <- matrix(dy-dx%*%iv.coef,ncol=1)\r\n\r\n iv.solve <- try(solveiv(Y=dy,X=dx,Z=dz),silent = T)\r\n if ('try-error' %in% class(iv.solve)) {\r\n stop(\"Exact collinearity in the regression.\\n\")\r\n }\r\n inv.x <- iv.solve[[\"invxx\"]]\r\n inv.z <- iv.solve[[\"invzz\"]]\r\n inv.xPzx <- iv.solve[[\"invXPzX\"]]\r\n iv.coef <- iv.solve[[\"coef\"]]\r\n inv.z.zx <- iv.solve[[\"invzzx\"]]\r\n rownames(iv.coef) <- colnames(x)\r\n u.hat <- iv.solve[[\"residual\"]]\r\n ZY <- iv.solve[[\"ZY\"]]; #t(Z)*y\r\n XZ <- iv.solve[[\"XZ\"]]; #t(X)*Z\r\n\r\n if(sum(is.na(inv.x))>0){\r\n stop(\"Exact collinearity in the regression.\")\r\n }\r\n if(sum(is.na(inv.z))>0){\r\n stop(\"Exact collinearity in the regression.\")\r\n }\r\n\r\n colnames(inv.xPzx) <- rownames(inv.xPzx) <- colnames(inv.x) <- rownames(inv.x) <- colnames(dx)\r\n colnames(inv.z) <- rownames(inv.z) <- colnames(dz)\r\n rownames(XZ) <- colnames(dx)\r\n colnames(XZ) <- colnames(dz)\r\n \r\n colnames(ZY) <- colnames(dy)\r\n rownames(ZY) <- colnames(dz)\r\n \r\n model.iv <- list(coefficients=iv.coef,res=u.hat)\r\n model.iv$fe <- fe\r\n if(se == 1){\r\n if(is.null(df.use)){\r\n dof.output <- get.dof(model=model,\r\n x=x,\r\n cl=NULL,\r\n ind=ind,\r\n sfe.index=sfe.index,\r\n cfe.index=cfe.index)\r\n gtot <- dof.output$gtot \r\n model.iv$dof <- dof.output$dof\r\n ## degree of freedom\r\n df <- dim(dy)[1] - gtot\r\n }else{\r\n df <- df.use\r\n }\r\n model.iv$df.original <- df\r\n model$df.original <- df\r\n \r\n if(is.null(cl)){\r\n\r\n sigma2 <- t(u.hat)%*%u.hat/(df)\r\n RMSE <- sqrt(sigma2)\r\n R2 <- 1 - sum(t(u.hat)%*%u.hat)/sum((data[, 1] - mean(data[, 1]))^2)\r\n Adj_R2 <- 1 - (1 - R2) * (dim(x)[1] - 1) / df\r\n projR2 <- 1 - sum(t(u.hat)%*%u.hat)/sum((c(model$demeaned$y) - mean(model$demeaned$y))^2)\r\n projAdj_R2 <- 1 - (1 - projR2) * (dim(x)[1] - 1) / df\r\n\r\n if (robust == FALSE) {\r\n vcov <- as.matrix(c(t(u.hat)%*%u.hat/(df))*inv.xPzx)\r\n stderror <- as.matrix(sqrt(diag(vcov)))\r\n } else{\r\n meat <- dz * matrix(rep(c(u.hat), dim(dz)[2]), dim(dz)[1], dim(dz)[2])\r\n meat <- t(meat) %*% meat\r\n vcov <- inv.xPzx%*%(t(inv.z.zx)%*%meat%*%inv.z.zx)%*%inv.xPzx\r\n vcov <- dim(dx)[1] / df*vcov\r\n stderror <- as.matrix(sqrt(diag(vcov)))\r\n }\r\n\r\n Tx <- c(model.iv$coefficients)/c(stderror)\r\n\r\n P_t <- NULL\r\n for (i in 1:length(Tx)) {\r\n subt <- pt(Tx[i], df)\r\n P_t <- c(P_t, 2 * min(1 - subt, subt))\r\n } \r\n CI <- cbind(c(model.iv$coefficients) - qt(0.975,df=df)*c(stderror), c(model.iv$coefficients) + qt(0.975,df=df)*c(stderror))\r\n model.iv$df.residual <- df\r\n\r\n ## F test\r\n if (robust == FALSE) {\r\n ## full model\r\n ##fF <- R2/(1 - R2) * df/(dim(x)[1] - df - 1)\r\n ## projection model\r\n projF <- t(model.iv$coefficients) %*% solve(vcov) %*% model.iv$coefficients/dim(x)[2]\r\n\r\n ##F_statistic <- cbind(fF, dim(x)[1] - df - 1, df, 1 - pf(fF, dim(x)[1] - df - 1, df))\r\n proj_F_statistic <- cbind(projF, dim(x)[2], df, 1 - pf(projF, dim(x)[2], df))\r\n\r\n ##colnames(F_statistic) <- c(\"F_statistic\", \"df1\", \"df2\", \"P value\")\r\n colnames(proj_F_statistic) <- c(\"F_statistic\", \"df1\", \"df2\", \"P value\")\r\n\r\n ##model.iv$F_statistic <- F_statistic\r\n model.iv$proj_F_statistic <- proj_F_statistic\r\n } else {\r\n ## robust wald test \r\n fF <- t(model.iv$coefficients) %*% solve(vcov) %*% model.iv$coefficients\r\n fF <- c(fF) / dim(x)[2]\r\n F_statistic <- cbind(fF, dim(x)[2], df, 1 - pf(fF, dim(x)[2], df))\r\n colnames(F_statistic) <- c(\"F_statistic\", \"df1\", \"df2\", \"P value\")\r\n model.iv$proj_F_statistic <- F_statistic\r\n }\r\n\r\n est.coefficients <- cbind(model.iv$coefficients, stderror, Tx, P_t, CI)\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\", \"t value\", \"Pr(>|t|)\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(x)\r\n model.iv$est.coefficients <- est.coefficients\r\n }else{ \r\n #clusted fe\r\n model.iv$cl <- cl\r\n if (dim(cl)[2] == 1) {\r\n stderror <- iv.cluster.se(cl = cl, x = x, u.hat = u.hat, dz=dz,\r\n sfe.index = sfe.index, \r\n cfe.index = cfe.index,\r\n ind = ind, df = df, df.cl = df.cl.use,\r\n model = model,\r\n inv.z.zx = inv.z.zx,\r\n inv.xPzx = inv.xPzx\r\n )\r\n num.cl <- stderror$num.cl\r\n vcov <- stderror$vcov.cl\r\n df.cl <- stderror$df.cl\r\n dof <- stderror$dof\r\n stderror <- stderror$stderror\r\n model.iv$dof <- dof\r\n }\r\n else if (dim(cl)[2] == 2) {\r\n\r\n stderror1 <- iv.cluster.se(cl = as.matrix(cl[,1]), x = x, u.hat = u.hat, dz=dz,\r\n sfe.index = sfe.index, \r\n cfe.index = cfe.index,\r\n ind = ind, df = df, df.cl = df.cl.use[1],\r\n model = model,\r\n inv.z.zx = inv.z.zx,\r\n inv.xPzx = inv.xPzx)\r\n num.cl1 <- stderror1$num.cl\r\n vcov1 <- stderror1$vcov.cl\r\n df.cl1 <- stderror1$df.cl\r\n dof1 <- stderror1$dof\r\n stderror1 <- stderror1$stderror\r\n\r\n stderror2 <- iv.cluster.se(cl = as.matrix(cl[,2]), x = x, u.hat = u.hat, dz=dz,\r\n sfe.index = sfe.index, \r\n cfe.index = cfe.index,\r\n ind = ind, df = df, df.cl = df.cl.use[2],\r\n model = model,\r\n inv.z.zx = inv.z.zx,\r\n inv.xPzx = inv.xPzx)\r\n num.cl2 <- stderror2$num.cl\r\n vcov2 <- stderror2$vcov.cl\r\n df.cl2 <- stderror2$df.cl\r\n dof2 <- stderror2$dof\r\n stderror2 <- stderror2$stderror\r\n\r\n cl_inter <- as.numeric(as.factor(paste(cl[,1], \"-:-\", cl[,2], sep = \"\")))\r\n\r\n #if cl_inter is unique; then stderror3 is robust standard error\r\n cl_inter.count <- table(cl_inter)\r\n if(max(cl_inter.count)==1){\r\n meat3 <- dz * matrix(rep(c(u.hat), dim(dz)[2]), dim(dz)[1], dim(dz)[2])\r\n meat3 <- as.matrix(t(meat3) %*% meat3)\r\n vcov3 <- inv.xPzx%*%(t(inv.z.zx)%*%meat3%*%inv.z.zx)%*%inv.xPzx\r\n vcov3 <- dim(dx)[1]/model.iv$df.original*vcov3\r\n stderror3 <- c()\r\n for (i in 1:dim(x)[2]) {\r\n stderror3 <- c(stderror3, sqrt(vcov3[i, i]))\r\n }\r\n stderror3 <- as.matrix(stderror3)\r\n num.cl3 <- length(cl_inter.count)\r\n df.cl3 <- model.iv$df.original\r\n dof3 <- model.iv$dof\r\n }else{\r\n stderror3 <- iv.cluster.se(cl = as.matrix(cl_inter), x = x, u.hat = u.hat, dz=dz,\r\n sfe.index = sfe.index, \r\n cfe.index = cfe.index,\r\n ind = ind, df = df, df.cl = df.cl.use[3],\r\n model = model,\r\n inv.z.zx = inv.z.zx,\r\n inv.xPzx = inv.xPzx)\r\n num.cl3 <- stderror3$num.cl\r\n vcov3 <- stderror3$vcov.cl\r\n df.cl3 <- stderror3$df.cl\r\n dof3 <- stderror3$dof\r\n stderror3 <- stderror3$stderror\r\n }\r\n\r\n df.cl <- c(df.cl1,df.cl2,df.cl3)\r\n num.cl <- min(num.cl1,num.cl2,num.cl3)\r\n dof.output <- list()\r\n dof.names <- names(dof1)\r\n for(sub.dof.name in dof.names){\r\n min.index <- which.min(c(dof1[[sub.dof.name]][1]-dof1[[sub.dof.name]][2],\r\n dof2[[sub.dof.name]][1]-dof2[[sub.dof.name]][2],\r\n dof3[[sub.dof.name]][1]-dof3[[sub.dof.name]][2]))\r\n if(min.index==1){\r\n dof.output[[sub.dof.name]] <- dof1[[sub.dof.name]]\r\n }\r\n if(min.index==2){\r\n dof.output[[sub.dof.name]] <- dof2[[sub.dof.name]]\r\n }\r\n if(min.index==3){\r\n dof.output[[sub.dof.name]] <- dof3[[sub.dof.name]]\r\n }\r\n }\r\n\r\n model.iv$dof <- dof.output\r\n vcov <- vcov1+vcov2-vcov3\r\n stderror <- sqrt(stderror1^2 + stderror2^2 - stderror3^2)\r\n }\r\n\r\n df <- min(num.cl-1,df)\r\n Tx <- c(model.iv$coefficients)/c(stderror)\r\n P_t <- NULL\r\n for (i in 1:length(Tx)) {\r\n subt <- pt(Tx[i], df)\r\n P_t <- c(P_t, 2 * min(1 - subt, subt))\r\n } \r\n\r\n CI <- cbind(c(model.iv$coefficients) - qt(0.975,df)*c(stderror), c(model.iv$coefficients) + qt(0.975,df)*c(stderror))\r\n est.coefficients <- cbind(model.iv$coefficients, stderror, Tx, P_t, CI)\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\", \"t value\", \"Pr(>|t|)\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(x)\r\n model.iv$est.coefficients <- est.coefficients\r\n\r\n #Wald Test\r\n \r\n fF <- try(t(model.iv$coefficients) %*% solve(vcov) %*% model.iv$coefficients,silent = T)\r\n if ('try-error' %in% class(fF)) {\r\n fF <- NULL\r\n F_statistic <- NULL\r\n warning(\"Number of clusters insufficient to calculate robust covariance matrix.\\n\")\r\n }\r\n else{\r\n fF <- c(fF) / dim(x)[2]\r\n F_statistic <- cbind(fF, dim(x)[2], df, 1 - pf(fF, dim(x)[2], df))\r\n colnames(F_statistic) <- c(\"F_statistic\", \"df1\", \"df2\", \"P value\")\r\n }\r\n \r\n \r\n model.iv$proj_F_statistic <- F_statistic\r\n model.iv$df.residual <- df\r\n model.iv$df.cl <- df.cl\r\n\r\n df.cl.max <- max(df.cl)\r\n sigma2 <- t(u.hat)%*%u.hat/df.cl.max\r\n RMSE <- sqrt(sigma2)\r\n R2 <- 1 - sum(t(u.hat)%*%u.hat)/sum((data[, 1] - mean(data[, 1]))^2)\r\n Adj_R2 <- 1 - (1 - R2) * (dim(x)[1] - 1) / df.cl.max\r\n projR2 <- 1 - sum(t(u.hat)%*%u.hat)/sum((c(model$demeaned$y) - mean(model$demeaned$y))^2)\r\n projAdj_R2 <- 1 - (1 - projR2) * (dim(x)[1] - 1) / df.cl.max\r\n }\r\n colnames(vcov) <- rownames(vcov) <- colnames(x)\r\n model.iv$vcov <- vcov\r\n model.iv$RMSE <- RMSE\r\n model.iv$R2 <- R2\r\n model.iv$Adj_R2 <- Adj_R2\r\n model.iv$projR2 <- projR2\r\n model.iv$projAdj_R2 <- projAdj_R2\r\n }\r\n\r\n if(need.fe==TRUE){ #recover the fixed effects\r\n model.y <- SolveFixedEffects(matrix(y,ncol=1), fe$ptr, core.num)\r\n model.y <- name.fe.model(model.y, inds, fe)\r\n sfe.x.list <- list()\r\n cfe.x.list <- list()\r\n intercept.x <- c()\r\n\r\n if(identical(model.y$sfe.coefs,character(0))==FALSE){\r\n for(sub.sfe.name in names(model.y$sfe.coefs)){\r\n sfe.x.list[[sub.sfe.name]] <- model.y$sfe.coefs[[sub.sfe.name]]\r\n }\r\n }\r\n\r\n if(identical(model.y$cfe.coefs,character(0))==FALSE){\r\n for(sub.cfe.name in names(model.y$cfe.coefs)){\r\n cfe.x.list[[sub.cfe.name]] <- model.y$cfe.coefs[[sub.cfe.name]]\r\n }\r\n }\r\n\r\n intercept.x <- model.y$intercept\r\n\r\n if(dim(x)[2]!=0){\r\n for(i in 1:dim(x)[2]){\r\n model.x <- SolveFixedEffects(matrix(x[,i],ncol=1), fe$ptr, core.num)\r\n model.x <- name.fe.model(model.x, inds, fe)\r\n\r\n if(identical(model.y$sfe.coefs,character(0))==FALSE){\r\n for(sub.sfe.name in names(model.y$sfe.coefs)){\r\n sfe.x.list[[sub.sfe.name]] <- sfe.x.list[[sub.sfe.name]]-iv.coef[i,]*model.x$sfe.coefs[[sub.sfe.name]]\r\n }\r\n }\r\n\r\n if(identical(model.y$cfe.coefs,character(0))==FALSE){\r\n for(sub.cfe.name in names(model.y$cfe.coefs)){\r\n cfe.x.list[[sub.cfe.name]] <- cfe.x.list[[sub.cfe.name]]-iv.coef[i,]*model.x$cfe.coefs[[sub.cfe.name]]\r\n }\r\n }\r\n intercept.x <- intercept.x-iv.coef[i,]*model.x$intercept\r\n }\r\n }\r\n\r\n \r\n if(identical(cfe.x.list,list())){\r\n cfe.x.list <- character(0)\r\n }\r\n model.iv$sfe.coefs <- sfe.x.list\r\n model.iv$cfe.coefs <- cfe.x.list\r\n model.iv$intercept <- intercept.x\r\n }\r\n \r\n model.iv$y <- y\r\n model.iv$x <- x\r\n model.iv$z <- z \r\n model.iv$residuals <- u.hat\r\n model.iv$fitted.values <- y - u.hat\r\n model.iv$ols.model <- model\r\n model.iv$reduce.model <- model.reduce\r\n model.iv$demeaned <- list(dx=dx,dy=dy,dz=dz)\r\n model.iv$inds <- inds \r\n model.iv$matrix <- list(inv.x=inv.x,inv.z=inv.z,inv.z.zx=inv.z.zx,inv.xPzx=inv.xPzx,XZ=XZ,ZY=ZY)\r\n\r\n #all endogenous variables, extracted from x\r\n en.var.x <- c()\r\n ex.var.x <- c()\r\n #from z\r\n include.iv <- c()\r\n exclude.iv <- c()\r\n for(sub.dx in colnames(x)){\r\n get.ex <- matrix(sapply(as.data.frame(dz), identical, dx[,sub.dx]),nrow = 1)\r\n colnames(get.ex) <- colnames(z)\r\n if(any(get.ex)==TRUE){\r\n include.iv <- c(include.iv,colnames(get.ex)[which(get.ex==TRUE)])\r\n ex.var.x <- c(ex.var.x,sub.dx)\r\n }\r\n }\r\n include.iv <- unique(include.iv)\r\n ex.var.x <- unique(ex.var.x)\r\n exclude.iv <- colnames(dz)[which(!colnames(dz)%in%include.iv)]\r\n en.var.x <- colnames(dx)[which(!colnames(dx)%in%ex.var.x)]\r\n model.iv$names <- list(en.var.x=en.var.x,ex.var.x=ex.var.x,include.iv=include.iv,exclude.iv=exclude.iv)\r\n\r\n if(iv.test == TRUE){\r\n iv.test.results <- iv.test(model.iv, robust=robust, cl=cl, first = first, orthog=orthog, endog=endog)\r\n model.iv$tests <- iv.test.results\r\n }\r\n\r\n class(model.iv) <- \"ivfastplm\"\r\n return(model.iv)\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "e11a672deb9dbfe96c6564d0fdd7182a319f159f", "size": 18291, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ivfastplm_core.r", "max_stars_repo_name": "xuyiqing/fastplm", "max_stars_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-02T17:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T12:54:00.000Z", "max_issues_repo_path": "R/ivfastplm_core.r", "max_issues_repo_name": "xuyiqing/fastplm", "max_issues_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T05:58:47.000Z", "max_forks_repo_path": "R/ivfastplm_core.r", "max_forks_repo_name": "xuyiqing/fastplm", "max_forks_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:58:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T00:55:38.000Z", "avg_line_length": 42.2424942263, "max_line_length": 136, "alphanum_fraction": 0.4398884697, "num_tokens": 4867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.41203545220724197}}
{"text": "#' Plot MCMC\r\n#' \r\n#' Makes a number of diagnostic plots to evaluate convergence in the Monte Carlo Markov Chain results.\r\n#' @param wd directory where ASAP run is located\r\n#' @param asap.name Base name of original dat file (without the .dat extension)\r\n#' @param asap name of the variable that read in the asap.rdat file\r\n#' @param mcmc.burn number of realizations to remove from start of MCMC (defaults to 0)\r\n#' @param mcmc.thin thinning parameter for MCMC (defaults to 1)\r\n#' @param save.plots save individual plots\r\n#' @param od output directory for plots and csv files \r\n#' @param plotf type of plot to save\r\n#' @export\r\n\r\nPlotMCMC <- function(wd,asap.name,asap,mcmc.burn=0,mcmc.thin=1,save.plots,od,plotf){\r\n \r\n # kk5 <- library(plotMCMC, logical.return=T)\r\n # if (kk5==F) install.packages(\"plotMCMC\" )\r\n # library(plotMCMC)\r\n \r\n f.chain <- paste0(asap.name, \".MCM\" )\r\n #f.chain <- \"asap3MCMC.dat\"\r\n # don't run this function if chains are not present\r\n # just in case Enable MCMC Calculations box checked in General Tab of GUI but MCMC not actually run\r\n if (file.exists(paste0(wd,\"\\\\\",f.chain)) == FALSE){\r\n return()\r\n }\r\n chain1c <- read.table(paste0(wd,\"\\\\\",f.chain), header=T)\r\n ## new stuff\r\n niter <- dim(chain1c)[1]\r\n if (niter == 0) return() # in case asap$options$do.mcmc>0 but MCMC not actually run\r\n chain1b <- chain1c[(mcmc.burn+1):niter,]\r\n niter <- dim(chain1b)[1]\r\n chain1a <- chain1b[seq(1,niter,by=mcmc.thin),]\r\n \r\n bsn1c <- read.table(paste0(wd,\"\\\\\",asap.name, \".BSN\"), header=T)\r\n niter <- dim(bsn1c)[1]\r\n bsn1b <- bsn1c[(mcmc.burn):niter,]\r\n niter <- dim(bsn1b)[1]\r\n bsn1a <- bsn1b[seq(1,niter,by=mcmc.thin),]\r\n write.table(bsn1a, file=paste0(od, \"New_BSN_file.BSN\"), row.names=T)\r\n write.table(bsn1a, file=paste0(wd, \"\\\\New_\", asap.name,\".BSN\"), row.names=F, col.names=F)\r\n \r\n niter <- dim(chain1a)[1]\r\n nyears <- asap$parms$nyears\r\n years <- seq(asap$parms$styr, asap$parms$endyr)\r\n \r\n f.chain <- chain1a[,seq(1,nyears)]\r\n ssb.cols1 <- which(substr(names(chain1a),1,3)==\"SSB\")\r\n ssb.chain <- chain1a[,ssb.cols1[1:(length(ssb.cols1)-2)] ]\r\n fmult.chain <- chain1a[,which(substr(names(chain1a),1,3)==\"Fmu\")]\r\n totB.chain <- chain1a[,which(substr(names(chain1a),1,3)==\"tot\")]\r\n MSY.chain <- chain1a[,which(substr(names(chain1a),1,3)==\"MSY\")]\r\n MSY.col <- which(substr(names(chain1a),1,3)==\"MSY\")\r\n SSBmsy.chain <- chain1a[,(MSY.col+1)]\r\n Fmsy.chain <- chain1a[,(MSY.col+2) ]\r\n SSBmsy.ratio.chain <- chain1a[,(MSY.col+3) ]\r\n Fmsy.ratio.chain <- chain1a[,(MSY.col+4 ) ]\r\n \r\n \r\n # examine Trace in first and last year\r\n \r\n par(mfcol=c(2,1),mar=c(4,4,2,2), oma=c(1,1,1,1))\r\n plot(seq(1,niter), ssb.chain[,1], type='l', xlab=\"Iteration\", ylab=paste0(\"SSB\",years[1]) )\r\n plot(seq(1,niter), ssb.chain[,nyears], type='l', xlab=\"Iteration\", ylab=paste0(\"SSB\",years[nyears]))\r\n if (save.plots==T) savePlot(paste0(od,'Trace.SSB.first.last.yr.',plotf),type=plotf)\r\n \r\n par(mfcol=c(2,1),mar=c(4,4,2,2), oma=c(1,1,1,1))\r\n plot(seq(1,niter), f.chain[,1], type='l', xlab=\"Iteration\", ylab=paste0(\"Freport\",years[1]) )\r\n plot(seq(1,niter), f.chain[,nyears], type='l', xlab=\"Iteration\", ylab=paste0(\"Freport\",years[nyears]))\r\n if (save.plots==T) savePlot(paste0(od,'Trace.Freport.first.last.yr.',plotf),type=plotf)\r\n \r\n \r\n ##NEW\r\n # examine cumuplot in first and last year to determine if chain long enough (quartiles stabilized)\r\n mcmc.outs <- cbind( f.chain[,c(1,nyears)], ssb.chain[,c(1,nyears)])\r\n plotMCMC::plotCumu(mcmc.outs,probs=c(0.05,0.95), div=1, xlab=\"Iterations\",\r\n ylab=\"Median with 90% PI\", lty.median=1, lwd.median=2, col.median=\"black\", lty.outer=2, lwd.outer=1,\r\n col.outer=\"black\" )\r\n \r\n if (save.plots==T) savePlot(paste0(od,'Cumu.F_and_SSB.first.last.yr.',plotf),type=plotf)\r\n\r\n \r\n \r\n # look at auto-correlation plot\r\n par(mfcol=c(2,1),mar=c(4,4,2,2))\r\n ac.ssb1<-acf(ssb.chain[,1], lag.max=10, plot=F)\r\n ac.ssb2<-acf(ssb.chain[,nyears], lag.max=10, plot=F)\r\n ylims <- c(1.1*min(ac.ssb1$acf,-2/sqrt(niter)), 1 ) \r\n plot(seq(0,10), ac.ssb1$acf, xlab=paste0(\"Lag SSB\",years[1]), ylab=\"ACF\", type=\"h\",ylim=ylims )\r\n abline(h=0, lwd=2, col='black')\r\n abline(h=2/sqrt(niter), col='red', lty=2)\r\n abline(h=-2/sqrt(niter), col='red', lty=2)\r\n \r\n plot(seq(0,10), ac.ssb2$acf, xlab=paste0(\"Lag SSB\",years[nyears]), ylab=\"ACF\", type=\"h\",ylim=ylims )\r\n abline(h=0, lwd=2, col='black')\r\n abline(h=2/sqrt(niter), col='red', lty=2)\r\n abline(h=-2/sqrt(niter), col='red', lty=2)\r\n \r\n if (save.plots==T) savePlot(file=paste0(od, \"lag.autocorrelation.SSB.\",plotf), type=plotf)\r\n \r\n par(mfcol=c(2,1),mar=c(4,4,2,2))\r\n ac.f1<-acf(f.chain[,1], lag.max=10, plot=F)\r\n ac.f2<-acf(f.chain[,nyears], lag.max=10, plot=F)\r\n ylims <- c(1.1*min(ac.f1$acf,-2/sqrt(niter)), 1 ) \r\n plot(seq(0,10), ac.f1$acf, xlab=paste0(\"Lag F\",years[1]), ylab=\"ACF\", type=\"h\",ylim=ylims )\r\n abline(h=0, lwd=2, col='black')\r\n abline(h=2/sqrt(niter), col='red', lty=2)\r\n abline(h=-2/sqrt(niter), col='red', lty=2)\r\n \r\n plot(seq(0,10), ac.f2$acf, xlab=paste0(\"Lag F\",years[nyears]), ylab=\"ACF\", type=\"h\",ylim=ylims )\r\n abline(h=0, lwd=2, col='black')\r\n abline(h=2/sqrt(niter), col='red', lty=2)\r\n abline(h=-2/sqrt(niter), col='red', lty=2)\r\n \r\n if (save.plots==T) savePlot(file=paste0(od, \"lag.autocorrelation.Freport.\",plotf), type=plotf)\r\n \r\n \r\n # examine Distribution in first and last year\r\n ssb1.hist<-hist(ssb.chain[,1],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n ssb2.hist<-hist(ssb.chain[,nyears],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n xlims <- c(min(ssb1.hist$mids, ssb2.hist$mids), max(ssb1.hist$mids, ssb2.hist$mids))\r\n \r\n x1 <- (ssb1.hist$mids)\r\n y1 <- (ssb1.hist$counts) \r\n x2 <- (ssb2.hist$mids)\r\n y2 <- (ssb2.hist$counts) \r\n \r\n par(mfrow=c(2,1) )\r\n plot(x1,y1, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"SSB\", years[1]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y1)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=asap$SSB[1], col='red', lty=4)\r\n legend('topleft', legend=c(\"MCMC\", \"Point Est.\"), col=c(\"blue\", \"red\"), lwd=c(2,2),\r\n lty=c(1,4), cex=0.85 )\r\n \r\n plot(x2,y2, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"SSB\", years[nyears]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y2)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=asap$SSB[nyears], col='red', lty=4)\r\n if (save.plots==T) savePlot(paste0(od, 'Distribution.SSB.first.last.yr.',plotf), type=plotf)\r\n \r\n \r\n \r\n f1.hist<-hist(f.chain[,1],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n f2.hist<-hist(f.chain[,nyears],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n xlims <- c(min(f1.hist$mids, f2.hist$mids), max(f1.hist$mids, f2.hist$mids))\r\n \r\n x1 <- (f1.hist$mids)\r\n y1 <- (f1.hist$counts) \r\n x2 <- (f2.hist$mids)\r\n y2 <- (f2.hist$counts) \r\n \r\n par(mfrow=c(2,1) )\r\n plot(x1,y1, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Freport\", years[1]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y1)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=asap$F.report[1], col='red', lty=4)\r\n legend('topleft', legend=c(\"MCMC\", \"Point Est.\"), col=c(\"blue\", \"red\"), lwd=c(2,2),\r\n lty=c(1,4), cex=0.85 )\r\n \r\n \r\n plot(x2,y2, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Freport\", years[nyears]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y2)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=asap$F.report[nyears], col='red', lty=4)\r\n \r\n if (save.plots==T) savePlot(paste0(od, 'Distribution.Freport.first.last.yr.',plotf), type=plotf)\r\n \r\n \r\n \r\n fm1.hist<-hist(fmult.chain[,1],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n fm2.hist<-hist(fmult.chain[,nyears],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n xlims <- c(min(fm1.hist$mids, fm2.hist$mids), max(fm1.hist$mids, fm2.hist$mids))\r\n \r\n x1 <- (fm1.hist$mids)\r\n y1 <- (fm1.hist$counts) \r\n x2 <- (fm2.hist$mids)\r\n y2 <- (fm2.hist$counts) \r\n full.f <- apply(asap$F.age,1,max)\r\n \r\n par(mfrow=c(2,1) )\r\n plot(x1,y1, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Full F\", years[1]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y1)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=full.f[1], col='red', lty=4)\r\n legend('topleft', legend=c(\"MCMC\", \"Point Est.\"), col=c(\"blue\", \"red\"), lwd=c(2,2),\r\n lty=c(1,4), cex=0.85 )\r\n \r\n \r\n plot(x2,y2, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Full F\", years[nyears]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y2)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=full.f[nyears], col='red', lty=4)\r\n \r\n if (save.plots==T) savePlot(paste0(od, 'Distribution.Fmult.first.last.yr.',plotf), type=plotf)\r\n \r\n \r\n b1.hist<-hist(totB.chain[,1],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n b2.hist<-hist(totB.chain[,nyears],breaks = \"Sturges\", include.lowest = TRUE, right = TRUE, plot=F)\r\n xlims <- c(min(b1.hist$mids, b2.hist$mids), max(b1.hist$mids, b2.hist$mids))\r\n \r\n x1 <- (b1.hist$mids)\r\n y1 <- (b1.hist$counts) \r\n x2 <- (b2.hist$mids)\r\n y2 <- (b2.hist$counts) \r\n tot.B <- asap$tot.jan1.B\r\n \r\n par(mfrow=c(2,1) )\r\n plot(x1,y1, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Jan-1 B\", years[1]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y1)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=tot.B[1], col='red', lty=4)\r\n legend('topleft', legend=c(\"MCMC\", \"Point Est.\"), col=c(\"blue\", \"red\"), lwd=c(2,2),\r\n lty=c(1,4), cex=0.85 )\r\n \r\n \r\n plot(x2,y2, type=\"l\",lty=2,col=\"blue\",lwd=4,xlab=paste0(\"Jan-1 B\", years[nyears]), ylab=\"Freq\", \r\n ylim=c(0, max( 1.02*y2)), xlim=c(0.98*xlims[1], 1.02*xlims[2]) )\r\n abline(v=tot.B[nyears], col='red', lty=4)\r\n \r\n if (save.plots==T) savePlot(paste0(od, 'Distribution.Jan1.B.first.last.yr.',plotf), type=plotf)\r\n \r\n \r\n #### Probability Interval Plots\r\n #plot 95% PI\r\n \r\n #sort \r\n par(mfrow=c(1,1), mar=c(4,4,2,3), oma=c(1,1,1,1) )\r\n \r\n ssb.sort<- (apply(ssb.chain,2,sort ))\r\n p5 <- trunc( dim(ssb.sort)[1] *.05)\r\n p95 <- trunc( dim(ssb.sort)[1] *.95)\r\n \r\n p50 <- median(dim(ssb.sort)[1])\r\n p10 <- trunc( dim(ssb.sort)[1] *.10)\r\n p90 <- trunc( dim(ssb.sort)[1] *.90)\r\n \r\n \r\n plot(years, ssb.sort[p5,], type='l', col='grey35', lwd=2, xlab='Year',\r\n ylab='', ylim=c(0,1.03*max(ssb.sort[p95,])), axes=F )\r\n axis(side=1, at=years[seq(1,nyears,by=2)], labels=years[seq(1,nyears,by=2)], las=2)\r\n axis(side=2, at=pretty(seq(0,1.01*max(ssb.sort)), n=10) , \r\n labels=format(pretty(seq(0,1.01*max(ssb.sort)), n=10), scientific=T), las=1)\r\n axis(side=4, at=pretty(seq(0,1.01*max(ssb.sort)), n=10) , \r\n labels=format(pretty(seq(0,1.01*max(ssb.sort)), n=10), scientific=T), las=1)\r\n box()\r\n mtext(side=2, text=\"SSB\", outer=T) \r\n lines( years, ssb.sort[p95,] , col='grey35', lwd=2) \r\n lines( years, apply(ssb.sort,2,median) , col='red', lwd=2) \r\n lines( years, asap$SSB , col='green3', lwd=1) \r\n points( years, asap$SSB , col='green3', pch=17, cex=0.7) \r\n \r\n legend('topleft', horiz=T, legend=c(\"5th, 95th\", \"Median\",\"Point Est.\"), \r\n col=c(\"grey35\", \"red\", \"green3\"), lwd=c(2,2,2), lty=c(1,1,1), cex=0.85,\r\n pch=c(1,1,17), pt.cex=c(0,0,1) )\r\n \r\n if (save.plots==T) savePlot(paste0(od, \"SSB.90PI.\", plotf), type=plotf)\r\n \r\n \r\n ssb.pi <- cbind(years, \"5th\"=ssb.sort[p5,], \"Median\"=apply(ssb.sort,2,median), \"95th\"=ssb.sort[p95,])\r\n write.csv(ssb.pi, file=paste0(od, \"ssb.90pi_\",asap.name,\".csv\"), \r\n row.names=F )\r\n \r\n \r\n \r\n f.sort <- (apply(f.chain,2,sort ))\r\n p5 <- trunc( dim(f.sort)[1] *.05)\r\n p95 <- trunc( dim(f.sort)[1] *.95)\r\n \r\n p50 <- median(dim(f.sort)[1])\r\n p10 <- trunc( dim(f.sort)[1] *.10)\r\n p90 <- trunc( dim(f.sort)[1] *.90)\r\n \r\n par(mfrow=c(1,1), mar=c(4,4,2,3), oma=c(1,1,1,1) )\r\n plot(years, f.sort[p5,], type='l', col='grey35', lwd=2, xlab='Year',\r\n ylab='Freport', ylim=c(0,1.1*max(f.sort[p95,])), axes=F )\r\n axis(side=1, at=years[seq(1,nyears,by=2)], labels=years[seq(1,nyears,by=2)], las=2)\r\n axis(side=2, at=pretty(seq(0,1.01*max(f.sort), by=0.1), n=10) , \r\n labels=pretty(seq(0,1.01*max(f.sort), by=0.1), n=10), las=1)\r\n axis(side=4, at=pretty(seq(0,1.01*max(f.sort), by=0.1), n=10) , \r\n labels=pretty(seq(0,1.01*max(f.sort), by=0.1), n=10), las=1)\r\n box()\r\n \r\n lines( years, f.sort[p95,] , col='grey35', lwd=2) \r\n lines( years, apply(f.sort,2,median) , col='red', lwd=2) \r\n lines( years, asap$F.report , col='green3', lwd=1) \r\n points( years, asap$F.report , col='green3', pch=17, cex=0.7) \r\n legend('topleft', horiz=T, legend=c(\"5th, 95th\", \"Median\",\"Point Est.\"), \r\n col=c(\"grey35\", \"red\", \"green3\"), lwd=c(2,2,2), lty=c(1,1,1), cex=0.85,\r\n pch=c(1,1,17), pt.cex=c(0,0,1) )\r\n \r\n if (save.plots==T) savePlot(paste0(od, \"Freport.90PI.\", plotf), type=plotf)\r\n \r\n \r\n Freport.pi <- cbind(years, \"5th\"=f.sort[p5,], \"Median\"=apply(f.sort,2,median), \"95th\"=f.sort[p95,])\r\n write.csv(Freport.pi, file=paste0(od, \"Freport.90pi_\",asap.name,\".csv\"), row.names=F)\r\n \r\n \r\n \r\n \r\n fm.sort <- (apply(fmult.chain,2,sort ))\r\n p5 <- trunc( dim(fm.sort)[1] *.05)\r\n p95 <- trunc( dim(fm.sort)[1] *.95)\r\n \r\n p50 <- median(dim(fm.sort)[1])\r\n p10 <- trunc( dim(fm.sort)[1] *.10)\r\n p90 <- trunc( dim(fm.sort)[1] *.90)\r\n \r\n par(mfrow=c(1,1), mar=c(4,4,2,3), oma=c(1,1,1,1) )\r\n plot(years, fm.sort[p5,], type='l', col='grey35', lwd=2, xlab='Year',\r\n ylab='Full F', ylim=c(0,1.1*max(fm.sort[p95,])), axes=F )\r\n axis(side=1, at=years[seq(1,nyears,by=2)], labels=years[seq(1,nyears,by=2)], las=2)\r\n axis(side=2, at=pretty(seq(0,1.01*max(fm.sort), by=0.1), n=10) , \r\n labels=pretty(seq(0,1.01*max(fm.sort), by=0.1), n=10), las=1)\r\n axis(side=4, at=pretty(seq(0,1.01*max(fm.sort), by=0.1), n=10) , \r\n labels=pretty(seq(0,1.01*max(fm.sort), by=0.1), n=10), las=1)\r\n box()\r\n \r\n lines( years, fm.sort[p95,] , col='grey35', lwd=2) \r\n lines( years, apply(fm.sort,2,median) , col='red', lwd=2) \r\n lines( years, full.f , col='green3', lwd=1) \r\n points( years, full.f, col='green3', pch=17, cex=0.7) \r\n legend('topleft', horiz=T, legend=c(\"5th, 95th\", \"Median\",\"Point Est.\"), \r\n col=c(\"grey35\", \"red\", \"green3\"), lwd=c(2,2,2), lty=c(1,1,1), cex=0.85,\r\n pch=c(1,1,17), pt.cex=c(0,0,1) )\r\n \r\n if (save.plots==T) savePlot(paste0(od, \"Full.F.90PI.\", plotf), type=plotf)\r\n \r\n \r\n Full.F.pi <- cbind(years, \"5th\"=fm.sort[p5,], \"Median\"=apply(fm.sort,2,median), \"95th\"=fm.sort[p95,])\r\n write.csv(Full.F.pi, file=paste0(od, \"Full.F.90pi_\",asap.name,\".csv\"), row.names=F)\r\n \r\n \r\n \r\n tb.sort <- (apply(totB.chain,2,sort ))\r\n p5 <- trunc( dim(tb.sort)[1] *.05)\r\n p95 <- trunc( dim(tb.sort)[1] *.95)\r\n \r\n p50 <- median(dim(tb.sort)[1])\r\n p10 <- trunc( dim(tb.sort)[1] *.10)\r\n p90 <- trunc( dim(tb.sort)[1] *.90)\r\n \r\n par(mfrow=c(1,1), mar=c(4,4,2,3), oma=c(1,1,1,1) )\r\n plot(years, tb.sort[p5,], type='l', col='grey35', lwd=2, xlab='Year',\r\n ylab='', ylim=c(0,1.03*max(tb.sort[p95,])), axes=F )\r\n axis(side=1, at=years[seq(1,nyears,by=2)], labels=years[seq(1,nyears,by=2)], las=2)\r\n axis(side=2, at=pretty(seq(0,1.01*max(tb.sort), by=max(tb.sort)/10), n=10) , \r\n labels=format(pretty(seq(0,1.01*max(tb.sort), by=max(tb.sort)/10), n=10), scientific=T), las=1)\r\n axis(side=4, at=pretty(seq(0,1.01*max(tb.sort), by=max(tb.sort)/10), n=10) , \r\n labels=format(pretty(seq(0,1.01*max(tb.sort), by=max(tb.sort)/10), n=10), scientific=T), las=1)\r\n \r\n box()\r\n mtext(side=2, text=\"Jan-1 Biomass\", outer=T) \r\n lines( years, tb.sort[p95,] , col='grey35', lwd=2) \r\n lines( years, apply(tb.sort,2,median) , col='red', lwd=2) \r\n lines( years, asap$tot.jan1.B , col='green3', lwd=1) \r\n points( years, asap$tot.jan1.B, col='green3', pch=17, cex=0.7) \r\n legend('topleft', horiz=T, legend=c(\"5th, 95th\", \"Median\",\"Point Est.\"), \r\n col=c(\"grey35\", \"red\", \"green3\"), lwd=c(2,2,2), lty=c(1,1,1), cex=0.85,\r\n pch=c(1,1,17), pt.cex=c(0,0,1) )\r\n \r\n if (save.plots==T) savePlot(paste0(od, \"Jan1.B.90PI.\", plotf), type=plotf)\r\n \r\n \r\n Tot.B.pi <- cbind(years, \"5th\"=tb.sort[p5,], \"Median\"=apply(tb.sort,2,median), \"95th\"=tb.sort[p95,])\r\n write.csv(Tot.B.pi, file=paste0(od, \"Jan1.B.90pi_\",asap.name,\".csv\"), row.names=F)\r\n \r\n return()\r\n} # end function\r\n", "meta": {"hexsha": "8873bf80e14cf5fad927dd089d974c3986197941", "size": 16338, "ext": "r", "lang": "R", "max_stars_repo_path": "R/plot_mcmc.r", "max_stars_repo_name": "liz-brooks/ASAPplots", "max_stars_repo_head_hexsha": "f42263d80f28b9de5d1abd2f87676d26bb30d4ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-03-25T20:24:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T20:54:15.000Z", "max_issues_repo_path": "R/plot_mcmc.r", "max_issues_repo_name": "liz-brooks/ASAPplots", "max_issues_repo_head_hexsha": "f42263d80f28b9de5d1abd2f87676d26bb30d4ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21, "max_issues_repo_issues_event_min_datetime": "2017-04-11T18:32:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T21:03:06.000Z", "max_forks_repo_path": "R/plot_mcmc.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": 45.0082644628, "max_line_length": 112, "alphanum_fraction": 0.5897294651, "num_tokens": 6554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4120200715779532}}
{"text": "\n#' @title Livestock resilience model\n#'\n#' @description A model of resilience in arid rangelands.\n#' @usage\n#' library(livestock)\n#'\n#'\n#' library(caspr)\n#' ca(l, livestock, parms = p)\n#'\n#' @param b environmental quality\n#' @param m intrinsic plant mortality, i.e. inverse of av. lifespan\n#' @param r max. regeneration rate of plants\n#' @param K carrying capacity of the landscape (i.e. global competition)\n#' @param f local facilitation\n#' @param c local competition\n#' @param L livestock density\n#' @param a attack rate of livestock\n#' @param h handling time of livestock\n#' @param q hill-exponent of livestock\n#' @param p associational resistance against livestock grazing\n#' @param v attractant-decoy effect of plants to livestock\n#'\n#' @author F.D. Schneider\n#' @family models\n#' @details\n#' An unpublished, generalized model of positive and negative local feedbacks in arid rangelands, including mechanisms such as local facilitation, competition, associational resistance and attractant-decoy.\n#'\n#' @export\n\n\"livestock\"\n\nlivestock <- list(\n name = \"Livestock resilience model\",\n ref = NA , # a bibliographic reference,\n states = c(\"1\", \"0\"),\n cols = c(\"black\", \"white\"),\n template = ini_rho(rho_1 = 0.9999),\n parms = list(\n r = 1,\n b = 1,\n K = 1,\n alpha = 0,\n c = 0,\n f = 0,\n m = 0.05,\n a = 10,\n h = 20,\n L = 1,\n q = 0,\n v = 0,\n p = 0\n ),\n pair = function(t, rho, parms = model_parms) {\n\n # insert equations here\n delta_1 = (1-rho[[1]]) * colonization(rho, parms) - rho[[1]] * death(rho, parms)\n delta_11 = 2 * (rho[[1]]-rho[[2]]) * colonization(rho, parms) - 2 * rho[[2]] * death(rho, parms)\n\n if(rho[[1]] < 1e-6) {\n out <- list(c(\n rho_1 = 0,\n rho_11 = 0\n ) )\n } else {\n out <- list(c(\n rho_1 = delta_1,\n rho_11 = delta_11\n ) )\n }\n return(out)\n },\n pairmeanfield = function(t, rho, parms = model_parms) {\n pair(t, ini_rho(rho[[1]]), parms)\n },\n meanfield = function(t, rho, parms = model_parms) {\n\n rho <- ini_rho(rho[[1]])\n delta_1 <- (1-rho[[1]])*colonization(rho, parms) - rho[[1]]*death(rho, parms)\n\n if(rho[[1]]+delta_1 < 1e-6) {\n out <- list(c(\n rho_1 = 0,\n rho_11 = 0\n ) )\n } else {\n out <- list(c(\n rho_1 = delta_1,\n rho_11 = delta_1\n ) )\n }\n return(out)\n },\n update = function(x_old, parms, subs = 24, i = i) { #for cellular automata simulation in package caspr\n\n x_new <- x_old\n\n for(s in 1:subs) {\n\n # define update procedures depending on parms\n\n # model specific part:\n # 1 - setting time-step parameters\n rho_one <- as.numeric(sum(x_old$cells == \"1\")/(x_old$dim[1]*x_old$dim[2])) # get initial vegetation cover\n q_one_one <- neighbors(x_old, \"1\")/4 # count local density of occupied fields for each cell\n\n # 2 - drawing random numbers\n rnum <- runif(x_old$dim[1]*x_old$dim[2]) # one random number between 0 and 1 for each cell\n\n # 3 - setting transition probabilities\n growth <- colonization(ini_rho(rho_one, q_11 = q_one_one), parms) *1/subs # recolonisation rates of all cells\n\n growth[growth < 0] <- 0\n\n death <- death(ini_rho(rho_one, q_11 = q_one_one), parms) *1/subs # set probability of death for each cell\n\n death[death < 0] <- 0\n\n # check for sum of probabilities to be inferior 1 and superior 0\n if(any(c(growth, death) > 1 )) warning(paste(\"a set probability is exceeding 1 ! decrease delta!!!\"))\n #if(any(c(growth, death) < 0)) warning(paste(\"a set probability falls below 0 in time step\", i, \"! balance parameters!!!\"))\n\n # 4 - apply transition probabilities\n\n x_new$cells[which(x_old$cells == \"0\" & rnum <= growth)] <- \"1\"\n x_new$cells[which(x_old$cells == \"1\" & rnum <= death)] <- \"0\"\n\n # 5- store x_new as next x_old\n\n x_old <- x_new\n\n }\n\n return(x_new)\n\n }\n\n)\n\nclass(livestock) <- c(\"ca_model\", \"list\")\n", "meta": {"hexsha": "ce2394a7ac40333b373194d37f8563d3e27e88aa", "size": 3959, "ext": "r", "lang": "R", "max_stars_repo_path": "R/livestock.r", "max_stars_repo_name": "fdschneider/livestock", "max_stars_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-01T02:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:59:02.000Z", "max_issues_repo_path": "R/livestock.r", "max_issues_repo_name": "fdschneider/livestock", "max_issues_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/livestock.r", "max_forks_repo_name": "fdschneider/livestock", "max_forks_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8802816901, "max_line_length": 206, "alphanum_fraction": 0.6072240465, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.41198082342105785}}
{"text": "#' @title\n#' Plot heatmap for the functional regression surface\n#'\n#' @description\n#' This function creates heatmaps for the functional regression surface in a\n#' multivariate functional linear regression. Based on the fitting results from the\n#' nested reduced-rank regression, different kinds of regression surfaces\n#' (at the original scale or the latent scale) can be visualized to give a\n#' clear illustration of the functional correlation between the user-specified\n#' predictor (or latent predictor) trajectory and response\n#' (or latent response) trajectory.\n#'\n#'\n#' @usage\n#' NRRR.plot.reg(Ag, Bg, Al, Bl, rx, ry, sseq, phi, tseq, psi,\n#' x_ind, y_ind, x_lab = NULL, y_lab = NULL,\n#' tseq_index = NULL, sseq_index = NULL,\n#' method = c(\"latent\", \"x_original\",\n#' \"y_original\", \"original\")[1])\n#'\n#'\n#' @param Ag,Bg,Al,Bl,rx,ry the estimated U, V, A, B, rx and ry from a NRRR fitting.\n#' @param sseq the sequence of time points at which the predictor trajectory is observed.\n#' @param phi the set of basis functions to expand the predictor trajectory.\n#' @param tseq the sequence of time points at which the response trajectory is observed.\n#' @param psi the set of basis functions to expand the response trajectory.\n#' @param x_ind,y_ind two indices to locate the regression surface for which the heat map is to be drawn.\n#' If \\code{method = \"original\"}, then \\eqn{0 < x_ind <= p, 0 < y_ind <= d}\n#' and the function plots \\eqn{C_{x_ind,y_ind}(s,t)} in Eq. (1) of the NRRR paper.\n#' If \\code{method = \"latent\"}, then \\eqn{0 < x_ind <= rx, 0 < y_ind <= ry}\n#' and the function plots \\eqn{C^*_{x_ind,y_ind}(s,t)} in Eq. (2) of the NRRR paper.\n#' If \\code{method = \"y_original\"}, then \\eqn{0 < x_ind <= rx, 0 < y_ind <= d}.\n#' If \\code{method = \"x_original\"}, then \\eqn{0 < x_ind <= p, 0 < y_ind <= ry}.\n#' @param x_lab,y_lab the user-specified x-axis (with x_lab for predictor) and\n#' y-axis (with y_lab for response) label,\n#' and it should be given as a character string, e.g., x_lab = \"Temperature\".\n#' @param tseq_index,sseq_index the user-specified x-axis (with sseq_index for predictor)\n#' and y-axis (with tseq_index for response) tick marks, and it should be\n#' given as a vector of character strings of the same length as sseq or tseq, respectively.\n#' @param method 'original': the function plots the correlation heatmap between the original\n#' functional response \\eqn{y_i(t)} and the original functional predictor \\eqn{x_j(s)};\n#' 'latent': the function plots the correlation heatmap between\n#' the latent functional response \\eqn{y^*_i(t)} and the latent functional predictor \\eqn{x^*_j(s)};\n#' 'y_original': the function plots the correlation heatmap between \\eqn{y_i(t)} and \\eqn{x^*_j(s)};\n#' 'x_original': the function plots the correlation heatmap between \\eqn{y^*_i(t)} and \\eqn{x_j(s)}.\n#'\n#' @return A ggplot2 object.\n#'\n#' @details\n#' More details and the examples of its usage can be found in the vignette of electricity demand analysis.\n#'\n#' @references\n#' Liu, X., Ma, S., & Chen, K. (2020). Multivariate Functional Regression via Nested Reduced-Rank Regularization.\n#' arXiv: Methodology.\n#'\n#' @import ggplot2\n#' @importFrom reshape2 melt\n#' @export\n\nNRRR.plot.reg <- function(Ag, Bg, Al, Bl, rx, ry,\n sseq, phi, tseq, psi,\n x_ind, y_ind,\n x_lab = NULL, y_lab = NULL,\n tseq_index = NULL, sseq_index = NULL,\n method = c(\"latent\", \"x_original\", \"y_original\",\"original\")[1]\n){\n ry <- ry\n rx <- rx\n Al <- Al\n Bl <- Bl\n Ag <- Ag\n Bg <- Bg\n p <- dim(Bg)[1]\n d <- dim(Ag)[1]\n ns <- dim(phi)[1]\n nt <- dim(psi)[1]\n jx <- dim(phi)[2]\n jy <- dim(psi)[2]\n\n if (method == \"original\" & any(c(0 > x_ind, x_ind > p, 0 > y_ind, y_ind > d))) stop(\"when 'original' is selected, 0 < x_ind <= p, 0 < y_ind <= d\")\n if (method == \"latent\" & any(c(0 > x_ind, x_ind > rx, 0 > y_ind, y_ind > ry))) stop(\"when 'latent' is selected, 0 < x_ind <= rx, 0 < y_ind <= ry\")\n if (method == \"y_original\" & any(c(0 > x_ind, x_ind > rx, 0 > y_ind, y_ind > d))) stop(\"when 'y_original' is selected, 0 < x_ind <= rx, 0 < y_ind <= d\")\n if (method == \"x_original\" & any(c(0 > x_ind, x_ind > p, 0 > y_ind, y_ind > ry))) stop(\"when 'x_original' is selected, 0 < x_ind <= p, 0 < y_ind <= ry\")\n\n\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 alindex <- rep(1:ry,jy)\n Alstar <- Al[order(alindex),]\n blindex <- rep(1:rx,jx)\n Blstar <- Bl[order(blindex),]\n\n\n Alstar <- kronecker(diag(ry),Jpsihalfinv)%*%Alstar\n Core <- Alstar%*%t(Blstar)\n\n\n comp <- array(dim = c(ry, rx, nt, ns), NA)\n\n for (i in 1:ry){\n for (j in 1:rx){\n comp[i,j,,] <- psi%*%Core[c(((i-1)*jy + 1):(i*jy)),\n c(((j-1)*jx + 1):(j*jx))]%*%t(phi) # nt \\times ns\n }\n }\n\n\n if (method == \"original\"){\n comp.ori <- array(dim = c(d, p, nt, ns), NA)\n for (i in 1:nt){\n for (j in 1:ns){\n comp.ori[ , , i, j] <- Ag%*%comp[ , , i, j]%*%t(Bg)\n }\n }\n comp <- comp.ori\n } else if (method == \"y_original\"){\n comp.ori <- array(dim = c(d, rx, nt, ns), NA)\n for (i in 1:nt){\n for (j in 1:ns){\n comp.ori[ , , i, j] <- Ag%*%comp[ , , i, j]\n }\n }\n comp <- comp.ori\n } else if (method == \"x_original\"){\n comp.ori <- array(dim = c(ry, p, nt, ns), NA)\n for (i in 1:nt){\n for (j in 1:ns){\n comp.ori[ , , i, j] <- comp[ , , i, j]%*%t(Bg)\n }\n }\n comp <- comp.ori\n }\n\n # heatmap for coefficient function\n # library(ggplot2)\n # library(reshape2)\n\n dat <- reshape2::melt(as.matrix(comp[y_ind, x_ind, , ]))\n\n dat$Var1 <- factor(dat$Var1)\n dat$Var2 <- factor(dat$Var2)\n if (is.null(tseq_index)) {\n levels(dat$Var1) <- factor(tseq)\n y_breaks <- tseq[seq(1,nt,2)]\n } else {\n levels(dat$Var1) <- tseq_index\n y_breaks <- tseq_index[seq(1,nt,2)]\n }\n\n if (is.null(sseq_index)) {\n levels(dat$Var2) <- factor(sseq)\n x_breaks <- sseq[seq(1,ns,2)]\n } else {\n levels(dat$Var2) <- sseq_index\n x_breaks <- sseq_index[seq(1,ns,2)]\n }\n\n # Var1 <- dat$Var1\n # Var2 <- dat$Var2\n # value <- dat$value\n\n\n ggplot2::ggplot(dat, aes(Var2, Var1, fill = value)) + geom_tile() +\n scale_fill_gradient2(low = \"blue\", mid = \"white\",\n high = \"red\", midpoint = 0, limits= range(comp),\n space = \"Lab\", name = \"\",\n na.value = \"grey50\", guide = \"colourbar\", aesthetics = \"fill\")+\n scale_x_discrete(breaks = x_breaks) +\n scale_y_discrete(breaks = y_breaks) +\n ylab(ifelse(is.null(y_lab), \"response (t)\", y_lab)) +\n xlab(ifelse(is.null(x_lab), \"predictor (s)\", x_lab)) +\n theme_classic() +\n theme(axis.text.x = element_text(angle = 45, hjust = 1)) +\n theme(axis.text=element_text(size=10),axis.title=element_text(size=13),\n plot.title = element_text(hjust = 0.5, size = 15))\n}\n", "meta": {"hexsha": "920477365d592a95b74e363266d837ecaf5cf010", "size": 7623, "ext": "r", "lang": "R", "max_stars_repo_path": "R/NRRR.plot.RegSurface.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.plot.RegSurface.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.plot.RegSurface.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": 41.6557377049, "max_line_length": 154, "alphanum_fraction": 0.5706414797, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41157530773824313}}
{"text": "# Explained Variance (R2) calculation for left-handedness (binomial trait)\n# V.Odintsova, J.van Dongen, C.Dolan\n# Based on Lee et al.\n# Genetic Epidemiology 36 : 214–224 (2012)\n# A Better Coefficient of Determination for Genetic Profile Analysis\n\n########################### ############## ##############\n# Load data\n########################### ############## ##############\n# polygenic risk scores (PGS)\n# methylation scores (MS)\n# EWAS covariates\n# PGS covariates\n\n########################### ############## ##############\n# Select variables for the prediction models\n########################### ############## ##############\n# FISNumber\n# FamilyNumber\n# sex\n# age (age at DNA bloodsampling, scaled)\n# hand01 (left-handedness variable: right-handed = 0, left-handed = 1)\n\n# PGS and GWAS covariates\n# PGS\n# PC1 - PC10 (principal components)\n# platform2 - platform6 (platform dummy variables)\n\n# Methylation scores and EWAS covariates from adjusted model\n# MS1 (methylation score calculated with weights at p-value thresholds 10^-1)\n# MS3 (methylation score calculated with weights at p-value thresholds 10^-3)\n# MS5 (methylation score calculated with weights at p-value thresholds 10^-5)\n# smoking\n# BMI\n# Neut_Perc (neutrophils percentage)\n# Mono_Perc (monocytes percentage)\n# Eos_Perc (eosinophils percentage)\n# Array_rownum (array rownumber)\n# Sample_Plate (sample plate)\n# Sample_Plate1 - Sample_PlateN (dummy variables for sample plate)\n\n########################### ############## ##############\n# Logistic regression to calculate R2 for PGS and MS\n############################ ############## ##############\n# function for logistic regression model with PGS and covariates prints PGS effect size, se, p-value, R2\nPGSlogit_function = function(NTRdata) {\n dat = NTRdata\n hand01=as.numeric(dat$hand01)\n sex=as.numeric(dat$sex)\n PGS=as.numeric(dat$PGS)\n PC1 = as.numeric(dat$PC1)\n PC2 = as.numeric(dat$PC2)\n PC3 = as.numeric(dat$PC3)\n PC4 = as.numeric(dat$PC4)\n PC5 = as.numeric(dat$PC5)\n PC6 = as.numeric(dat$PC6)\n PC7 = as.numeric(dat$PC7)\n PC8 = as.numeric(dat$PC8)\n PC9 = as.numeric(dat$PC9)\n PC10 = as.numeric(dat$PC10)\n platform2=as.numeric(dat$platform2)\n platform3=as.numeric(dat$platform3)\n platform5=as.numeric(dat$platform5)\n platform6=as.numeric(dat$platform6)\n # MODEL 1: handedness ~ PGS + GWAS covariates\n vare1 = pi^2 / 3 # residual (homoskedastic) variance\n r1=glm(hand01~PGS+sex+ platform2+platform3+platform5+platform6+PC1+PC2+PC3+PC4+PC5+PC6+PC7+PC8+PC9+PC10,\n family=binomial(link='logit')) # logistic regression\n vp1=var( r1$coefficients[\"PGS\"]*PGS+\n r1$coefficients[\"sex\"]*sex+\n r1$coefficients[\"platform2\"]*platform2+\n r1$coefficients[\"platform3\"]*platform3+\n r1$coefficients[\"platform5\"]*platform5+\n r1$coefficients[\"platform6\"]*platform6+\n r1$coefficients[\"PC1\"]*PC1+\n r1$coefficients[\"PC2\"]*PC2+\n r1$coefficients[\"PC3\"]*PC3+\n r1$coefficients[\"PC4\"]*PC4+\n r1$coefficients[\"PC5\"]*PC5+\n r1$coefficients[\"PC6\"]*PC6+\n r1$coefficients[\"PC7\"]*PC7+\n r1$coefficients[\"PC8\"]*PC8+\n r1$coefficients[\"PC9\"]*PC9+\n r1$coefficients[\"PC10\"]*PC10) # variance explained\n R2logist1 = vp1 / (vp1+vare1) # explained var / total var\n # MODEL 2: handedness ~ GWAS covariates\n r2=glm(hand01~sex+platform2+platform3+platform5+platform6+PC1+PC2+PC3+PC4+PC5+PC6+PC7+PC8+PC9+PC10,\n family=binomial(link='logit'))\n vp2=var(\n r2$coefficients[\"sex\"]*sex+\n r2$coefficients[\"platform2\"]*platform2+\n r2$coefficients[\"platform3\"]*platform3+\n r2$coefficients[\"platform5\"]*platform5+\n r2$coefficients[\"platform6\"]*platform6+\n r1$coefficients[\"PC1\"]*PC1+\n r1$coefficients[\"PC2\"]*PC2+\n r1$coefficients[\"PC3\"]*PC3+\n r1$coefficients[\"PC4\"]*PC4+\n r1$coefficients[\"PC5\"]*PC5+\n r1$coefficients[\"PC6\"]*PC6+\n r1$coefficients[\"PC7\"]*PC7+\n r1$coefficients[\"PC8\"]*PC8+\n r1$coefficients[\"PC9\"]*PC9+\n r1$coefficients[\"PC10\"]*PC10) # variance explained\n R2logist2 = vp2 / (vp2+vare1) # explained var / total var\n t = matrix(0, 1, 6)\n t[1,1] = summary(r1)$coefficients[2,1]\n t[1,2] = summary(r1)$coefficients[2,2]\n t[1,3] = summary(r1)$coefficients[2,4]\n t[1,4] = R2logist1 - R2logist2\n print(t)\n}\n\n\n# function for logistic regression model with MS, PGS and covariates prints MS effect size, se, p-value, R2\nMSlogit_function = function(NTRdata, MScore) {\n dat = NTRdata\n MS = as.numeric(MScore)\n hand01=as.numeric(dat$hand01)\n age=as.numeric(dat$age)\n sex=as.numeric(dat$sex)\n PGS=as.numeric(dat$PGS)\n PC1 = as.numeric(dat$PC1)\n PC2 = as.numeric(dat$PC2)\n PC3 = as.numeric(dat$PC3)\n PC4 = as.numeric(dat$PC4)\n PC5 = as.numeric(dat$PC5)\n PC6 = as.numeric(dat$PC6)\n PC7 = as.numeric(dat$PC7)\n PC8 = as.numeric(dat$PC8)\n PC9 = as.numeric(dat$PC9)\n PC10 = as.numeric(dat$PC10)\n platform1=as.numeric(dat$platform1) # not used in models\n platform2=as.numeric(dat$platform2)\n platform3=as.numeric(dat$platform3)\n platform5=as.numeric(dat$platform5)\n platform6=as.numeric(dat$platform6)\n smoking = as.numeric(dat$smoking)\n BMI = as.numeric(dat$BMI)\n Neut_Perc = as.numeric(dat$Neut_Perc)\n Mono_Perc = as.numeric(dat$Mono_Perc)\n Eos_Perc = as.numeric(dat$Eos_Perc)\n Sample_Plate = as.factor(dat$Sample_Plate)\n Sample_Plate1 = ifelse(Sample_Plate== 1, 1, 0)\n Sample_Plate2 = ifelse(Sample_Plate== 2, 1, 0)\n Sample_Plate3 = ifelse(Sample_Plate== 3, 1, 0)\n Sample_Plate4 = ifelse(Sample_Plate== 4, 1, 0)\n Sample_Plate5 = ifelse(Sample_Plate== 5, 1, 0)\n Sample_Plate6 = ifelse(Sample_Plate== 6, 1, 0)\n Sample_Plate7 = ifelse(Sample_Plate== 7, 1, 0)\n Sample_Plate8 = ifelse(Sample_Plate== 8, 1, 0)\n Sample_Plate9 = ifelse(Sample_Plate== 9, 1, 0)\n Sample_Plate10 = ifelse(Sample_Plate== 10, 1, 0)\n Sample_Plate11 = ifelse(Sample_Plate== 11, 1, 0)\n Sample_Plate12 = ifelse(Sample_Plate== 12, 1, 0)\n Sample_Plate13 = ifelse(Sample_Plate== 13, 1, 0)\n Sample_Plate14 = ifelse(Sample_Plate== 14, 1, 0)\n Sample_Plate15 = ifelse(Sample_Plate== 15, 1, 0)\n Sample_Plate16 = ifelse(Sample_Plate== 16, 1, 0)\n Sample_Plate17 = ifelse(Sample_Plate== 17, 1, 0)\n Sample_Plate18 = ifelse(Sample_Plate== 18, 1, 0)\n Sample_Plate19 = ifelse(Sample_Plate== 19, 1, 0)\n Sample_Plate20 = ifelse(Sample_Plate== 20, 1, 0)\n Sample_Plate21 = ifelse(Sample_Plate== 21, 1, 0)\n Sample_Plate22 = ifelse(Sample_Plate== 22, 1, 0)\n Sample_Plate23 = ifelse(Sample_Plate== 23, 1, 0)\n Sample_Plate24 = ifelse(Sample_Plate== 24, 1, 0)\n Sample_Plate25 = ifelse(Sample_Plate== 25, 1, 0)\n Sample_Plate26 = ifelse(Sample_Plate== 26, 1, 0)\n Sample_Plate27 = ifelse(Sample_Plate== 27, 1, 0)\n Sample_Plate28 = ifelse(Sample_Plate== 28, 1, 0)\n Sample_Plate29 = ifelse(Sample_Plate== 29, 1, 0)\n Sample_Plate30 = ifelse(Sample_Plate== 30, 1, 0)\n Sample_Plate31 = ifelse(Sample_Plate== 31, 1, 0)\n Sample_Plate32 = ifelse(Sample_Plate== 32, 1, 0)\n Sample_Plate33 = ifelse(Sample_Plate== 33, 1, 0)\n Sample_Plate34 = ifelse(Sample_Plate== 34, 1, 0)\n # MODEL 1: handedness ~ MS+PGS + covariates\n vare1 = pi^2 / 3 # residual (homoskedastic) variance\n r1=glm(hand01~PGS+age+sex+\n platform2+platform3+platform5+platform6+PC1+PC2+PC3+PC4+PC5+PC6+PC7+PC8+PC9+PC10+\n smoking+BMI+Neut_Perc+Mono_Perc+Eos_Perc+Sample_Plate+MS,\n family=binomial(link='logit')) # logistic regression\n vp1=var( r1$coefficients[\"PGS\"]*PGS+\n r1$coefficients[\"age\"]*age+\n r1$coefficients[\"sex\"]*sex+\n r1$coefficients[\"platform2\"]*platform2+\n r1$coefficients[\"platform3\"]*platform3+\n r1$coefficients[\"platform5\"]*platform5+\n r1$coefficients[\"platform6\"]*platform6+\n r1$coefficients[\"PC1\"]*PC1+\n r1$coefficients[\"PC2\"]*PC2+\n r1$coefficients[\"PC3\"]*PC3+\n r1$coefficients[\"PC4\"]*PC4+\n r1$coefficients[\"PC5\"]*PC5+\n r1$coefficients[\"PC6\"]*PC6+\n r1$coefficients[\"PC7\"]*PC7+\n r1$coefficients[\"PC8\"]*PC8+\n r1$coefficients[\"PC9\"]*PC9+\n r1$coefficients[\"PC10\"]*PC10+\n r1$coefficients[\"smoking\"]*smoking+\n r1$coefficients[\"BMI\"]*BMI+\n r1$coefficients[\"Neut_Perc\"]*Neut_Perc+\n r1$coefficients[\"Mono_Perc\"]*Mono_Perc+\n r1$coefficients[\"Eos_Perc\"]*Eos_Perc+\n r1$coefficients[\"Sample_Plate2\"]*Sample_Plate2+\n r1$coefficients[\"Sample_Plate3\"]*Sample_Plate3+\n r1$coefficients[\"Sample_Plate4\"]*Sample_Plate4+\n r1$coefficients[\"Sample_Plate5\"]*Sample_Plate5+\n r1$coefficients[\"Sample_Plate6\"]*Sample_Plate6+\n r1$coefficients[\"Sample_Plate7\"]*Sample_Plate7+\n r1$coefficients[\"Sample_Plate8\"]*Sample_Plate8+\n r1$coefficients[\"Sample_Plate9\"]*Sample_Plate9+\n r1$coefficients[\"Sample_Plate10\"]*Sample_Plate10+\n r1$coefficients[\"Sample_Plate11\"]*Sample_Plate11+\n r1$coefficients[\"Sample_Plate12\"]*Sample_Plate12+\n r1$coefficients[\"Sample_Plate13\"]*Sample_Plate13+\n r1$coefficients[\"Sample_Plate14\"]*Sample_Plate14+\n r1$coefficients[\"Sample_Plate15\"]*Sample_Plate15+\n r1$coefficients[\"Sample_Plate16\"]*Sample_Plate16+\n r1$coefficients[\"Sample_Plate17\"]*Sample_Plate17+\n r1$coefficients[\"Sample_Plate18\"]*Sample_Plate18+\n r1$coefficients[\"Sample_Plate19\"]*Sample_Plate19+\n r1$coefficients[\"Sample_Plate20\"]*Sample_Plate20+\n r1$coefficients[\"Sample_Plate21\"]*Sample_Plate21+\n r1$coefficients[\"Sample_Plate22\"]*Sample_Plate22+\n r1$coefficients[\"Sample_Plate23\"]*Sample_Plate23+\n r1$coefficients[\"Sample_Plate24\"]*Sample_Plate24+\n r1$coefficients[\"Sample_Plate25\"]*Sample_Plate25+\n r1$coefficients[\"Sample_Plate26\"]*Sample_Plate26+\n r1$coefficients[\"Sample_Plate27\"]*Sample_Plate27+\n r1$coefficients[\"Sample_Plate28\"]*Sample_Plate28+\n r1$coefficients[\"Sample_Plate29\"]*Sample_Plate29+\n r1$coefficients[\"Sample_Plate30\"]*Sample_Plate30+\n r1$coefficients[\"Sample_Plate31\"]*Sample_Plate31+\n r1$coefficients[\"Sample_Plate32\"]*Sample_Plate32+\n r1$coefficients[\"Sample_Plate33\"]*Sample_Plate33+\n r1$coefficients[\"Sample_Plate34\"]*Sample_Plate34+\n r1$coefficients[\"MS\"]*MS) # variance explained\n R2logist1 = vp1 / (vp1+vare1) # explained var / total var\n # MODEL 2: handedness ~ PGS + covariates\n r2=glm(hand01~PGS5+age+sex+platform2+platform3+platform5+platform6+\n PC1+PC2+PC3+PC4+PC5+PC6+PC7+PC8+PC9+PC10+\n smoking+BMI+Neut_Perc+Mono_Perc+Eos_Perc+Sample_Plate,\n family=binomial(link='logit'))\n \n vp2=var( r2$coefficients[\"PGS\"]*PGS+\n r2$coefficients[\"age\"]*age+\n r2$coefficients[\"sex\"]*sex+\n r2$coefficients[\"platform2\"]*platform2+\n r2$coefficients[\"platform3\"]*platform3+\n r2$coefficients[\"platform5\"]*platform5+\n r2$coefficients[\"platform6\"]*platform6+\n r2$coefficients[\"PC1\"]*PC1+\n r2$coefficients[\"PC2\"]*PC2+\n r2$coefficients[\"PC3\"]*PC3+\n r2$coefficients[\"PC4\"]*PC4+\n r2$coefficients[\"PC5\"]*PC5+\n r2$coefficients[\"PC6\"]*PC6+\n r2$coefficients[\"PC7\"]*PC7+\n r2$coefficients[\"PC8\"]*PC8+\n r2$coefficients[\"PC9\"]*PC9+\n r2$coefficients[\"PC10\"]*PC10+\n r2$coefficients[\"smoking\"]*smoking+\n r2$coefficients[\"BMI\"]*BMI+\n r2$coefficients[\"Neut_Perc\"]*Neut_Perc+\n r2$coefficients[\"Mono_Perc\"]*Mono_Perc+\n r2$coefficients[\"Eos_Perc\"]*Eos_Perc+\n r2$coefficients[\"Sample_Plate2\"]*Sample_Plate2+\n r2$coefficients[\"Sample_Plate3\"]*Sample_Plate3+\n r2$coefficients[\"Sample_Plate4\"]*Sample_Plate4+\n r2$coefficients[\"Sample_Plate5\"]*Sample_Plate5+\n r2$coefficients[\"Sample_Plate6\"]*Sample_Plate6+\n r2$coefficients[\"Sample_Plate7\"]*Sample_Plate7+\n r2$coefficients[\"Sample_Plate8\"]*Sample_Plate8+\n r2$coefficients[\"Sample_Plate9\"]*Sample_Plate9+\n r2$coefficients[\"Sample_Plate10\"]*Sample_Plate10+\n r2$coefficients[\"Sample_Plate11\"]*Sample_Plate11+\n r2$coefficients[\"Sample_Plate12\"]*Sample_Plate12+\n r2$coefficients[\"Sample_Plate13\"]*Sample_Plate13+\n r2$coefficients[\"Sample_Plate14\"]*Sample_Plate14+\n r2$coefficients[\"Sample_Plate15\"]*Sample_Plate15+\n r2$coefficients[\"Sample_Plate16\"]*Sample_Plate16+\n r2$coefficients[\"Sample_Plate17\"]*Sample_Plate17+\n r2$coefficients[\"Sample_Plate18\"]*Sample_Plate18+\n r2$coefficients[\"Sample_Plate19\"]*Sample_Plate19+\n r2$coefficients[\"Sample_Plate20\"]*Sample_Plate20+\n r2$coefficients[\"Sample_Plate21\"]*Sample_Plate21+\n r2$coefficients[\"Sample_Plate22\"]*Sample_Plate22+\n r2$coefficients[\"Sample_Plate23\"]*Sample_Plate23+\n r2$coefficients[\"Sample_Plate24\"]*Sample_Plate24+\n r2$coefficients[\"Sample_Plate25\"]*Sample_Plate25+\n r2$coefficients[\"Sample_Plate26\"]*Sample_Plate26+\n r2$coefficients[\"Sample_Plate27\"]*Sample_Plate27+\n r2$coefficients[\"Sample_Plate28\"]*Sample_Plate28+\n r2$coefficients[\"Sample_Plate29\"]*Sample_Plate29+\n r2$coefficients[\"Sample_Plate30\"]*Sample_Plate30+\n r2$coefficients[\"Sample_Plate31\"]*Sample_Plate31+\n r2$coefficients[\"Sample_Plate32\"]*Sample_Plate32+\n r2$coefficients[\"Sample_Plate33\"]*Sample_Plate33+\n r2$coefficients[\"Sample_Plate34\"]*Sample_Plate34\n ) # variance explained\n R2logist2 = vp2 / (vp2+vare1) # explained var / total var\n t = matrix(0, 1, 6)\n t[1,1] = summary(r1)$coefficients[57,1]\n t[1,2] = summary(r1)$coefficients[57,2]\n t[1,3] = summary(r1)$coefficients[57,4]\n t[1,6] = R2logist1 - R2logist2\n print(t)\n}\n\n\n", "meta": {"hexsha": "0d3f7f7393e70cb91b8cc0eab889a8d5c7966e1b", "size": 19195, "ext": "r", "lang": "R", "max_stars_repo_path": "ntr/explained_variance_NTR.r", "max_stars_repo_name": "MRCIEU/handedness-ewas", "max_stars_repo_head_hexsha": "6cd486d0a796cdb4ff517aede424ac488905626e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ntr/explained_variance_NTR.r", "max_issues_repo_name": "MRCIEU/handedness-ewas", "max_issues_repo_head_hexsha": "6cd486d0a796cdb4ff517aede424ac488905626e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ntr/explained_variance_NTR.r", "max_forks_repo_name": "MRCIEU/handedness-ewas", "max_forks_repo_head_hexsha": "6cd486d0a796cdb4ff517aede424ac488905626e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 61.3258785942, "max_line_length": 122, "alphanum_fraction": 0.4791351915, "num_tokens": 4774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4115708055708515}}
{"text": "#'@title calcKristPwr\n#'\n#' @description Calculate instantaneous main engine power (kW) using the\n#' Kristensen 2016 updates of Harvald equations.\n#'\n#' @param totalInstalledPwr Total installed main engine power (vector of\n#' numericals, kW) (maximum\n#' continuous rated power)\n#' @param shipSpeed Ship actual speed (vector of numericals, m/s) (see\n#' \\code{\\link{calcSpeedUnitConversion}})\n#' @param actualDraft Actual draft (vector of numericals, m)\n#' @param maxDraft Maximum summer load line draft (vector of numericals, m)\n#' @param shipType Ship type (vector of strings, see \\code{\\link{calcShipType}}),\n#' determined by Stat 5 code: \\itemize{\n#' \\item\"container.ship\"\n#' \\item\"bulk.carrier\"\n#' \\item\"tanker\"\n#' \\item\"general.cargo\"\n#' \\item\"vehicle.carrier\"\n#' \\item\"reefer\"\n#' \\item\"ro.ro\"\n#' \\item\"passenger\"\n#' \\item\"tug\"\n#' \\item\"misc\"\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 maxDisplacement Maximum ship displacement (vector of numericals, m^3)\n#' @param Cb Maximum block coefficient (vector of numericals, dimensionless)\n#' (see \\code{\\link{calcCb}})\n#' @param nProp Number of propellers (vector of numericals, see\n#' \\code{\\link{calcPropNum}})\n#' @param dwt Ship maximum deadweight tonnage (vector of numericals, tonnage)\n#' @param serviceMargin A service margin to account for weather and sea effects:\n#' \\itemize{\\item At-sea operations = 15 (Default) \\item Coastal operations = 10}\n#' Can supply either a vector of numericals, a single number, or rely on the\n#' default\n#' @param shaftEff Shaft efficiency (dimensionless). Default = 0.98.\n#' Ratio of power delivered to the propeller and the brake power delivered by\n#' the engine. Can supply either a vector of numericals, a single number, or\n#' rely on the default\n#' @param relRotationEff Relative rotational efficiency (dimensionless).\n#' Default = 1. Accounts for effect of rotational flow of water around propeller.\n#' Can supply either a vector of numericals, a single number, or rely on the\n#' default\n#' @param seawaterTemp Sea water temperature. Default = 15 (degrees Celsius). Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#' @param seawaterDensity Sea water density. Default = 1.025 (g/cm^3). Can\n#' supply either a vector of numericals, a single number, or rely on the default\n#' @param pwrUpperBoundPercent Percent of total installed power at which\n#' required power is capped. Default = 1, which indicates required power cannot\n#' exceed \\code{totalInstalledPwr}. Can supply either a vector of numericals, a\n#' single number, or rely on the default\n#' @param pwrLowerBoundPercent Percent of total installed power to act as lower\n#' bound for required power. Default = 0.02, which indicates required power\n#' cannot go below 2\\% of \\code{totalInstalledPwr}. Can supply either a vector\n#' of numericals, a single number, or rely on the default\n#' @param CmEquationType Type of equation to estimate the midship section\n#' coefficient (see \\code{\\link{calcCm}}): \\itemize{\n#' \\item\"kristensen\"\n#' \\item\"benford\"\n#' \\item\"schneekluth\"}\n#' @param tankerBulkCarrierShipTypes Ship types specified in input\n#' \\code{shipTypes} to be modeled as tankers and bulk carriers.\n#' @param tugShipTypes Ship types specified in input \\code{shipTypes} to be\n#' modeled as tugs\n#' @param roroPaxShipTypes Ship types specified in input \\code{shipTypes} to be\n#' modeled as RORO and passenger ships\n#' @param gCargoShipTypes Ship types specified in input \\code{shipTypes} to be\n#' modeled as general cargo\n#' @param containerShipTypes Ship types specified in input \\code{shipTypes} to\n#' be modeled as container ships\n#'\n#' @details\n#' Primary method from Kristensen (2013). Estimation of some inputs use\n#' methodology from Rakke (2016).\n#'\n#' This method this requires ship types to be grouped. Use the\n#' \\code{tankerBulkCarrierShipTypes}, \\code{tugShipTypes}, \\code{roroPaxShipTypes},\n#' \\code{gCargoShipTypes}, \\code{containerShipTypes} grouping parameters to\n#' provide these ship type groupings. Any ship types not included in these groupings\n#' will be considered as miscellaneous vessels.\n#'\n#' Ship speed and actual draft are typically obtained from sources such as AIS\n#' messages or ship records.\n#'\n#' @return power (vector of numericals, kW)\n#'\n#' @references\n#'Kristensen, H. O. and Lutzen, M. 2013. \"Prediction of Resistance and Propulsion\n#'Power of Ships.\"\n#'\n#'Kristensen, H. O. 2016. \"Revision of statistical analysis and determination of\n#'regression formulas for main dimensions of container ships based on data from\n#'Clarkson.\"\n#'\n#'\\href{https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}{Kristensen, H. O.\n#'\"Ship-Desmo-Tool.\" https://gitlab.gbar.dtu.dk/oceanwave3d/Ship-Desmo}\n#'\n#'\\href{http://hdl.handle.net/11250/2410741}{Rakke, S. G. 2016. \"Ship Emissions\n#'Calculation from AIS.\" NTNU.}\n#'\n#'@seealso \\itemize{\n#'\\item \\code{\\link{calclwl}}\n#'\\item \\code{\\link{calcSpeedUnitConversion}}\n#'\\item \\code{\\link{calcCb}}\n#'\\item \\code{\\link{calcPropNum}}\n#'\\item \\code{\\link{calcCm}}\n#'\\item \\code{\\link{calcShipType}}\n#'\\item \\code{vignette(\"OverviewOfPowerModels\", package=\"ShipPowerModel\")}\n#'\\item \\code{vignette(\"Kristensen.Example\", package=\"ShipPowerModel\")}\n#'}\n#'\n#' @family Kristensen Calculations\n#'\n#' @examples\n#' calcKristPwr(\n#' totalInstalledPwr=9363,\n#' shipSpeed=10.8,\n#' actualDraft=12.5,\n#' maxDraft=13.6,\n#' shipType=\"bulk.carrier\",\n#' lwl=218,\n#' breadth=32.25,\n#' maxDisplacement=80097,\n#' Cb=0.8162717,\n#' nProp=1,\n#' dwt=70000,\n#' serviceMargin=15,\n#' shaftEff=0.98,\n#' relRotationEff=1,\n#' seawaterTemp=15,\n#' seawaterDensity=1.025,\n#' CmEquationType=\"kristensen\"\n#' )\n#'\n#' @export\n\ncalcKristPwr<-function(\n totalInstalledPwr,\n shipSpeed,\n actualDraft,\n maxDraft,\n shipType,\n lwl,\n breadth,\n maxDisplacement,\n Cb,\n nProp,\n dwt,\n serviceMargin=15,\n shaftEff=0.98,\n relRotationEff=1,\n seawaterTemp=15,\n seawaterDensity=1.025,\n pwrUpperBoundPercent=1,\n pwrLowerBoundPercent=0.02,\n CmEquationType=\"kristensen\",\n tankerBulkCarrierShipTypes=c(\"tanker\",\"chemical.tanker\",\"liquified.gas.tanker\",\"oil.tanker\",\"other.tanker\",\"bulk.carrier\"),\n tugShipTypes=c(\"service.tug\",\"tug\"),\n roroPaxShipTypes=c(\"passenger\",\"ferry.pax\",\"ferry.ro.pax\",\"cruise\",\"cruise.ed\",\"yacht\",\"ro.ro\"),\n gCargoShipTypes=c(\"general.cargo\"),\n containerShipTypes=c(\"container.ship\")\n){\n#=============================================================\n #Inputs\n Cbw<-calcCbw(Cb, actualDraft, maxDraft)\n actualDisplacement<-calcActualDisp(Cb,\n Cbw,\n actualDraft,\n maxDraft,\n maxDisplacement)\n\n Cm<-calcCm(shipType,Cbw,maxDraft,actualDraft,CmEquationType,tankerBulkCarrierShipTypes,tugShipTypes,roroPaxShipTypes)\n\n\n Cp<-calcCp(Cm, Cbw,shipType, bounds=\"none\", roroPaxContainerShipTypes=union(roroPaxShipTypes,containerShipTypes),gCargoShipTypes,tankerBulkCarrierShipTypes)\n\n propDiam<-calcPropDia(shipType, maxDraft,tankerBulkCarrierGCargoShipTypes=union(tankerBulkCarrierShipTypes,gCargoShipTypes),containerShipTypes)\n\n M<- calcShipM(actualDisplacement,lwl)\n\n froudeNum<- calcFroudeNum(shipSpeed,lwl)\n#=============================================================\n#Frictional Resistance\nCf<-calcCf(shipSpeed, lwl, seawaterTemp, seawaterDensity)\n#=============================================================\n#Wetted Surface Area\nwettedSA<-calcKristWettedSA(shipType,\n maxDisplacement,\n maxDraft,\n actualDraft,\n lwl,\n breadth,\n Cbw,\n seawaterDensity,\n tankerBulkCarrierGCargoShipTypes=union(tankerBulkCarrierShipTypes,gCargoShipTypes),\n containerShipTypes,\n paxTugShipTypes=union(roroPaxShipTypes, tugShipTypes))\n\n#==========================================\n#Incremental Resistance\nCa<-calcKristCa(shipType,actualDisplacement,\n tankerBulkCarrierGCargoShipTypes=union(tankerBulkCarrierShipTypes,gCargoShipTypes),\n containerShipTypes)\n#==========================================\n#Air Resistance\nCaa<-calcKristCaa(shipType,dwt,\n tankerBulkCarrierGCargoShipTypes=union(tankerBulkCarrierShipTypes,gCargoShipTypes),\n containerShipTypes)\n#==========================================\n#Residual Resistance\nCr<-calcKristCr(shipType,\n M,\n froudeNum,\n actualDraft,\n breadth,\n Cp,\n tankerBulkCarrierGCargoShipTypes=union(tankerBulkCarrierShipTypes,gCargoShipTypes))\n\n#=============================================================\n#Thrust Deduction Factor\nt<-calcKristThrustFactor(\n shipType,\n breadth,\n lwl,\n Cbw,\n propDiam,\n M,\n nProp,\n tankerBulkCarrierShipTypes)\n#=============================================================\n#Wake Fraction\n#*(1-t)/(1-w)= hull efficiency\nw<-calcKristWakeFrac(shipType,\n breadth,\n lwl,\n Cbw,\n propDiam,\n M,\n nProp,\n tankerBulkCarrierShipTypes)\n#==========================================================\n#Total Resistance\nR<-calcKristTotalRes(wettedSA,\n Cf,\n Cr,\n Ca,\n Caa,\n seawaterDensity,\n shipSpeed,\n serviceMargin)\n#==========================================================\n# Open Water Efficiency\nno<-calcOpenWaterEff(R,\n t,\n nProp,\n w,\n propDiam,\n shipSpeed,\n seawaterDensity)\n#=============================================================\npower<-calcResistanceShipPwr(R,shipSpeed, (1-t)/(1-w), no,totalInstalledPwr, shaftEff,relRotationEff, pwrUpperBoundPercent, pwrLowerBoundPercent)\n\nreturn(power)\n}\n", "meta": {"hexsha": "88cdaffbe039cc8b076f16a9264765f25517aee7", "size": 10389, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipPowerModel/R/calcKristPwr.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/calcKristPwr.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/calcKristPwr.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 38.7649253731, "max_line_length": 158, "alphanum_fraction": 0.6310520743, "num_tokens": 2574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.41123142781723154}}
{"text": "########################### BayesKin ###########################\n## Code for a comparison of Bayesian models for inverse kinematic problems\n## with Maximum likelihood estimation\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: May 2020\n################################################################\n\n########################### library.r #########################\n## Contains source functions for BayesKin package - modified for performing\n## sensitivity to measurement noise.\n################################################################\n##### Preliminaries\nlibrary(coda)\nlibrary(numDeriv)\nlibrary(rjags)\n\n# set number of parallel cores\noptions(mc.cores=4)\n\n########################### Section A #########################\n## Miscellaneous helper functions\n################################################################\nrt_ls <- function(n, df, mu, a){\n # Generates a random sample from the location scale student-t distribution with mean mu, degrees of freedom\n # df and scale a\n\n return(rt(n,df)*a + mu)\n}\n\nmod_180 = function(angles){\n # Rescales an angle on the (-inf, inf) scale to the interval [-180, 180)\n temp = sapply(angles, function(ang){\n if(abs(ang)<=180){\n return(ang)\n }else if(ang >180){\n remainder = ang-180\n return(-180 + remainder)\n }else if (ang< -180){\n remainder = ang + 180\n return(180 + remainder)\n }\n })\n return(temp)\n}\n########################### Section B #########################\n## Links, posture and observations\n################################################################\n\ngen_link = function(seg.length,\n plate.center,\n marker.plate.dim = c(0.1, 0.05)){\n # Creates a rigid link of length seg.length with a marker plate at plate.center\n # with dimensions plate.placement.length*seg.length and markers at each corner\n # of the marker plate.\n plate.loc = c(plate.center,0)\n\n\n markers = cbind(c(plate.loc[1]-marker.plate.dim[1]/2, marker.plate.dim[2]/2),\n c(plate.loc[1]+marker.plate.dim[1]/2, marker.plate.dim[2]/2),\n c(plate.loc[1]+marker.plate.dim[1]/2, -marker.plate.dim[2]/2),\n c(plate.loc[1]-marker.plate.dim[1]/2, -marker.plate.dim[2]/2))\n\n link = list(length = seg.length,\n x = markers)\n return(link)\n\n}\n\ngen_posture = function(links,\n r,\n theta,\n degrees = TRUE){\n # Applies rigid body transformations translation r and rotation by theta to a\n # collection of links. Note that links must be specified in order (link 1 -\n # link 3) and the length of theta should be the same as the number of links\n\n if(degrees){\n theta = theta * pi/180\n }\n\n nlinks = length(links)\n\n # Generate rotation matrix for eac link\n Gam = vector('list', nlinks)\n for(i in 1:nlinks){\n Gam[[i]] = matrix(c(cos(theta[i]), sin(theta[i]),\n -sin(theta[i]), cos(theta[i])), 2, 2)\n }\n\n # Compute the locations of joint centers for each link in the kinematic chain\n J = vector('list', nlinks+1)\n J[[1]] = matrix(r, 2, 1)\n for(i in 2:(nlinks+1)){\n J[[i]] = J[[i-1]] + Gam[[i-1]] %*% c(links[[i-1]]$length, 0)\n }\n\n # Compute actual position of markers alpha in the global coordinate system\n alpha = vector(mode = 'list', length = nlinks)\n for(i in 1:nlinks){\n nmarkers = ncol(links[[i]]$x)\n alpha[[i]] = matrix(NA, 2, nmarkers)\n for(j in 1:nmarkers){\n x_ij = links[[i]]$x[,j]\n alpha[[i]][,j] = J[[i]] + Gam[[i]]%*%x_ij\n }\n }\n\n # Return posture object (list with origin r, joint position J and expected marker position alpha)\n return(list(r = r, J = J, alpha = alpha))\n}\n\ngen_obs = function(posture, sigma){\n # Generates an observation of a given posture subject to random 0 mean gaussain\n # noise with standard deviation sigma\n nlinks = length(posture$alpha)\n\n y = vector(mode = 'list', length = nlinks)\n for(i in 1:nlinks){\n nmarkers = ncol(links[[i]]$x)\n y[[i]] = matrix(NA, ncol = nmarkers, nrow = 2)\n for(j in 1:nmarkers){\n y[[i]][1, j] = rnorm(1, mean = posture$alpha[[i]][1, j], sd= sigma)\n y[[i]][2, j] = rnorm(1, mean = posture$alpha[[i]][2, j], sd= sigma)\n }\n }\n return(y)\n}\n\nplot_system= function(posture, y=NA, ...){\n # Plots the Kinematic chain and observed markers y\n plot(NULL, NULL,\n xlim = c(0, 1), ylim = c(-1, 0.1),\n xlab = 'x', ylab = 'y')\n points(t(do.call(cbind,posture$J)), type = \"o\", pch = 20,...) # mu_tmp\n orange = rgb(255/255, 140/255, 0, 0.5)\n blue = rgb(0, 0, 1, 0.5)\n points(t(do.call(cbind,posture$alpha)), pch = 20, col = orange)\n if(!is.na(y)){\n points(t(do.call(cbind,y)), pch = 20, col = blue)\n }\n}\n\n########################### Section C #########################\n## Maximum likelihood/Least Squares solutions.\n################################################################\n\ncost = function(params, y, links){\n # The cost function (equation ... in paper) given a vector\n # params = vector of parameters (rx, ry, theta1, theta2, theta3 ), observations\n # y and known positions of markers within the LCS of each link links.\n nlinks = length(links)\n r.hat = params[1:2]\n theta.hat = params[3:(nlinks+2)]\n\n obs.hat = gen_posture(links, r = r.hat, theta = theta.hat)\n y.hat = obs.hat$alpha\n\n cost = 0\n for(i in 1:nlinks){\n nmarkers = ncol(y.hat[[i]])\n for(j in 1:nmarkers){\n diff = y.hat[[i]][,j] - y[[i]][,j]\n cost = cost+ (sqrt(sum(diff*diff)))\n }\n }\n return(cost)\n}\n\n\ncostgrad_analytical = function(x, y, links){\n # Generates the analytical gradient of the cost function. Originally generated\n # via MATLAB and the symbolic toolbox.\n # x is parameter vector (r1, r2, theta1, theta2, theta3)\n # y[[nlinks]] of observations\n # links contains the known LCS information of each link\n\n nlinks = length(links)\n r1 = x[1]\n r2 = x[2]\n x111 = links[[1]]$x[1,1]\n x112 = links[[1]]$x[2,1]\n x121 = links[[1]]$x[1,2]\n x122 = links[[1]]$x[2,2]\n x131 = links[[1]]$x[1,3]\n x132 = links[[1]]$x[2,3]\n x141 = links[[1]]$x[1,4]\n x142 = links[[1]]$x[2,4]\n\n y111 = y[[1]][1,1]\n y112 = y[[1]][2,1]\n y121 = y[[1]][1,2]\n y122 = y[[1]][2,2]\n y131 = y[[1]][1,3]\n y132 = y[[1]][2,3]\n y141 = y[[1]][1,4]\n y142 = y[[1]][2,4]\n\n\n if(nlinks ==1){\n theta1 = x[3]\n gradient = rep(NA, 3)\n for(i in 1:length(x)){\n gradtxtfile = sprintf(\"./AnalyticalCostGrad/SingleLink/CostGradientChar%.0f.txt\", i)\n gradtxt = read.table(file = gradtxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(gradtxt)[1] != 1) & (dim(gradtxt)[2] !=1)){stop(\"Error in reading gradient text file!\")}\n gradient[i] = eval(parse(text = gradtxt[1,1]))\n }\n }else if(nlinks ==2){\n theta1 = x[3]\n theta2 = x[4]\n\n L1 = links[[1]]$length\n\n x211 = links[[2]]$x[1,1]\n x212 = links[[2]]$x[2,1]\n x221 = links[[2]]$x[1,2]\n x222 = links[[2]]$x[2,2]\n x231 = links[[2]]$x[1,3]\n x232 = links[[2]]$x[2,3]\n x241 = links[[2]]$x[1,4]\n x242 = links[[2]]$x[2,4]\n\n y211 = y[[2]][1,1]\n y212 = y[[2]][2,1]\n y221 = y[[2]][1,2]\n y222 = y[[2]][2,2]\n y231 = y[[2]][1,3]\n y232 = y[[2]][2,3]\n y241 = y[[2]][1,4]\n y242 = y[[2]][2,4]\n\n gradient = rep(NA, 4)\n for(i in 1:length(x)){\n gradtxtfile = sprintf(\"./AnalyticalCostGrad/DoubleLink/CostGradientChar%.0f.txt\", i)\n gradtxt = read.table(file = gradtxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(gradtxt)[1] != 1) & (dim(gradtxt)[2] !=1)){stop(\"Error in reading gradient text file!\")}\n gradient[i] = eval(parse(text = gradtxt[1,1]))\n }\n\n }else if(nlinks ==3){\n theta1 = x[3]\n theta2 = x[4]\n theta3 = x[5]\n\n L1 = links[[1]]$length\n L2 = links[[2]]$length\n\n x211 = links[[2]]$x[1,1]\n x212 = links[[2]]$x[2,1]\n x221 = links[[2]]$x[1,2]\n x222 = links[[2]]$x[2,2]\n x231 = links[[2]]$x[1,3]\n x232 = links[[2]]$x[2,3]\n x241 = links[[2]]$x[1,4]\n x242 = links[[2]]$x[2,4]\n\n y211 = y[[2]][1,1]\n y212 = y[[2]][2,1]\n y221 = y[[2]][1,2]\n y222 = y[[2]][2,2]\n y231 = y[[2]][1,3]\n y232 = y[[2]][2,3]\n y241 = y[[2]][1,4]\n y242 = y[[2]][2,4]\n\n x311 = links[[3]]$x[1,1]\n x312 = links[[3]]$x[2,1]\n x321 = links[[3]]$x[1,2]\n x322 = links[[3]]$x[2,2]\n x331 = links[[3]]$x[1,3]\n x332 = links[[3]]$x[2,3]\n x341 = links[[3]]$x[1,4]\n x342 = links[[3]]$x[2,4]\n\n y311 = y[[3]][1,1]\n y312 = y[[3]][2,1]\n y321 = y[[3]][1,2]\n y322 = y[[3]][2,2]\n y331 = y[[3]][1,3]\n y332 = y[[3]][2,3]\n y341 = y[[3]][1,4]\n y342 = y[[3]][2,4]\n gradient = rep(NA, 5)\n for(i in 1:length(x)){\n gradtxtfile = sprintf(\"./AnalyticalCostGrad/TripleLink/CostGradientChar%.0f.txt\", i)\n gradtxt = read.table(file = gradtxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(gradtxt)[1] != 1) & (dim(gradtxt)[2] !=1)){stop(\"Error in reading gradient text file!\")}\n gradient[i] = eval(parse(text = gradtxt[1,1]))\n }\n }\n return(gradient)\n}\n\nhess_analytical = function(x, y, links){\n # Generates the analytical hessian of the cost function. Originally generated\n # via MATLAB and the symbolic toolbox.\n # x is parameter vector (r1, r2, theta1, theta2, theta3)\n # y[[nlinks]] of observations\n # links contains the known LCS information of each link\n\n nlinks = length(links)\n r1 = x[1]\n r2 = x[2]\n lsigma = x[length(x)]\n\n x111 = links[[1]]$x[1,1]\n x112 = links[[1]]$x[2,1]\n x121 = links[[1]]$x[1,2]\n x122 = links[[1]]$x[2,2]\n x131 = links[[1]]$x[1,3]\n x132 = links[[1]]$x[2,3]\n x141 = links[[1]]$x[1,4]\n x142 = links[[1]]$x[2,4]\n\n y111 = y[[1]][1,1]\n y112 = y[[1]][2,1]\n y121 = y[[1]][1,2]\n y122 = y[[1]][2,2]\n y131 = y[[1]][1,3]\n y132 = y[[1]][2,3]\n y141 = y[[1]][1,4]\n y142 = y[[1]][2,4]\n\n\n if(nlinks ==1){\n theta1 = x[3]\n hess = matrix(NA, nrow = length(x), ncol = length(x))\n for(i in 1:length(x)){\n for(j in 1:length(x)){\n hesstxtfile = sprintf(\"./AnalyticalHessian/SingleLink/hesschar%.0f_%.0f.txt\", i,j)\n hesstxt = read.table(file = hesstxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(hesstxt)[1] != 1) & (dim(hesstxt)[2] !=1)){stop(\"Error in reading hessian text file!\")}\n hess[i,j] = eval(parse(text = hesstxt[1,1]))\n }\n }\n\n }else if(nlinks ==2){\n theta1 = x[3]\n theta2 = x[4]\n L1 = links[[1]]$length\n\n x211 = links[[2]]$x[1,1]\n x212 = links[[2]]$x[2,1]\n x221 = links[[2]]$x[1,2]\n x222 = links[[2]]$x[2,2]\n x231 = links[[2]]$x[1,3]\n x232 = links[[2]]$x[2,3]\n x241 = links[[2]]$x[1,4]\n x242 = links[[2]]$x[2,4]\n\n y211 = y[[2]][1,1]\n y212 = y[[2]][2,1]\n y221 = y[[2]][1,2]\n y222 = y[[2]][2,2]\n y231 = y[[2]][1,3]\n y232 = y[[2]][2,3]\n y241 = y[[2]][1,4]\n y242 = y[[2]][2,4]\n\n hess = matrix(NA, nrow = length(x), ncol = length(x))\n for(i in 1:length(x)){\n for(j in 1:length(x)){\n hesstxtfile = sprintf(\"./AnalyticalHessian/DoubleLink/hesschar%.0f_%.0f.txt\", i,j)\n hesstxt = read.table(file = hesstxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(hesstxt)[1] != 1) & (dim(hesstxt)[2] !=1)){stop(\"Error in reading hessian text file!\")}\n hess[i,j] = eval(parse(text = hesstxt[1,1]))\n }\n }\n }else if(nlinks ==3){\n theta1 = x[3]\n theta2 = x[4]\n theta3 = x[5]\n\n L1 = links[[1]]$length\n L2 = links[[2]]$length\n\n x211 = links[[2]]$x[1,1]\n x212 = links[[2]]$x[2,1]\n x221 = links[[2]]$x[1,2]\n x222 = links[[2]]$x[2,2]\n x231 = links[[2]]$x[1,3]\n x232 = links[[2]]$x[2,3]\n x241 = links[[2]]$x[1,4]\n x242 = links[[2]]$x[2,4]\n\n y211 = y[[2]][1,1]\n y212 = y[[2]][2,1]\n y221 = y[[2]][1,2]\n y222 = y[[2]][2,2]\n y231 = y[[2]][1,3]\n y232 = y[[2]][2,3]\n y241 = y[[2]][1,4]\n y242 = y[[2]][2,4]\n\n x311 = links[[3]]$x[1,1]\n x312 = links[[3]]$x[2,1]\n x321 = links[[3]]$x[1,2]\n x322 = links[[3]]$x[2,2]\n x331 = links[[3]]$x[1,3]\n x332 = links[[3]]$x[2,3]\n x341 = links[[3]]$x[1,4]\n x342 = links[[3]]$x[2,4]\n\n y311 = y[[3]][1,1]\n y312 = y[[3]][2,1]\n y321 = y[[3]][1,2]\n y322 = y[[3]][2,2]\n y331 = y[[3]][1,3]\n y332 = y[[3]][2,3]\n y341 = y[[3]][1,4]\n y342 = y[[3]][2,4]\n\n hess = matrix(NA, nrow = length(x), ncol = length(x))\n for(i in 1:length(x)){\n for(j in 1:length(x)){\n hesstxtfile = sprintf(\"./AnalyticalHessian/TripleLink/hesschar%.0f_%.0f.txt\", i,j)\n hesstxt = read.table(file = hesstxtfile, sep=',' , stringsAsFactors = FALSE)\n if((dim(hesstxt)[1] != 1) & (dim(hesstxt)[2] !=1)){stop(\"Error in reading hessian text file!\")}\n hess[i,j] = eval(parse(text = hesstxt[1,1]))\n }\n }\n }\n return(hess)\n}\n\n\nLS_soln = function(y, links,\n init_type = 'random',\n inits = NA){\n # Computes the least squares solution given observations y.\n # y = observaitons\n # links = known LCS geometry\n # init_type = type of initial values to specify (random = randomly generated\n # true_vals = true values of the simulation or speicified = custom\n # specification of initial values.)\n # inits = specified initis if true_vals or specified is used for init_type\n nlinks = length(links)\n\n if(init_type =='random'){\n inits.r = c(runif(1, -0.1, 0.1),\n runif(1, -0.1, 0.1))\n inits.theta = runif(nlinks, -180, 180)\n print(paste('Computing LS solution with initial Values set to the RANDOM VALUES:', paste(c(inits.r, inits.theta), collapse = ', ' )))\n }else if(init_type == 'true_vals'){\n if (is.na(inits)){stop(\"If init_type is not random then inits must be specified\")}\n print('Computing LS solution with initial Values set to the TRUE VALUES')\n inits.r = inits[1:2]\n inits.theta = inits[3:(nlinks +2)]\n }else if (init_type == \"specified\"){\n if (is.na(inits)){stop(\"If init_type is not random then inits must be specified\")}\n print('Computing LS solution with initial Values set to the SPECIFIED VALUES')\n inits.r = inits[1:2]\n inits.theta = inits[3:(nlinks +2)]\n }\n inits = c(inits.r, inits.theta)\n\n # run optimisation using BFGS method.\n t1 = Sys.time()\n temp = optim(par=inits,fn = cost, gr = costgrad_analytical,\n y = y, links = links,\n method = \"BFGS\", control = list(trace=FALSE, maxit = 10000, reltol = 1e-20))\n t2 = Sys.time()\n return_list = list(r.hat = temp$par[1:2],\n theta.hat = temp$par[3:(nlinks+2)],\n value = temp$val, time = as.numeric(t2-t1))\n\n # generate residuals and use for corresponding estimate of sigma_hat\n nmarkers = 0\n obs.hat = gen_posture(links, return_list$r.hat, return_list$theta.hat)\n residual_sum = 0\n for(i in 1:nlinks){\n nmarkers = ncol(y[[i]])\n for(j in 1:nmarkers){\n residual_sum = residual_sum +\n (y[[i]][1, j]- obs.hat$alpha[[i]][1,j])^2 + # xresidual\n (y[[i]][2, j]- obs.hat$alpha[[i]][2, j])^2 # yresidual\n nmarkers = nmarkers +1\n }\n\n }\n p = length(return_list$r.hat) + length(return_list$theta.hat)\n return_list$sigma.hat = sqrt(residual_sum / (2*nmarkers))\n\n # Generate CI estimate via hessian matrix\n hess = hess_analytical(x = c(return_list$r.hat, return_list$theta.hat, log(return_list$sigma.hat)),\n links = links,\n y = y)\n fisher_info = solve(-hess)\n prop_sigma = diag(diag(sqrt(diag(fisher_info))))\n intervals = matrix(NA, nrow=nlinks+3, ncol =2)\n intervals[,1] = c(return_list$r.hat, return_list$theta.hat, return_list$sigma.hat) - 1.96*prop_sigma\n intervals[,2] = c(return_list$r.hat, return_list$theta.hat, return_list$sigma.hat) + 1.96*prop_sigma\n intervals[nrow(intervals), ] = exp(intervals[nrow(intervals),])\n return_list$intervals = intervals\n\n return(return_list)\n}\n\n########################### Section D #########################\n## Compute Bayesian solution.\n################################################################\n\nBayes_soln = function(y, links, mdlfile,\n true_vals,\n init_type = 'random',\n ls_est = NA,\n ...){\n # Applies the Bayesian model to observations y and known data links.\n # y = observaitons\n # links = known LCS geometry\n # mdlfile = specified jags model file\n # true_vals = true values of the specified simulation.\n # init_type = type of initial values to specify (random = randomly generated\n # true_vals = true values of the simulation or speicified = custom\n # specification of initial values.)\n # inits = specified initis if true_vals is specified.\n\n\n nlinks = length(links)\n nmarkers = sapply(links, function(x){ncol(x$x)})\n M = 2 # dimension\n seg_lengths = sapply(links, function(x){x$length})\n x = lapply(links, function(x){x$x})\n\n # initilise x and y data for jags models\n xjags = yjags = array(NA, dim = c(nlinks, max(nmarkers), 2))\n for(i in 1:nlinks){\n xjags[i,,] = t(x[[i]])\n yjags[i,,] = t(y[[i]])\n }\n\n # input data for jags model\n jags_input = list(nlinks = nlinks,\n nmarkers = nmarkers,\n ndim = 2,\n x = xjags,\n y = yjags,\n leng = cbind(seg_lengths, rep(0,nlinks)))\n\n # Specify initial values\n if(grepl('p4|p5', mdlfile)){\n # LS centered priors require the ls solution\n jags_input$ls_r = ls_est[1:2]\n jags_input$ls_theta = ls_est[3:(2+nlinks)]\n jags_input$ls_sigma = ls_est[length(ls_est)]\n }\n\n if(init_type =='true_vals'){\n r_true = true_vals[1:2]\n theta_true = true_vals[3:(2+nlinks)]\n sigma_true = true_vals[length(ls_est)]\n if(grepl('p3', mdlfile)){\n # if weakly informative prior specify inits in terms of hip, knee and ankle angles.\n print('Computing Bayes P3 solution with initial Values set to the TRUE VALUES')\n inits = list(hip = theta_true[1],\n knee = theta_true[2] - theta_true[1],\n ankle = -90 -theta_true[2] + theta_true[3],\n r = r_true,\n sigma_mm = sigma_true*1000)\n }else if(grepl('p2', mdlfile)){\n print('Computing Bayes P2 solution with initial Values set to the TRUE VALUES')\n inits = list(thetar = theta_true * pi/180,\n r = r_true,\n tau = 1/sigma_true/sigma_true)\n jags_input$true_vals = true_vals\n }else{\n print('Computing Bayes solution with initial Values set to the TRUE VALUES')\n inits = list(thetar = theta_true * pi/180,\n r = r_true,\n sigma = sigma_true)\n\n }\n }\n else if(init_type == 'random'){\n if(grepl('p3', mdlfile)){\n # if weakly informative prior specify inits in terms of hip, knee and ankle angles.\n print('Computing Bayes P3 solution with initial Values set to the RANDOM VALUES')\n r_random = rt_ls(2, df = 5, mu = 0, a = 1)\n hip_random = rt_ls(1, df = 5, mu=-45, a = 15)\n knee_random = rt_ls(1, df=5, mu=30, a=6)\n ankle_random = rt_ls(1, df=5, mu=0, a=7)\n sigma_mm_random = rgamma(1, shape = 1.2, scale=0.1)\n inits = list(hip = hip_random,\n knee = knee_random,\n ankle = ankle_random,\n r = r_random,\n sigma_mm = sigma_mm_random)\n }else if(grepl('p2', mdlfile)){\n print('Computing Bayes P2 solution with initial Values set to the RANDOM VALUES')\n r_random = c(rnorm(1, true_vals[1], 0.001), dnorm(1, true_vals[2], 0.001))\n theta_random = runif(nlinks, -180,180)\n tau_random = rnorm(1, 1/(true_vals[nlinks+3]*true_vals[nlinks+3]), 1)\n inits = list(thetar = theta_random * pi/180,\n r = r_random,\n tau = tau_random)\n jags_input$true_vals = true_vals\n }else if (grepl('p4', mdlfile)){\n print('Computing Bayes P4 solution with initial Values set to the RANDOM VALUES')\n r_random = c(runif(1, jags_input$ls_r[1]-0.1,jags_input$ls_r[1] + 0.1), runif(1, jags_input$ls_r[2]-0.1, jags_input$ls_r[2] + 0.1))\n theta_random = rep(0, nlinks)\n for(nl in 1:nlinks){\n theta_random[nl] = runif(1, jags_input$ls_theta[nl]-180, jags_input$ls_theta[nl]+180)\n }\n inits = list(theta = theta_random,\n r = r_random,\n sigma = runif(1, 0.1*jags_input$ls_sigma, 10*jags_input$ls_sigma))\n }else if (grepl('p5', mdlfile)){\n print('Computing Bayes P5 solution with initial Values set to the RANDOM VALUES')\n r_random = c(rnorm(1, jags_input$ls_r[1], 0.005), rnorm(1, jags_input$ls_r[2], 0.005))\n theta_random = rep(0, nlinks)\n for(nl in 1:nlinks){\n theta_random[nl] = rnorm(1, jags_input$ls_theta[nl], 1)\n }\n inits = list(theta = theta_random,\n r = r_random,\n sigma = abs(rnorm(1, jags_input$ls_sigma, 0.002)))\n }else{\n print('Computing Bayes P1 solution with initial Values set to the RANDOM VALUES')\n theta_random = runif(nlinks, -180,180)\n r_random = runif(2, -0.1, 0.1)\n inits = list(thetar = theta_random * pi/180,\n r = r_random,\n sigma = runif(1, 0.1*true_vals[nlinks+3], 10*true_vals[nlinks+3]))\n }\n }else if(init_type == 'ls_est'){\n if(sum(is.na(ls_est))>0){stop(\"If using 'ls_est' as initials please supply LS estimates\")}\n if(grepl('p3', mdlfile)){\n # if wealky informative prior specify inits in terms of hip, knee and ankle angles.\n print('Computing Bayes P3 solution with initial Values set to the LS VALUES')\n hip_random = rt_ls(1, df = 5, mu=-45, a = 15)\n knee_random = rt_ls(1, df=5, mu=30, a=6)\n ankle_random = rt_ls(1, df=5, mu=0, a=7)\n\n inits = list(hip = hip_random,\n knee = knee_random,\n ankle = ankle_random,\n r = c(ls_est[1], ls_est[2]),\n sigma_mm = tail(ls_est,1)*1000)\n }else if(grepl('p2', mdlfile)){\n print('Computing Bayes P2 solution with initial Values set to the LS VALUES')\n jags_input$true_vals = true_vals\n inits = list(thetar = c(ls_est[3:(nlinks+2)]) * pi/180,\n r = c(ls_est[1], ls_est[2]),\n tau = 1/tail(ls_est,1)/tail(ls_est,1))\n }else if(grepl('p4|p5', mdlfile)){\n print('Computing Bayes P4 or P5 solution with initial Values set to the LS VALUES')\n inits = list(theta = c(ls_est[3:(nlinks+2)]),\n r = c(ls_est[1], ls_est[2]),\n sigma = tail(ls_est,1))\n }else if (grepl('p1_2', mdlfile)){\n print('Computing Bayes P1_2 solution with initial Values set to the LS VALUES')\n jags_input$true_vals = true_vals\n inits = list(thetar = c(ls_est[3:(nlinks+2)]) * pi/180,\n r = c(ls_est[1], ls_est[2]),\n tau = 1/tail(ls_est,1)/tail(ls_est,1))\n }\n else{\n print('Computing Bayes P1 solution with initial Values set to the LS VALUES')\n inits = list(thetar = c(ls_est[3:(nlinks+2)]) * pi/180,\n r = c(ls_est[1], ls_est[2]),\n sigma = tail(ls_est,1))\n }\n }\n\n # Compile jags model\n t1 = Sys.time()\n m1 = jags.model(file = mdlfile,\n data = jags_input,\n inits = inits,\n n.chains = 4,\n n.adapt = 10000\n )\n\n # Sample from model\n out1 = coda.samples(model = m1,\n variable.names = c(\"theta\", \"r\", \"sigma\"),\n n.iter = 50000,\n thin = 5)\n t2 = Sys.time()\n\n\n return(list(fit = out1, time = as.numeric(t2-t1)))\n}\n", "meta": {"hexsha": "80bd69748c989dea1ecdcc6f25dff05aa6c78c88", "size": 23890, "ext": "r", "lang": "R", "max_stars_repo_path": "src/SupplementD/library.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SupplementD/library.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SupplementD/library.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7743813683, "max_line_length": 139, "alphanum_fraction": 0.5469233989, "num_tokens": 7688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4104048290274244}}
{"text": "# data_in is a comma separted list of data points\n# groups_in is a comma separted list of group indeces for the points in data_in\n\nMGRAST_do_stats <<- function (data_file,\n groups_file,\n data_type = c(\"raw\", \"normalized\"),\n sig_test = c(\n \"t-test-paired\", \"Wilcoxon-paired\",\n \"t-test-un-paired\", \"Mann-Whitney_un-paired-Wilcoxon\",\n \"ANOVA-one-way\", \"Kruskal-Wallis\"\n ),\n file_out = \"my_stats\")\n \n{\n\n \n\n ### SUB TO WRITE OUTPUT\n write_log <<- function (sig_test, data_type){\n write(paste(\"test is : \", sig_test), file = \"do_stats.log\")\n write(paste(\"data-type : \", data_type), file = \"do_stats.log\", append = TRUE)\n write(paste(\"num-samples : \", num_samples), file = \"do_stats.log\", append = TRUE)\n write(paste(\"num-groups : \", num_groups), file = \"do_stats.log\", append = TRUE)\n }\n \n\n \n ### SUB TO PREP DATA FOR TWO GROUP ANALYSES\n prep_two_groups <<- function(row_data){\n group_1 = levels(row_data[,2])[1]\n group_2 = levels(row_data[,2])[2]\n group_1_size = 0\n group_2_size = 0\n for (i in 1:as.matrix(dim(row_data)[1])){\n if(identical(as.character(row_data[i,2]), as.character(group_1))){\n group_1_size = group_1_size + 1\n }\n if(identical(as.character(row_data[i,2]), as.character(group_2))){\n group_2_size = group_2_size + 1\n }\n }\n group_1_data <<- matrix(,group_1_size,1)\n group_2_data <<- matrix(,group_2_size,1)\n group_1_index = 0\n group_2_index = 0\n for (i in 1:as.matrix(dim(row_data)[1])){\n if (identical(as.character(row_data[i,2]), as.character(group_1))){\n group_1_index = group_1_index + 1\n group_1_data[group_1_index,1] <<- row_data[i,1]\n }\n if (identical(as.character(row_data[i,2]), as.character(group_2))){\n group_2_index = group_2_index + 1\n group_2_data[group_2_index,1] <<- row_data[i,1]\n }\n }\n }\n\n\n \n ### ### MAIN SCRIPT STARTS HERE ### ###\n \n ### TEST TO MAKE SURE ALL OF THE ARGUMENTS ARE SUPPLIED\n #if()\n\n # LOAD NECESSARY PACKAGES\n library(stats)\n library(nlme)\n\n ### IMPORT AND FORMAT THE DATA ###\n all_data = data.frame(read.table(data_file, row.names=1, header=TRUE, sep=\"\\t\", comment.char=\"\", quote=\"\"))\n groups = data.matrix(scan(file = groups_file, what = \"character\", sep = \"\\t\", quiet=TRUE))\n num_samples = dim(all_data)[2]\n num_rows = dim(all_data)[1]\n num_groups <<- nlevels(as.factor(groups[,1])) # <----- Rats\n group_names <<- matrix(levels(as.factor(groups[,1])))\n\n # CREATE OUTPUT TABLE AND GIVE IT APPROPRIATE HEADERS\n output_table <<- data.frame(matrix(0, num_rows, num_groups+2))\n row.names(output_table) <<- row.names(all_data)\n names(output_table) <<- c(paste(\"group_(\", levels(as.factor(groups[,1])),\")_stddev\",sep =\"\"),\n paste(sig_test, \"_stat\",sep=\"\"),\n paste(sig_test, \"_p_value\",sep=\"\")\n )\n \n ### PERFORM THE ANALYSES\n for (my_row in 1:num_rows){\n \n numeric_row_data <<- as.numeric(all_data[my_row,])\n factor_row_groups <<- as.character(groups[,1]) # is ok here\n row_data <<- cbind(numeric_row_data, factor_row_groups)\n row_data <<- data.frame(row_data)\n row_data[,1] <<- numeric_row_data # some values get changed if you don;t reload them here\n row_data[,2] <<- as.factor(row_data[,2])\n names(row_data)<<-c(\"values\",\"ind\")\n \n for (group in 1:num_groups){\n \n group_ind <<- levels(row_data[,2])[group]\n \n ### CALCULATE THE STANDARD DEVIATION FOR EACH GROUP \n num_samples_in_group <<- 0\n for(sample in 1:num_samples){\n if(identical(((matrix(row_data[sample,2]))[1,1]), group_ind)){\n if (num_samples_in_group==0){\n group_sample_counts <<- row_data[sample,1]\n num_samples_in_group <<- num_samples_in_group + 1\n }else{\n group_sample_counts <<- c(group_sample_counts, row_data[sample,1])\n num_samples_in_group <<- num_samples_in_group + 1\n }\n }\n }\n output_table[my_row, group] <<- as.real(sd(group_sample_counts))\n }\n\n if(identical(sig_test, \"t-test-un-paired\")){ # <-- new\n prep_two_groups(row_data)\n ttest_unpaired_output = t.test(group_1_data, group_2_data)\n t_unpaired_stat_value = as.real(ttest_unpaired_output[\"statistic\"])\n t_unpaired_p_value = as.real(ttest_unpaired_output[\"p.value\"])\n output_table[my_row, num_groups+1] <<- t_unpaired_stat_value\n output_table[my_row, num_groups+2] <<- t_unpaired_p_value \n }\n \n else if(identical(sig_test, \"t-test-paired\")){ # <-- new\n prep_two_groups(row_data)\n ttest_paired_output = t.test(group_1_data, group_2_data, paired = TRUE)\n t_paired_stat_value = as.real(ttest_paired_output[\"statistic\"])\n t_paired_p_value = as.real(ttest_paired_output[\"p.value\"])\n \n output_table[my_row, num_groups+1] <<- t_paired_stat_value\n output_table[my_row, num_groups+2] <<- t_paired_p_value\n }\n\n else if (identical(sig_test, \"ANOVA-one-way\")){\n anova_output = anova(aov(values~ind, data=row_data)) \n anova_F = anova_output[\"F value\"]\n F_value = as.real(anova_F[1,1]) \n anova_p = anova_output[\"Pr(>F)\"]\n anova_p_value = as.real(anova_p[1,1])\n output_table[my_row, num_groups+1] <<- F_value \n output_table[my_row, num_groups+2] <<- anova_p_value\n }\n \n else if (identical(sig_test, \"Mann-Whitney_un-paired-Wilcoxon\")){\n prep_two_groups(row_data)\n MWhitney_output = wilcox.test(group_1_data, group_2_data, exact=TRUE) # x -> s in text\n MWhitney_stat_value = as.real(MWhitney_output[\"statistic\"])\n MWhitney_p_value = as.real(MWhitney_output[\"p.value\"])\n output_table[my_row, num_groups+1] <<- MWhitney_stat_value\n output_table[my_row, num_groups+2] <<- MWhitney_p_value\n }\n\n else if (identical(sig_test, \"Wilcoxon-paired\")){ # <-- new\n prep_two_groups(row_data)\n wilcox_output = wilcox.test(group_1_data, group_2_data, exact=TRUE, paired=TRUE) # x -> s in text\n wilcox_stat_value = as.real(wilcox_output[\"statistic\"])\n wilcox_p_value = as.real(wilcox_output[\"p.value\"])\n output_table[my_row, num_groups+1] <<- wilcox_stat_value\n output_table[my_row, num_groups+2] <<- wilcox_p_value\n }\n \n else if (identical(sig_test, \"Kruskal-Wallis\")){\n kruskal_output = kruskal.test(row_data[,1], row_data[,2])\n kruskal_K_value = as.real(kruskal_output[\"statistic\"])\n kruskal_p_value = as.real(kruskal_output[\"p.value\"])\n output_table[my_row, num_groups+1] <<- kruskal_K_value\n output_table[my_row, num_groups+2] <<- kruskal_p_value\n }\n \n else{\n stop(\"no significance test was chosen\")\n }\n \n write.table(output_table, file = file_out, sep = \"\\t\", col.names=NA, row.names = TRUE)\n \n }\n \n}\n", "meta": {"hexsha": "d6f95bf83a0ee9828e2a706a659ed0f65edcaa5f", "size": 7065, "ext": "r", "lang": "R", "max_stars_repo_path": "src/MGRAST/r/do_stats_11-22-10.r", "max_stars_repo_name": "wilke/MG-RAST", "max_stars_repo_head_hexsha": "508e4736bafcf2a45d3f67d87dd196890f2da7a0", "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": "src/MGRAST/r/do_stats_11-22-10.r", "max_issues_repo_name": "wilke/MG-RAST", "max_issues_repo_head_hexsha": "508e4736bafcf2a45d3f67d87dd196890f2da7a0", "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": "src/MGRAST/r/do_stats_11-22-10.r", "max_forks_repo_name": "wilke/MG-RAST", "max_forks_repo_head_hexsha": "508e4736bafcf2a45d3f67d87dd196890f2da7a0", "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": 39.25, "max_line_length": 109, "alphanum_fraction": 0.6217975938, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.41034611817713074}}
{"text": "#' @title Regression analysis of prevalence\n#' @param table_file (optional) file to save parameter table to\n#' @return a list of two plots (effect size and posterior predicitons) and a\n#' table of effect size estimates\n#' @importFrom dplyr select left_join mutate filter group_by ungroup inner_join bind_rows recode_factor summarise arrange if_else\n#' @importFrom tidyr pivot_longer pivot_wider separate\n#' @importFrom stats as.formula median quantile\n#' @importFrom brms brm negbinomial\n#' @importFrom tidybayes spread_draws median_qi\n#' @importFrom forcats fct_rev\n#' @importFrom ggplot2 ggplot aes xlab ylab xlim geom_hline coord_flip theme_minimal geom_point geom_ribbon theme scale_color_brewer scale_y_log10\n#' @importFrom ggdist geom_pointinterval\n#' @importFrom rstantools posterior_predict\n#' @importFrom tidyselect starts_with matches\n#' @importFrom tibble as_tibble\n#' @importFrom kableExtra kable save_kable\n#' @importFrom tools file_ext\n#' @export\nregression <- function(table_file = NULL) {\n unemp <- covariates$unemp\n age <- covariates$age\n pop_dens <- covariates$pop_dens\n roma <- covariates$roma\n\n ## all covariates and outcome\n prev <- ms.tst %>%\n dplyr::select(county, region, pop, dplyr::starts_with(\"attendance_\"),\n dplyr::starts_with(\"positive_\"), pilot) %>%\n dplyr::left_join(unemp, by = \"county\") %>%\n dplyr::left_join(age, by = \"county\") %>%\n dplyr::left_join(pop_dens, by = \"county\") %>%\n dplyr::mutate(xcounty = sub(\" [IV]+$\", \"\", county)) %>%\n dplyr::left_join(roma %>% select(xcounty = county, proportion_roma),\n by = \"xcounty\") %>%\n simplify_names() %>%\n dplyr::left_join(Rt.county %>%\n rename(simple_name = county), by = \"simple_name\") %>%\n dplyr::select(-xcounty, -simple_name) %>%\n dplyr::mutate(unemp_rate = unemployed / active) %>%\n dplyr::select(county, region, pop, tidyselect::matches(\"^attendance_[123]\"),\n tidyselect::matches(\"^positive_[123]\"), mean_age,\n pop_dens, unemp_rate, proportion_roma, R)\n\n ## extract pilot variables\n pilot <- prev %>%\n dplyr::filter(!is.na(attendance_1)) %>%\n dplyr::mutate(round_attendance_prec = attendance_1 / pop,\n round_prev_prec = positive_1 / attendance_1,\n round_R_prec = R) %>%\n dplyr::select(county, dplyr::starts_with(\"round_\")) %>%\n tidyr::pivot_longer(-county) %>%\n dplyr::group_by(name) %>%\n dplyr::mutate(value = (value - mean(value)) / sd(value)) %>%\n dplyr::ungroup() %>%\n tidyr::pivot_wider() %>%\n dplyr::mutate(`0` = 0, `1` = 1, `2` = 1) %>%\n tidyr::pivot_longer(tidyselect::matches(\"^[012]\"),\n names_to = \"round\", values_to = \"multiplier\") %>%\n dplyr::mutate(round = as.integer(round)) %>%\n tidyr::pivot_longer(c(-county, -round, -multiplier)) %>%\n dplyr::mutate(value = value * multiplier) %>%\n tidyr::pivot_wider() %>%\n dplyr::select(-multiplier)\n\n ## extract round 1 variables\n round1 <- prev %>%\n dplyr::filter(is.na(attendance_1)) %>%\n dplyr::mutate(round_attendance_prec = attendance_2 / pop,\n round_prev_prec = positive_2 / attendance_2,\n round_R_prec = R) %>%\n dplyr::select(county, tidyselect::starts_with(\"round_\")) %>%\n tidyr::pivot_longer(-county) %>%\n dplyr::group_by(name) %>%\n dplyr::mutate(value = (value - mean(value)) / sd(value)) %>%\n dplyr::ungroup() %>%\n pivot_wider() %>%\n dplyr::mutate(`0` = 0, `1` = 1) %>%\n tidyr::pivot_longer(tidyselect::matches(\"^[01]\"),\n names_to = \"round\", values_to = \"multiplier\") %>%\n dplyr::mutate(round = as.integer(round)) %>%\n tidyr::pivot_longer(c(-county, -round, -multiplier)) %>%\n dplyr::mutate(value = value * multiplier) %>%\n tidyr::pivot_wider() %>%\n dplyr::select(-multiplier)\n\n prev_long <- prev %>%\n tidyr::pivot_longer(tidyselect::matches(\"^(positive|attendance)_[123]$\")) %>%\n tidyr::separate(name, c(\"name\", \"round\"), sep = \"_\") %>%\n dplyr::select(-R) %>%\n dplyr::filter(!is.na(value)) %>%\n tidyr::pivot_wider() %>%\n tidyr::pivot_longer(c(-county, -region, -positive, -attendance, -round)) %>%\n dplyr::group_by(name) %>%\n dplyr::mutate(value = (value - mean(value, na.rm = TRUE)) /\n sd(value, na.rm = TRUE)) %>%\n dplyr::ungroup() %>%\n tidyr::pivot_wider() %>%\n dplyr::group_by(county) %>%\n dplyr::mutate(round = as.integer(round),\n round = dplyr::if_else(rep(any(round == 1), n()),\n round - 1L, round - 2L)) %>%\n dplyr::ungroup()\n\n pilot_long <- prev_long %>%\n dplyr::inner_join(pilot, by = c(\"county\", \"round\"))\n round1_long <- prev_long %>%\n dplyr::inner_join(round1, by = c(\"county\", \"round\"))\n\n prev_long <- pilot_long %>%\n dplyr::bind_rows(round1_long)\n\n model <-\n stats::as.formula(positive ~\n 1 + (1 | county) + round + mean_age + pop_dens +\n unemp_rate + proportion_roma + round_attendance_prec +\n round_prev_prec + round_R_prec +\n offset(log(attendance)))\n\n ## Fit model --------------------------------------------------------------\n fit <- brms::brm(model, data = prev_long, family = brms::negbinomial(),\n iter = 3000)\n\n effects <- fit %>%\n tidybayes::spread_draws(`^b_.*`, regex = TRUE) %>%\n tidybayes::median_qi(.width = c(.95, .50)) %>%\n tidyr::pivot_longer(dplyr::starts_with(\"b_\")) %>%\n dplyr::mutate(name =\n dplyr::if_else(grepl(\"\\\\.\", name), name,\n paste(name, .point, sep = \".\"))) %>%\n tidyr::separate(name, c(\"variable\", \"name\"), sep = \"\\\\.\") %>%\n tidyr::pivot_wider() %>%\n dplyr::mutate(affects = dplyr::if_else(variable %in% c(\"b_Intercept\",\n \"b_mean_age\",\n \"b_pop_dens\",\n \"b_unemp_rate\",\n \"b_proportion_roma\"),\n \"Prevalence\", \"Reduction\"),\n variable =\n dplyr::recode_factor(\n variable,\n b_Intercept = \"Intercept\",\n b_mean_age = \"Mean age\",\n b_pop_dens = \"Population density\",\n b_unemp_rate = \"Unemployment rate\",\n b_proportion_roma = \"Size of Marginalised Roma Community\",\n b_round = \"Round\",\n b_round_attendance_prec = \"Previous attendance\",\n b_round_prev_prec = \"Previous prevalence\",\n b_round_R_prec = \"Reproduction number\"\n ),\n variable = forcats::fct_rev(variable))\n\n ep <-\n ggplot2::ggplot(effects %>%\n dplyr::filter(variable != \"Intercept\") %>%\n dplyr::mutate_at(vars(median, lower, upper), exp),\n ggplot2::aes(x = variable, y = median,\n ymin = lower, ymax = upper,\n colour = affects)) +\n ggdist::geom_pointinterval() +\n ggplot2::xlab(\"\") + ggplot2::ylab(\"Posterior ratio\") +\n ggplot2::geom_hline(yintercept = 1, linetype = \"dashed\") +\n ggplot2::ylim(c(0.25, 1.75)) +\n ggplot2::coord_flip() +\n ggplot2::theme_minimal() +\n ggplot2::scale_color_brewer(\"\", palette = \"Set1\") +\n ggplot2::theme(legend.position = \"none\")\n\n ## Posterior predictive plot -----------------------------------------------\n yhat <- rstantools::posterior_predict(fit)\n colnames(yhat) <- paste(prev_long$county, prev_long$round, sep = \"_\")\n\n plotpp <- tibble::as_tibble(yhat) %>%\n tidyr::pivot_longer(everything(), names_to = \"county_round\") %>%\n tidyr::separate(county_round, c(\"county\", \"round\"), sep = \"_\") %>%\n dplyr::mutate(round = as.integer(round)) %>%\n dplyr::group_by(county, round) %>%\n dplyr::summarise(median = stats::median(value),\n lower = stats::quantile(value, 0.25),\n upper = stats::quantile(value, 0.75),\n lowest = stats::quantile(value, 0.05),\n uppest = stats::quantile(value, 0.95),\n .groups = \"drop\") %>%\n dplyr::ungroup() %>%\n dplyr::left_join(prev_long, by = c(\"county\", \"round\")) %>%\n dplyr::arrange(median) %>%\n dplyr::mutate(id = seq_len(n())) %>%\n dplyr::group_by(county) %>%\n dplyr::mutate(round = dplyr::if_else(rep(any(round == 2), n()),\n round + 1, round + 2)) %>%\n dplyr::ungroup() %>%\n dplyr::mutate(round = dplyr::if_else(round == 1, \"Pilot\",\n paste(\"Round\", round - 1)))\n\n pp <- ggplot2::ggplot(plotpp, aes(x = id, y = median, color = round)) +\n ggplot2::geom_point(aes(y = positive), size = 1) +\n ggplot2::geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.3,\n color = NA) +\n ggplot2::geom_ribbon(aes(ymin = lowest, ymax = uppest), alpha = 0.15,\n color = NA) +\n ggplot2::xlab(\"County\") +\n ggplot2::ylab(\"Estimated # positive\") +\n ggplot2::theme_minimal() +\n ggplot2::theme(axis.text.x = element_blank(),\n axis.ticks.x = element_blank()) +\n ggplot2::scale_color_brewer(\"\", palette = \"Dark2\") +\n ggplot2::scale_y_log10()\n\n if (!is.null(table_file)) {\n align <- c(\"l|\", \"r\", \"r\", \"r\")\n if (file_ext(table_file) == \"pdf\") {\n format <- \"latex\"\n } else if (file_ext(table_file) == \"html\") {\n format <- \"html\"\n align <- sub(\"\\\\|\", \"\", align)\n }\n col.names <- c(\"Variable\", \"Lower 95%\", \"Median\", \"Upper 95%\")\n k <- kableExtra::kable(effects %>%\n dplyr::filter(.width == 0.95) %>%\n dplyr::select(variable, lower, median, upper) %>%\n dplyr::mutate_if(is.numeric, exp) %>%\n dplyr::mutate_if(is.numeric, signif, digits = 2) %>%\n dplyr::mutate_if(is.numeric, as.character),\n format = format,\n col.names = col.names,\n align = align,\n booktabs = FALSE)\n\n kableExtra::save_kable(k, table_file)\n }\n\n\n return(list(plots = list(effects = ep,\n predictions = pp),\n table = effects,\n covariates = prev))\n}\n", "meta": {"hexsha": "d9ec8fd27eda9b3978ae986d8cd7ff75a737982b", "size": 10756, "ext": "r", "lang": "R", "max_stars_repo_path": "R/regression.r", "max_stars_repo_name": "kevinvzandvoort/covid19.slovakia.mass.testing", "max_stars_repo_head_hexsha": "03b60024ff2bf17c0061c9e5e2a7877b27ca99de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-11-30T09:48:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T09:48:06.000Z", "max_issues_repo_path": "R/regression.r", "max_issues_repo_name": "kevinvzandvoort/covid19.slovakia.mass.testing", "max_issues_repo_head_hexsha": "03b60024ff2bf17c0061c9e5e2a7877b27ca99de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-11-30T11:13:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-29T11:42:39.000Z", "max_forks_repo_path": "R/regression.r", "max_forks_repo_name": "kevinvzandvoort/covid19.slovakia.mass.testing", "max_forks_repo_head_hexsha": "03b60024ff2bf17c0061c9e5e2a7877b27ca99de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-11-30T10:56:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T09:21:53.000Z", "avg_line_length": 45.1932773109, "max_line_length": 146, "alphanum_fraction": 0.536444775, "num_tokens": 2898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41027501801213734}}
{"text": "\n\n shannon.diversity = function(x, base=2, getid=TRUE) {\n rs = rowSums(x, na.rm=T)\n good = which(rs>0)\n if (length(good)==0) {\n if (getid) {\n out = rep(NA,4)\n } else {\n out = rep(NA,3)\n }\n }\n\n if (length(good)>0) {\n rs = rs[good]\n x = x[ good , ]\n id = rownames( x )\n pr = x / rs\n\n if (is.array(x) ) {\n shannon = - rowSums( pr * log( pr, base=base ), na.rm=T )\n } else {\n shannon = - sum( pr * log( pr, base=base ), na.rm=T )\n }\n\n Hmax = - log( rs, base=base )\n evenness = shannon / Hmax\n\n if (getid) {\n out = data.frame( id=id, shannon=shannon, evenness=evenness, Hmax=Hmax )\n } else {\n out = data.frame( shannon=shannon, evenness=evenness, Hmax=Hmax )\n }\n }\n\n return(out)\n }\n", "meta": {"hexsha": "32b21e64f4cb463dd9846e6dea5fa01192c8244b", "size": 817, "ext": "r", "lang": "R", "max_stars_repo_path": "R/shannon.diversity.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/shannon.diversity.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/shannon.diversity.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": 21.5, "max_line_length": 80, "alphanum_fraction": 0.4761321909, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40997793859819387}}
{"text": "#!/usr/bin/env Rscript\n\nargs = commandArgs(trailingOnly = TRUE)\n\nif (length(args) != 1) {\n stop(\"Provide Motor Type (cim, 775) as Command Line Argument.\")\n}\n\nif (args[1] == \"cim\") {\n rpm = 2670\n} else if (args[1] == \"775\") {\n rpm = 9370\n} else {\n rpm = 1\n}\n\npeakFile = paste(args[1], \"-peak-power.csv\", sep=\"\")\nstallFile = paste(args[1], \"-stall-6v.csv\", sep=\"\")\n\npeak <- read.csv(peakFile, header = TRUE)\nstall <- read.csv(stallFile, header = TRUE)\n\nx11()\n\npeak$Torque = (9.5488 * peak$Power) / rpm\n\nplot(peak$Time,\n peak$Torque,\n col=\"red\",\n type=\"l\",\n ylim=c(0, 1.3),\n xlim=c(0, 300),\n xlab=\"Time (s)\",\n ylab=\"Torque (Nm)\",\n main=\"Torque Output - Slipping vs Stalling\")\npoints(stall$Time,\n stall$Torque,\n col=\"blue\",\n type=\"l\")\nlegend(x = \"bottomright\",\n legend = c(\"Slipping (Peak Power)\", \"Stalling (6 Volts)\"),\n col = c(\"red\", \"blue\"),\n lty = 1,\n bty = \"n\",\n cex = 0.8)\n\ndev.print(png, \"torque.png\", width = 1000, height = 1000)\n\nx11()\n\nplot(peak$Time,\n peak$Current,\n col=\"red\",\n type=\"l\",\n ylim=c(0,70),\n xlim=c(0,300),\n ylab=\"Current (A)\",\n xlab=\"Time(s)\",\n main=\"Current Draw, Slipping vs Stalling\")\npoints(stall$Time,\n stall$Amps,\n col=\"blue\",\n type=\"l\")\n\ndev.print(png, \"current.png\", width = 1000, height = 1000)\n\nx11()\n\npeak$TorquePerAmp = 1000 * peak$Torque / peak$Current\nstall$TorquePerAmp = 1000 * stall$Torque / stall$Amps\n\nplot(peak$Time,\n peak$TorquePerAmp,\n col=\"red\",\n type=\"l\",\n ylim=c(0,30),\n ylab=\"Torque per Amp (mNm/A)\",\n xlab=\"Time (s)\",\n main=\"Torque per Amp, Slipping vs Stalling\")\npoints(stall$Time,\n stall$TorquePerAmp,\n col=\"blue\",\n type=\"l\")\n\ndev.print(png, \"torque-per-amp.png\", width = 1000, height = 1000)\n\nSys.sleep(1000)\n\n# Do both draw the same current? We could plot this, or also Torque per Amp.\n", "meta": {"hexsha": "a6855277a3e974f07f54d0f9f925c7949728816e", "size": 1927, "ext": "r", "lang": "R", "max_stars_repo_path": "graph.r", "max_stars_repo_name": "karagenit/slip-stall", "max_stars_repo_head_hexsha": "2face266783298b31b32ee01a27ebb611415521b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph.r", "max_issues_repo_name": "karagenit/slip-stall", "max_issues_repo_head_hexsha": "2face266783298b31b32ee01a27ebb611415521b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph.r", "max_forks_repo_name": "karagenit/slip-stall", "max_forks_repo_head_hexsha": "2face266783298b31b32ee01a27ebb611415521b", "max_forks_repo_licenses": ["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.4111111111, "max_line_length": 76, "alphanum_fraction": 0.5744680851, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.6187804267137442, "lm_q1q2_score": 0.40958491131651587}}
{"text": "# -----------------------------------------------------------------------------\n# logs\n# -----------------------------------------------------------------------------\n\n#' Logarithms and Exponentials\n#' \n#' exp/log functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' @param base\n#' The logarithm base.\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrunif(10)\n#' log(x)\n#' }\n#' \n#' @useDynLib float R_exp_spm R_expm1_spm R_log_spm R_log10_spm R_log2_spm\n#' @name log\n#' @rdname log\nNULL\n\n\n\nexp_float32 = function(x)\n{\n ret = .Call(R_exp_spm, DATA(x))\n float32(ret)\n}\n\nexpm1_float32 = function(x)\n{\n ret = .Call(R_expm1_spm, DATA(x))\n float32(ret)\n}\n\nlog_float32 = function(x, base=exp(1))\n{\n if (is.float(base))\n base = dbl(base[1])\n \n ret = .Call(R_log_spm, DATA(x), as.double(base))\n float32(ret)\n}\n\nlog10_float32 = function(x)\n{\n ret = .Call(R_log10_spm, DATA(x))\n float32(ret)\n}\n\nlog2_float32 = function(x)\n{\n ret = .Call(R_log2_spm, DATA(x))\n float32(ret)\n}\n\n\n\n#' @rdname log\n#' @export\nsetMethod(\"exp\", signature(x=\"float32\"), exp_float32)\n\n#' @rdname log\n#' @export\nsetMethod(\"expm1\", signature(x=\"float32\"), expm1_float32)\n\n#' @rdname log\n#' @export\nsetMethod(\"log\", signature(x=\"float32\"), log_float32)\n\n#' @rdname log\n#' @export\nsetMethod(\"log10\", signature(x=\"float32\"), log10_float32)\n\n#' @rdname log\n#' @export\nsetMethod(\"log2\", signature(x=\"float32\"), log2_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# trig\n# -----------------------------------------------------------------------------\n\n#' Trigonometric functions\n#' \n#' Basic trig functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrunif(10)\n#' sin(x)\n#' }\n#' \n#' @useDynLib float R_sin_spm R_cos_spm R_tan_spm R_asin_spm R_acos_spm R_atan_spm \n#' @name trig\n#' @rdname trig\nNULL\n\n\n\nsin_float32 = function(x)\n{\n ret = .Call(R_sin_spm, DATA(x))\n float32(ret)\n}\n\ncos_float32 = function(x)\n{\n ret = .Call(R_cos_spm, DATA(x))\n float32(ret)\n}\n\ntan_float32 = function(x)\n{\n ret = .Call(R_tan_spm, DATA(x))\n float32(ret)\n}\n\nasin_float32 = function(x)\n{\n ret = .Call(R_asin_spm, DATA(x))\n float32(ret)\n}\n\nacos_float32 = function(x)\n{\n ret = .Call(R_acos_spm, DATA(x))\n float32(ret)\n}\n\natan_float32 = function(x)\n{\n ret = .Call(R_atan_spm, DATA(x))\n float32(ret)\n}\n\n\n\n#' @rdname trig\n#' @export\nsetMethod(\"sin\", signature(x=\"float32\"), sin_float32)\n\n#' @rdname trig\n#' @export\nsetMethod(\"cos\", signature(x=\"float32\"), cos_float32)\n\n#' @rdname trig\n#' @export\nsetMethod(\"tan\", signature(x=\"float32\"), tan_float32)\n\n#' @rdname trig\n#' @export\nsetMethod(\"asin\", signature(x=\"float32\"), asin_float32)\n\n#' @rdname trig\n#' @export\nsetMethod(\"acos\", signature(x=\"float32\"), acos_float32)\n\n#' @rdname trig\n#' @export\nsetMethod(\"atan\", signature(x=\"float32\"), atan_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# hyperbolic\n# -----------------------------------------------------------------------------\n\n#' Hyperbolic functions\n#' \n#' Hyperbolic functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrunif(10)\n#' sinh(x)\n#' }\n#' \n#' @useDynLib float R_sinh_spm R_cosh_spm R_tanh_spm R_asinh_spm R_acosh_spm R_atanh_spm\n#' @name hyperbolic\n#' @rdname hyperbolic\nNULL\n\n\n\nsinh_float32 = function(x)\n{\n ret = .Call(R_sinh_spm, DATA(x))\n float32(ret)\n}\n\ncosh_float32 = function(x)\n{\n ret = .Call(R_cosh_spm, DATA(x))\n float32(ret)\n}\n\ntanh_float32 = function(x)\n{\n ret = .Call(R_tanh_spm, DATA(x))\n float32(ret)\n}\n\nasinh_float32 = function(x)\n{\n ret = .Call(R_asinh_spm, DATA(x))\n float32(ret)\n}\n\nacosh_float32 = function(x)\n{\n ret = .Call(R_acosh_spm, DATA(x))\n float32(ret)\n}\n\natanh_float32 = function(x)\n{\n ret = .Call(R_atanh_spm, DATA(x))\n float32(ret)\n}\n\n\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"sinh\", signature(x=\"float32\"), sinh_float32)\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"cosh\", signature(x=\"float32\"), cosh_float32)\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"tanh\", signature(x=\"float32\"), tanh_float32)\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"asinh\", signature(x=\"float32\"), asinh_float32)\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"acosh\", signature(x=\"float32\"), acosh_float32)\n\n#' @rdname hyperbolic\n#' @export\nsetMethod(\"atanh\", signature(x=\"float32\"), atanh_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# misc\n# -----------------------------------------------------------------------------\n\n#' Miscellaneous mathematical functions\n#' \n#' Miscellaneous mathematical functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrunif(10)\n#' sqrt(x)\n#' }\n#' \n#' @useDynLib float R_abs_spm R_sqrt_spm\n#' @name miscmath\n#' @rdname miscmath\nNULL\n\n\n\nabs_float32 = function(x)\n{\n ret = .Call(R_abs_spm, DATA(x))\n float32(ret)\n}\n\nsqrt_float32 = function(x)\n{\n ret = .Call(R_sqrt_spm, DATA(x))\n float32(ret)\n}\n\n\n\n#' @rdname miscmath\n#' @export\nsetMethod(\"abs\", signature(x=\"float32\"), abs_float32)\n\n#' @rdname miscmath\n#' @export\nsetMethod(\"sqrt\", signature(x=\"float32\"), sqrt_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# special\n# -----------------------------------------------------------------------------\n\n#' Special mathematical functions\n#' \n#' Special mathematical functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrunif(10)\n#' lgamma(x)\n#' }\n#' \n#' @useDynLib float R_gamma_spm R_lgamma_spm\n#' @name specialmath\n#' @rdname specialmath\nNULL\n\n\n\ngamma_float32 = function(x)\n{\n ret = .Call(R_gamma_spm, DATA(x))\n float32(ret)\n}\n\nlgamma_float32 = function(x)\n{\n ret = .Call(R_lgamma_spm, DATA(x))\n float32(ret)\n}\n\n\n\n#' @rdname specialmath\n#' @export\nsetMethod(\"gamma\", signature(x=\"float32\"), gamma_float32)\n\n#' @rdname specialmath\n#' @export\nsetMethod(\"lgamma\", signature(x=\"float32\"), lgamma_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# mathis\n# -----------------------------------------------------------------------------\n\n#' Finite, infinite, and NaNs\n#' \n#' Finite, infinite, and NaNs.\n#' \n#' @param x\n#' A float vector/matrix.\n#' \n#' @return\n#' An integer vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' \\dontrun{\n#' library(float)\n#' \n#' x = flrnorm(10)\n#' is.nan(sqrt(x))\n#' }\n#' \n#' @useDynLib float R_isfinite_spm R_isinfinite_spm R_isnan_spm\n#' @name mathis\n#' @rdname mathis\nNULL\n\n\n\nis.finite_float32 = function(x)\n{\n .Call(R_isfinite_spm, DATA(x))\n}\n\nis.infinite_float32 = function(x)\n{\n .Call(R_isinfinite_spm, DATA(x))\n}\n\nis.nan_float32 = function(x)\n{\n .Call(R_isnan_spm, DATA(x))\n}\n\n\n\n#' @rdname mathis\n#' @export\nsetMethod(\"is.finite\", signature(x=\"float32\"), is.finite_float32)\n\n#' @rdname mathis\n#' @export\nsetMethod(\"is.infinite\", signature(x=\"float32\"), is.infinite_float32)\n\n#' @rdname mathis\n#' @export\nsetMethod(\"is.nan\", signature(x=\"float32\"), is.nan_float32)\n\n\n\n# -----------------------------------------------------------------------------\n# rounding\n# -----------------------------------------------------------------------------\n\n#' Round\n#' \n#' Rounding functions.\n#' \n#' @param x\n#' A float vector/matrix.\n#' @param digits\n#' The number of digits to use in rounding.\n#' @param ...\n#' ignored\n#' \n#' @return\n#' A float vector/matrix of the same dimensions as the input.\n#' \n#' @examples\n#' library(float)\n#' \n#' x = flrnorm(10)\n#' floor(x)\n#' \n#' @useDynLib float R_ceiling_spm R_floor_spm R_trunc_spm R_round_spm\n#' @name round\n#' @rdname round\nNULL\n\n\n\nceiling_float32 = function(x)\n{\n ret = .Call(R_ceiling_spm, DATA(x))\n float32(ret)\n}\n\nfloor_float32 = function(x)\n{\n ret = .Call(R_floor_spm, DATA(x))\n float32(ret)\n}\n\ntrunc_float32 = function(x, ...)\n{\n ret = .Call(R_trunc_spm, DATA(x))\n float32(ret)\n}\n\nround_float32 = function(x, digits=0)\n{\n ret = .Call(R_round_spm, DATA(x), as.double(digits))\n float32(ret)\n}\n\n\n\n#' @rdname round\n#' @export\nsetMethod(\"ceiling\", signature(x=\"float32\"), ceiling_float32)\n\n#' @rdname round\n#' @export\nsetMethod(\"floor\", signature(x=\"float32\"), floor_float32)\n\n#' @rdname round\n#' @export\nsetMethod(\"trunc\", signature(x=\"float32\"), trunc_float32)\n\n#' @rdname round\n#' @export\nsetMethod(\"round\", signature(x=\"float32\"), round_float32)\n", "meta": {"hexsha": "24d96e02bed52b02ebd7b066220507636811ae0c", "size": 8847, "ext": "r", "lang": "R", "max_stars_repo_path": "R/math.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/math.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/math.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": 17.2456140351, "max_line_length": 88, "alphanum_fraction": 0.5795184808, "num_tokens": 2512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.40925069723229107}}
{"text": "# 5- Clump Finding Problem\n\ngenome <- \"AAAATAAAA\"\n\nk_mer <- 3\nL <- 4\nt <- 2\nall_sub_genome <- substring(genome, first = 1:(nchar(genome)-L+1) ,\n last = L:nchar(genome))\nall_occuerance <- data.frame()\nfor (i_sub in all_sub_genome){\nsub_dna <- substring(i_sub, first = 1:(nchar(i_sub)-k_mer + 1) ,\n last = k_mer:nchar(i_sub))\n\ntable_count <- table(sub_dna)\nall_occuerance <- rbind(all_occuerance, data.frame(table_count) )\n}\nresult <- subset(all_occuerance, Freq >= t)\nresult_unique <- unique(result)\nresult_unique\n", "meta": {"hexsha": "089f39ea6965760275b1f3b5d1a673f0be5372a1", "size": 554, "ext": "r", "lang": "R", "max_stars_repo_path": "R.code/5.ClumpFindingProblem.r", "max_stars_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_stars_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "max_stars_repo_licenses": ["MIT"], "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/5.ClumpFindingProblem.r", "max_issues_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_issues_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "max_issues_repo_licenses": ["MIT"], "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/5.ClumpFindingProblem.r", "max_forks_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_forks_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "max_forks_repo_licenses": ["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.380952381, "max_line_length": 67, "alphanum_fraction": 0.655234657, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4089413334831328}}
{"text": "################################################################################\n# Part of the R/EpiILM package\n#\n# AUTHORS:\n# Vineetha Warriyar. K. V. ,\n# Waleed Almutiry , and\n# Rob Deardon \n#\n# Free software under the terms of the GNU General Public License, version 2,\n# a copy of which is available at http://www.r-project.org/Licenses/.\n################################################################################\n\nepiBR0 <- function(x = NULL, y = NULL, contact = NULL, sus.par, trans.par = NULL, beta,\n spark = NULL, infperiod, Sformula = NULL, Tformula = NULL, tmax, niter) {\n\n # Error checks for input arguments\n if (all(is.null(contact) & (is.null(x) | is.null(y))) == TRUE) {\n stop('epiBR0: Specify contact network or x, y coordinates')\n }\n\n if (is.null(spark)) {\n spark <- 0\n }\n\n ns <- length(sus.par)\n if (is.null(trans.par)) {\n nt <- 1\n trans.par <- 1\n } else {\n nt <- length(trans.par)\n }\n ni <- length(beta)\n\n if (!is.null(x)) {\n n <- length(x)\n\n if (any((length(y) != n) | (length(x) != n)) == TRUE) {\n stop('epiBR0: Length of x or y is not compatible')\n }\n }\n\n if (!is.null(contact)) {\n if (is.matrix(contact)) {\n if (dim(contact)[1] != dim(contact)[2]) {\n stop('epiBR0: The contact network matrix is not a square matrix.')\n }\n n <- dim(contact)[1]\n network <- array(contact, c(n, n, ni))\n } else if (is.array(contact)) {\n if (dim(contact)[1] != dim(contact)[2] | length(contact)/(sqrt(dim(contact)[1]) * sqrt(dim(contact)[2])) != dim(contact)[3]) {\n stop('epiBR0: One or all of the contact network matrix are not a square matrix.')\n }\n n <- sqrt(dim(contact)[1])\n network <- contact #array(contact, c(n, n, ni))\n\n } else {\n stop('epiBR0: The contact network must be specified as an n by n square matrix or an array of n by n square matrices.')\n }\n }\n\n if (length(infperiod) != n) {\n stop('epiBR0: Length of infperiod is not compatible')\n }\n\n # formula for susceptibility function\n if (!is.null(Sformula)) {\n covmat.sus <- model.matrix(Sformula)\n\n if (all((ncol(covmat.sus) == length(all.vars(Sformula))) & (ns != length(all.vars(Sformula)))) == TRUE) {\n stop('epiBR0: Check Sformula (no intercept term) and the dimension of sus.par')\n }\n\n if (all((ncol(covmat.sus) > length(all.vars(Sformula))) & (ns != ncol(covmat.sus))) == TRUE) {\n stop('epiBR0: Check Sformula (intercept term) and the dimension of sus.par')\n }\n } else {\n if (ns == 1) {\n covmat.sus <- matrix(1.0, nrow = n, ncol = ns)\n }\n if (ns > 1) {\n stop('epiBR0: Please specify the susceptibility covariate')\n }\n }\n\n # formula for transmissibility function\n\n if (!is.null(Tformula)) {\n covmat.trans <- model.matrix(Tformula)\n\n if (all((ncol(covmat.trans) == length(all.vars(Tformula))) & (nt != length(all.vars(Tformula)))) == TRUE) {\n stop('epiBR0: Check Tformula (no intercept term) and the dimension of trans.par')\n }\n\n } else {\n if (nt == 1) {\n covmat.trans <- matrix(1.0, nrow = n, ncol = 1)\n }\n if (nt > 1) {\n stop('epiBR0: Please specify the transmissibility covariate')\n }\n }\n\n # Calling Fortran subroutines : contact network model\n if (!is.null(contact)) {\n tmp <- .Fortran(\"rconsir\",\n n = as.integer(n),\n tmax = as.integer(tmax),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n lambda = as.integer(infperiod),\n suspar = as.numeric(sus.par),\n transpar = as.numeric(trans.par),\n beta = as.numeric(beta),\n spark = as.numeric(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n network = as.vector(network),\n sim = as.integer(niter),\n val = as.double(0),\n countinf = as.integer(rep(0,niter))\n )\n\n result1 <- list(BasicR0 = tmp$val,\n simulated_BR0 = tmp$countinf)\n } else {\n # Calling Fortran subroutines : spatial model\n tmp <- .Fortran(\"rxysir\",\n n = as.integer(n),\n tmax = as.integer(tmax),\n ns = as.integer(ns),\n nt = as.integer(nt),\n ni = as.integer(ni),\n suspar = as.numeric(sus.par),\n transpar = as.numeric(trans.par),\n beta = as.numeric(beta),\n spark = as.numeric(spark),\n covmatsus = matrix(as.double(covmat.sus), ncol = ncol(covmat.sus), nrow = n),\n covmattrans = matrix(as.double(covmat.trans), ncol = ncol(covmat.trans), nrow = n),\n lambda = as.integer(infperiod),\n x = as.double(x),\n y = as.double(y),\n sim = as.integer(niter),\n val = as.double(0),\n countinf = as.integer(rep(0,niter)))\n\n result1 <- list(BasicR0 = tmp$val,\n simulated_BR0 = tmp$countinf)\n }\n return(result1)\n}\n", "meta": {"hexsha": "258e48bbaa773064862f40fcad6d76722cb6c54e", "size": 5475, "ext": "r", "lang": "R", "max_stars_repo_path": "R/epiBR0.r", "max_stars_repo_name": "waleedalmutiry/EpiILM", "max_stars_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_stars_repo_licenses": ["Intel"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-06-30T03:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:15:25.000Z", "max_issues_repo_path": "R/epiBR0.r", "max_issues_repo_name": "waleedalmutiry/EpiILM", "max_issues_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/epiBR0.r", "max_forks_repo_name": "waleedalmutiry/EpiILM", "max_forks_repo_head_hexsha": "a22caac0e2f5af69fe202b2c750e237cbe6e295b", "max_forks_repo_licenses": ["Intel"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-02-01T20:50:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T17:44:20.000Z", "avg_line_length": 36.0197368421, "max_line_length": 132, "alphanum_fraction": 0.5176255708, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.40894122875197414}}
{"text": "#1, degree of freedom calculation\r\n#2, singletons detection and drop\r\n#3, clustered standard error\r\n\r\nget.dof <- function(model,\r\n x,\r\n cl=NULL,\r\n ind,\r\n sfe.index,\r\n cfe.index){\r\n df.info <- list() \r\n #calculate the degree of freedom\r\n gtot <- 0 #total loss of degree of freedom\r\n if(is.null(sfe.index)){\r\n for (i in 1:length(model$inds$levels)) {\r\n cat.num <- length(model$inds$levels[[i]]) \r\n redund.num <- 1\r\n out.cum <- c(cat.num,redund.num)\r\n names(out.cum) <- c(\"Category\",\"Redundant\")\r\n df.info[[i]] <- out.cum\r\n }\r\n }else{\r\n for (i in 1:length(sfe.index)) {\r\n cat.num <- length(model$inds$levels[[sfe.index[i]]]) \r\n redund.num <- 1\r\n out.cum <- c(cat.num,redund.num)\r\n names(out.cum) <- c(\"Category\",\"Redundant\")\r\n df.info[[model$fe$sfe.names[i]]] <- out.cum\r\n }\r\n }\r\n\r\n ## we test nest among the first two sets of fixed effects, that is \"firstpair\" option in reghdfe\r\n need.adj.dof <- FALSE\r\n if (is.null(sfe.index)) {\r\n if (dim(ind)[2] >= 2) {\r\n need.adj.dof <- TRUE\r\n }\r\n } else {\r\n if (length(sfe.index) >= 2) {\r\n need.adj.dof <- TRUE\r\n }\r\n }\r\n\r\n if (need.adj.dof) {\r\n if (is.null(sfe.index)) {\r\n pos1 <- 1\r\n pos2 <- 2\r\n } else {\r\n pos1 <- sfe.index[1]\r\n pos2 <- sfe.index[2]\r\n }\r\n level1 <- ind[, pos1]\r\n level2 <- ind[, pos2]\r\n c.level1 <- length(model$inds$levels[[pos1]])\r\n c.level2 <- length(model$inds$levels[[pos2]])\r\n \r\n if (c.level1 > c.level2) {\r\n fe.level <- table(unlist(tapply(level1, level2, unique)))\r\n } else {\r\n fe.level <- table(unlist(tapply(level2, level1, unique)))\r\n }\r\n\r\n if (max(fe.level) == 1) {\r\n if(c.level1 > c.level2){\r\n df.info[[model$fe$sfe.names[1]]]['Redundant'] <- c.level2\r\n }\r\n if(c.level1 <= c.level2){\r\n df.info[[model$fe$sfe.names[2]]]['Redundant'] <- c.level1\r\n }\r\n #adj.dof <- min(c.level1, c.level2) - 1\r\n }\r\n }\r\n\r\n if (!is.null(cfe.index)) {\r\n sum.cfe.coef <- NULL \r\n for (i in 1:length(cfe.index)) {\r\n sum.cfe.coef <- sum(c(model$cfe.coefs[[i]])) \r\n if (sum.cfe.coef <= 1e-7) {\r\n cat.num <- length(model$inds$levels[[cfe.index[[i]][1]]])\r\n redund.num <- 1\r\n out.cum <- c(cat.num,redund.num)\r\n names(out.cum) <- c(\"Category\",\"Redundant\")\r\n df.info[[model$fe$cfe.names[i]]] <- out.cum\r\n } else {\r\n cat.num <- length(model$inds$levels[[cfe.index[[i]][1]]])\r\n redund.num <- 0\r\n out.cum <- c(cat.num,redund.num)\r\n names(out.cum) <- c(\"Category\",\"Redundant\")\r\n df.info[[model$fe$cfe.names[i]]] <- out.cum\r\n }\r\n }\r\n }\r\n\r\n if(is.null(cl)==FALSE){\r\n raw.cl <- as.numeric(as.factor(cl))\r\n level.cl <- unique(raw.cl)\r\n \r\n ## check cluster for the first 2 levels of fixed effects\r\n cluster.adj <- 0\r\n contain.cl <- NULL\r\n if (is.null(sfe.index)) {\r\n contain.cl <- apply(ind, 2, function(vec) sum(vec == cl)) == dim(x)[1]\r\n } else {\r\n contain.cl <- apply(as.matrix(ind[, sfe.index]), 2, function(vec) sum(vec == cl)) == dim(x)[1]\r\n }\r\n \r\n ## adjust q formula for finite sample\r\n if (max(contain.cl) == 1) {\r\n correct.index <- which.max(contain.cl)\r\n if(is.null(sfe.index)){\r\n df.info[[correct.index]][\"Redundant\"] <- df.info[[i]][\"Category\"] \r\n }else{\r\n df.info[[model$fe$sfe.names[correct.index]]][\"Redundant\"] <- df.info[[model$fe$sfe.names[correct.index]]][\"Category\"] \r\n }\r\n }\r\n\r\n if (length(contain.cl) >= 2) {\r\n if (max(contain.cl[c(1,2)]) == 1) {\r\n cluster.adj <- 1 \r\n }\r\n }\r\n\r\n ## check fixed effects nested within clusters\r\n if (is.null(sfe.index)) {\r\n for (i in 1:dim(ind)[2]) {\r\n fe.level <- as.numeric(table(unlist(tapply(ind[,i], c(cl), unique))))\r\n #if (length(fe.level) != length(level.cl)) {\r\n if (sum(fe.level == 1) == length(fe.level)) {\r\n df.info[[i]]['Redundant'] <- df.info[[i]]['Category']\r\n }\r\n #} \r\n }\r\n } else {\r\n for (i in 1:length(sfe.index)) {\r\n fe.level <- as.numeric(table(unlist(tapply(ind[,sfe.index[i]], c(cl), unique))))\r\n #if (length(fe.level) != length(level.cl)) {\r\n if (sum(fe.level == 1) == length(fe.level)) {\r\n df.info[[model$fe$sfe.names[i]]]['Redundant'] <- df.info[[model$fe$sfe.names[i]]]['Category']\r\n }\r\n #}\r\n }\r\n }\r\n\r\n if (!is.null(cfe.index)) {\r\n for (i in 1:length(cfe.index)) {\r\n fe.level <- unlist(tapply(ind[,cfe.index[[i]][1]], c(cl), unique))\r\n #if (length(fe.level) != length(level.cl)) {\r\n if (sum(fe.level == 1) == length(fe.level)) {\r\n df.info[[model$fe$cfe.names[i]]]['Redundant'] <- df.info[[model$fe$cfe.names[i]]]['Category']\r\n }\r\n #}\r\n }\r\n }\r\n }\r\n\r\n gtot<-0\r\n for(element in df.info){\r\n gtot <- gtot + element[1]-element[2]\r\n }\r\n\r\n if(is.null(x)){\r\n gtot <- gtot + 1\r\n }else{\r\n gtot <- gtot + 1 + dim(x)[2]\r\n }\r\n names(gtot) <- NULL\r\n output <- list(gtot=gtot,dof=df.info)\r\n return(output)\r\n\r\n}\r\n\r\nhave.singletons <- function(ind=NULL){ #Matrix\r\n for(k in 1:dim(ind)[2]){\r\n if(min(table(ind[,k]))==1){\r\n return(TRUE)\r\n }\r\n }\r\n return(FALSE) \r\n} \r\n\r\ndrop.singletons <- function(ind=NULL){ #Matrix\r\n to.check <- ind\r\n colnames(to.check) <- NULL\r\n keep.all <- c()\r\n result <- apply(to.check, 2, sub.check) \r\n \r\n for(i in 1:length(result)){\r\n if(!is.null(result[[i]])){\r\n tar.all <- result[[i]][which(result[[i]][,2]==1),1]\r\n tar.index <- which(!to.check[,i]%in%c(tar.all))\r\n keep.all <- c(keep.all,tar.index)\r\n }\r\n }\r\n\r\n keep.all <- unique(keep.all)\r\n return(keep.all) \r\n}\r\n\r\nsub.check <- function(col){\r\n t <- aggregate(col, by=list(col), FUN=length)\r\n if(min(t[,2])==1){\r\n return(t)\r\n }\r\n}\r\n\r\n## subfunction for clustered se\r\ncluster.se <- function(cl, \r\n x,\r\n res,\r\n dx,\r\n sfe.index,\r\n cfe.index,\r\n ind,\r\n df,\r\n df.cl = NULL,\r\n invx,\r\n model = NULL) {\r\n\r\n ## replicate degree of freedom \r\n df.Redundant <- 0\r\n\r\n raw.cl <- as.numeric(as.factor(cl))\r\n level.cl <- unique(raw.cl)\r\n #meat <- matrix(0, dim(dx)[2], dim(dx)[2])\r\n #get.sub.meat <- function(cl.index){\r\n # sub.id <- which(raw.cl == cl.index)\r\n # if(length(sub.id)>1){\r\n # hmeat <- as.matrix(t(as.matrix(dx[sub.id,])) %*% as.matrix(res[sub.id,]))\r\n # }\r\n # if(length(sub.id)==1){\r\n # hmeat <- t(as.matrix(t(as.matrix(dx[sub.id,]))*res[sub.id]))\r\n # }\r\n # return(hmeat%*%t(hmeat))\r\n #}\r\n #asx <- lapply(level.cl,get.sub.meat)\r\n #meat <- Reduce(`+`, asx)\r\n cal.cl <- 0\r\n if(is.null(df.cl)){\r\n cal.cl <- 1\r\n dof.output.cl <- get.dof(model=model,\r\n x=x,\r\n cl=cl,\r\n ind=ind,\r\n sfe.index=sfe.index,\r\n cfe.index=cfe.index)\r\n gtot <- dof.output.cl$gtot \r\n df.cl <- length(raw.cl)-gtot\r\n }\r\n q <- length(level.cl)/(length(level.cl) - 1) * (dim(dx)[1] - 1)/(df.cl)\r\n\r\n \r\n clustercpp.output <- clustercpp(rawcl = matrix(raw.cl,ncol=1),X = dx,Res = res, q = q,invX = invx)\r\n vcov <- clustercpp.output[[\"vcov\"]]\r\n meat <- clustercpp.output[[\"meat\"]]\r\n stderror <- as.matrix(sqrt(diag(vcov)))\r\n \r\n \r\n #vcov <- q*invx %*% meat %*% invx\r\n #stderror <- sqrt(q) * as.matrix(sqrt(diag(invx %*% meat %*% invx)))\r\n\r\n if(cal.cl==1){\r\n out <- list(stderror=stderror,num.cl=length(level.cl),meat=meat,vcov.cl=vcov,df.cl=df.cl,dof=dof.output.cl$dof) \r\n }\r\n else{\r\n out <- list(stderror=stderror,num.cl=length(level.cl),meat=meat,vcov.cl=vcov,df.cl=df.cl,dof=NULL) \r\n }\r\n return(out)\r\n}\r\n\r\n## subfunction for iv clustered se\r\niv.cluster.se <- function(cl, \r\n x,\r\n u.hat,\r\n dz,\r\n sfe.index,\r\n cfe.index,\r\n ind,\r\n df,\r\n df.cl = NULL,\r\n inv.xPzx,\r\n inv.z.zx,\r\n model) {\r\n\r\n ## replicate degree of freedom \r\n df.Redundant <- 0\r\n\r\n raw.cl <- as.numeric(as.factor(cl))\r\n level.cl <- unique(raw.cl)\r\n\r\n #meat <- matrix(0, dim(dz)[2], dim(dz)[2])\r\n #get.sub.meat <- function(cl.index){\r\n # sub.id <- which(raw.cl == cl.index)\r\n # if(length(sub.id)>1){\r\n # hmeat <- as.matrix(t(as.matrix(dz[sub.id,])) %*% as.matrix(u.hat[sub.id,]))\r\n # }\r\n # if(length(sub.id)==1){\r\n # hmeat <- t(as.matrix(t(as.matrix(dz[sub.id,]))*u.hat[sub.id]))\r\n # }\r\n # return(hmeat%*%t(hmeat))\r\n #}\r\n #asx <- lapply(level.cl,get.sub.meat)\r\n #meat <- Reduce(`+`, asx)\r\n\r\n cal.cl <- 0\r\n if(is.null(df.cl)){\r\n cal.cl <- 1\r\n dof.output.cl <- get.dof(model=model,\r\n x=x,\r\n cl=cl,\r\n ind=ind,\r\n sfe.index=sfe.index,\r\n cfe.index=cfe.index)\r\n gtot <- dof.output.cl$gtot \r\n df.cl <- length(raw.cl)-gtot\r\n }\r\n q <- length(level.cl)/(length(level.cl) - 1) * (dim(x)[1] - 1)/(df.cl)\r\n\r\n clustercpp.output <- ivclustercpp(rawcl = matrix(raw.cl,ncol=1),X = dz,Res = u.hat, q = q,invxPzx=inv.xPzx, invzzx=inv.z.zx)\r\n vcov <- clustercpp.output[[\"vcov\"]]\r\n meat <- clustercpp.output[[\"meat\"]]\r\n stderror <- as.matrix(sqrt(diag(vcov)))\r\n \r\n\r\n #vcov <- inv.xPzx%*%(t(inv.z.zx)%*%meat%*%inv.z.zx)%*%inv.xPzx\r\n #vcov <- q*vcov\r\n #stderror <- as.matrix(sqrt(diag(vcov)))\r\n\r\n if(cal.cl==1){\r\n out <- list(stderror=stderror,num.cl=length(level.cl),meat=meat,vcov.cl=vcov,df.cl=df.cl,dof=dof.output.cl$dof) \r\n }\r\n else{\r\n out <- list(stderror=stderror,num.cl=length(level.cl),meat=meat,vcov.cl=vcov,df.cl=df.cl,dof=NULL) \r\n }\r\n return(out)\r\n}\r\n", "meta": {"hexsha": "8b9ee287a17d969abd7dd490ae24d7c9652e28ff", "size": 11432, "ext": "r", "lang": "R", "max_stars_repo_path": "R/getdof.r", "max_stars_repo_name": "xuyiqing/fastplm", "max_stars_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-02T17:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T12:54:00.000Z", "max_issues_repo_path": "R/getdof.r", "max_issues_repo_name": "xuyiqing/fastplm", "max_issues_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T05:58:47.000Z", "max_forks_repo_path": "R/getdof.r", "max_forks_repo_name": "xuyiqing/fastplm", "max_forks_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:58:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T00:55:38.000Z", "avg_line_length": 34.0238095238, "max_line_length": 136, "alphanum_fraction": 0.4370188943, "num_tokens": 3013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4087324355855454}}
{"text": "\r\n\r\n# Goals: Lots of times, you need to give an R object to a friend,\r\n# or embed data into an email.\r\n\r\n# First I invent a little dataset --\r\nset.seed(101) # To make sure you get the same random numbers as me\r\n # FYI -- runif(10) yields 10 U(0,1) random numbers.\r\nA = data.frame(x1=runif(10), x2=runif(10), x3=runif(10))\r\n# Look at it --\r\nprint(A)\r\n\r\n# Writing to a binary file that can be transported\r\nsave(A, file=\"/tmp/my_data_file.rda\") # You can give this file to a friend\r\nload(\"/tmp/my_data_file.rda\")\r\n\r\n# Plan B - you want pure ascii, which can be put into an email --\r\ndput(A)\r\n# This gives you a block of R code. Let me utilise that generated code\r\n# to create a dataset named \"B\".\r\nB <- structure(list(x1 = c(0.372198376338929, 0.0438248154241592,\r\n0.709684018278494, 0.657690396532416, 0.249855723232031, 0.300054833060130,\r\n0.584866625955328, 0.333467143354937, 0.622011963743716, 0.54582855431363\r\n), x2 = c(0.879795730113983, 0.706874740775675, 0.731972594512627,\r\n0.931634427979589, 0.455120594473556, 0.590319729177281, 0.820436094887555,\r\n0.224118480458856, 0.411666829371825, 0.0386105608195066), x3 = c(0.700711545301601,\r\n0.956837461562827, 0.213352001970634, 0.661061500199139, 0.923318882007152,\r\n0.795719761401415, 0.0712125543504953, 0.389407767681405, 0.406451216200367,\r\n0.659355078125373)), .Names = c(\"x1\", \"x2\", \"x3\"), row.names = c(\"1\",\r\n\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"), class = \"data.frame\")\r\n\r\n# Verify that A and B are near-identical --\r\nA-B\r\n# or,\r\nall.equal(A,B)\r\n\r\n", "meta": {"hexsha": "8ffa934d620fa7fcf3989f8ee4f81b4e7648af3c", "size": 1544, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/r5.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)/r5.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)/r5.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": 41.7297297297, "max_line_length": 85, "alphanum_fraction": 0.6917098446, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.40845061994937315}}
{"text": "=begin\n[(())] \n(())\n/\n(())\n/\n(())\n/\n(())\n\n= Algebra::MPolynomial\n((*(多変数多項式環クラス)*))\n\n多変数の多項式環を表現します。実際のクラスを生成するには環を指定して、\nクラスメソッド((<::create>))あるいは関数(())()を\n用います。\n\n== ファイル名:\n* ((|m-polynomial.rb|))\n\n== スーパークラス:\n\n* ((|Object|))\n\n== インクルードしているモジュール:\n\n* ((|Enumerable|))\n* ((|Comparable|))\n* (())\n\n== 関連する関数:\n\n--- Algebra.MPolynomial(ring [, obj0 [, obj1 [, ...]]])\n ((<::create(ring [, obj0[, obj1[, ...]]])>))に同じ。\n\n== クラスメソッド:\n\n--- ::create(ring [, obj0 [, obj1 [, ...]]])\n ((|ring|))で表現されるクラスを係数環とする多変数多項式環\n クラスを生成します。\n \n オブジェクト(({obj0, obj1, ...}))で変数を登録し、戻り値である\n 多変数多項式環クラスは Algebra::MPolynomial クラスのサブクラスです。\n \n オブジェクト(({obj0, obj1, ...}))は変数の区別と\n 名(((|to_s|))の値)に利用されるだけです。\n\n このサブクラスにはクラスメソッドとして((|ground|))と\n ((|vars|))が定義され、それぞれ、係数環((|ring|))、変数\n の配列を返します。 \n \n 登録されたオブジェクト (({obj0, obj1, ...})) で表現される\n される変数は(({var(obj0)})), (({var(obj1)})),...\n で得ることができます。すなわち(({vars == [var(obj0), var(obj1), ...]}))\n です。\n \n 各変数の大小関係は(({obj0 > obj1 > ...}))となります。各単項式\n の順序は((<::set_ord>))で指定します。\n\n\n 例: 整数を係数とする多項式環の生成\n require \"m-polynomial\"\n P = Algebra::MPolynomial.create(Integer, \"x\", \"y\", \"z\")\n x, y, z = P.vars\n p((-x + y + z)*(x + y - z)*(x - y + z))\n #=> -x^3 + x^2y + x^2z + xy^2 - 2xyz + xz^2 - y^3 + y^2z + yz^2 - z^3\n p P.ground #=> integer\n\n--- ::vars([obj0 [, obj1 [, ...]]])\n ((*引数が1つもないとき*))、既に登録されている全ての変数を\n 配列として返します。\n \n 例:\n P = Algebra.MPolynomial(Integer, \"x\", \"y\", \"z\")\n p P.vars #=> [x, y, z]\n \n ((*引数がただ1つで文字列であるとき*))、文字列を「英字1字+数字の列」\n に分解し、それで表現される変数を登録します。オブジェクトが既\n に登録されていれば新たな登録はしません。戻り値はそれぞれのオ\n ブジェクトに対応する変数の配列です。\n \n 例: \n P = Algebra.MPolynomial(Integer)\n x, y, z, w = P.vars(\"a0b10cd\")\n p P.vars #=> [a0, b10, c, d]\n p [x, y, z, w] #=> [a0, b10, c, d]\n\n ((*それ以外のとき*))、引数であるオブジェクト\n (({obj0, obj1, ...})) で表現される変数\n を登録します。オブジェクトが既に登録されていれば新たな登録\n はしません。戻り値は(({obj0, obj1, ...}))に対応する変数\n の配列です。\n\n 例:\n P = Algebra.MPolynomial(Integer)\n p P.vars(\"x\", \"y\", \"z\") #=> [x, y, z]\n\n--- ::mvar([obj0 [, obj1 [, ...]]])\n\n ((*引数が1つもないとき*))、既に登録されている全ての変数を\n 配列として返します。\n\n ((*それ以外のとき*))、引数であるオブジェクト\n (({obj0, obj1, ...})) で表現される変数\n を登録します。オブジェクトが既に登録されていれば新たな登録\n はしません。戻り値は (({obj0, obj1, ...})) に対応する変数\n の配列です。\n\n--- ::to_ary\n (({[self, *vars]})) を返します。\n\n 例: 多項式環と変数を同時に定義する。\n P, x, y, z, w = Algebra.MPolynomial(Integer, \"a\", \"b\", \"c\", \"d\")\n\n--- ::var(obj)\n ((|obj|)) で登録されたオブジェクトによって表現される変数を返します。\n \n 例: \n P = Algebra.MPolynomial(Integer, \"X\", \"Y\", \"Z\")\n x, y, z = P.vars\n P.var(\"Y\") == y #=> true\n\n--- ::variables\n 既に登録されている変数を表現するオブジェクトの配列を返します。\n\n--- ::indeterminate(obj)\n ((<::var>)) と同じです。\n\n--- ::zero?\n 零元であるとき真を返します。\n\n--- ::zero\n 零元を返します。\n \n--- ::unity\n 単位元を返します。\n\n--- ::set_ord(ord [, v_ord])\n ((|ord|)) に単項式順序をシンボルで指定します。順序として可能な指定\n は (({:lex})) (辞書式順序(デフォルト))、(({:grlex})) (次数付き辞書\n 式順序)、(({:grevlex})) (次数付き逆辞書式順序)の3つです。\n \n 各変数間の順序は登録された順(先に登録されるほど大きい)に\n なります。((|v_ord|)) に配列を与えてこの順番を変更する事が\n できます。\n \n 例: (({x, y, z = P.var(\"xyz\")})) としたときの順位\n require \"m-polynomial\"\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n\n P.set_ord(:lex)\n p f #=> -5x^3 + 7x^2z^2 + 4xy^2z + 4z^2\n\n f.method_cash_clear\n P.set_ord(:grlex)\n p f #=> 7x^2z^2 + 4xy^2z - 5x^3 + 4z^2\n\n f.method_cash_clear\n P.set_ord(:grevlex)\n p f #=> 4xy^2z + 7x^2z^2 - 5x^3 + 4z^2\n\n f.method_cash_clear\n P.set_ord(:lex, [2, 1, 0]) # z > y > x\n p f #=> 7x^2z^2 + 4z^2 + 4xy^2z - 5x^3\n\n# ((<::with_ord>)) も参照してください。\n\n--- ::order=(x)\n ((<::set_ord(x)>)) と同じです。\n\n#--- ::order=(obj)\n# ((<::set_ord(obj)>)) と同じです。\n\n--- ::get_ord\n 単項式順序(:lex, :grlex, :grevlex)を返します。\n\n--- ::ord\n ((<::get_ord>)) と同じです。\n\n#--- ::order\n# ((<::get_ord>)) と同じです。\n\n--- ::with_ord(ord [, v_ord[ [, array_of_polys]])\n ((|ord|)) を単項式順序、((|v_ord|)) を変数の順序の変換配列として、\n ブロックを実行します。\n ブロックを抜けると以前の順序に戻ります。\n 多項式の配列 ((|array_of_polys|)) が与えられれば、それらに対して\n (()) が実行されてから、ブロックが実行されます。\n (このブロックはスレッドセーフではありません。)\n\n 例:\n require \"m-polynomial\"\n P = Algebra.MPolynomial(Integer)\n x, y, z = P.vars(\"xyz\")\n f = -5*x**3 + 7*x**2*z**2 + 4*x*y**2*z + 4*z**2\n\n P.with_ord(:lex, nil, [f]) do\n p f #=> -5x^3 + 7x^2z^2 + 4xy^2z + 4z^2\n p f.lt #=> -5x^3\n end\n\n P.with_ord(:grlex, nil, [f]) do\n p f #=> 7x^2z^2 + 4xy^2z - 5x^3 + 4z^2\n p f.lt #=> 7x^2z^2\n end\n\n P.with_ord(:grevlex, nil, [f]) do\n p f #=> 4xy^2z + 7x^2z^2 - 5x^3 + 4z^2\n p f.lt #=> 4xy^2z\n end\n\n P.with_ord(:lex, [2, 1, 0], [f]) do # z > y > x\n p f #=> 7x^2z^2 + 4z^2 + 4xy^2z - 5x^3\n p f.lt #=> 7x^2z^2\n end\n\n ((<::set_ord>)) も参照してください。\n\n--- ::monomial(ind[, c])\n multi-degree ((|ind|)) で、係数が ((|c|)) の単項式を返します。\n (ただし、(()) は extend\n されていない。)\n ((|c|)) が省略されれば、単位元とみなされます。\n\n#--- ::const(x)\n#--- ::regulate(x)\n#--- ::[](*x)\n#--- ::method_cash_clear(*m)\n\n== メソッド:\n\n--- monomial(ind[, c])\n ((<::monomial>)) と同じ。\n\n#--- each\n#--- keys\n#--- values\n#--- [](ind)\n#--- []=(ind, c)\n#--- constant_coeff\n#--- include?\n#--- compact!\n#--- rt!\n\n--- constant?\n 定数(0次式)であるとき、真を返します。\n\n--- monomial?\n 単項式であるとき、真を返します。\n\n--- zero?\n 零であるとき、真を返します。 \n\n--- zero\n 零元を返します。\n \n--- unity\n 単位元を返します。\n\n--- method_cash_clear\n このライブラリは、同じ計算を繰り返ししないように結果を保存\n していますが、それをクリアします。この操作は単項式順序の変\n 更などを行った後に必要になります。\n \n 結果が保存されているメソッドは、\n (()), (()), (()), ((