{"text": "#' @title Bland-Altman drawing function for R\n#'\n#' @description Bland-Altman drawing function. Depends on the blandr.statistics function in the package. Will generate a plot via the standard R plotting functions.\n#'\n#' @author Deepankar Datta \n#'\n#' @note Started 2015-11-14\n#' @note Last update 2015-11-19\n#' @note Originally designed for LAVAS and CVLA\n#'\n#' @param method1 A list of numbers.\n#' @param method2 A list of numbers.\n#' @inheritParams blandr.statistics\n#' @inheritParams blandr.plot.limits\n#' @inheritParams blandr.plot.ggplot\n#'\n#' @examples\n#' # Generates two random measurements\n#' measurement1 <- rnorm(100)\n#' measurement2 <- rnorm(100)\n#'\n#' # Generates a plot, with no optional arguments\n#' gg_bland_altman(measurement1, measurement2)\n#' @export\ngg_bland_altman <- function(method1,\n method2,\n method1name = \"Method 1\",\n method2name = \"Method 2\",\n plotTitle = \"Bland-Altman plot for comparison of 2 methods\",\n sig.level = 0.95,\n LoA.mode = 1,\n ciDisplay = TRUE,\n ciShading = TRUE,\n ciFillColors = c(\"steelblue3\", \"gray85\"),\n normalLow = FALSE,\n normalHigh = FALSE,\n lowest_y_axis = FALSE,\n highest_y_axis = FALSE,\n point_size = 0.8,\n overlapping = FALSE,\n x.plot.mode = \"means\",\n y.plot.mode = \"difference\",\n plotProportionalBias = FALSE,\n plotProportionalBias.se = TRUE,\n assume.differences.are.normal = TRUE) {\n\n # Passes data to the blandr.statistics function to generate Bland-Altman statistics\n statistics.results <- blandr.statistics(method1, method2, sig.level, LoA.mode)\n\n # Passed data to the blandr.plot.limits function to generate plot limits\n # Only used for the basic R plots\n plot.limits <- blandr.plot.limits(statistics.results, lowest_y_axis, highest_y_axis)\n\n # Plots data\n\n # Pass data to the blandr.plot.ggplot function to use ggplot2 graphics system\n ba.plot <- blandr.plot.ggplot(\n statistics.results = statistics.results,\n method1name = method1name,\n method2name = method2name,\n plotTitle = plotTitle,\n ciDisplay = ciDisplay,\n ciShading = ciShading,\n ciFillColors = ciFillColors,\n normalLow = normalLow,\n normalHigh = normalHigh,\n overlapping = overlapping,\n x.plot.mode = x.plot.mode,\n y.plot.mode = y.plot.mode,\n point_size = point_size,\n plotProportionalBias = plotProportionalBias,\n plotProportionalBias.se = plotProportionalBias.se,\n assume.differences.are.normal = assume.differences.are.normal\n )\n return(ba.plot)\n # END OF FUNCTION\n}\n\n#' @title Data preparation for method comparison analysis\n#'\n#' @description Prepares the data and runs error checks before the calling function runs whatever method analysis mode is wants.\n#'\n#' @author Deepankar Datta \n#'\n#' @param method1 A list of numbers.\n#' @param method2 A list of numbers.\n#' @param sig.level Significance level. Is not optional in this function, as the calling package should have a default value to pass if needed\n#'\n#' @return method.comparison A data frame of paired values. These have been data checked, and empty rows omitted, from the originally supplied data.\n#'\n#' @examples\n#' # Generates two random measurements\n#' measurement1 <- rnorm(100)\n#' measurement2 <- rnorm(100)\n#'\n#' # Calls the function - do note that this function was really\n#' # meant to be called from other functions and not a stand-alone funtion\n#' blandr.data.preparation(measurement1, measurement2, sig.level = 0.95)\n#' @export\nblandr.data.preparation <- function(method1, method2, sig.level) {\n\n # Put everything into a data frame for easier handling Stems from the error in some of\n # the sepsis data I had\n method.comparison <- data.frame(method1, method2)\n\n # Omit rows which have empty values\n method.comparison <- na.omit(method.comparison)\n\n # Data checks\n if (length(method.comparison$method1) != length(method.comparison$method2)) {\n stop(\"Method comparison analysis error: the 2 methods must have paired values.\")\n }\n if (!is.numeric(method.comparison$method1)) {\n stop(\"Method comparison analysis error: the first method is not a number.\")\n }\n if (!is.numeric(method.comparison$method2)) {\n stop(\"Method comparison analysis error: the second method is not a number.\")\n }\n if (sig.level < 0) {\n stop(\"Method comparison analysis error: you can't have a significance level less than 0.\")\n }\n if (sig.level < 0.8) {\n warning(\"Method comparison analysis warning: do you really want a significance level <0.8?\")\n }\n if (sig.level > 1) {\n stop(\"Method comparison analysis error: you can't have a significance level greater than 1.\")\n }\n if (sig.level == 1) {\n warning(\"Method comparison analysis warning: selecting a significance level of 1 suggest that probability testing might not be what you need.\")\n }\n\n # Returns the data\n return(method.comparison)\n}\n\n#' @title Bland-Altman plotting function, using ggplot2\n#'\n#' @description Draws a Bland-Altman plot using data calculated using the other functions, using ggplot2\n#'\n#' @author Deepankar Datta \n#'\n#' @param statistics.results A list of statistics generated by the blandr.statistics function: see the function's return list to see what variables are passed to this function\n#' @param method1name (Optional) Plotting name for 1st method, default \"Method 1\"\n#' @param method2name (Optional) Plotting name for 2nd method, default \"Method 2\"\n#' @param plotTitle (Optional) Title name, default \"Bland-Altman plot for comparison of 2 methods\"\n#' @param point_size (Optional) Default = 0.8\n#' @param ciDisplay (Optional) TRUE/FALSE switch to plot confidence intervals for bias and limits of agreement, default is TRUE\n#' @param ciShading (Optional) TRUE/FALSE switch to plot confidence interval shading to plot, default is TRUE\n#' @param ciFillColors (Optional) 2-vector of colors to use in the bias shading and confidence band shading\n#' @param normalLow (Optional) If there is a normal range, entering a continuous variable will plot a vertical line on the plot to indicate its lower boundary\n#' @param normalHigh (Optional) If there is a normal range, entering a continuous variable will plot a vertical line on the plot to indicate its higher boundary\n#' @param overlapping (Optional) TRUE/FALSE switch to increase size of plotted point if multiple values using ggplot's geom_count, deafault=FALSE. Not currently recommend until I can tweak the graphics to make them better\n#' @param x.plot.mode (Optional) Switch to change x-axis from being plotted by means (=\"means\") or by either 1st method (=\"method1\") or 2nd method (=\"method2\"). Default is \"means\". Anything other than \"means\" will switch to default mode.\n#' @param y.plot.mode (Optional) Switch to change y-axis from being plotted by difference (=\"difference\") or by proportion magnitude of measurements (=\"proportion\"). Default is \"difference\". Anything other than \"proportional\" will switch to default mode.\n#' @param plotProportionalBias (Optional) TRUE/FALSE switch. Plots a proportional bias line. Default is FALSE.\n#' @param plotProportionalBias.se (Optional) TRUE/FALSE switch. If proportional bias line is drawn, switch to plot standard errors. See stat_smooth for details. Default is TRUE.\n#' @param assume.differences.are.normal (Optional, not operationally used currently) Assume the difference of means has a normal distribution. Will be used to build further analyses\n#'\n#' @return ba.plot Returns a ggplot data set that can then be plotted\n#'\n#' @import ggplot2\n#'\n#' @examples\n#' # Generates two random measurements\n#' measurement1 <- rnorm(100)\n#' measurement2 <- rnorm(100)\n#'\n#' # Generates a ggplot\n#' # Do note the ggplot function wasn't meant to be used on it's own\n#' # and is generally called via the bland.altman.display.and.draw function\n#'\n#' # Passes data to the blandr.statistics function to generate Bland-Altman statistics\n#' statistics.results <- blandr.statistics(measurement1, measurement2)\n#'\n#' # Generates a ggplot, with no optional arguments\n#' blandr.plot.ggplot(statistics.results)\n#'\n#' # Generates a ggplot, with title changed\n#' blandr.plot.ggplot(statistics.results, plotTitle = \"Bland-Altman example plot\")\n#'\n#' # Generates a ggplot, with title changed, and confidence intervals off\n#' blandr.plot.ggplot(statistics.results,\n#' plotTitle = \"Bland-Altman example plot\",\n#' ciDisplay = FALSE, ciShading = FALSE\n#' )\n#' @export\n\nblandr.plot.ggplot <- function(statistics.results,\n method1name = \"Method 1\",\n method2name = \"Method 2\",\n plotTitle = \"Bland-Altman plot for comparison of 2 methods\",\n point_size = 0.8,\n ciDisplay = TRUE,\n ciShading = TRUE,\n ciFillColors = c(\"steelblue3\", \"gray85\"),\n normalLow = FALSE,\n normalHigh = FALSE,\n overlapping = FALSE,\n x.plot.mode = \"means\",\n y.plot.mode = \"difference\",\n plotProportionalBias = FALSE,\n plotProportionalBias.se = TRUE,\n assume.differences.are.normal = TRUE) {\n\n # Does a check if ggplot2 is available\n # It should be as it is in the imports section but in CRAN checks some systems don't have it!\n if (!requireNamespace(\"ggplot2\", quietly = TRUE)) {\n stop(\"Package \\\"ggplot2\\\" needed for this function to work. Please install it.\",\n call. = FALSE\n )\n }\n\n # Selects if x-axis uses means (traditional) or selects one of the methods\n # as the gold standard (non-traditional BA)\n # See Krouwer JS (2008) Why Bland-Altman plots should use X, not (Y+X)/2 when X is a reference method. Statistics in Medicine 27:778-780\n # NOT ENABLED YET\n x.axis <- statistics.results$means\n\n # Selects if uses differences (traditional) or proportions (non-traditional BA)\n if (y.plot.mode == \"proportion\") {\n y.axis <- statistics.results$proportion\n } else {\n y.axis <- statistics.results$differences\n }\n\n # Constructs the plot.data dataframe\n plot.data <- data.frame(x.axis, y.axis)\n\n # Rename to allow plotting\n # This was a hangover from an older version so I'm not sure we need it anymore\n # But not really a priority to check and remove now\n colnames(plot.data)[1] <- \"x.axis\"\n colnames(plot.data)[2] <- \"y.axis\"\n\n # Plot using ggplot\n ba.plot <- ggplot(plot.data, aes(x = x.axis, y = y.axis))\n\n # Drawing confidence intervals (OPTIONAL) -- put this here so that it appears under the points\n if (ciDisplay == TRUE) {\n ba.plot <- ba.plot +\n geom_hline(yintercept = statistics.results$biasUpperCI, linetype = 3) + # Bias - upper confidence interval\n geom_hline(yintercept = statistics.results$biasLowerCI, linetype = 3) + # Bias - lower confidence interval\n geom_hline(yintercept = statistics.results$upperLOA_upperCI, linetype = 3) + # Upper limit of agreement - upper confidence interval\n geom_hline(yintercept = statistics.results$upperLOA_lowerCI, linetype = 3) + # Upper limit of agreement - lower confidence interval\n geom_hline(yintercept = statistics.results$lowerLOA_upperCI, linetype = 3) + # Lower limit of agreement - upper confidence interval\n geom_hline(yintercept = statistics.results$lowerLOA_lowerCI, linetype = 3) # Lower limit of agreement - lower confidence interval\n\n # Shading areas for 95% confidence intervals (OPTIONAL)\n # This needs to be nested into the ciDisplay check\n if (ciShading == TRUE) {\n ba.plot <- ba.plot +\n annotate(\"rect\", xmin = -Inf, xmax = Inf, ymin = statistics.results$biasLowerCI, ymax = statistics.results$biasUpperCI, fill = ciFillColors[1], alpha = 0.3) + # Bias confidence interval shading\n annotate(\"rect\", xmin = -Inf, xmax = Inf, ymin = statistics.results$upperLOA_lowerCI, ymax = statistics.results$upperLOA_upperCI, fill = ciFillColors[2], alpha = 0.3) + # Upper limits of agreement confidence interval shading\n annotate(\"rect\", xmin = -Inf, xmax = Inf, ymin = statistics.results$lowerLOA_lowerCI, ymax = statistics.results$lowerLOA_upperCI, fill = ciFillColors[2], alpha = 0.3) # Lower limits of agreement confidence interval shading\n }\n }\n\n # continue plotting\n ba.plot <- ba.plot +\n geom_point(size = point_size) +\n theme(plot.title = element_text(hjust = 0.5)) +\n geom_hline(yintercept = 0, linetype = 1) + # \"0\" line\n geom_hline(yintercept = statistics.results$bias, linetype = 2) + # Bias\n geom_hline(yintercept = statistics.results$bias + (statistics.results$biasStdDev * statistics.results$sig.level.convert.to.z), linetype = 2) + # Upper limit of agreement\n geom_hline(yintercept = statistics.results$bias - (statistics.results$biasStdDev * statistics.results$sig.level.convert.to.z), linetype = 2) + # Lower limit of agreement\n ggtitle(plotTitle) +\n xlab(\"Means\")\n\n # Re-titles the y-axis dependent on which plot option was used\n if (y.plot.mode == \"proportion\") {\n ba.plot <- ba.plot + ylab(\"Difference / Average %\")\n } else {\n ba.plot <- ba.plot + ylab(\"Differences\")\n }\n\n\n ### Function has finished drawing of confidence intervals at this line\n\n # If a normalLow value has been sent, plots this line\n if (normalLow != FALSE) {\n # Check validity of normalLow value to plot line\n if (is.numeric(normalLow) == TRUE) {\n ba.plot <- ba.plot + geom_vline(xintercept = normalLow, linetype = 4, col = 6)\n }\n }\n\n # If a normalHighvalue has been sent, plots this line\n if (normalHigh != FALSE) {\n # Check validity of normalHigh value to plot line\n if (is.numeric(normalHigh) == TRUE) {\n ba.plot <- ba.plot + geom_vline(xintercept = normalHigh, linetype = 4, col = 6)\n }\n }\n\n # If overlapping=TRUE uses geom_count\n # See the param description at the top\n if (overlapping == TRUE) {\n ba.plot <- ba.plot + geom_count()\n }\n\n # If plotProportionalBias switch is TRUE, plots a proportional bias line as well\n if (plotProportionalBias == TRUE) {\n\n # Check for validity of options passed to the plotProportionalBias.se switch\n # As if we throw an invalid option to ggplot it will just stop with an error\n if (plotProportionalBias.se != TRUE && plotProportionalBias.se != FALSE) {\n plotProportionalBias.se <- TRUE\n }\n\n # Plots line\n ba.plot <- ba.plot + ggplot2::geom_smooth(method = \"lm\", se = plotProportionalBias.se)\n } # End of drawing proportional bias line\n\n # Draws marginal histograms if option selected\n # Idea from http://labrtorian.com/tag/bland-altman/\n # REMOVED AS INTRODUCED SOME INCOMPATIBILITIES DEPENDENT ON USERS R VERSION\n # ALSO MASSIVELY INCREASED PACKAGE SIZE\n # if( marginalHistogram == TRUE ) { ba.plot <- ggMarginal( ba.plot , type=\"histogram\" ) }\n\n # Return the ggplot2 output\n return(ba.plot)\n\n # END OF FUNCTION\n}\n\n#' @title Bland-Altman plot limits for R\n#'\n#' @description Works out plot limits for the Bland-Altman plots. Depends on the blandr.statistics function in the package.\n#'\n#' @author Deepankar Datta \n#'\n#' @param statistics.results A list of statistics generated by the blandr.statistics function: see the function's return list to see what variables are passed to this function\n#' @param lowest_y_axis (Optional) Defaults to NULL If given a continuous variable will use this as the lower boundary of the y axis. Useful if need multiple plots with equivalent y-axes.\n#' @param highest_y_axis (Optional) Defaults to NULL If given a continuous variable will use this as the upper boundary of the y axis. Useful if need multiple plots with equivalent y-axes.\n#' @return x_upper The upper limit of the X-axis\n#' @return x_lower The lower limit of the X-axis\n#' @return y_upper The upper limit of the Y-axis\n#' @return y_lower The lower limit of the Y-axis\n#'\n#' @examples\n#' # Generates two random measurements\n#' measurement1 <- rnorm(100)\n#' measurement2 <- rnorm(100)\n#'\n#' # Passes data to the blandr.statistics function to generate Bland-Altman statistics\n#' statistics.results <- blandr.statistics(measurement1, measurement2)\n#'\n#' # Calls the function\n#' blandr.plot.limits(statistics.results)\n#' @export\n\nblandr.plot.limits <- function(statistics.results, lowest_y_axis = FALSE, highest_y_axis = FALSE) {\n\n # Calculates a margin for error - therefore labelled bounds\n x_bounds <- (max(statistics.results$means) - min(statistics.results$means)) * 0.1 ### this is a margin of error for drawing the x axis\n y_bounds <- (max(statistics.results$differences) - min(statistics.results$differences)) *\n 0.1 ### this is a margin of error for drawing the y axis\n\n # Sets limits for plot on the x-axis\n x_upper <- max(statistics.results$means) + x_bounds\n x_lower <- min(statistics.results$means) - x_bounds\n\n # Sets limits for plot on the y-axis\n y_upper <- max(statistics.results$differences) + y_bounds\n y_lower <- min(statistics.results$differences) - y_bounds\n\n # Ensures that y-axis includes the whole range of confidence intervals\n if (y_upper <= statistics.results$upperLOA_upperCI) {\n y_upper <- statistics.results$upperLOA_upperCI + y_bounds\n }\n if (y_lower >= statistics.results$lowerLOA_lowerCI) {\n y_lower <- statistics.results$lowerLOA_lowerCI - y_bounds\n }\n\n # If the user has requested specific limits to the y-axis the following 2 lines execute\n # this\n if (highest_y_axis != FALSE) {\n y_upper <- highest_y_axis\n }\n if (lowest_y_axis != FALSE) {\n y_lower <- lowest_y_axis\n }\n\n return(\n list(x_upper = x_upper, x_lower = x_lower, y_upper = y_upper, y_lower = y_lower) # CLOSE OF LIST\n ) # CLOSE OF RETURN\n\n # END OF FUNCTION\n}\n\n\n#' @title Bland-Altman statistics for R\n#'\n#' @description Bland-Altman analysis function for R. Package created as existing\n#' functions don't suit my needs, and don't generate 95\\% confidence intervals\n#' for bias and limits of agreement. This base function calculates the basic\n#' statistics, and generates return values which can be used in the related\n#' \\code{blandr.display} and \\code{bland.altamn.plot} functions. However\n#' the return results can be used to generate a custom chart if desired.\n#'\n#' @author Deepankar Datta \n#'\n#' @note The function will give similar answers when used on the original Bland-Altman PEFR data sets. They won't be exactly the same as (a) for 95\\% limits of agreement I have used +/-1.96, rather than 2, and (b) the computerised calculation means that the rounding that is present in each step of the original examples does not occur. This will give a more accurate answer, although I can understand why in 1986 rounding would occur at each step for ease of calculation.\n#' @note The function depends on paired values.\n#' @note It currently only can currently work out fixed bias.\n#' @note Improvements for the future: proportional bias charts will need further work\n#'\n#' @note Started 2015-11-14\n#' @note Last update 2016-02-04\n#' @note Originally designed for LAVAS and CVLA\n#'\n#' @references Based on: (1) Bland, J. M., & Altman, D. (1986). Statistical methods for assessing agreement between two methods of clinical measurement. The Lancet, 327(8476), 307-310. http://dx.doi.org/10.1016/S0140-6736(86)90837-8\n#' @references Confidence interval work based on follow-up paper: (2) Altman, D. G., & Bland, J. M. (2002). Commentary on quantifying agreement between two methods of measurement. Clinical chemistry, 48(5), 801-802. http://www.clinchem.org/content/48/5/801.full.pdf\n#'\n#' @param x Either a formula, or a vector of numbers corresponding to the results from method 1.\n#' @param y A vector of numbers corresponding to the results from method 2. Only needed if \\code{X} is a vector.\n#' @param sig.level (Optional) Two-tailed significance level. Expressed from 0 to 1. Defaults to 0.95.\n#' @param LoA.mode (Optional) Switch to change how accurately the limits of agreement (LoA) are calculated from the bias and its standard deviation. The default is LoA.mode=1 which calculates LoA with the more accurate 1.96x multiplier. LoA.mode=2 uses the 2x multiplier which was used in the original papers. This should really be kept at default, except to double check calculations in older papers.\n#'\n#' @return An object of class 'blandr' is returned. This is a list with the following elements:\n#' \\item{means}{List of arithmetic mean of the two methods}\n#' \\item{differences}{List of differences of the two methods}\n#' \\item{method1}{Returns the 'method1' list in the data frame if further evaluation is needed}\n#' \\item{method2}{Returns the 'method2' list in the data frame if further evaluation is needed}\n#' \\item{sig.level}{Significance level supplied to the function}\n#' \\item{sig.level.convert.to.z}{Significance level convert to Z value}\n#' \\item{bias}{Bias of the two methods}\n#' \\item{biasUpperCI}{Upper confidence interval of the bias (based on significance level)}\n#' \\item{biasLowerCI}{Lower confidence interval of the bias (based on significance level)}\n#' \\item{biasStdDev}{Standard deviation for the bias}\n#' \\item{biasSEM}{Standard error for the bias}\n#' \\item{LOA_SEM}{Standard error for the limits of agreement}\n#' \\item{upperLOA}{Upper limit of agreement}\n#' \\item{upperLOA_upperCI}{Upper confidence interval of the upper limit of agreement}\n#' \\item{upperLOA_lowerCI}{Lower confidence interval of the upper limit of agreement}\n#' \\item{lowerLOA}{Lower limit of agreement}\n#' \\item{lowerLOA_upperCI}{Upper confidence interval of the lower limit of agreement}\n#' \\item{lowerLOA_lowerCI}{Lower confidence interval of the lower limit of agreement}\n#' \\item{proportion}{Differences/means*100}\n#' \\item{no.of.observations}{Number of observations}\n#' \\item{regression.equation}{A regression equation to help determine if there is any proportional bias}\n#' \\item{regression.fixed.slope}{The slope value of the regression equation}\n#' \\item{regression.fixed.intercept}{The intercept value of the regression equation}\n#'\n#' @importFrom stats coef cor lm na.omit qnorm qt sd t.test\n#'\n#' @examples\n#'\n#' # Generates two random measurements\n#' measurement1 <- rnorm(100)\n#' measurement2 <- rnorm(100)\n#'\n#' # Generates Bland-Altman statistics data of the two measurements\n#' blandr.statistics(measurement1, measurement2)\n#' @rdname blandr.statistics\n#' @export\nblandr.statistics <- function(x,\n y,\n sig.level = 0.95,\n LoA.mode = 1) {\n\n # This sends to the preparation function, which does some sense checks on the data And\n # makes sure that the values are prepared\n method1 <- x\n method2 <- y\n ba.data <- blandr.data.preparation(method1, method2, sig.level)\n\n # method1 and method2 are the measurements\n means <- (ba.data$method1 + ba.data$method2) / 2\n differences <- ba.data$method1 - ba.data$method2\n bias <- mean(differences)\n biasStdDev <- sd(differences)\n\n # Convert confidence interval to a two-tailed z-value Don't really need this but kept as\n # a remnant of old version to possibly use in the future\n alpha <- 1 - sig.level\n sig.level.two.tailed <- 1 - (alpha / 2)\n sig.level.convert.to.z <- qnorm(sig.level.two.tailed)\n\n # Compute the 95% limits of agreement (based on 1st paper) Don't use the significance\n # level supplied to the function here! (The significance level is for confidence\n # intervals, not for limits of agreement!) We want to know in the sample what limits 95%\n # of the pop resides within The LoA.mode switch can change before the +/-1.96 multiplier\n # used in more recent papers Or the estimated +/-2 multiplier used in the original paper\n # The default is LoA.mode which gives a LoA.multiplier of 1.96. In future we could use an\n # even more precise multipler for limits of agreement.\n if (LoA.mode == 2) {\n LoA.multiplier <- 2\n } else {\n LoA.multiplier <- 1.96\n }\n upperLOA <- bias + (LoA.multiplier * biasStdDev)\n lowerLOA <- bias - (LoA.multiplier * biasStdDev)\n\n # Confidence intervals (based on 2nd paper) Based on significance level supplied\n # (defaults to 95% CI) CI for mean\n biasSEM <- sd(differences) / sqrt(length(differences))\n biasCI <- qt(sig.level.two.tailed, df = length(differences) - 1) * biasSEM\n biasUpperCI <- bias + biasCI\n biasLowerCI <- bias - biasCI\n\n # CI for limits of agreement LOAVariance from Carkeet\n LOAVariance <- ((1 / length(differences)) + ((sig.level.convert.to.z^2) / (2 * (length(differences) -\n 1)))) * biasStdDev^2\n LOA_SEM <- sqrt(LOAVariance)\n LOA_CI <- qt(sig.level.two.tailed, df = length(differences) - 1) * LOA_SEM\n upperLOA_upperCI <- upperLOA + LOA_CI\n upperLOA_lowerCI <- upperLOA - LOA_CI\n lowerLOA_upperCI <- lowerLOA + LOA_CI\n lowerLOA_lowerCI <- lowerLOA - LOA_CI\n\n # Difference/mean proportion\n proportion <- differences / means * 100\n\n # Number of observations\n no.of.observations <- length(means)\n\n # Works out numbers for proportional bias\n # Couldn't figure this out myself So took example code from\n # http://rforpublichealth.blogspot.co.uk/2013/11/ggplot2-cheatsheet-for-scatterplots.html\n m <- lm(differences ~ means)\n a <- signif(coef(m)[1], digits = 2)\n b <- signif(coef(m)[2], digits = 2)\n regression.equation <- paste(\"y(differences) = \", b, \" x(means) + \", a, sep = \"\")\n\n results <-\n list(\n means = means,\n differences = differences,\n method1 = method1,\n method2 = method2,\n sig.level = sig.level,\n sig.level.convert.to.z = sig.level.convert.to.z,\n bias = bias,\n biasUpperCI = biasUpperCI,\n biasLowerCI = biasLowerCI,\n biasStdDev = biasStdDev,\n biasSEM = biasSEM,\n LOA_SEM = LOA_SEM,\n upperLOA = upperLOA,\n upperLOA_upperCI = upperLOA_upperCI,\n upperLOA_lowerCI = upperLOA_lowerCI,\n lowerLOA = lowerLOA,\n lowerLOA_upperCI = lowerLOA_upperCI,\n lowerLOA_lowerCI = lowerLOA_lowerCI,\n proportion = proportion,\n no.of.observations = no.of.observations,\n regression.equation = regression.equation,\n regression.fixed.slope = b,\n regression.fixed.intercept = a\n ) # CLOSE OF LIST\n\n class(results) <- \"blandr\"\n return(results)\n\n # END OF FUNCTION\n}", "meta": {"hexsha": "4b289b7c970461a81187655bec32aafe1708611a", "size": 26765, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gg_blandAltman.r", "max_stars_repo_name": "adamleejohnson/R-ajtools", "max_stars_repo_head_hexsha": "817e4a406599017987392091014603dd476e9716", "max_stars_repo_licenses": ["MIT"], "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/gg_blandAltman.r", "max_issues_repo_name": "adamleejohnson/R-ajtools", "max_issues_repo_head_hexsha": "817e4a406599017987392091014603dd476e9716", "max_issues_repo_licenses": ["MIT"], "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/gg_blandAltman.r", "max_forks_repo_name": "adamleejohnson/R-ajtools", "max_forks_repo_head_hexsha": "817e4a406599017987392091014603dd476e9716", "max_forks_repo_licenses": ["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.052064632, "max_line_length": 472, "alphanum_fraction": 0.6983000187, "num_tokens": 6743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29973144312736716}} {"text": "##\n## Replicating the analyses in Koster & Leckie (2014) - \"Food sharing networks in lowland Nicaragua: An application of the social relations model to count data\"\n## using the R interface to WinBUGS\n##\n## Author: Matthew Gwynfryn Thomas (@matthewgthomas)\n## URL: http://matthewgthomas.co.uk\n## Date: 16 April 2015\n##\n## Before running the code, do these:\n## 1. install WinBUGS from: http://www.mrc-bsu.cam.ac.uk/software/bugs/the-bugs-project-winbugs/\n## - install patch for version 1.4.3\n## - load the license key\n##\n## 2. install the R packages R2WinBUGS and memisc\n##\n## 3. download the supplementary data files from http://dx.doi.org/10.1016/j.socnet.2014.02.002\n## and unzip them into your R working directory\n##\n## Note: This code uses a modified version of Koster & Leckie's \"model1.txt\" model specification.\n## The only difference is that in \"model1_mgt.txt\" the intercept 'beta' is no longer an array.\n## (The diff in this GitHub project shows the exact change made.)\n##\n##\n## Copyright (c) 2015 Matthew Gwynfryn Thomas\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#install.packages(\"R2WinBUGS\", \"memisc\")\nlibrary(R2WinBUGS)\nlibrary(memisc) # for the mtables() model summariser function\n\n# this file contains a summariser function for BUGS social relations models\n# see: https://gist.github.com/matthewgthomas/beef5ee7a434d3da934d\nsource(\"https://gist.githubusercontent.com/matthewgthomas/beef5ee7a434d3da934d/raw/06fbdc38003b7648b503f7dc0464549e053c84ad/getSummary.bugs.r\")\n\nwinbugs_dir = \"C:/Program Files/WinBUGS14/\" # change this to your WinBUGS directory\n\n\n###############################################################\n## Load and prepare data\n##\ndyads = read.csv(\"dyads.csv\")\nhh = read.csv(\"households.csv\")\n\n# remove \"did\" (dyad ID) and \"hid\" (household ID)\ndyads$did = NULL\nhh$hid = NULL\n\n# convert the dyads and households column names into one list\ndata = c(as.list(colnames(dyads)), as.list(colnames(hh)))\n\n# add \"R_gr\" (scale matrix associated with the Wishart prior for the giver-receiver covariance matrix)\ndata = c(data, \"R_gr\")\n\n# make R_gr scale matrix\nR_gr = matrix(c(1,0,0,1), nrow=2, ncol=2)\n\n# create separate lists in the workspace for each column in the dyads and hh dataframes \n## code from: http://stackoverflow.com/questions/16052239/split-a-data-frame-by-columns-and-storing-each-column-as-an-object-with-the-colu\ninvisible(lapply(names(dyads), function(x) assign(x, dyads[, x], envir = .GlobalEnv)))\ninvisible(lapply(names(hh), function(x) assign(x, hh[, x], envir = .GlobalEnv)))\n\n# what do we want out of the model?\nparameters <- c(\"beta\", \"COV_gr\", \"COV_dd\", \"gr\", \"dd\", \"rho_dd\", \"sigma_dd\", \"sigma2_d\")\n\n\n###############################################################\n## Model 1\n##\ndata_m1 = data[c(1:5, length(data))] # keep only hidA, hidB, giftsAB, giftsBA, offset and R_gr\n\n# specify initial values for the model parameters\ninits_m1 = function() {\n list (beta = 0, # only intercept in this model\n TAU_gr = matrix(c(2,0,0,2), nrow=2, ncol=2), # giver-receiver precision matrix\n tau_d = 1.333, # relationship precision == relationship variance of 0.75 (1 / tau_d)\n rho_dd = 0.500 # dyadid reciprocity\n )\n}\n\n# run the model\nmodel1 = bugs(data_m1, inits_m1, parameters, \"model1_mgt.txt\", \n n.chains=1, n.burnin=50000, n.iter=100000, n.thin=100, \n debug=F, bugs.directory=winbugs_dir)\n\n\n###############################################################\n## Model 2\n##\n# specify initial values for the model parameters\ninits_m2 = function() {\n list (beta = rep(0, 17), # 17 coefficients = 0\n TAU_gr = matrix(c(2,0,0,2), nrow=2, ncol=2), # giver-receiver precision matrix\n tau_d = 1.333, # relationship precision == relationship variance of 0.75 (1 / tau_d)\n rho_dd = 0.500 # dyadid reciprocity\n )\n}\n\n# run the model\nmodel2 = bugs(data, inits_m2, parameters, \"model2.txt\", \n n.chains=1, n.burnin=50000, n.iter=100000, n.thin=100, \n debug=F, bugs.directory=winbugs_dir)\n\n\n###############################################################\n## Show output of models (Table 2 in Koster & Leckie 2014)\n##\nplot(model1)\nplot(model2)\n\nbugs.summary = mtable(\"Model 1\"=model1, \"Model 2\"=model2, \n coef.style=\"ci.se.horizontal\", digits=2)\nrelabel(bugs.summary, \n \"beta[1]\" = \"Intercept\",\n \"beta[2]\" = \"Giver – Game\",\n \"beta[3]\" = \"Giver – Fish\",\n \"beta[4]\" = \"Giver – Pigs\",\n \"beta[5]\" = \"Giver – Wealth\",\n \"beta[6]\" = \"Receiver – Game\",\n \"beta[7]\" = \"Receiver – Fish\",\n \"beta[8]\" = \"Receiver – Pigs\",\n \"beta[9]\" = \"Receiver – Wealth\",\n \"beta[10]\" = \"Receiver – Pastors\",\n \"beta[11]\" = \"Relationship – Relatedness 1\",\n \"beta[12]\" = \"Relationship – Relatedness 2\",\n \"beta[13]\" = \"Relationship – Relatedness 3\",\n \"beta[14]\" = \"Relationship – Relatedness 4\",\n \"beta[15]\" = \"Relationship – Distance (log transformed)\",\n \"beta[16]\" = \"Relationship – Association index\",\n \"beta[17]\" = \"Relationship – Giver 1 & Receiver 25\"\n )\n", "meta": {"hexsha": "b954fd2c32b06a4df0d80fccaa1d42415289f0b0", "size": 6239, "ext": "r", "lang": "R", "max_stars_repo_path": "koster and leckie winbugs.r", "max_stars_repo_name": "matthewgthomas/social-relations-model-r", "max_stars_repo_head_hexsha": "c77f3195d88af1e683d3e261d05330a3676a4e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-01-11T20:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-11T20:43:32.000Z", "max_issues_repo_path": "koster and leckie winbugs.r", "max_issues_repo_name": "matthewgthomas/social-relations-model-r", "max_issues_repo_head_hexsha": "c77f3195d88af1e683d3e261d05330a3676a4e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "koster and leckie winbugs.r", "max_forks_repo_name": "matthewgthomas/social-relations-model-r", "max_forks_repo_head_hexsha": "c77f3195d88af1e683d3e261d05330a3676a4e5a", "max_forks_repo_licenses": ["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.8724832215, "max_line_length": 160, "alphanum_fraction": 0.646097131, "num_tokens": 1712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.29908460970036255}} {"text": "#!/usr/bin/env Rscript\noptions(warn=-1)\n\n# CLI args\nlibrary(\"optparse\")\n\n# Set opts\nopt.list = list(\nmake_option(c(\"-i\", \"--input\"), type=\"character\", default=NULL,\n help=\"input dataset file name\", metavar=\"character\"),\nmake_option(c(\"-o\", \"--output\"), type=\"character\", default=\"output\",\n help=\"output file set base name [default = %default]\", metavar=\"character\"),\nmake_option(c(\"-a\", \"--algorithm\"), type=\"character\", default=\"bf\",\n help=\"search algorithm to be used [fw | bf | spfa]\", metavar=\"character\"),\nmake_option(c(\"-b\", \"--benchmark\"), type=\"logical\", action=\"store_true\", default=FALSE,\n help=\"benchmark all algorithms and show metrics (makes -a irrelevant)\")\n)\n\n# Parse opts\nopt.parser = OptionParser(option_list=opt.list)\nopt = parse_args(opt.parser)\n\n# Treat errors\nif (is.null(opt$input)) {\n print_help(opt.parser)\n stop(\"Input dataset file must be specified\\n\", call.=F)\n}\n\n# Source scripts\nsource(\"fw-arbitrate.r\")\nsource(\"bf-arbitrate.r\")\n\n# Read input data\ninput.edges = as.matrix(read.table(opt$input))\ninput.nodes = unique(matrix(input.edges[,1:2], ncol=1))\n\n# Adapt edge weights\nweights.new = -log(as.numeric(as.character(input.edges[,3])))\nweights.new[which(weights.new==-Inf)] = 0 # cleaning -logs\ninput.edges.new = cbind(input.edges[,1:2], weights.new)\n\nret = NULL\n\n# IF BENCHMARKING, measure all algorithms\nif (opt$benchmark) {\n cat(\"\\nRunning benchmark for all algorithms...\\n\")\n lines = c()\n nruns = 15\n\n # Message\n line = \"Benchmarking Floyd-Warshall\\n\"\n lines = c(lines, line)\n cat(\"\\n \", line)\n\n # Run FW\n times.fw = c()\n for (i in 1:nruns) {\n start = Sys.time()\n ret = fw.find(input.edges.new, input.edges, debug=F)\n time = Sys.time() - start\n\n # Record\n times.fw = c(times.fw, time)\n line = paste0(\" Execution \", as.character(i), \": \", as.character(time), \" seconds\\n\")\n lines = c(lines, line)\n cat(line)\n }\n\n ## Include the dummy node every possible\n ## negative cycle is made reachable from\n ## it (For the Bellman-Ford based algorithms)\n voids = cbind(rep(\"VOIDCURRENCY\", NROW(input.nodes)),\n input.nodes, rep(0, NROW(input.nodes)))\n input.edges = rbind(voids, as.matrix(input.edges))\n input.edges.new = rbind(voids, input.edges.new)\n\n # Message\n line = \"Benchmarking Bellman-Ford\\n\"\n lines = c(lines, line)\n cat(\"\\n \", line)\n\n # Run BF\n times.bf = c()\n for (i in 1:nruns) {\n start = Sys.time()\n ret = bf.find(input.edges.new, input.edges, debug=F)\n time = Sys.time() - start\n\n # Record\n times.bf = c(times.bf, time)\n line = paste0(\" Execution \", as.character(i), \": \", as.character(time), \" seconds\\n\")\n lines = c(lines, line)\n cat(line)\n }\n\n # Message\n line = \"Benchmarking SPFA\\n\"\n lines = c(lines, line)\n cat(\"\\n \", line)\n\n # Run SPFA\n times.spfa = c()\n for (i in 1:nruns) {\n start = Sys.time()\n ret = bf.spfa(input.edges.new, input.edges, debug=F)\n time = Sys.time() - start\n\n # Record\n times.spfa = c(times.spfa, time)\n line = paste0(\" Execution \", as.character(i), \": \", as.character(time), \" seconds\\n\")\n lines = c(lines, line)\n cat(line)\n }\n\n times.fw = as.numeric(times.fw)\n times.bf = as.numeric(times.bf)\n times.spfa = as.numeric(times.spfa)\n means = as.numeric(c(mean(times.fw), mean(times.bf), mean(times.spfa)))\n sdevs = as.numeric(c(sd(times.fw), sd(times.bf), sd(times.spfa)))\n\n # Prepare output\n out.summary = paste0(opt$output, \".summary\")\n out.plot = paste0(opt$output, \".plot.png\")\n\n # Output summary\n lines = c(lines, \"\\nAverage times and standard deviations:\\n\")\n timedata = as.matrix(cbind(means, sdevs))\n colnames(timedata) = c(\"Mean\", \"SD\")\n rownames(timedata) = c(\"Floyd-Warshall\", \"Bellman-Ford\", \"SPFA\")\n write(lines, out.summary)\n capture.output(print(timedata), file=out.summary, append=T)\n\n # Prepare plot\n png(out.plot)\n xaxis = 1:NROW(means)\n plot(xaxis, means, xlim=range(c(0, NROW(means) + 1)),\n ylim=range(c(means-sdevs, means+sdevs)), pch=20,\n xlab=\"Measures for FW, BF and SPFA respectively\",\n ylab=\"Mean of 15 runs +/- SD in seconds\",\n main=\"Algorithm performance measures\")\n\n # Hachy arrows\n arrows(xaxis, means-sdevs, xaxis, means+sdevs, length=0.05, angle=90, code=3)\n text(x=xaxis, y=means, labels=c(\"Floyd-Warshall\", \"Bellman-Ford\", \"SPFA\"), pos=4)\n dev.off()\n\n # OTHERWISE, run method specified via --algorithm\n cat(\"\\n-> Execution summmary written to\", out.summary, \"\\n\")\n cat(\"-> Plot image written to\", out.plot, \"\\n\\n\")\n browseURL(out.plot)\n} else {\n\n if (opt$algorithm == \"fw\") {\n\n # Just run\n ret = fw.find(input.edges.new, input.edges)\n\n } else if (opt$algorithm == \"bf\") {\n\n ## Include the dummy node every possible\n ## negative cycle is made reachable from it\n voids = cbind(rep(\"VOIDCURRENCY\", NROW(input.nodes)),\n input.nodes, rep(0, NROW(input.nodes)))\n input.edges = rbind(voids, as.matrix(input.edges))\n input.edges.new = rbind(voids, input.edges.new)\n\n # Run\n ret = bf.find(input.edges.new, input.edges)\n\n } else if (opt$algorithm == \"spfa\") {\n\n ## Include the dummy node every possible\n ## negative cycle is made reachable from it\n voids = cbind(rep(\"VOIDCURRENCY\", NROW(input.nodes)),\n input.nodes, rep(0, NROW(input.nodes)))\n input.edges = rbind(voids, as.matrix(input.edges))\n input.edges.new = rbind(voids, input.edges.new)\n\n # Run\n ret = bf.spfa(input.edges.new, input.edges)\n\n } else {\n stop(\"No such algorithm implemented\\n\", call.=F)\n }\n\n # Ready output file names\n out.nodes = paste0(opt$output, \".nodes\")\n out.cycle = paste0(opt$output, \".cycle\")\n out.summary = paste0(opt$output, \".summary\")\n\n # Write out everything\n cycle = cbind(ret$cycle[1:(NROW(ret$cycle)-1)], ret$cycle[2:NROW(ret$cycle)])\n write.table(ret$nodes, out.nodes, row.names=F, col.names=F, sep=\"\\t\", quote=F)\n write.table(cycle, out.cycle, row.names=F, col.names=F, sep=\"\\t\", quote=F)\n\n # This is ugly, sorry\n write(paste0(\"Starting from 1 unit of \", cycle[1,1], \", performing these transactions\\n(or, in stock terms, SELLING or BIDDING these PAIRS) can\\npossibly grant you back\", ret$profit, \" \", cycle[1,1], \":\\n\"), out.summary)\n write.table(cycle, out.summary, row.names=F, col.names=F, sep=\"/\", quote=F, append=T)\n\n # Final messages\n cat(\"\\n-> Graph nodes written to\", out.nodes, \"\\n\")\n cat(\"-> Negative cycle edges written to\", out.cycle, \"\\n\")\n cat(\"-> Execution summmary written to\", out.summary, \"\\n\\n\")\n}\n\n# Reset warnings\noptions(warn=-1)\n", "meta": {"hexsha": "a098b6d4d882a5ecf6d184f850eccd9204ab79ce", "size": 6903, "ext": "r", "lang": "R", "max_stars_repo_path": "assignment1/main.r", "max_stars_repo_name": "felipecustodio/ai", "max_stars_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-03T03:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-03T03:12:39.000Z", "max_issues_repo_path": "assignment1/main.r", "max_issues_repo_name": "felipecustodio/ai", "max_issues_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-05-08T11:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-19T03:12:42.000Z", "max_forks_repo_path": "assignment1/main.r", "max_forks_repo_name": "felipecustodio/ai", "max_forks_repo_head_hexsha": "55f332d7070b79833d005ee2c2243c9e67d6e7e2", "max_forks_repo_licenses": ["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.1875, "max_line_length": 224, "alphanum_fraction": 0.6093003042, "num_tokens": 1871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.2967681312105448}} {"text": "#=================================================================================================#\n# utilities.r\n# Generic utility methods\n# Adam Erickson, PhD, Washington State University\n# Contact: adam.michael.erickson@gmail.com\n# March 14, 2019\n# License: Apache 2.0\n#\n# Copyright 2019 Washington State University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#=================================================================================================#\n\n#' Estimate empirical PDF and sample from CDF; bw = SD of density kernel; value range = 0:1.\n#' @param x Numeric vector of empirical values.\n#' @param n Numeric number of samples to draw.\n#' @param from Numeric minimum sample value.\n#' @param to Numeric maximum sample value.\n#' @param bw Numeric smoothing bandwidth or standard deviation for Gaussian kernel.\n#' @return Numeric vector.\nsample_empirical_cdf = function(x, n, from=0, to=1, bw=0.1, ...) {\n x = x[!is.na(x) & is.finite(x)]\n if (length(x) < 1) { return(NA) }\n x_pdf = stats::density(x=x, kernel=\"gaussian\", from=from, to=to, bw=bw, n=512)\n return(stats::approx(cumsum(x_pdf$y)/sum(x_pdf$y), x_pdf$x, stats::runif(n=n))$y)\n}\n\n#' Helper function to calculate mean from arbitrary inputs.\n#' @param ... Numeric vector or multiple numeric arguments.\n#' @return Numeric value.\nmean0 = function(...) {\n x = as.numeric(unlist(list(...)))\n return(sum(x, na.rm=TRUE) / length(x))\n}\n\n#' Coefficient of determination (R2) helper method.\n#' @note Different methods of calculating R2 produce slightly different results.\n#' @note Similar to Nash-Sutcliffe efficiency coefficient in the general case.\n#' @param x Numeric observation values.\n#' @param y Numeric prediction values.\n#' @return Numeric value.\nr_squared = function(x, y) {\n if (length(x) != length(y)) { stop(\"Lengths of y and y_hat differ\") }\n #return(1 - sum((x-y)^2) / sum((x-mean(x))^2))\n #return(cov(x, y, method=\"pearson\") / (sd(x) * sd(y)))\n return(cor(x, y, method=\"pearson\")^2)\n}\n\n#' Nash-Sutcliffe efficiency coefficient (NSE) helper method.\n#' @note Implementation based on R2 in Nash and Sutcliffe (1970) River flow forecasting through conceptual models.\n#' @note This metric is \"analogous to the coefficent of determination.\"\n#' @param x Numeric observation values.\n#' @param y Numeric prediction values.\n#' @return Numeric value.\nnse = function(x, y) {\n if (length(x) != length(y)) { stop(\"Lengths of y and y_hat differ\") }\n return((sum((x-mean(x))^2) - sum((x-y)^2)) / sum((x-mean(x))^2))\n}\n\n#' Root mean squared error (RMSE) helper method.\n#' @param x Numeric observation values.\n#' @param y Numeric prediction values.\n#' @return Numeric value.\nrmse = function(x, y) {\n if (length(x) != length(y)) { stop(\"Lengths of y and y_hat differ\") }\n return(sqrt(sum((y-x)^2) / length(x)))\n}\n\n#' Mean absolute error (MAE) helper method.\n#' @param x Numeric observation values.\n#' @param y Numeric prediction values.\n#' @return Numeric value.\nmae = function(x, y) {\n if (length(x) != length(y)) { stop(\"Lengths of y and y_hat differ\") }\n return(mean(abs(y-x)))\n}\n\n#' Mean error (ME) helper method.\n#' @note Equivalent to bias.\n#' @param x Numeric observation values.\n#' @param y Numeric prediction values.\n#' @return Numeric value.\nme = function(x, y) {\n if (length(x) != length(y)) { stop(\"Lengths of y and y_hat differ\") }\n return(mean(y-x))\n}\n\n#' Helper method for listing files.\n#' @note List files in folder with extension matching pattern\n#' @param folder Character folder path containing files.\n#' @param filnames Character vector of filenames to search.\n#' @param extension Character file extension to search.\n#' @return Character vector of files matching pattern.\nget_files = function(path, filenames, extension, ...) {\n pattern = paste0(\"^(\", paste(filenames, collapse=\"|\"), \").*?\", \".\", extension, \"$\")\n return(list.files(path=path, pattern=pattern, full.names=TRUE))\n}\n\n#' Helper method for moving multiple files.\n#' @param files Character vector of file paths\n#' @param to Character directory target\n#' @param recursive Boolean recursive switch\n#' @param overwrite Boolean overwrite switch\n#' @return 0\nfiles_move = function(files, to, recursive=TRUE, overwrite=TRUE) {\n if (!dir.exists(file.path(to))) { dir.create(path=file.path(to), recursive=recursive) }\n file.copy(from=files, to=file.path(to), recursive=recursive, overwrite=overwrite, copy.mode=TRUE)\n file.remove(files)\n return(invisible(0))\n}\n\n#' Helper method for moving directories.\n#' @param from Character directory origin\n#' @param to Character directory target\n#' @param recursive Boolean recursive switch\n#' @param overwrite Boolean overwrite switch\n#' @return 0\ndir_move = function(from, to, recursive=TRUE, overwrite=TRUE) {\n if (!dir.exists(paths=file.path(to))) { dir.create(path=file.path(to), recursive=recursive) }\n files = list.files(from, full.names=TRUE, recursive=FALSE)\n file.copy(from=files, to=file.path(to), recursive=recursive, overwrite=overwrite, copy.mode=TRUE)\n unlink(file.path(from), recursive=recursive)\n return(invisible(0))\n}\n\n#' Helper method for downloading files\n#' @note Download observation data and add to list\n#' @param url Character url to a file.\n#' @param destination Character path to save downloaded file.\ndownload_file = function(url, destination) {\n curl::curl_download(url=url, destfile=destination, quiet=FALSE, mode=\"w\")\n message(paste(\"Download successful:\", destination))\n return(invisible(0))\n}\n\n#' Helper method to interpolate points to raster\n#' @param x Numeric x,y coordinates or n-dimensional vector of predictor variables.\n#' @param y Numeric 1-d vector for target variable.\n#' @param xi Numeric x,y coordinates or n-dimensional data.frame() for imputing values.\n#' @param method Character method selection.\n#' @param fun Function for caret trainControl or RandomFields model.\n#' @param multicore Boolean flag for multicore computation using OpenMP.\n#' @param spatial Boolean flag for whether xi contains x,y coordinates.\n#' @param proj4string Character Proj4 projection string for raster image.\n#' @param plot Boolean flag for plotting results.\n#' @examples\n#' Classification\n#' data(iris)\n#' intrain = caret::createDataPartition(iris$Species, p=0.7, list=FALSE)\n#' train = iris[ intrain,]\n#' test = iris[-intrain,]\n#' x = train[,1:4]\n#' y = train[,5]\n#' xi = test[,1:4]\n#' yi = test[,5]\n#' p = interpolate_points(x=x, y=y, xi=xi, method=\"knn\", multicore=FALSE, spatial=FALSE, plot=TRUE)\n#' sum(p == yi) / length(p)\n#' p = interpolate_points(x=x, y=y, xi=xi, method=\"xgbTree\", multicore=TRUE, spatial=FALSE, plot=TRUE)\n#' sum(p == yi) / length(p)\n#' Spatial regression\n#' x = cbind(x=runif(100, 1, 100), y=runif(100, 1, 100))\n#' y = rowSums(xy)\n#' xi = expand.grid(x=seq(1, 100, length.out=100), y=seq(1, 100, length.out=100))\n#' p = interpolate_points(x=x, y=y, xi=xi, method=\"knn\", fun=NA, multicore=FALSE, spatial=TRUE,\n#' proj4string=\"+proj=longlat +ellps=WGS84 +datum=WGS84\", plot=TRUE)\n#' or\n#' p = interpolate_points(x=x, y=y, xi=xi, method=\"rf\", fun=NA, multicore=TRUE, spatial=TRUE,\n#' proj4string=\"+proj=longlat +ellps=WGS84 +datum=WGS84\", plot=TRUE)\n#' Kriging\n#' xi = data.frame(x=seq(1, 100, length.out=100), y=seq(1, 100, length.out=100))\n#' fun = RandomFields::RMexp() + RandomFields::RMtrend(mean=NA)\n#' fun = ~1 + RandomFields::RMwhittle(scale=NA, var=NA, nu=NA) + RandomFields::RMnugget(var=NA)\n#' p = interpolate_points(x=x, y=y, xi=xi, method=\"kriging\", fun=fun, multicore=FALSE, spatial=TRUE,\n#' proj4string=\"+proj=longlat +ellps=WGS84 +datum=WGS84\", plot=TRUE)\ninterpolate_points = function(x, y, xi=NA, method=\"knn\", fun=NA, multicore=FALSE, spatial=TRUE,\n proj4string=\"+proj=longlat +ellps=WGS84 +datum=WGS84\", plot=FALSE, ...) {\n if (method != \"kriging\") {\n if (multicore == TRUE) { doMC::registerDoMC(cores=parallel::detectCores()-1) }\n if (!is.na(fun)) {\n ctl = fun\n } else {\n ctl = caret::trainControl(method=\"repeatedcv\", number=3, repeats=3, search=\"grid\")\n }\n mod = caret::train(x, y, method=method, trControl=ctl, preProcess=c(\"center\",\"scale\"), tuneLength=10)\n yhat = predict(mod, newdata=xi)\n if (spatial == TRUE) {\n coords = colnames(x) %in% c(\"x\",\"y\",\"lat\",\"lon\",\"latitude\",\"longitude\")\n proj4crs = sp::CRS(proj4string)\n yhat = sp::SpatialPixelsDataFrame(points=sp::SpatialPoints(xi[,coords]), data=data.frame(y=yhat),\n proj4string=proj4crs)\n }\n } else if (method == \"kriging\" & spatial == TRUE) {\n if (length(unique(round(diff(xi[,1]),6))) > 2 | length(unique(round(diff(xi[,2]),6))) > 2) {\n stop(\"Please enter an evenly spaced grid for xi parameter\")\n }\n if (any(duplicated(xi[,1]) | duplicated(xi[,2]))) {\n warning(\"Parameter xi appears to be a grid, creating list of unique coordinates\", immediate.=TRUE)\n xi = data.frame(x=min(xi[,1]):max(xi[,1]), y=min(xi[,2]):max(xi[,2]))\n }\n proj4crs = sp::CRS(proj4string)\n coords = colnames(x) %in% c(\"x\",\"y\",\"lat\",\"lon\",\"latitude\",\"longitude\")\n spdf = sp::SpatialPointsDataFrame(coords=x[,coords], data=data.frame(y=y), proj4string=proj4crs)\n fit = RandomFields::RFfit(fun, data=spdf)\n yhat = RandomFields::RFinterpolate(fit, x=xi[,coords], grid=TRUE, data=spdf)\n } else {\n stop(\"Parameters incorrectly specified\")\n }\n if (spatial == TRUE) {\n yhat = raster::raster(yhat)\n if (plot == TRUE) { raster::plot(yhat, col=viridis::magma(256)) }\n }\n return(yhat)\n}\n\n#' Helper method to generate raster image\n#' @note Used to generate random maps, point value maps, or matrix maps.\n#' @note A RandomFields model can also be passed to generator.\n#' @param values Numeric matrix, single value, \"random\", or \"scrf\" for spatially correlated random fields.\n#' @param path Character file path for saving the result.\n#' @param format Character raster file format.\n#' @param params Optional numeric vector of parameters to pass to distribution function.\n#' @param generator Optional statistical generator for drawing random values. Default is runif().\n#' @param size Optional numeric vector of length 2 for the n*n size of the map.\n#' @param extent Optional numeric vector of length 4 for the image bounds.\n#' @param crs Optional character vector proj4-compatible coordinate reference system.\n#' @examples\n#' f = \"/Users/julia/rasters\"\n#' g = RandomFields::RMexp(var=3, scale=5) + RandomFields::RMnugget(var=3)\n#' r = generate_raster(\"randomfield\", size=c(100,100), generator=g, filename=f)\ngenerate_raster = function(values=\"random\", size=c(10,10), bounds=c(-1,1,-1,1), generator=runif,\n params=c(prod(size)), filename=NA, format=\"GTiff\",\n proj4string=\"+proj=longlat +ellps=WGS84 +datum=WGS84\", plot=TRUE, ...) {\n if (values != \"random\" & class(values) == \"numeric\" & class(values) != \"matrix\") {\n if (length(values) != prod(size)) { stop(\"Number of values must equal the product of size\") }\n values = matrix(values, nrow=size[1], ncol=size[2])\n } else if (values == \"random\" & class(generator) == \"function\") {\n values = do.call(generator, as.list(params))\n values = matrix(values, nrow=size[1], ncol=size[2])\n } else if (values == \"randomfields\" & class(generator)[1] == \"RMmodel\") {\n x = 1:size[1]\n y = 1:size[2]\n values = RandomFields::RFsimulate(generator, x, y, grid=TRUE)\n } else {\n stop(\"Parameters incorrectly specified\")\n }\n ri = raster::raster(values)\n raster::extent(ri) = bounds\n raster::projection(ri) = raster::crs(proj4string)\n if (!is.na(filename) == TRUE) { raster::writeRaster(ri, filename=filename, format=format) }\n if (plot == TRUE) { raster::plot(ri, col=viridis::magma(256)) }\n return(ri)\n}\n", "meta": {"hexsha": "17fa8ef6e9e272fbda4ed759762949425e0e1ff9", "size": 12284, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/utilities.r", "max_stars_repo_name": "adam-erickson/ecosystem-model-comparison", "max_stars_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-02T13:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T11:36:59.000Z", "max_issues_repo_path": "scripts/utilities.r", "max_issues_repo_name": "adam-erickson/ecosystem-model-comparison", "max_issues_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "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": "scripts/utilities.r", "max_forks_repo_name": "adam-erickson/ecosystem-model-comparison", "max_forks_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "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.7072243346, "max_line_length": 114, "alphanum_fraction": 0.6708726799, "num_tokens": 3286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.2964449579727892}} {"text": "###########################################################\n## An intro to time series forecasting with ARIMA ##\n## R Ladies London 24 October 2019 workshop ##\n## Sample code by julia.shen1@lshtm.ac.uk ##\n###########################################################\n\n\n### 0. Load required packages + data and set filepath ###\n\n# install.packages(c('tidyverse', 'forecast', 'here'))\n\nlibrary(tidyverse) \nlibrary(forecast)\nlibrary(here)\n\n# set_here() # sets filepath to folder currently containing this script\n\ndata_orig <- read.csv(here::here('ARIMA-intro.csv')) # load example data\n\n\n### 1. Clean up date formats for an analysis file ###\n\nstr(data_orig) # examine data structure\nlevels(data_orig$�..month) # note \"�..month\" imported as an icky factor var\n\n# specify a new date variable with day-month-year to replace the disaggregated factor vars\n# nb NHS sitrep data from last Thursday of each month, so pick arbitrary consistent date 24\n# nb Green et al (2017) analysis is based on 2010/08 to 2015/03, as reflected in plots etc\n\ndata_use <- data_orig %>% \n mutate(�..month=as.character(�..month)) %>% # change factor var to a string\n mutate(date=paste0('24', �..month, year, sep = \"\", collapse = NULL)) %>% #combine strings\n mutate(date=as.Date(date, \"%d%B%Y\")) # convert string to date\n\n# str(data_use) # check this worked and some cleanup below\n\ndata_use <- data_use %>% \n select(-�..month, -year)\n\nrm(data_orig)\n\n\n### 2. Create some analysis variables and look at summary descriptives ###\n\ndata_use <- data_use %>% \n mutate(annual_mort = out_deaths_total * 1000 / ONS_pop_est, \n dtoc_days_rate = exp_days_dtoc * 1000 / ONS_pop_est,\n dtoc_pts_rate = exp_patients_dtoc * 100000 / ONS_pop_est, \n dtoc_days_percapita = exp_days_dtoc / exp_patients_dtoc, \n prop_acute_days = exp_days_acute / exp_days_dtoc, \n prop_acute_patients = exp_patients_acute / exp_patients_dtoc)\n\nsummary(data_use) # note data descriptives, and also the NAs. What data are missing?\n\n# data_use <- data_use %>%\n# filter(!is.na(ONS_pop_est)) # if you want to drop 8 missing obs in 2019 \n\n\n### 3. Explore descriptive plots ###\n\n# Examine trends in absolute COUNTS over time for the exposures and outcome of interest\n# for DAYS of delayed transfers of care vs. deaths\nggplot(data=data_use, aes(x=date)) +\n ggtitle(\"Trends in English mortality and NHS DAYS delayed\") +\n geom_line(aes(y=out_deaths_total), color=\"darkred\") +\n geom_line(aes(y=exp_days_dtoc), color=\"black\") +\n geom_line(aes(y=exp_days_acute), color=\"black\", linetype=\"longdash\") +\n geom_line(aes(y=exp_days_nonacute), color=\"black\", linetype=\"dotted\") +\n xlab(\"Time\") + ylab(\"Total counts of deaths and dtoc days\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\n# for PATIENTS with dtocs vs. deaths\nggplot(data=data_use, aes(x=date)) +\n ggtitle(\"Trends in English mortality and NHS PATIENTS delayed\") +\n geom_line(aes(y=out_deaths_total), color=\"darkred\") + # nb could rescale deaths here for viz\n geom_line(aes(y=exp_patients_dtoc), color=\"blue\") +\n geom_line(aes(y=exp_patients_acute), color=\"blue\", linetype=\"longdash\") +\n geom_line(aes(y=exp_patients_nonacute), color=\"blue\", linetype=\"dotted\") +\n xlab(\"Time\") + ylab(\"Total counts of deaths and dtoc patients\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\n# Examine seasonal \"trends\" in per capita days hospitalised (days of delay per patient delayed)\nggplot(data=data_use, aes(x=date)) +\n geom_line(aes(y=dtoc_days_percapita), color=\"darkblue\", linetype=\"dotdash\") +\n xlab(\"Time\") + ylab(\"Mean days of delay per hospitalised patient\") + \n scale_x_date(minor_breaks=seq(as.Date(\"2010/08/24\"), as.Date(\"2019/08/24\"), by=\"months\"), \n breaks=seq(as.Date(\"2010/08/24\"), as.Date(\"2019/08/24\"), by=\"quarter\")) + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\") + \n theme(axis.text.x = element_blank())\n#... After inspecting this as well as the table, perhaps find that values are suspiciously round\n#... Note nevertheless global dips during end-of-year (holidays)\n\n\n# Examine the created analysis vars to assess summary change in RISK over time\n# The below is constant for population growth and thus (crudely) factors in demographics\nggplot(data=data_use, aes(x=date, y=c(annual_mort, dtoc_days_rate, dtoc_pts_rate))) +\n ggtitle(\"Trend in English risk RATES\") +\n geom_line(aes(y=annual_mort), color=\"darkred\", linetype=\"dotdash\") +\n geom_line(aes(y=dtoc_days_rate), color=\"black\", linetype=\"dotdash\") +\n xlab(\"Time\") + ylab(\"Mortality (red) and DTOC days (black) per 1000 pop.\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\nggplot(data=data_use, aes(x=date, y=c(annual_mort, dtoc_days_rate, dtoc_pts_rate))) +\n ggtitle(\"Trend in English RISK RATES\") +\n geom_line(aes(y=annual_mort*10), color=\"darkred\", linetype=\"dotdash\") + #nb scale factor for viz\n geom_line(aes(y=dtoc_pts_rate), color=\"blue\", linetype=\"dotdash\") +\n xlab(\"Time\") + ylab(\"Mortality (red) per 10000 pop. and DTOC patients (blue) per 100000 pop.\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\n\n### 4. Create time series objects and examine potential seasonality in plots ###\n\n# Cut a version of the dataset from Green et al paper, to test replication\ndata_green <- data_use %>% \n filter(date<\"2016-04-24\")\n\n# Create some time series objects\n#... Specify a monthly time series for DTOC days and deaths, starting from August 2010\nts_dtocdays_all <- ts(data_use$exp_days_dtoc, frequency=12, start=c(2010, 8))\nts_deaths_all <- ts(data_use$out_deaths_total, frequency=12, start=c(2010, 8))\n#... Do the same for the retrospective Green 'training' data\nts_dtocdays_green <- ts(data_green$exp_days_dtoc, frequency=12, start=c(2010, 8))\nts_deaths_green <- ts(data_green$out_deaths_total, frequency=12, start=c(2010, 8))\n\n# In principle, one can use tsclean() to identify & smooth outliers but this doesn't apply here\n# tsclean(ts_dtocdays_all)\n\n# Generate MOVING AVERAGES for any time series and see how this smooths trends\n#... for deaths as outcome of interest\ndata_use$deaths_ma_q = ma(data_use$out_deaths_total, order=4)\ndata_use$deaths_ma_y = ma(data_use$out_deaths_total, order=12)\n\nggplot(data=data_use, aes(x=date)) +\n ggtitle(\"Deaths in England, monthly snapshot vs quarterly and annual moving average\") +\n geom_line(aes(y=out_deaths_total), color=\"darkred\") +\n geom_line(aes(y=deaths_ma_q), color=\"darkred\", linetype=\"longdash\") +\n geom_line(aes(y=deaths_ma_y), color=\"darkred\", linetype=\"twodash\") +\n xlab(\"Time\") + ylab(\"Deaths\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\n#... for DTOC days as exposure\ndata_use$dtoc_days_ma_q = ma(data_use$exp_days_dtoc, order=4)\ndata_use$dtoc_days_ma_y = ma(data_use$exp_days_dtoc, order=12)\n\nggplot(data=data_use, aes(x=date)) +\n ggtitle(\"NHS DAYS delayed, monthly snapshot vs quarterly and annual moving average\") +\n geom_line(aes(y=exp_days_dtoc), color=\"black\") +\n geom_line(aes(y=dtoc_days_ma_q), color=\"black\", linetype=\"longdash\") +\n geom_line(aes(y=dtoc_days_ma_y), color=\"black\", linetype=\"twodash\") +\n xlab(\"Time\") + ylab(\"DTOC days\") + \n geom_vline(aes(xintercept = as.numeric(as.Date(\"2015/03/24\"))), color=\"darkgreen\")\n\n\n# Seasonal plots also help to assess trend\nggseasonplot(ts_deaths_all, year.labels=TRUE, year.labels.left=TRUE) +\n ylab(\"Count of deaths\") + ggtitle(\"Seasonal plot: deaths in England\")\n\nggseasonplot(ts_dtocdays_all, year.labels=TRUE, year.labels.left=TRUE) +\n ylab(\"Count of days delayed in transfers of care\") + ggtitle(\"Seasonal plot: days of DTOCs in England\")\n\n# A nice alternative view of the above data\nggseasonplot(ts_deaths_all, polar=TRUE) +\n ylab(\"Count of deaths\") + ggtitle(\"Polar seasonal plot: deaths in England\")\n\nggseasonplot(ts_dtocdays_all, polar=TRUE) +\n ylab(\"Count of days delayed in transfers of care\") + ggtitle(\"Polar seasonal plot: days of DTOCs in England\")\n\n\n# optionally, explore...\n# ts_dtoc_days_acute <- ts(data_use$exp_days_acute, frequency=12, start=c(2010, 8))\n# ts_dtoc_patients <- ts(data_use$exp_patients_dtoc, frequency=12, start=c(2010, 8))\n# ts_dtoc_patients_acute <- ts(data_use$exp_patients_acute, frequency=12, start=c(2010, 8))\n\n\n### 5. Decompose the exposure and outcome time series of interest ###\n\n# Decompose the death outcome of interest\n#... Method 1a using decompose with additive model\ndecomp_deaths_add <- \n decompose(ts_deaths_all, type=\"additive\") \nplot(decomp_deaths_add)\n\n#... Method 1b using decompose with multiplicative model\ndecomp_deaths_mult <- \n decompose(ts_deaths_all, type=\"multiplicative\") \nplot(decomp_deaths_mult)\n\n#... Alternative method 2 using stl()\nstl_deaths <- \n stl(ts_deaths_all, s.window=\"periodic\") \nautoplot(stl_deaths)\n\n\n# Decompose the days of DTOC exposure\ndecomp_dtocdays_all <- \n decompose(ts_dtocdays_all, type=\"additive\") \nplot(decomp_dtocdays_all)\n\n\n### 6. Evaluate stationarity of the time series ###\n\n# Looking at the raw data (0 differences), the ACF/PACF plots and stats test show clear problems\nAcf(ts_deaths_all, lag.max = NULL, type = c(\"correlation\", \"covariance\",\n \"partial\"), plot = TRUE, na.action = na.contiguous, demean = TRUE)\nPacf(ts_deaths_all, lag.max = NULL, plot = TRUE, na.action = na.contiguous, demean = TRUE)\nts_deaths_all %>% ggtsdisplay() # summary view across data, Acf, and Pacf\nBox.test(diff(ts_deaths_all), lag=12, type=\"Ljung-Box\")\n\n# For NONSEASONAL data, ndiffs() can be used to evaluate usefulness of differencing \n# ndiffs(ts_deaths_all, alpha = 0.05, test = c(\"kpss\", \"adf\", \"pp\"),\n# type = c(\"level\", \"trend\"), max.d = 2)\n\n# Here, let's take a seasonal (monthly) difference to try to get to more stationary data\nts_deaths_all %>% diff(lag=12) %>% ggtsdisplay() # set a lag of 12 to reflect monthly seasonality\nts_deaths_all %>% diff(lag=12) %>% diff() %>% ggtsdisplay() # differencing=2 doesn't seem to change much\n\n\n### 7. Fit ARIMA models using auto.arima including some forward forecasts ###\n\n# Univariate time series models from machine-automated selection\nfit_deaths_all <- ts_deaths_all %>%\n auto.arima()\nfit_deaths_all\n\nfit_deaths_all %>% forecast(h=12) %>% autoplot()\n\nfit_deaths_green <- ts_deaths_green %>%\n auto.arima()\nfit_deaths_green\n\nfit_deaths_green %>% forecast(h=12) %>% autoplot()\n\n\n### 8. Check fit and predictiveness, refining as needed ###\n\n# What about residuals of the univariate ARIMA models?\ncheckresiduals(fit_deaths_all)\ncheckresiduals(fit_deaths_green)\n\nrefit_deaths_all <- ts_deaths_all %>%\n auto.arima(approximation=FALSE)\nrefit_deaths_all # we see that approximation in the algo isn't the root issue\n\nrefit_deaths_green <- ts_deaths_green %>% \n auto.arima(approximation=FALSE)\nrefit_deaths_green # ditto for Green et al's analysis\n \nautoplot(refit_deaths_all)\nautoplot(refit_deaths_green)\n# Maybe we decide to live with the fit as-is, unless we have other data on cause of difference?\n \n\n### 9. Extend to regression between different time-series ###\n\n# Specify the acute days time-series, as found by Green et al\nts_acutedays_all <- ts(data_use$exp_days_acute, frequency=12, start=c(2010, 8))\nts_acutedays_green <- ts(data_green$exp_days_acute, frequency=12, start=c(2010, 8))\n\n# Regress the two time-series\nregress_green_auto <- auto.arima(ts_deaths_green, xreg=ts_acutedays_green, allowdrift=TRUE)\nregress_green_auto\n\n# Alternatively one could manually specify as below based on the best-fit UNIVARIATE model\nregress_green_manual <- Arima(ts_deaths_green, xreg=ts_acutedays_green, \n order=c(0,0,0), seasonal=c(1,1,0),\n include.drift=TRUE)\nregress_green_manual # these estimates still differ from the JECH article\n\n# What happens when we include 41 more months of data?\nregress_all_auto <- auto.arima(ts_deaths_all, xreg=ts_acutedays_all, allowdrift=TRUE)\nregress_all_auto\n\n# Check that the automatic ARIMA regression residuals look like white noise/random walk (2nd plot)\ncbind(\"Regression Errors\" = residuals(regress_all_auto, type=\"regression\"),\n \"ARIMA errors\" = residuals(regress_all_auto, type=\"innovation\")) %>%\n autoplot(facets=TRUE)\n\n# What do forecasts look like if DTOCs are unchanged in future?\nregress_all_auto %>% forecast(xreg = ts_acutedays_all, h=12) %>% autoplot()\n", "meta": {"hexsha": "bab7cded5b669634d61b59344440982d1f007353", "size": 12480, "ext": "r", "lang": "R", "max_stars_repo_path": "ARIMA-intro.r", "max_stars_repo_name": "cgpu/R-ladies-ARIMA-intro", "max_stars_repo_head_hexsha": "19c6a8a8ba1101a85877ecb5498758f1271544cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ARIMA-intro.r", "max_issues_repo_name": "cgpu/R-ladies-ARIMA-intro", "max_issues_repo_head_hexsha": "19c6a8a8ba1101a85877ecb5498758f1271544cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ARIMA-intro.r", "max_forks_repo_name": "cgpu/R-ladies-ARIMA-intro", "max_forks_repo_head_hexsha": "19c6a8a8ba1101a85877ecb5498758f1271544cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5714285714, "max_line_length": 111, "alphanum_fraction": 0.7219551282, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.29580001210277684}} {"text": "\n bathymetry_db = function( p=NULL, DS=NULL, varnames=NULL, redo=FALSE, ... ) {\n\n #\\\\ Note inverted convention: depths are positive valued\n #\\\\ i.e., negative valued for above sea level and positive valued for below sea level\n if ( is.null(p)) {\n p_add = list(...)\n if (length(p_add) > 0 ) {\n p = bathymetry_parameters(...)\n } else {\n p = bathymetry_parameters()\n }\n }\n\n\n if ( DS==\"gebco\") {\n #library(RNetCDF)\n # request at: https://www.bodc.ac.uk/data/online_delivery/gebco/ [ jae.choi@dfo ] ... / gate.gate\n # extent: (WSEN) = -+72,36,-45.,53\n # and saved as: bio.data/bathymetry/data/gebco.{xyz,nc} # still waiting\n # and xz compressed\n fn = file.path( p$datadir, \"bathymetry.gebco.rdata\" )\n if (file.exists (fn) ) {\n load(fn)\n return(gebco)\n }\n\n fn_local = file.path( p$datadir, \"gebco.xyz.xz\") # xz compressed file\n nc = open.nc(bathy_fname)\n read.nc(nc)\n array(tmp$z, dim=tmp$dim)\n gebco = read.table( xzfile( fn_local ) )\n names(gebco) = c(\"lon\", \"lat\", \"z\")\n gebco$z = - gebco$z\n # levelplot( log(z+ min(gebco$z) ))~lon+lat, gebco, aspect=\"iso\")\n save( gebco, file=fn, compress=TRUE )\n }\n\n # --------------\n\n if ( DS==\"etopo1\") {\n # etopo1_bedrock.xyz ---> 1 min resolution\n # extent: (WSEN) = -72,36,-45.,53\n # download manually from: http://maps.ngdc.noaa.gov/viewers/wcs-client/\n # and saved as: bio.data/bathymetry/data/etopo1_bedrock.xyz\n # and xz compressed\n fn = file.path( p$datadir, \"bathymetry.etopo1.rdata\" )\n if (file.exists (fn) ) {\n load(fn)\n return(etopo1)\n }\n fn_local = file.path( p$datadir, \"etopo1_bedrock.xyz.xz\") # xz compressed file\n etopo1 = read.table( xzfile( fn_local ) )\n names(etopo1) = c(\"lon\", \"lat\", \"z\")\n etopo1$z = - etopo1$z\n # levelplot( log(z+ min(etopo1$z) ))~lon+lat, etopo1, aspect=\"iso\")\n save( etopo1, file=fn, compress=TRUE )\n }\n\n # --------------\n\n if ( DS ==\"Greenlaw_DEM\") {\n # DEM created 2014\n # GCS_WGS_1984, UTM_Zone_20N; spheroid:: 6378137.0, 298.257223563\n # 322624071 \"grid points\n # 50 m horizontal resolution\n # depth range: -5053.6 to 71.48 m\n fn = file.path( p$datadir, \"bathymetry.greenlaw.rdata\" )\n if (file.exists (fn) ) {\n load(fn)\n return(gdem)\n }\n\n require(rgdal)\n demfile.adf = file.path( p$datadir, \"greenlaw_DEM\", \"mdem_50\", \"w001001.adf\" ) # in ArcInfo adf format\n dem = new( \"GDALReadOnlyDataset\", demfile.adf )\n # gdem = asSGDF_GROD( dem, output.dim=dim(dem) ) # regrid to another dim\n # gdem = getRasterData(dem) # in matrix format\n gdem = getRasterTable(dem) # as a data frame\n names(gdem) = c(\"plon\", \"plat\", \"z\")\n gdem = gdem[ is.finite( gdem$z ) , ]\n gdem$plon = gdem$plon / 1000\n gdem$plat = gdem$plat / 1000\n gdem = planar2lonlat( gdem, \"utm20\" ) # plon,plat in meters but crs for utm20 in km\n gdem = gdem[, c(\"lon\", \"lat\", \"z\") ]\n save( gdem, file=file.path( p$datadir, \"bathymetry.greenlaw.rdata\"), compress=TRUE )\n }\n\n\n\n\n # --------------\n\n if ( DS %in% c(\"z.lonlat.rawdata.redo\", \"z.lonlat.rawdata\") ) {\n\t\t\t# raw data minimally modified all concatenated, dups removed\n fn = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.rdata\" )\n\n if (DS ==\"z.lonlat.rawdata\" ) {\n load( fn )\n return( bathy )\n }\n\n print( \"This is going to take a lot of RAM!\")\n\n\t\t\t# this data was obtained from CHS via David Greenberg in 2004; range = -5467.020, 383.153; n=28,142,338\n fn_nwa = file.path( p$datadir, \"nwa.chs15sec.xyz.xz\") # xz compressed file\n chs15 = read.table( xzfile( fn_nwa ) )\n names(chs15) = c(\"lon\", \"lat\", \"z\")\n # chs15 = chs15[ which( chs15$z < 1000 ) , ]\n chs15$z = - chs15$z\n\n # temporary break up of data to make it functional in smaller RAM systems\n chs1000_5000 = chs15[ which( chs15$z > 1000 ), ]\n u = which(duplicated( chs1000_5000))\n if (length(u)>0) chs1000_5000 = chs1000_5000[-u,]\n\n chs0_1000 = chs15[ which( chs15$z <= 1000 ), ]\n u = which(duplicated( chs0_1000 ))\n if (length(u)>0) chs0_1000 = chs0_1000[-u,]\n\n rm ( chs15); gc()\n\n fn0 = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.temporary_0_1000.rdata\" )\n fn1 = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.temporary_1000_5000.rdata\" )\n\n save ( chs0_1000, file=fn0 )\n save ( chs1000_5000, file=fn1 )\n\n rm ( chs0_1000, chs1000_5000 )\n gc()\n\n # pei = which( chs15$lon < -60.5 & chs15$lon > -64.5 & chs15$lat>45.5 & chs15$lat<48.5 )\n # levelplot( z~lon+lat, data=chs15[pei,] )\n\n\n # Michelle Greenlaw's DEM from 2014\n # range -3000 to 71.5 m; n=155,241,029 .. but mostly interpolated\n gdem = bathymetry_db( DS=\"Greenlaw_DEM\" )\n gdem$z = - gdem$z\n\n # pei = which( gdem$lon < -60.5 & gdem$lon > -65 & gdem$lat>45.5 & gdem$lat<49 )\n # levelplot( z~I(round(lon,3))+I(round(lat,3)), data=gdem[pei,] )\n\n # bad boundaries in Greenlaw's gdem:\n # southern Gulf of St lawrence has edge effects\n bd1 = rbind( c( -62, 46.5 ),\n c( -61, 47.5 ),\n c( -65, 47.5 ),\n c( -65, 46.2 ),\n c( -64, 46.2 ),\n c( -62, 46.5 ) )\n\n a = which( point.in.polygon( gdem$lon, gdem$lat, bd1[,1], bd1[,2] ) != 0 )\n gdem = gdem[- a,]\n\n # remove also the northern and eastern margins for edge effects\n gdem = gdem[ which( gdem$lat < 47.1) ,]\n gdem = gdem[ which( gdem$lon < -56.5) ,]\n\n fn0g = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.temporary_0_1000_gdem.rdata\" )\n fn1g = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.temporary_1000_5000_gdem.rdata\" )\n\n # temporary break up of data to make it functional in smaller RAM systems\n gdem1000_5000 = gdem[ which( gdem$z > 1000 ), ]\n # u = which(duplicated( gdem1000_5000))\n # if (length(u)>0) gdem1000_5000 = gdem1000_5000[-u,]\n save ( gdem1000_5000, file=fn1g )\n rm( gdem1000_5000 ); gc()\n\n gdem0_1000 = gdem[ which( gdem$z <= 1000 ), ]\n # u = which(duplicated( gdem0_1000 ))\n # if (length(u)>0) gdem0_1000 = gdem0_1000[-u,]\n save ( gdem0_1000, file=fn0g )\n rm( gdem0_1000 )\n rm( gdem)\n gc()\n\n\n # chs and others above use chs depth convention: \"-\" is below sea level,\n\t\t\t# in snowcrab and groundfish convention \"-\" is above sea level\n\t\t\t# retain postive values at this stage to help contouring near coastlines\n\n bathy = bathymetry_db( DS=\"etopo1\" )\n\n additional.data=c(\"snowcrab\", \"groundfish\", \"lobster\")\n\n\t\t\tif ( \"snowcrab\" %in% additional.data ) {\n # range from 23.8 to 408 m below sea level ... these have dropped the \"-\" for below sea level; n=5925 (in 2014)\n # project.library( \"bio.snowcrab\")\n sc = bio.snowcrab::snowcrab.db( DS=\"set.clean\")[,c(\"lon\", \"lat\", \"z\") ]\n\t\t\t\tsc = sc [ which (is.finite( rowSums( sc ) ) ) ,]\n\t\t\t\tj = which(duplicated(sc))\n if (length (j) > 0 ) sc = sc[-j,]\n bathy = rbind( bathy, sc )\n\t\t\t # p = p0\n rm (sc); gc()\n\n #sc$lon = round(sc$lon,1)\n #sc$lat = round(sc$lat,1)\n # contourplot( z~lon+lat, sc, cuts=10, labels=F )\n }\n\n if ( \"groundfish\" %in% additional.data ) {\n # n=13031; range = 0 to 1054\n\n warning( \"Should use bottom contact estimates as a priority ?\" )\n\t\t\t\tgf = groundfish_survey_db( DS=\"set.base\" )[, c(\"lon\",\"lat\", \"sdepth\") ]\n\t\t\t\tgf = gf[ which( is.finite(rowSums(gf) ) ) ,]\n names(gf) = c(\"lon\", \"lat\", \"z\")\n\t\t\t\tj = which(duplicated(gf))\n if (length (j) > 0 ) gf = gf[-j,]\n \t\t\t\tbathy = rbind( bathy, gf )\n rm (gf); gc()\n\n #gf$lon = round(gf$lon,1)\n #gf$lat = round(gf$lat,1)\n #contourplot( z~lon+lat, gf, cuts=10, labels=F )\n\n\t\t\t}\n\n if ( \"lobster\" %in% additional.data ) {\n current.year = lubridate::year(lubridate::now())\n p0temp = aegis.temperature::temperature_parameters( yrs=1900:current.year )\n lob = temperature_db( p=p0temp, DS=\"lobster\", yr=1900:current.year ) # FSRS data ... new additions have to be made at the rawdata level manually; yr must be passed to retrieve data ..\n lob = lob[, c(\"lon\",\"lat\", \"z\") ]\n lob = lob[ which( is.finite(rowSums(lob) ) ) ,]\n j = which(duplicated(lob))\n if (length (j) > 0 ) lob = lob[-j,]\n bathy = rbind( bathy, lob )\n rm (lob); gc()\n\n #lob$lon = round(lob$lon,1)\n #lob$lat = round(lob$lat,1)\n #contourplot( z~lon+lat, lob, cuts=10, labels=F )\n\n }\n\n\n u = which(duplicated( bathy ))\n if (length(u)>0) bathy = bathy[ -u, ]\n rm (u)\n\n bathy0 = bathy[ which(bathy$z <= 1000), ]\n bathy1 = bathy[ which(bathy$z > 1000), ]\n rm(bathy)\n\n gc()\n\n load( fn0)\n bathy0 = rbind( bathy0, chs0_1000 )\n rm(chs0_1000) ;gc()\n\n load( fn0g )\n bathy0 = rbind( bathy0, gdem0_1000 )\n rm ( gdem0_1000 ) ;gc()\n\n u = which(duplicated( bathy0 ))\n if (length(u)>0) bathy0 = bathy0[ -u, ]\n\n fn0b = file.path( p$datadir, \"bathymetry.canada.east.lonlat.rawdata.temporary_0_1000_bathy.rdata\" )\n save ( bathy0, file=fn0b )\n rm (bathy0); gc()\n\n # ---\n\n load( fn1 )\n bathy1 = rbind( bathy1, chs1000_5000 )\n rm ( chs1000_5000 ) ; gc()\n\n load( fn1g )\n bathy1 = rbind( bathy1, gdem1000_5000 )\n rm ( gdem1000_5000 ) ; gc()\n\n u = which(duplicated( bathy1 ))\n if (length(u)>0) bathy1 = bathy1[ -u, ]\n rm (u)\n\n load( fn0b )\n\n bathy = rbind( bathy0, bathy1 )\n rm( bathy1, bathy0 ) ; gc()\n\n bid = paste( bathy$lon, bathy$lat, round(bathy$z, 1) ) # crude way to find dups\n bathy = bathy[!duplicated(bid),]\n save( bathy, file=fn, compress=T )\n\n # save ascii in case someone needs it ...\n fn.bathymetry.xyz = file.path( p$datadir, \"bathymetry.canada.east.xyz\" )\n fn.xz = xzfile( paste( fn.bathymetry.xyz, \".xz\", sep=\"\" ) )\n write.table( bathy, file=fn.xz, col.names=F, quote=F, row.names=F)\n system( paste( \"xz\", fn.bathymetry.xyz )) # compress for space\n\n if (file.exists (fn.bathymetry.xyz) ) file.remove(fn.bathymetry.xyz)\n if (file.exists (fn0) ) file.remove( fn0 )\n if (file.exists (fn1) ) file.remove( fn1 )\n if (file.exists (fn0g) ) file.remove( fn0g )\n if (file.exists (fn1g) ) file.remove( fn1g )\n if (file.exists (fn0b) ) file.remove( fn0b )\n\n return ( fn )\n }\n\n\n # ------------------------------\n\n if ( DS==\"aggregated_data\") {\n\n if (!exists(\"inputdata_spatial_discretization_planar_km\", p) ) p$inputdata_spatial_discretization_planar_km = 1\n\n fn = file.path( p$datadir, paste( \"bathymetry\", \"aggregated_data\", p$spatial_domain, round(p$inputdata_spatial_discretization_planar_km, 6) , \"rdata\", sep=\".\") )\n M = NULL\n if (!redo) {\n if (file.exists(fn)) {\n message(\"Using: \", fn)\n load( fn)\n return( M )\n }\n }\n message(\"Making: \", fn)\n\n M = bathymetry_db ( p=p, DS=\"z.lonlat.rawdata\" ) # 16 GB in RAM just to store!\n \n setDT(M)\n M = M[ which( M$lon > p$corners$lon[1] & M$lon < p$corners$lon[2] & M$lat > p$corners$lat[1] & M$lat < p$corners$lat[2] ), ]\n M = lonlat2planar( M, proj.type=p$aegis_proj4string_planar_km) # first ensure correct projection\n \n M$lon = NULL\n M$lat = NULL\n M$z = M[[p$variabletomodel]]\n\n # thin data a bit ... remove potential duplicates and robustify\n\n M$plon = aegis_floor(M$plon / p$inputdata_spatial_discretization_planar_km + 1 ) * p$inputdata_spatial_discretization_planar_km\n M$plat = aegis_floor(M$plat / p$inputdata_spatial_discretization_planar_km + 1 ) * p$inputdata_spatial_discretization_planar_km\n\n gc()\n \n M = M[ geo_subset( spatial_domain=p$spatial_domain, Z=M ) , ] # need to Pbe careful with extrapolation ... filter depths\n\n if (exists(\"quantile_bounds\", p)) {\n TR = quantile(M[[p$variabletomodel]], probs=p$quantile_bounds, na.rm=TRUE )\n keep = which( M[[p$variabletomodel]] >= TR[1] & M[[p$variabletomodel]] <= TR[2] )\n if (length(keep) > 0 ) M = M[ keep, ]\n keep = NULL\n gc()\n }\n\n setDT(M)\n M = M[, .( mean=mean(z, na.rm=TRUE), sd=sd(z, na.rm=TRUE), n=length(which(is.finite(z))) ), by=list(plon, plat) ]\n\n colnames(M) = c( \"plon\", \"plat\", paste( p$variabletomodel, c(\"mean\", \"sd\", \"n\"), sep=\".\") )\n M = planar2lonlat( M, p$aegis_proj4string_planar_km )\n \n attr( M, \"proj4string_planar\" ) = p$aegis_proj4string_planar_km\n attr( M, \"proj4string_lonlat\" ) = projection_proj4string(\"lonlat_wgs84\")\n setDF(M)\n save(M, file=fn, compress=TRUE)\n\n return( M )\n }\n\n\n # ------------------------------\n\n \n if ( DS==\"areal_units_input\" ) {\n\n fn = file.path( p$datadir, \"areal_units_input.rdata\" )\n if ( !file.exists(p$datadir)) dir.create( p$datadir, recursive=TRUE, showWarnings=FALSE )\n\n xydata = NULL\n if (!redo) {\n if (file.exists(fn)) {\n load( fn)\n return( xydata )\n }\n }\n xydata = bathymetry_db( p=p, DS=\"aggregated_data\" ) #\n names(xydata)[which(names(xydata)==\"z.mean\" )] = \"z\"\n xydata = xydata[ , c(\"lon\", \"lat\" )]\n\n save(xydata, file=fn, compress=TRUE )\n return( xydata )\n }\n\n # -----------------------\n\n\n if ( DS==\"carstm_inputs\") {\n\n # prediction surface\n #\\\\ Note inverted convention: depths are positive valued\n #\\\\ i.e., negative valued for above sea level and positive valued for below sea level\n crs_lonlat = st_crs(projection_proj4string(\"lonlat_wgs84\"))\n sppoly = areal_units( p=p ) # will redo if not found\n sppoly = st_transform(sppoly, crs=crs_lonlat )\n areal_units_fn = attributes(sppoly)[[\"areal_units_fn\"]]\n\n fn = carstm_filenames( p=p, returntype=\"carstm_inputs\", areal_units_fn=areal_units_fn )\n if (p$carstm_inputs_prefilter ==\"rawdata\") {\n fn = carstm_filenames( p=p, returntype=\"carstm_inputs_rawdata\", areal_units_fn=areal_units_fn )\n }\n if (p$carstm_inputs_prefilter ==\"sampled\") {\n fn = carstm_filenames( p=p, returntype=paste(\"carstm_inputs_sampled\", p$carstm_inputs_prefilter_n, sep=\"_\"), areal_units_fn=areal_units_fn )\n }\n\n # inputs are shared across various secneario using the same polys\n #.. store at the modeldir level as default\n outputdir = dirname( fn )\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n if (!redo) {\n if (file.exists(fn)) {\n load( fn)\n return( M )\n }\n }\n\n # reduce size\n if (p$carstm_inputs_prefilter ==\"aggregated\") {\n M = bathymetry_db ( p=p, DS=\"aggregated_data\" ) # 16 GB in RAM just to store!\n names(M)[which(names(M)==paste(p$variabletomodel, \"mean\", sep=\".\") )] = p$variabletomodel\n\n } else if (p$carstm_inputs_prefilter ==\"sampled\") {\n M = bathymetry_db ( p=p, DS=\"z.lonlat.rawdata\" ) # 16 GB in RAM just to store!\n\n require(data.table)\n setDT(M)\n names(M)[which(names(M)==\"z\") ] = p$variabletomodel\n\n M = M[ which( !duplicated(M)), ]\n M = M[ which( M$lon > p$corners$lon[1] & M$lon < p$corners$lon[2] & M$lat > p$corners$lat[1] & M$lat < p$corners$lat[2] ), ]\n # levelplot( eval(paste(p$variabletomodel, \"mean\", sep=\".\"))~plon+plat, data=M, aspect=\"iso\")\n\n # thin data a bit ... remove potential duplicates and robustify\n M = lonlat2planar( M, proj.type=p$aegis_proj4string_planar_km ) # first ensure correct projection\n setDT(M)\n\n M$plon = aegis_floor(M$plon / p$inputdata_spatial_discretization_planar_km + 1 ) * p$inputdata_spatial_discretization_planar_km\n M$plat = aegis_floor(M$plat / p$inputdata_spatial_discretization_planar_km + 1 ) * p$inputdata_spatial_discretization_planar_km\n \n M = M[,.SD[sample(.N, min(.N, p$carstm_inputs_prefilter_n))], by =list(plon, plat) ] # compact, might be slightly slower\n # M = M[ M[, sample(.N, min(.N, p$carstm_inputs_prefilter_n) ), by=list(plon, plat)], .SD[i.V1], on=list(plon, plat), by=.EACHI] # faster .. just a bit\n setDF(M)\n\n } else {\n\n M = bathymetry_db ( p=p, DS=\"z.lonlat.rawdata\" ) # 16 GB in RAM just to store!\n names(M)[which(names(M)==\"z\") ] = p$variabletomodel\n M = M[ which( !duplicated(M)), ]\n M = M[ which( M$lon > p$corners$lon[1] & M$lon < p$corners$lon[2] & M$lat > p$corners$lat[1] & M$lat < p$corners$lat[2] ), ]\n # levelplot( eval(paste(p$variabletomodel, \"mean\", sep=\".\"))~plon+plat, data=M, aspect=\"iso\")\n\n }\n \n\n if (p$carstm_inputs_prefilter != \"aggregated\") {\n if (exists(\"quantile_bounds\", p)) {\n TR = quantile(M[[p$variabletomodel]], probs=p$quantile_bounds, na.rm=TRUE )\n keep = which( M[[p$variabletomodel]] >= TR[1] & M[[p$variabletomodel]] <= TR[2] )\n if (length(keep) > 0 ) M = M[ keep, ]\n keep = NULL\n gc()\n }\n }\n\n # if (exists(\"quantile_bounds\", p)) {\n # TR = quantile(M[,p$variabletomodel], probs=p$quantile_bounds, na.rm=TRUE )\n # keep = which( M[,p$variabletomodel] >= TR[1] & M[,p$variabletomodel] <= TR[2] )\n # if (length(keep) > 0 ) M = M[ keep, ]\n # }\n\n attr( M, \"proj4string_planar\" ) = p$aegis_proj4string_planar_km\n attr( M, \"proj4string_lonlat\" ) = projection_proj4string(\"lonlat_wgs84\")\n # p$quantile_bounds = c(0.0005, 0.9995)\n\n M$AUID = st_points_in_polygons(\n pts = st_as_sf( M, coords=c(\"lon\",\"lat\"), crs=crs_lonlat ),\n polys = sppoly[, \"AUID\"],\n varname=\"AUID\"\n )\n M = M[ which(!is.na(M$AUID)),]\n M$AUID = as.character( M$AUID ) # match each datum to an area\n\n eps = .Machine$double.eps\n M$z = M$z + runif( nrow(M), min=-eps, max=eps )\n\n M$lon = NULL\n M$lat = NULL\n\n M$tag = \"observations\"\n\n region.id = slot( slot(sppoly, \"nb\"), \"region.id\" )\n APS = st_drop_geometry(sppoly)\n sppoly = NULL\n gc()\n\n APS[, p$variabletomodel] = NA\n APS$AUID = as.character( APS$AUID )\n APS$tag =\"predictions\"\n\n vn = c(\"z\", \"tag\", \"AUID\" )\n\n M = rbind( M[, vn], APS[, vn] )\n APS = NULL\n\n #required for carstm formulae\n M$space = as.character( M$AUID)\n\n save( M, file=fn, compress=TRUE )\n return( M )\n }\n\n\n # ------------------------------\n\n\n if ( DS %in% c(\"bathymetry\", \"stmv_inputs\", \"stmv_inputs_redo\" )) {\n\n fn = file.path( p$modeldir, paste( \"bathymetry\", \"stmv_inputs\", \"rdata\", sep=\".\") )\n if (DS %in% c(\"bathymetry\", \"stmv_inputs\") ) {\n load( fn)\n return( hm )\n }\n\n B = bathymetry_db ( p=p, DS=\"aggregated_data\", redo=TRUE ) # 16 GB in RAM just to store!\n B$lon = NULL\n B$lat = NULL\n names(B)[which(names(B) == paste(p$variabletomodel, \"mean\", sep=\".\"))] = p$variabletomodel\n\n print( \"Warning: this needs a lot of RAM .. ~60GB depending upon resolution of discretization .. a few hours \" )\n\n hm = list( input=B, output=list( LOCS = spatial_grid(p) ) )\n B = NULL; gc()\n save( hm, file=fn, compress=FALSE)\n hm = NULL\n gc()\n return(fn)\n\n }\n\n # ------------------------------\n\n\n if ( DS %in% c(\"stmv_inputs_highres\", \"stmv_inputs_highres_redo\" )) {\n\n fn = file.path( p$modeldir, paste( \"bathymetry\", \"stmv_inputs_highres\", \"rdata\", sep=\".\") )\n if (DS %in% c(\"stmv_inputs_highres\") ) {\n load( fn)\n return( hm )\n }\n\n B = bathymetry_db ( p=p, DS=\"z.lonlat.rawdata\" ) # 16 GB in RAM just to store!\n\n # p$quantile_bounds = c(0.0005, 0.9995)\n if (exists(\"quantile_bounds\", p)) {\n TR = quantile(B[,p$variabletomodel], probs=p$quantile_bounds, na.rm=TRUE )\n keep = which( B[,p$variabletomodel] >= TR[1] & B[,p$variabletomodel] <= TR[2] )\n if (length(keep) > 0 ) B = B[ keep, ]\n }\n\n # thin data a bit ... remove potential duplicates and robustify\n B = lonlat2planar( B, proj.type=p$aegis_proj4string_planar_km ) # first ensure correct projection\n\n B$lon = NULL\n B$lat = NULL\n\n attr( B, \"proj4string_planar\" ) = p$aegis_proj4string_planar_km\n\n hm = list( input=B, output=list( LOCS = spatial_grid(p) ) )\n B = NULL; gc()\n save( hm, file=fn, compress=FALSE)\n hm = NULL\n gc()\n return(fn)\n\n }\n\n # ----------------\n\n if ( DS == \"landmasks.create\" ) {\n\n ## NOTE::: This does not get used\n\n # on resolution of predictions\n V = SpatialPoints( planar2lonlat( spatial_grid(p), proj.type=p$aegis_proj4string_planar_km )[, c(\"lon\", \"lat\" )], CRS(\"+proj=longlat +datum=WGS84\") )\n landmask( lonlat=V, db=\"worldHires\", regions=c(\"Canada\", \"US\"), ylim=c(36,53), xlim=c(-72,-45), tag=\"predictions\", crs=p$aegis_proj4string_planar_km)\n\n # on resolution of statistics\n sbox = list(\n plats = seq( p$corners$plat[1], p$corners$plat[2], by=p$stmv_distance_statsgrid ),\n plons = seq( p$corners$plon[1], p$corners$plon[2], by=p$stmv_distance_statsgrid ) )\n V = as.matrix( expand.grid( sbox$plons, sbox$plats ))\n names(V) = c(\"plon\", \"plat\")\n V = SpatialPoints( planar2lonlat( V, proj.type=p$aegis_proj4string_planar_km )[, c(\"lon\", \"lat\" )], CRS(\"+proj=longlat +datum=WGS84\") )\n landmask( lonlat=V, db=\"worldHires\",regions=c(\"Canada\", \"US\"), ylim=c(36,53), xlim=c(-72,-45), tag=\"statistics\", crs=p$aegis_proj4string_planar_km)\n }\n\n #-------------------------\n\n if ( DS %in% c(\"complete\", \"complete.redo\" )) {\n #// merge all stmv results and compute stats and warp to different grids\n outdir = file.path( p$modeldir, p$stmv_model_label, p$project_class, paste( p$stmv_global_modelengine, p$stmv_local_modelengine, sep=\"_\") )\n\n fn = file.path( outdir, paste( \"bathymetry\", \"complete\", p$spatial_domain, \"rdata\", sep=\".\") )\n\n if ( DS %in% c( \"complete\") ) {\n Z = NULL\n if ( file.exists ( fn) ) load( fn)\n return( Z )\n }\n\n nr = p$nplons\n nc = p$nplats\n\n # data prediction grid\n B = spatial_grid( p)\n Bmean = stmv_db( p=p, DS=\"stmv.prediction\", ret=\"mean\" )\n Blb = stmv_db( p=p, DS=\"stmv.prediction\", ret=\"lb\" )\n Bub = stmv_db( p=p, DS=\"stmv.prediction\", ret=\"ub\" )\n Z = data.frame( cbind(B, Bmean, Blb, Bub) )\n names(Z) = c( \"plon\", \"plat\", \"z\", \"z.lb\", \"z.ub\") # really Z.mean but for historical compatibility \"z\"\n B = Bmean = Blb = Bub = NULL\n\n # # remove land\n # oc = landmask( db=\"worldHires\", regions=c(\"Canada\", \"US\"), return.value=\"land\", tag=\"predictions\" )\n # Z$z[oc] = NA\n # Z$z.sd[oc] = NA\n\n Zmn = matrix( Z[,p$variabletomodel], nrow=nr, ncol=nc ) # means\n\n # first order central differences but the central term drops out:\n # diffr = ( ( Zmn[ 1:(nr-2), ] - Zmn[ 2:(nr-1), ] ) + ( Zmn[ 2:(nr-1), ] - Zmn[ 3:nr, ] ) ) / 2\n # diffc = ( ( Zmn[ ,1:(nc-2) ] - Zmn[ ,2:(nc-1) ] ) + ( Zmn[ ,2:(nc-1) ] - Zmn[ ,3:nc ] ) ) / 2\n diffr = Zmn[ 1:(nr-2), ] - Zmn[ 3:nr, ]\n diffc = Zmn[ ,1:(nc-2) ] - Zmn[ ,3:nc ]\n rm (Zmn); gc()\n\n dZ = ( diffr[ ,2:(nc-1) ] + diffc[ 2:(nr-1), ] ) / 2\n dZ = rbind( dZ[1,], dZ, dZ[nrow(dZ)] ) # top and last rows are copies .. dummy value to keep dim correct\n dZ = cbind( dZ[,1], dZ, dZ[,ncol(dZ)] )\n\n Z$dZ = abs(c(dZ))\n\n # gradients\n ddiffr = dZ[ 1:(nr-2), ] - dZ[ 3:nr, ]\n ddiffc = dZ[ ,1:(nc-2) ] - dZ[ ,3:nc ]\n dZ = diffc = diffr = NULL\n\n ddZ = ( ddiffr[ ,2:(nc-1) ] + ddiffc[ 2:(nr-1), ] ) / 2\n ddZ = rbind( ddZ[1,], ddZ, ddZ[nrow(ddZ)] ) # top and last rows are copies .. dummy value to keep dim correct\n ddZ = cbind( ddZ[,1], ddZ, ddZ[,ncol(ddZ)] )\n Z$ddZ = abs(c(ddZ))\n\n # merge into statistics\n BS = stmv_db( p=p, DS=\"stmv.stats\" )\n colnames(BS) = paste(\"b\", colnames(BS), sep=\".\")\n Z = cbind( Z, BS )\n\n save( Z, file=fn, compress=TRUE)\n\n BS = ddZ = ddiffc = ddiffr = NULL\n gc()\n\n # now warp to the other grids\n p0 = p # the originating parameters\n\n Z0 = Z # rename as 'Z' will be overwritten below\n L0 = Z0[, c(\"plon\", \"plat\")]\n L0i = array_map( \"xy->2\", L0, gridparams=p0$gridparams )\n\n voi_bathy = setdiff( names(Z0), c(\"plon\", \"plat\", \"lon\", \"lat\") )\n grids = setdiff( unique( p0$spatial_domain_subareas ), p0$spatial_domain )\n\n for (gr in grids ) {\n print(gr)\n p1 = spatial_parameters( spatial_domain=gr ) #target projection\n # warping\n L1 = spatial_grid( p=p1 )\n L1i = array_map( \"xy->2\", L1[, c(\"plon\", \"plat\")], gridparams=p1$gridparams )\n L1 = planar2lonlat( L1, proj.type=p1$aegis_proj4string_planar_km )\n Z = L1\n L1$plon_1 = L1$plon # store original coords\n L1$plat_1 = L1$plat\n L1 = lonlat2planar( L1, proj.type=p0$aegis_proj4string_planar_km )\n\n p1$wght = fields::setup.image.smooth(\n nrow=p1$nplons, ncol=p1$nplats, dx=p1$pres, dy=p1$pres,\n theta=p1$pres/3, xwidth=4*p1$pres, ywidth=4*p1$pres )\n # theta=p1$pres/3 assume at pres most of variance is accounted ... correct if dense pre-intepolated matrices .. if not can be noisy\n\n for (vn in voi_bathy) {\n Z[,vn] = spatial_warp( Z0[,vn], L0, L1, p0, p1, \"fast\", L0i, L1i )\n }\n Z = Z[ , names(Z0) ]\n\n fn = file.path( outdir, paste( \"bathymetry\", \"complete\", p1$spatial_domain, \"rdata\", sep=\".\") )\n save (Z, file=fn, compress=TRUE)\n }\n\n return(fn)\n\n if (0) {\n aoi = which( Z$z > 10 & Z$z < 500 )\n datarange = log( quantile( Z[aoi,\"z\"], probs=c(0.001, 0.999), na.rm=TRUE ))\n dr = seq( datarange[1], datarange[2], length.out=100)\n\n levelplot( log(z) ~ plon + plat, Z[ aoi,], aspect=\"iso\", labels=FALSE, pretty=TRUE, xlab=NULL,ylab=NULL,scales=list(draw=FALSE), at=dr, col.regions=rev(color.code( \"seis\", dr)) )\n levelplot( log(phi) ~ plon + plat, Z[ aoi,], aspect=\"iso\", labels=FALSE, pretty=TRUE, xlab=NULL,ylab=NULL,scales=list(draw=FALSE) )\n levelplot( log(range) ~ plon + plat, Z[aoi,], aspect=\"iso\", labels=FALSE, pretty=TRUE, xlab=NULL,ylab=NULL,scales=list(draw=FALSE) )\n\n }\n }\n\n\n # ------------\n\n if (DS %in% c(\"baseline\", \"baseline.redo\") ) {\n # form prediction surface in planar coords over the ocean\n\n outdir = file.path( p$modeldir, p$stmv_model_label, p$project_class, paste( p$stmv_global_modelengine, p$stmv_local_modelengine, sep=\"_\") )\n\n if ( DS==\"baseline\" ) {\n # used to obtain coordinates\n fn = paste( \"bathymetry\", \"baseline\", p$spatial_domain, \"rdata\" , sep=\".\")\n outfile = file.path( outdir, fn )\n Z = NULL\n load( outfile )\n Znames = names(Z)\n if (is.null(varnames)) varnames =c(\"plon\", \"plat\") # default is to send locs only .. different reative to all other data streams\n varnames = intersect( Znames, varnames ) # send anything that results in no match causes everything to be sent\n if (length(varnames) == 0) varnames=Znames # no match .. send all\n Z = Z[ , varnames]\n return (Z)\n }\n\n for (domain in unique( c(p$spatial_domain_subareas, p$spatial_domain ) ) ) {\n pn = spatial_parameters( p=p, spatial_domain=domain )\n # if ( pn$spatial_domain == \"snowcrab\" ) {\n # # NOTE::: snowcrab baseline == SSE baseline, except it is a subset so begin with the SSE conditions\n # pn = spatial_parameters( p=pn, spatial_domain=\"SSE\" )\n # }\n Z = bathymetry_db( p=pn, DS=\"complete\" )\n Z = Z[ geo_subset( spatial_domain=domain, Z=Z ), ]\n\n # range checks\n ii = which( Z$dZ < exp(-6))\n if (length(ii) > 0) Z$dZ[ii] = exp(-6)\n\n ii = which( Z$dZ > 50 )\n if (length(ii) > 0) Z$dZ[ii] = 50\n\n ii = which( Z$ddZ < exp(-6))\n if (length(ii) > 0) Z$ddZ[ii] = exp(-6)\n\n ii = which( Z$ddZ > 20 )\n if (length(ii) > 0) Z$ddZ[ii] = 20\n\n fn = paste( \"bathymetry\", \"baseline\", domain, \"rdata\" , sep=\".\" )\n outfile = file.path( outdir, fn )\n\n save (Z, file=outfile, compress=T )\n print( outfile )\n }\n # require (lattice); levelplot( z~plon+plat, data=Z, aspect=\"iso\")\n return( \"completed\" )\n }\n\n # ------------\n\n\n if (DS %in% c(\"baseline_prediction_locations\", \"baseline_prediction_locations.redo\") ) {\n # form prediction surface in planar coords over the ocean\n\n outdir = p$modeldir\n\n if ( DS==\"baseline_prediction_locations\" ) {\n # used to obtain coordinates\n fn = paste( \"bathymetry\", \"baseline_prediction_locations\", p$spatial_domain, \"rdata\" , sep=\".\")\n outfile = file.path( outdir, fn )\n Z = NULL\n if (file.exists(fn)) {\n load( outfile )\n Znames = names(Z)\n if (is.null(varnames)) varnames =c(\"plon\", \"plat\") # default is to send locs only .. different reative to all other data streams\n varnames = intersect( Znames, varnames ) # send anything that results in no match causes everything to be sent\n if (length(varnames) == 0) varnames=Znames # no match .. send all\n Z = Z[ , varnames]\n return (Z)\n }\n }\n\n pn = spatial_parameters( p=p, spatial_domain=p$spatial_domain )\n Z = spatial_grid(p)\n Z = planar2lonlat( Z, proj.type=p$aegis_proj4string_planar_km )\n Z$z = aegis_lookup( paramaters=\"bathymetry\", LOCS=Z[, c(\"lon\", \"lat\")], project_class=\"core\", output_format=\"points\" , DS=\"aggregated_data\", variable.name=\"z.mean\" ) # core == unmodelled\n Z = Z[ geo_subset( spatial_domain=p$spatial_domain, Z=Z ), ]\n\n fn = paste( \"bathymetry\", \"baseline_prediction_locations\", p$spatial_domain, \"rdata\" , sep=\".\")\n outfile = file.path( outdir, fn )\n\n save (Z, file=outfile, compress=TRUE )\n print( outfile )\n\n # require (lattice); levelplot( z~plon+plat, data=Z, aspect=\"iso\")\n return( Z )\n }\n\n # ------------\n\n\n\n } # end bathymetry_db\n", "meta": {"hexsha": "cafa259db2ee9d8a8590d6f329fb4eae2a9481d1", "size": 30439, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bathymetry_db.r", "max_stars_repo_name": "jae0/aegis.bathymetry", "max_stars_repo_head_hexsha": "000caf735d49a5e8a98557758bce7bd4542547e2", "max_stars_repo_licenses": ["MIT"], "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/bathymetry_db.r", "max_issues_repo_name": "jae0/aegis.bathymetry", "max_issues_repo_head_hexsha": "000caf735d49a5e8a98557758bce7bd4542547e2", "max_issues_repo_licenses": ["MIT"], "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/bathymetry_db.r", "max_forks_repo_name": "jae0/aegis.bathymetry", "max_forks_repo_head_hexsha": "000caf735d49a5e8a98557758bce7bd4542547e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-05-04T14:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T14:35:59.000Z", "avg_line_length": 37.3943488943, "max_line_length": 193, "alphanum_fraction": 0.5714051053, "num_tokens": 10084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.29422624072732206}} {"text": "model_evapotranspiration <- function (isWindVpDefined = 1,\n evapoTranspirationPriestlyTaylor = 449.367,\n evapoTranspirationPenman = 830.958){\n #'- Name: EvapoTranspiration -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Evapotranspiration 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: According to the availability of wind and/or vapor pressure daily data, the\n #' SiriusQuality2 model calculates the evapotranspiration rate using the Penman (if wind\n #' and vapor pressure data are available) (Penman 1948) or the Priestly-Taylor\n #' (Priestley and Taylor 1972) method \n #' * ShortDescription: It uses to choose evapotranspiration of Penmann or Priestly-Taylor \n #'- inputs:\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 #' * name: evapoTranspirationPriestlyTaylor\n #' ** description : evapoTranspiration of Priestly Taylor \n #' ** variablecategory : rate\n #' ** default : 449.367\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : mm\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #' * name: evapoTranspirationPenman\n #' ** description : evapoTranspiration of Penman \n #' ** datatype : DOUBLE\n #' ** variablecategory : rate\n #' ** default : 830.958\n #' ** min : 0\n #' ** max : 10000\n #' ** unit : mm\n #' ** uri : http://www1.clermont.inra.fr/siriusquality/?page_id=547\n #' ** inputtype : variable\n #'- outputs:\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 if (isWindVpDefined == 1)\n {\n evapoTranspiration <- evapoTranspirationPenman\n }\n else\n {\n evapoTranspiration <- evapoTranspirationPriestlyTaylor\n }\n return (list('evapoTranspiration' = evapoTranspiration))\n}", "meta": {"hexsha": "5dcb415117a4e00276e04b2e3f3c5fda81bd493f", "size": 3529, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Energy_Balance/Evapotranspiration.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/Evapotranspiration.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/Evapotranspiration.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": 54.2923076923, "max_line_length": 116, "alphanum_fraction": 0.4511192973, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.29355731834207455}} {"text": "#' Maximization step using coordinate descent optimization.\n#'\n#' @param p List of parameters.\n#' @param item_data Matrix or data frame of item responses.\n#' @param pred_data Matrix or data frame of DIF and/or impact predictors.\n#' @param mean_predictors Possibly different matrix of predictors for the mean\n#' impact equation.\n#' @param var_predictors Possibly different matrix of predictors for the\n#' variance impact equation.\n#' @param eout E step output, including matrix for item and impact equations,\n#' in addition to theta values (possibly adaptive).\n#' @param item_type Optional character value or vector indicating the type of\n#' item to be modeled.\n#' @param pen_type Character value indicating the penalty function to use.\n#' @param tau_current A single numeric value of tau that exists within\n#' \\code{tau_vec}.\n#' @param pen Current penalty index.\n#' @param alpha Numeric value indicating the alpha parameter in the elastic net\n#' penalty function.\n#' @param gamma Numeric value indicating the gamma parameter in the MCP\n#' function.\n#' @param anchor Optional numeric value or vector indicating which item\n#' response(s) are anchors (e.g., \\code{anchor = 1}).\n#' @param final_control Control parameters.\n#' @param samp_size Sample size in data set.\n#' @param num_responses Number of responses for each item.\n#' @param num_items Number of items in data set.\n#' @param num_quad Number of quadrature points used for approximating the\n#' latent variable.\n#' @param num_predictors Number of predictors.\n#' @param num_tau Logical indicating whether the minimum tau value needs to be\n#' identified during the regDIF procedure.\n#' @param max_tau Logical indicating whether to output the maximum tau value\n#' needed to remove all DIF from the model.\n#'\n#' @return a \\code{\"list\"} of estimates obtained from the maximization step using univariate\n#' Newton-Raphson (i.e., one step of coordinate descent)\n#'\n#' @importFrom foreach %dopar%\n#' @keywords internal\n#'\nMstep_cd <-\n function(p,\n item_data,\n pred_data,\n mean_predictors,\n var_predictors,\n eout,\n item_type,\n pen_type,\n tau_current,\n pen,\n alpha,\n gamma,\n anchor,\n final_control,\n samp_size,\n num_responses,\n num_items,\n num_quad,\n num_predictors,\n num_tau,\n max_tau) {\n\n # Set under-identified model to FALSE until proven TRUE.\n under_identified <- FALSE\n\n # Update theta and etable.\n theta <- eout$theta\n etable <- eout$etable\n\n # Last Mstep\n if(max_tau) id_max_z <- 0\n\n # Latent mean impact updates.\n for(cov in 1:ncol(mean_predictors)) {\n anl_deriv <- d_alpha(c(p[[num_items+1]],p[[num_items+2]]),\n etable,\n theta,\n mean_predictors,\n var_predictors,\n cov=cov,\n samp_size,\n num_items,\n num_quad)\n p[[num_items+1]][[cov]] <-\n p[[num_items+1]][[cov]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n # Latent variance impact updates.\n for(cov in 1:ncol(var_predictors)) {\n anl_deriv <- d_phi(c(p[[num_items+1]],p[[num_items+2]]),\n etable,\n theta,\n mean_predictors,\n var_predictors,\n cov=cov,\n samp_size,\n num_items,\n num_quad)\n p[[num_items+2]][[cov]] <-\n p[[num_items+2]][[cov]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n\n # Item response updates.\n if(final_control$parallel[[1]]) {\n parallel::clusterExport(final_control$parallel[[2]],\n c(\"num_responses\", \"pred_data\", \"item_data\",\n \"samp_size\", \"num_predictors\", \"num_quad\", \"num_items\",\n \"prox_data\", \"item_type\", \"anchor\", \"pen_type\",\n \"num_tau\", \"pen\", \"tau_vec\", \"alpha\", \"final_control\",\n \"max_tau\", \"d_bernoulli_itemblock\", \"d_bernoulli_itemblock_proxy\",\n \"grp_soft_threshold\", \"grp_firm_threshold\", \"soft_threshold\",\n \"firm_threshold\", \"p\", \"eout\", \"inv_hess_diag\", \"tau_current\",\n \"under_identified\", \"id_max_z\"),\n envir=environment())\n\n p_items <- foreach::foreach(item=1:num_items) %dopar% {\n # Get posterior probabilities.\n\n\n # Obtain E-tables for each response category.\n if(item_type[item] != \"cfa\") {\n etable_item <- lapply(1:num_responses[item], function(x) etable)\n for(resp in 1:num_responses[item]) {\n etable_item[[resp]][which(\n !(item_data[,item] == resp)), ] <- 0\n }\n }\n\n # Bernoulli responses.\n if(item_type[item] == \"2pl\") {\n\n # Intercept updates.\n anl_deriv <- d_bernoulli(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov=0,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[1]] <- p[[item]][[1]] - anl_deriv[[1]]/anl_deriv[[2]]\n\n # Slope updates.\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_bernoulli(\"a0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov=0,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[2]] <- p[[item]][[2]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n\n if(!any(item == anchor)) {\n\n p2 <- unlist(p)\n\n # Intercept DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"c1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n anl_deriv <- d_bernoulli(\"c1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][[2+cov]] - anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[2+cov]] <- ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n # Slope DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"a1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_bernoulli(\"a1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][[2+num_predictors+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[2+num_predictors+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n }\n\n }\n\n # Categorical.\n } else {\n\n # Intercept updates.\n anl_deriv <- d_categorical(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[1]] <- p[[item]][[1]] - anl_deriv[[1]]/anl_deriv[[2]]\n\n # Threshold updates.\n for(thr in 2:(num_responses[item]-1)) {\n anl_deriv <- d_categorical(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=thr,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[thr]] <- p[[item]][[thr]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n # Slope updates.\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_categorical(\"a0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[num_responses[[item]]]] <-\n p[[item]][[num_responses[[item]]]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n if(!any(item == anchor)){\n\n p2 <- unlist(p)\n\n # Intercept DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"c1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n anl_deriv <- d_categorical(\"c1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n z <- p[[item]][[num_responses[[item]]+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[num_responses[[item]]+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n # Slope DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"a1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_categorical(\"a1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n z <- p[[item]][[length(p[[item]])-ncol(pred_data)+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[length(p[[item]])-ncol(pred_data)+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n }\n }\n\n\n }\n return(list(unlist(p[item]),id_max_z))\n }\n\n\n for(item in 1:num_items) {\n p[[item]] <- p_items[[item]][[1]]\n }\n\n } else {\n\n for (item in 1:num_items) {\n\n # Obtain E-tables for each response category.\n if(item_type[item] != \"cfa\") {\n etable_item <- lapply(1:num_responses[item], function(x) etable)\n for(resp in 1:num_responses[item]) {\n etable_item[[resp]][which(\n !(item_data[,item] == resp)), ] <- 0\n }\n }\n\n if(item_type[item] == \"cfa\") {\n\n # Intercept updates.\n anl_deriv <- d_mu_gaussian(\"c0\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov=NULL,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[1]] <- p[[item]][[1]] - anl_deriv[[1]]/anl_deriv[[2]]\n\n # Slope updates.\n if(item_type[item] != \"rasch\") {\n a0_parms <- grep(paste0(\"a0_item\",item,\"_\"),names(p[[item]]),fixed=T)\n anl_deriv <- d_mu_gaussian(\"a0\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov=NULL,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[2]] <- p[[item]][a0_parms] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n\n # Residual updates.\n s0_parms <- grep(paste0(\"s0_item\",item,\"_\"),names(p[[item]]),fixed=T)\n anl_deriv <- d_sigma_gaussian(\"s0\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov=NULL,\n samp_size,\n num_items,\n num_quad)\n p[[item]][s0_parms][[1]] <- p[[item]][s0_parms][[1]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(p[[item]][s0_parms][[1]] < 0) p[[item]][s0_parms][[1]] <- 1\n\n\n if(!any(item == anchor)) {\n\n # Residual DIF updates.\n for(cov in 1:num_predictors) {\n s1_parms <-\n grep(paste0(\"s1_item\",item,\"_cov\",cov),names(p[[item]]),fixed=T)\n anl_deriv <- d_sigma_gaussian(\"s1\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov=cov,\n samp_size,\n num_items,\n num_quad)\n p[[item]][s1_parms][[1]] <- p[[item]][s1_parms][[1]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n p2 <- unlist(p)\n\n # Intercept DIF updates.\n for(cov in 1:num_predictors){\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"c1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n c1_parms <-\n grep(paste0(\"c1_item\",item,\"_cov\",cov),names(p[[item]]),fixed=T)\n anl_deriv <- d_mu_gaussian(\"c1\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][c1_parms] - anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][c1_parms][[1]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n # Slope DIF updates.\n for(cov in 1:num_predictors){\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"a1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n if(item_type[item] != \"rasch\"){\n a1_parms <-\n grep(paste0(\"a1_item\",item,\"_cov\",cov),names(p[[item]]),fixed=T)\n anl_deriv <- d_mu_gaussian(\"a1\",\n p[[item]],\n etable,\n theta,\n item_data[,item],\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][a1_parms] - anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][a1_parms][[1]] <- ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n }\n }\n\n\n # Bernoulli responses.\n } else if(item_type[item] == \"2pl\") {\n\n # Intercept updates.\n anl_deriv <- d_bernoulli(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov=0,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[1]] <- p[[item]][[1]] - anl_deriv[[1]]/anl_deriv[[2]]\n\n # Slope updates.\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_bernoulli(\"a0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov=0,\n samp_size,\n num_items,\n num_quad)\n p[[item]][[2]] <- p[[item]][[2]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n\n if(!any(item == anchor)) {\n\n p2 <- unlist(p)\n\n # Intercept DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"c1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n anl_deriv <- d_bernoulli(\"c1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][[2+cov]] - anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[2+cov]] <- ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n # Slope DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"a1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_bernoulli(\"a1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n cov,\n samp_size,\n num_items,\n num_quad)\n z <- p[[item]][[2+num_predictors+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[2+num_predictors+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n }\n\n }\n\n # Categorical.\n } else {\n\n # Intercept updates.\n anl_deriv <- d_categorical(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[1]] <- p[[item]][[1]] - anl_deriv[[1]]/anl_deriv[[2]]\n\n # Threshold updates.\n for(thr in 2:(num_responses[item]-1)) {\n anl_deriv <- d_categorical(\"c0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=thr,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[thr]] <- p[[item]][[thr]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n # Slope updates.\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_categorical(\"a0\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov=-1,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n p[[item]][[num_responses[[item]]]] <-\n p[[item]][[num_responses[[item]]]] - anl_deriv[[1]]/anl_deriv[[2]]\n }\n\n if(!any(item == anchor)){\n\n p2 <- unlist(p)\n\n # Intercept DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"c1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n anl_deriv <- d_categorical(\"c1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n z <- p[[item]][[num_responses[[item]]+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[num_responses[[item]]+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n\n # Slope DIF updates.\n for(cov in 1:num_predictors) {\n\n # End routine if only one anchor item is left on each covariate\n # for each item parameter.\n if(is.null(anchor) &\n sum(p2[grep(paste0(\"a1(.*?)cov\",cov),names(p2))] != 0) >\n (num_items - 1) &\n alpha == 1 &&\n (length(final_control$start.values) == 0 || pen > 1) &&\n num_tau >= 10){\n under_identified <- TRUE\n break\n }\n\n if(item_type[item] != \"rasch\") {\n anl_deriv <- d_categorical(\"a1\",\n p[[item]],\n etable_item,\n theta,\n pred_data,\n thr=-1,\n cov,\n samp_size,\n num_responses[[item]],\n num_items,\n num_quad)\n z <- p[[item]][[length(p[[item]])-ncol(pred_data)+cov]] -\n anl_deriv[[1]]/anl_deriv[[2]]\n if(max_tau) id_max_z <- c(id_max_z,z)\n p[[item]][[length(p[[item]])-ncol(pred_data)+cov]] <-\n ifelse(pen_type == \"lasso\",\n soft_threshold(z,alpha,tau_current),\n firm_threshold(z,alpha,tau_current,gamma))\n }\n }\n }\n\n\n\n }\n\n }\n\n }\n\n\n if(max_tau) {\n if(final_control$parallel[[1]]) {\n id_max_z <- max(abs(sapply(1:num_items, function(items) p_items[[items]][[2]])))\n } else{\n id_max_z <- max(abs(id_max_z))\n }\n return(id_max_z)\n } else {\n return(list(p=p,\n under_identified=under_identified))\n }\n\n}\n", "meta": {"hexsha": "4a913af1eaf01e1430462af7d5015b90d65e2971", "size": 30022, "ext": "r", "lang": "R", "max_stars_repo_path": "R/m_step_cd.r", "max_stars_repo_name": "wbelzak/regDIF", "max_stars_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/m_step_cd.r", "max_issues_repo_name": "wbelzak/regDIF", "max_issues_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/m_step_cd.r", "max_forks_repo_name": "wbelzak/regDIF", "max_forks_repo_head_hexsha": "14dcc75e0aa4f54d4e3d274e8eada3aa1c51f014", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4404609475, "max_line_length": 97, "alphanum_fraction": 0.3773232962, "num_tokens": 5847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.29326931708057213}} {"text": "\n subroutine inmodel \nc******************************************************************************\nc This subroutine reads in the model \nc****************************************************************************** \n\n implicit real*8 (a-h,o-z) \n include 'Atmos.com'\n include 'Linex.com'\n include 'Mol.com'\n include 'Quants.com'\n include 'Factor.com'\n include 'Dummy.com'\n include 'Pstuff.com'\n real*8 element(95), logepsilon(95)\n real*8 kaprefmass(100)\n real*8 bmol(110)\n integer nel(7)\n character list*80, list2*70\n integer append\n data (nel(i),i=1,7)/ 1, 2, 6, 12, 13, 14, 26/\n\n\nc*****Read in the key word to define the model type\n modelnum = modelnum + 1\n rewind nfmodel\n read (nfmodel,2001) modtype\n write (nf1out,1010) modtype\n if (modtype .eq. 'begn ' .or. modtype .eq. 'BEGN ') \n . write (nf1out,1011)\n\n\nc*****Read a comment line (usually describing the model)\n read (nfmodel,2002) moditle\n\n\nc*****Read the number of depth points\n read (nfmodel,2002) list\n list2 = list(11:)\n read (list2,*) ntau\n if (ntau .gt. 100) then\n write (array,1012)\n call prinfo (10)\n stop\n endif\n\n\nc*****EITHER: Read in a model from the output of the experimental new\nc MARCS code. This modtype is called \"NEWMARCS\". On each line \nc the numbers are:\nc tau(5000), t, pe, pgas, rho, model microtrubulent velocity,\nc and mean opacity (cm^2/gm) at the reference wavelength (5000A).\n if (modtype .eq. 'NEWMARCS ') then\n read (nfmodel,*) wavref \n do i=1,ntau\n read (nfmodel,*) tauref(i),t(i),ne(i),pgas(i),rho(i),\n . vturb(1),kaprefmass(i)\n enddo\nc*****OR: Read in a model from the output of the on-line new\nc MARCS code. This modtype is called \"WEBMARCS\". On each line\nc the numbers are:\nc layer number (not needed), log{tau(Rosseland)} (not needed),\nc log{tau(5000)}, depth, t, pe, pgas, prad (not read in) and\nc pturb (not read in)\n elseif (modtype .eq. 'WEBMARCS') then\n read (nfmodel,*) wavref\n do i=1,ntau\n read (nfmodel,*) k, dummy1(k), tauref(i), dummy2(k), t(i),\n . ne(i), pgas(i)\n enddo\nc*****OR: Read in a model from an alternative form of on-line new\nc MARCS code. This modtype is called \"WEB2MARC\". On each line\nc the numbers are:\nc atmospheric layer number (not needed), log{tau(5000)}, t, \nc log(Pe), log(Pgas), rhox\n elseif (modtype .eq. 'WEB2MARC') then\n read (nfmodel,*) wavref\n do i=1,ntau\n read (nfmodel,*) k,tauref(i),t(i),ne(i),pgas(i),rhox(i)\n enddo\nc OR: Read in a model from the output of the ATLAS code. This\nc modtype is called \"KURUCZ\". On each line the numbers are:\nc rhox, t, pgas, ne, and Rosseland mean opacity (cm^2/gm), and\nc two numbers not used by MOOG. \n elseif (modtype .eq. 'KURUCZ ') then\n do i=1,ntau\n read (nfmodel,*) rhox(i),t(i),pgas(i),ne(i),kaprefmass(i)\n enddo\nc OR: Read in a model from the output of the NEXTGEN code. This\nc modtype is called \"NEXTGEN\". These models have tau scaled at a \nc specific wavelength that is read in before the model. MOOG will \nc need to generate the opacities internally.On each line the numbers \nc are: tau, t, pgas, pe, density, mean molecular weight, two numbers\nc not used by MOOG, and Rosseland mean opacity (cm^2/gm).\n elseif (modtype .eq. 'NEXTGEN ') then\n read (nfmodel,*) wavref\n do i=1,ntau\n read (nfmodel,*) tauref(i),t(i),pgas(i),ne(i), rho(i), \n . molweight(i), x2, x3, kaprefmass(i)\n enddo\nc OR: Read in a model from the output of the MARCS code. This modtype\nc type is called \"BEGN\". On each line the numbers are:\nc tauross, t, log(pg), log(pe), mol weight, and kappaross.\n elseif (modtype .eq. 'BEGN ') then\n do i=1,ntau\n read (nfmodel,*) tauref(i),t(i),pgas(i),ne(i),\n . molweight(i), kaprefmass(i)\n enddo\nc OR: Read in a model generated from ATLAS, but without accompanying\nc opacities. MOOG will need to generate the opacities internally,\nc using a reference wavelength that it reads in before the model.\n elseif (modtype .eq. 'KURTYPE') then\n read (nfmodel,*) wavref \n do i=1,ntau\n read (nfmodel,*) rhox(i),t(i),pgas(i),ne(i)\n enddo\nc OR: Read in a model generated from ATLAS, with output generated\nc in Padova. The columns are in somewhat different order than normal\n elseif (modtype .eq. 'KUR-PADOVA') then\n read (nfmodel,*) wavref\n do i=1,ntau\n read (nfmodel,*) tauref(i),t(i),kaprefmass(i),\n . ne(i),pgas(i),rho(i)\n enddo\nc OR: Read in a generic model that has a tau scale at a specific \nc wavelength that is read in before the model. \nc MOOG will need to generate the opacities internally.\n elseif (modtype .eq. 'GENERIC ') then\n read (nfmodel,*) wavref \n do i=1,ntau\n read (nfmodel,*) tauref(i),t(i),pgas(i),ne(i)\n enddo\nc OR: quit in utter confusion if those model types are not specified\n else\n write (*,1001)\n stop\n endif\n\n\nc*****Compute other convenient forms of the temperatures\n do i=1,ntau\n theta(i) = 5040./t(i)\n tkev(i) = 8.6171d-5*t(i)\n tlog(i) = dlog(t(i))\n enddo\n\n\nc*****Convert from logarithmic Pgas scales, if needed\n if (pgas(ntau)/pgas(1) .lt. 10.) then\n do i=1,ntau \n pgas(i) = 10.0**pgas(i)\n enddo\n endif\n\n\nc*****Convert from logarithmic Ne scales, if needed\n if(ne(ntau)/ne(1) .lt. 20.) then\n do i=1,ntau \n ne(i) = 10.0**ne(i)\n enddo\n endif\n\n\nc*****Convert from Pe to Ne, if needed\n if(ne(ntau) .lt. 1.0e7) then\n do i=1,ntau \n ne(i) = ne(i)/1.38054d-16/t(i)\n enddo\n endif\n\n\nc*****compute the atomic partition functions\n do j=1,95\n elem(j) = dble(j)\n call partfn (elem(j),j)\n enddo\n\n\nc*****Read the microturbulence (either a single value to apply to \nc all layers, or a value for each of the ntau layers). \nc Conversion to cm/sec from km/sec is done if needed\n read (nfmodel,2003) (vturb(i),i=1,6)\n if (vturb(2) .ne. 0.) then\n read (nfmodel,2003) (vturb(i),i=7,ntau) \n else\n do i=2,ntau \n vturb(i) = vturb(1)\n enddo\n endif\n if (vturb(1) .lt. 100.) then\n write (moditle(55:62),1008) vturb(1)\n do i=1,ntau\n vturb(i) = 1.0e5*vturb(i)\n enddo\n else\n write (moditle(55:62),1008) vturb(1)/1.0e5\n endif\n\n\nc*****Read in the abundance data, storing the original abundances in xabu\nc*****The abundances not read in explicity are taken from the default\nc*****solar ones contained in array xsolar.\n read (nfmodel,2002) list\n list2 = list(11:)\n read (list2,*) natoms,abscale\n write (moditle(63:73),1009) abscale\n if(natoms .ne. 0) \n . read (nfmodel,*) (element(i),logepsilon(i),i=1,natoms) \n xhyd = 10.0**xsolar(1)\n xabund(1) = 1.0\n xabund(2) = 10.0**xsolar(2)/xhyd\n do i=3,95 \n xabund(i) = 10.0**(xsolar(i)+abscale)/xhyd\n xabu(i) = xabund(i)\n enddo\n if (natoms .ne. 0) then\n do i=1,natoms \n xabund(idint(element(i))) = 10.0**logepsilon(i)/xhyd\n xabu(idint(element(i))) = 10.0**logepsilon(i)/xhyd\n enddo\n endif\n\nc*****Compute the mean molecular weight, ignoring molecule formation\nc in this approximation (maybe make more general some day?)\n wtnum = 0.\n wtden = 0.\n do i=1,95\n wtnum = wtnum + xabund(i)*xam(i)\n wtden = wtden + xabund(i)\n enddo\n wtmol = wtnum/(xam(1)*wtden)\n nomolweight = 0\n if (modtype .eq. 'BEGN ' .or. modtype .eq. 'NEXTGEN ') then\n nomolweight = 1\n endif\n if (nomolweight .ne. 1) then\n do i=1,ntau\n molweight(i) = wtmol\n enddo\n endif\n\nc*****Compute the density \n if (modtype .ne. 'NEXTGEN ') then\n do i=1,ntau \n rho(i) = pgas(i)*molweight(i)*1.6606d-24/(1.38054d-16*t(i))\n enddo\n endif\n\n\nc*****Calculate the fictitious number density of hydrogen\nc Note: ph = (-b1 + dsqrt(b1*b1 - 4.0*a1*c1))/(2.0*a1)\n iatom = 1\n call partfn (dble(iatom),iatom)\n do i=1,ntau \n th = 5040.0/t(i) \n ah2 = 10.0**(-(12.7422+(-5.1137+(0.1145-0.0091*th)*th)*th))\n a1 = (1.0+2.0*xabund(2))*ah2\n b1 = 1.0 + xabund(2)\n c1 = -pgas(i) \n ph = (-b1/2.0/a1)+dsqrt((b1**2/(4.0*a1*a1))-(c1/a1))\n nhtot(i) = (ph+2.0*ph*ph*ah2)/(1.38054d-16*t(i))\n enddo\n\n\nc*****Molecular equilibrium called here.\nc First, a default list of ions and molecules is considered. Then the \nc user's list is read in. A check is performed to see if any of these \nc species need to be added. If so, then they are appended to the \nc default list. The molecular equilibrium routine is then called.\nc Certain species are important for continuous opacities and damping\nc calculations - these are read from the equilibrium solution and \nc saved.\n\n\nc*****Set up the default molecule list\n if (molset .eq. 0) then\n nmol = 30\n else\n nmol = 59\n endif\n if (molset .eq. 0) then\n do i=1,110\n amol(i) = smallmollist(i)\n enddo\n elseif (molset .eq. 1) then\n do i=1,110\n amol(i) = largemollist(i)\n enddo\n else\n array = 'molset = 0 or 1 only; I quit!'\n call putasci (29,6)\n stop\n endif\n\n\nc*****Read in the names of additional molecules to be used in \nc molecular equilibrium if needed.\n read (nfmodel,2002,end=101) list\n list2 = list(11:)\n read (list2,*) moremol\n if (moremol .ne. 0) then\n read (nfmodel,*) (bmol(i),i=1,moremol)\n append = 1\n do k=1,moremol\n do l=1,nmol\n if (nint(bmol(k)) .eq. nint(amol(l))) \n . append = 0 \n enddo\n if (append .eq. 1) then \n nmol = nmol + 1\n amol(nmol) = bmol(k)\n endif\n append = 1\n enddo \n endif\n\n\nc*****do the general molecular equilibrium\n101 call eqlib\n call resetmol\n\n\nc In the number density array \"numdens\", the elements denoted by\nc the first subscripts are named in at the ends of the assignment\nc lines; at present these are the only ones needed for continuous \nc opacities\nc the desired elements are H, He, C, Mg, Al, Si, Fe, along\nc with the H_2 molecule\nc first do the neutrals\n do j=1,7\n do k=1,neq\n if (nel(j) .eq. iorder(k)) then\n do i=1,ntau\n numdens(j,1,i) = xamol(k,i)\n enddo\n exit\n endif\n enddo\n enddo\nc then do the ions\n do j=1,7\n ispec10 = nint(dble(10*nel(j)+1))\n do k=1,nmol\n kmol10 = nint(10.*amol(k))\n if (ispec10 .eq. kmol10) then\n do i=1,ntau\n numdens(j,2,i) = xmol(k,i)\n enddo\n exit\n endif\n enddo\n enddo\nc finally add in H_2\n do k=1,nmol\n ispec = 101\n if (ispec .eq. nint(amol(k))) then\n do i=1,ntau\n numdens(8,1,i) = xmol(k,i)\n enddo\n exit\n endif\n enddo\n\n\nc*****compute partitiion functions for H_2O and CO_2; \n do i=1,ntau\n h2olog = 0.\n co2log = 0.\n if (t(i) .gt. 5000.) then\n uh2o(i) = 1.d8\n uco2(i) = 1.d8\n else\n do j=1,5\n h2olog = h2olog + h2ocoeff(j)*t(i)**(j-1)\n co2log = co2log + co2coeff(j)*t(i)**(j-1)\n enddo\n uh2o(i) = 10**h2olog\n uco2(i) = 10**co2log\n endif\n enddo\n\n\nc*****transfer H_2O and CO_2 number densities from the molecular \nc equilibrium output\nc note: HITRAN partition functions are given only for T < 5000K\n do j=1,nmol\n if (nint(amol(j)) .eq. 10108) ih2o = j\n if (nint(amol(j)) .eq. 60808) ico2 = j\n enddo\n do i=1,ntau\n xnh2o(i) = xmol(ih2o,i)\n xnco2(i) = xmol(ico2,i)\n enddo\n \n \nc*****SPECIAL NEEDS: for NEWMARCS models, to convert kaprefs to our units\n if (modtype .eq. 'NEWMARCS ') then\n do i=1,ntau\n kapref(i) = kaprefmass(i)*rho(i)\n enddo\nc SPECIAL NEEDS: for KURUCZ models, to create the optical depth array,\nc and to convert kaprefs to our units\n elseif (modtype .eq. 'KURUCZ ') then\n first = rhox(1)*kaprefmass(1)\n tottau = rinteg(rhox,kaprefmass,tauref,ntau,first) \n tauref(1) = first\n do i=2,ntau\n tauref(i) = tauref(i-1) + tauref(i)\n enddo\n do i=1,ntau\n kapref(i) = kaprefmass(i)*rho(i)\n enddo\nc SPECIAL NEEDS: for NEXTGEN models, to convert kaprefs to our units\n elseif (modtype .eq. 'NEXTGEN ') then\n do i=1,ntau \n kapref(i) = kaprefmass(i)*rho(i)\n enddo\nc SPECIAL NEEDS: for BEGN models, to convert kaprefs to our units\n elseif (modtype .eq. 'BEGN ') then\n do i=1,ntau \n kapref(i) = kaprefmass(i)*rho(i)\n enddo\nc SPECIAL NEEDS: for KURTYPE models, to create internal kaprefs,\nc and to compute taurefs from the kaprefs converted to mass units\n elseif (modtype .eq. 'KURTYPE ') then\n call opacit (1,wavref)\n do i=1,ntau \n kaprefmass(i) = kapref(i)/rho(i)\n enddo\n first = rhox(1)*kaprefmass(1)\n tottau = rinteg(rhox,kaprefmass,tauref,ntau,first) \n tauref(1) = first\n do i=2,ntau\n tauref(i) = tauref(i-1) + tauref(i)\n enddo\nc SPECIAL NEEDS: for NEWMARCS models, to convert kaprefs to our units\n elseif (modtype .eq. 'KUR-PADOVA') then\n do i=1,ntau\n kapref(i) = kaprefmass(i)*rho(i)\n enddo\nc SPECIAL NEEDS: for generic models, to create internal kaprefs,\n elseif (modtype .eq. 'GENERIC ' .or.\n . modtype .eq. 'WEBMARCS ' .or.\n . modtype .eq. 'WEB2MARC ') then\n call opacit (1,wavref)\n endif\n\n\nc*****Convert from logarithmic optical depth scales, or vice versa.\nc xref will contain the log of the tauref\n if(tauref(1) .lt. 0.) then\n do i=1,ntau \n xref(i) = tauref(i)\n tauref(i) = 10.0**xref(i)\n enddo\n else\n do i=1,ntau \n xref(i) = dlog10(tauref(i))\n enddo\n endif\n\n\nc*****Write information to output files\n if (modprintopt .lt. 1) return\n write (nf1out,1002) moditle\n do i=1,ntau\n dummy1(i) = dlog10(pgas(i))\n dummy2(i) = dlog10(ne(i)*1.38054d-16*t(i))\n enddo\n write (nf1out,1003) wavref,(i,xref(i),tauref(i),t(i),dummy1(i),\n . pgas(i),dummy2(i),ne(i),vturb(i),i=1,ntau)\n write (nf1out,1004)\n do i=1,95\n dummy1(i) = dlog10(xabund(i)) + 12.0\n enddo\n write (nf1out,1005) (names(i),i,dummy1(i),i=1,95)\n write (nf1out,1006) modprintopt, molopt, linprintopt, fluxintopt\n write (nf1out,1007) (kapref(i),i=1,ntau)\n return\n\n\nc*****format statements\n2001 format (a10)\n2002 format (a80)\n2003 format (6d13.0)\n1001 format('permitted model types are:'/'KURUCZ, BEGN, ',\n . 'KURTYPE, KUR-PADOVA, NEWMARCS, WEBMARCS, NEXTGEN, ',\n . 'WEB2MARC, or GENERIC'/ 'MOOG quits!')\n1002 format (/'MODEL ATMOSPHERE HEADER:'/a80/)\n1003 format ('INPUT ATMOSPHERE QUANTITIES', 10x,\n . '(reference wavelength =',f10.2,')'/3x, 'i', 2x, 'xref',\n . 3x, 'tauref', 7x, 'T', 6x, 'logPg', 4x, 'Pgas',\n . 6x, 'logPe', 5x, 'Ne', 9x, 'Vturb'/\n . (i4, 0pf6.2, 1pd11.4, 0pf9.1, f8.3, 1pd11.4, 0pf8.3,\n . 1pd11.4, d11.2))\n1004 format (/'INPUT ABUNDANCES: (log10 number densities, log H=12)'/\n . ' Default solar abundances: Asplund et al. 2009')\n1005 format (5(3x,a2, '(',i2,')=', f5.2))\n1006 format (/'OPTIONS: atmosphere = ', i1, 5x, 'molecules = ', i1/\n . ' lines = ', i1, 5x, 'flux/int = ', i1)\n1007 format (/'KAPREF ARRAY:'/(6(1pd12.4)))\n1008 format ('vt=', f5.2)\n1009 format (' M/H=', f5.2)\n1010 format (13('-'),'MOOG OUTPUT FILE', 10('-'),\n . '(MOOG version from 01/28/09)', 13('-')//\n . 'THE MODEL TYPE: ', a10)\n1011 format (' The Rosseland opacities and optical depths have ',\n . 'been read in')\n1012 format ('HOUSTON, WE HAVE MORE THAN 100 DEPTH POINTS! I QUIT!')\n\n\n end\n\n", "meta": {"hexsha": "149ba4106e18f998754da6015f99bb369632e5fa", "size": 17783, "ext": "r", "lang": "R", "max_stars_repo_path": "FASMA/MOOG/Setmols.r", "max_stars_repo_name": "ipelupessy/FASMA-synthesis", "max_stars_repo_head_hexsha": "68b9267aa53a1e7023f84f59a4dad76f815cfe3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FASMA/MOOG/Setmols.r", "max_issues_repo_name": "ipelupessy/FASMA-synthesis", "max_issues_repo_head_hexsha": "68b9267aa53a1e7023f84f59a4dad76f815cfe3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FASMA/MOOG/Setmols.r", "max_forks_repo_name": "ipelupessy/FASMA-synthesis", "max_forks_repo_head_hexsha": "68b9267aa53a1e7023f84f59a4dad76f815cfe3b", "max_forks_repo_licenses": ["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.5972762646, "max_line_length": 80, "alphanum_fraction": 0.5251644829, "num_tokens": 5713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2927832045933706}} {"text": "#The simulation script includes three aims.\r\n#when pi=0, to estimate the utility of detecting invers-axis in cases only.\r\n#when pi!=0, to estimate the power of detecting invers-axis in cases only.\r\n#simulations to compare the OR of disease risk between LEV and cSEV-PB\r\n\r\n#disease risk model setting\r\n#LTM (liability threshold model)\r\n#logit model\r\n\r\n#genetric architecture setting\r\n# a=Infinitesimal architecture\r\n# b=with negative selection\r\n# c=LD-adjusted kinship\r\n\r\nargs=commandArgs(TRUE) #subjob id\r\nsubjob_id=as.numeric(args[1]) #subjob id \r\n\r\nN_simulation=500 #simulation times\r\n\r\n#subjobs \r\nrun_i=1\r\nrun_array=list()\r\nfor (h2_p in c(0.1,0.2,0.3,0.4,0.5)){ #h2 poly\r\n for (N_causal_SNPs in c(95593)){ #N of causal SNPs\r\n for (vr in c(0.01,0.02,0.03,0.05,0.10)){ #h2 rare (var rare)\r\n for (freq_r in c(1e-4,0.001,0.005,0.01,0.05)){ #freq rare\r\n for (k in c(0.001,0.005,0.01,0.02,0.05)){ #prevalence\r\n for (genetic_model in c(1,2,3)){ #genetic architecture\r\n for (pi0 in c(0,0.1,0.3,0.5,0.7,0.9)[1]){ #pi0, proportion of causal variants pi0=0: utility; pi0!=0: power\r\n run_array[[run_i]]=c(h2_p,N_causal_SNPs,vr,freq_r,k,genetic_model,pi0)\r\n run_i=run_i+1\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nrun_array<-run_array[[subjob_id]]\r\nh2_p=run_array[1]\r\n#N_causal_SNPs=run_array[2]\r\nvr=run_array[3]\r\nfreq_r=run_array[4]\r\nk=run_array[5]\r\nN_samples=run_array[6]\r\ngenetic_model=switch(run_array[6],'a','b','c')\r\n# a=Infinitesimal architecture\r\n# b=with negative selection\r\n# c=LD-adjusted kinship\r\npi0=run_array[7]\r\n\r\n#load LDsc\r\nldsc<-read.table('/data/c***/z***/projects/prslev/geno/ldsc/ldsc.simulation_all_snps',header = T,stringsAsFactors = F)\r\n\r\n#load common snp table\r\ncommon_all<-read.table('/data/c***/z***/projects/prslev/common/common_all.bim',header = F,stringsAsFactors = F)\r\ncommon_all<-data.frame(rsid=common_all$V2,counted_allele=common_all$V5,effect=NA,stringsAsFactors = F)\r\n\r\n#load MAF for all the common variants (used for maf-dependent genetic architectures)\r\nmaf_all<-read.table('/data/c***/z***/projects/prslev/geno/geno_copies/common_all.frq',header = T,stringsAsFactors = F)\r\n\r\n#n of causal common variants\r\nN_causal_SNPs=nrow(common_all)\r\n\r\n#load rare snps\r\nrare_dosage<-readRDS('/data/c***/z***/data/biovu/geno/23k/prslev_simulation_rare.rds')\r\ncolnames(rare_dosage)[-1]<-sapply(colnames(rare_dosage)[-1], function(x) strsplit(x,\"[_]\")[[1]][1])\r\nrare_all<-data.frame(rsid=colnames(rare_dosage)[-1],effect=NA,stringsAsFactors = F)\r\n\r\n#load rare variant info (freq)\r\nrare_info<-read.table(paste0('/data/c***/z***/data/biovu/geno/chr/rare/rare.list'),header = T,stringsAsFactors = F)\r\nrare_info$SNP=paste0('X',sub(':','.',rare_info$SNP)) #match variants name with dosage data\r\nrare_info<-rare_info[rare_info$maf==freq_r,]\r\n\r\nrare=rare_all[which(rare_all$rsid %in% rare_info$SNP),]\r\n\r\n#allele frequency for rare variants (the actual number of freq, close to the setting)\r\nfreq_snp=sapply(rare$rsid,function(x) rare_info[which(rare_info$SNP==x),'maf'])\r\n#calculate the effect size for rare vatiants\r\nrare$effect=(vr/2/freq_snp/(1-freq_snp))^0.5\r\n#sample N rare variants for simulation (N= number of simulation times)\r\nset.seed(2019)\r\nrare<-rare[sample(nrow(rare),N_simulation,replace = T),]\r\n\r\n\r\n#simulation\r\nN_samples=10000;i=1 #for testing\r\n\r\nfor (N_samples in c(500,1000,2000,3000,5000,10000)){ \r\n print(N_samples)\r\n \r\n #output dataframe (liability-threshold model (LTM), probit)\r\n output_p<-data.frame(h2_p=h2_p,N_causal_SNPs=N_causal_SNPs,vr=vr,freq_r=freq_r,N_samples=N_samples,k=k,pi0=pi0,seed=seq(1,N_simulation),model=genetic_model)\r\n \r\n #output dataframe (logit)\r\n output_l<-data.frame(h2_p=h2_p,N_causal_SNPs=N_causal_SNPs,vr=vr,freq_r=freq_r,N_samples=N_samples,k=k,pi0=pi0,seed=seq(1,N_simulation),model=genetic_model)\r\n \r\n for (i in 1:N_simulation){\r\n print(i)\r\n \r\n #---generate effect sizes for common variants according to different genetic architectures---\r\n df<-common_all\r\n # a Infinitesimal architecture\r\n # beta_poly~(0,h2_p/N_caucal_SNPs)\r\n if(genetic_model=='a'){ \r\n set.seed(i)\r\n df$effect=(1-pi0)*rnorm(N_causal_SNPs,0,(h2_p/N_causal_SNPs)^0.5)\r\n \r\n # b Negative selection\r\n # beta_poly~N(O,k_constant([f(1-f)]^(1+alpha)))\r\n }else if(genetic_model=='b'){ \r\n set.seed(i)\r\n df$effect=df[,'effect']<-sapply(maf_all$MAF,function(f) rnorm(1,mean=0,sd=((f*(1-f))^0.63)^0.5))\r\n #find k constant\r\n k_constant=(h2_p/N_causal_SNPs/var(df[,'effect']))\r\n #multiply by k constant\r\n df[,'effect']<-df[,'effect']*k_constant^0.5*(1-pi0)\r\n \r\n # c LD-adjusted kinship\r\n # beta_poly~N(O,k_constant([f(1-f)]^(1+alpha)*(1/(1+ldsc))))\r\n }else if(genetic_model=='c'){ \r\n set.seed(i)\r\n df$effect=df[,'effect']<-mapply(function(f,ld) rnorm(1,mean=0,sd=(((f*(1-f))^0.75)*1/(1+ld))^0.5), maf_all$MAF, ldsc$ldscore)\r\n #find k constant\r\n k_constant=(h2_p/N_causal_SNPs/var(df[,'effect']))\r\n #multiply by k constant\r\n df[,'effect']<-df[,'effect']*k_constant^0.5*(1-pi0)\r\n }\r\n \r\n #write weight file\r\n write.table(df,paste0('/data/g***/z***/prslev/tmp/',subjob_id,'.weight'),row.names = F,col.names = F,sep='\\t',quote = F)\r\n \r\n #use plink to calculate the PB (PRS of common variants)\r\n #if(i %in% c(1,101,201,301,401)){\r\n cmd=paste0('/home/zhoud2/tools/plink2/plink2 --bfile /data/c***/z***/projects/prslev/common/common_all --score /data/g***/z***/prslev/tmp/',subjob_id,'.weight variance-standardize --out /data/g***/z***/prslev/tmp/',subjob_id,'.score')\r\n system(cmd,wait = T,ignore.stdout=T,ignore.stderr=T)\r\n #}\r\n \r\n #load PB results (A)\r\n PB=read.table(paste0('/data/g***/z***/prslev/tmp/',subjob_id,'.score.sscore'),stringsAsFactors = F)\r\n PB$IID=PB$V1;PB$A=PB$V5*2*nrow(common_all)\r\n PB<-PB[,c('IID','A')]\r\n \r\n #LEV (R)\r\n rare_id=rare[i,'rsid']\r\n rare_effect=rare[i,'effect']\r\n R=as.numeric(rare_dosage[,rare_id]*rare_effect)\r\n LEV<-data.frame(IID=rare_dosage$FID,R=R)\r\n \r\n #merge A and R\r\n combined<-merge(PB,LEV,by='IID')\r\n \r\n #---sampling subjects---\r\n set.seed(i)\r\n combined<-combined[sample(seq(1,nrow(combined)),N_samples,replace = F),]\r\n \r\n #x=A+R\r\n combined$x=combined$A+combined$R\r\n \r\n #h2_e\r\n h2_e=1-h2_p-vr\r\n \r\n #probability of disease (same with LTM)\r\n set.seed(i)\r\n combined$L=combined$x+rnorm(nrow(combined),0,h2_e^0.5)\r\n t=quantile(combined$L,1-k)[[1]]\r\n combined$prob=pnorm(-(t-combined$x)/h2_e^0.5)\r\n \r\n #--------logit model---start-------\r\n set.seed(i)\r\n combined$y_binary<-sapply(combined$prob,function(x) rbinom(1,1,x))\r\n combined$R<-ifelse(combined$R!=0,1,0)\r\n \r\n #test inverse axis in cases only\r\n if(length(which(combined$y_binary==1 & combined$R==1))>0 & length(which(combined$y_binary==1 & combined$R==0))>0){\r\n cases<-combined[combined$y_binary==1,]\r\n #test inverse axis\r\n ans_inverse<-wilcox.test(cases[cases$R==1,'A'],cases[cases$R==0,'A'],alternative = c(\"less\"))\r\n output_l[i,'case_inverse_wilcox_p']<-ans_inverse$p.value\r\n }else{\r\n output_l[i,'case_inverse_wilcox_p']<-1\r\n }\r\n \r\n #test inverse axis in controls only\r\n if(length(which(combined$y_binary==0 & combined$R==1))>0 & length(which(combined$y_binary==0 & combined$R==0))>0){\r\n controls<-combined[combined$y_binary==0,]\r\n #test inverse axis\r\n ans_inverse<-wilcox.test(controls[controls$R==1,'A'],controls[controls$R==0,'A'],alternative = c(\"less\"))\r\n output_l[i,'control_inverse_wilcox_p']<-ans_inverse$p.value\r\n }else{\r\n output_l[i,'control_inverse_wilcox_p']<-1\r\n }\r\n \r\n \r\n #--OR comparision between LEV and PB--\r\n for (top_p in c(0.01,0.05,0.1)){\r\n cut_off=quantile(combined$A,1-top_p)[[1]]\r\n combined$A_binary<-ifelse(combined$A>cut_off,1,0)\r\n \r\n A_check=table(combined$y_binary,combined$A_binary)\r\n R_check=table(combined$y_binary,combined$R)\r\n \r\n if(length(A_check)==4 & min(A_check)>0 & length(R_check)==4 & min(R_check)>0){\r\n ans_A<-summary(glm(combined$y_binary~combined$A_binary,family = 'binomial'))\r\n ans_R<-summary(glm(combined$y_binary~combined$R,family = 'binomial'))\r\n \r\n output_l[i,paste0('A_top_',top_p,'_beta')]<-ans_A$coefficients['combined$A_binary','Estimate']\r\n output_l[i,paste0('A_top_',top_p,'_se')]<-ans_A$coefficients['combined$A_binary','Std. Error']\r\n output_l[i,paste0('R_beta')]<-ans_R$coefficients['combined$R','Estimate']\r\n output_l[i,paste0('R_se')]<-ans_R$coefficients['combined$R','Std. Error']\r\n }\r\n }\r\n #--------logit model---end-------\r\n \r\n #------liability-threshold model (probit) ---start-----\r\n combined$y_binary<-ifelse(combined$L>t,1,0)\r\n table_check<-table(combined$y_binary,combined$R)\r\n \r\n #test inverse axis in cases only\r\n if(length(which(combined$y_binary==1 & combined$R==1))>0 & length(which(combined$y_binary==1 & combined$R==0))>0){\r\n cases<-combined[combined$y_binary==1,]\r\n #test inverse axis\r\n ans_inverse<-wilcox.test(cases[cases$R==1,'A'],cases[cases$R==0,'A'],alternative = c(\"less\"))\r\n output_p[i,'case_inverse_wilcox_p']<-ans_inverse$p.value\r\n }else{\r\n output_p[i,'case_inverse_wilcox_p']<-1\r\n }\r\n \r\n #test inverse axis in controls only\r\n if(length(which(combined$y_binary==0 & combined$R==1))>0 & length(which(combined$y_binary==0 & combined$R==0))>0){\r\n controls<-combined[combined$y_binary==0,]\r\n #test inverse axis\r\n ans_inverse<-wilcox.test(controls[controls$R==1,'A'],controls[controls$R==0,'A'],alternative = c(\"less\"))\r\n output_p[i,'control_inverse_wilcox_p']<-ans_inverse$p.value\r\n }else{\r\n output_p[i,'control_inverse_wilcox_p']<-1\r\n }\r\n \r\n \r\n #--OR comparision between LEV and PB--\r\n for (top_p in c(0.01,0.05,0.1)){\r\n cut_off=quantile(combined$A,1-top_p)[[1]]\r\n combined$A_binary<-ifelse(combined$A>cut_off,1,0)\r\n \r\n A_check=table(combined$y_binary,combined$A_binary)\r\n R_check=table(combined$y_binary,combined$R)\r\n \r\n if(length(A_check)==4 & min(A_check)>0 & length(R_check)==4 & min(R_check)>0){\r\n ans_A<-summary(glm(combined$y_binary~combined$A_binary,family = 'binomial'))\r\n ans_R<-summary(glm(combined$y_binary~combined$R,family = 'binomial'))\r\n \r\n output_p[i,paste0('A_top_',top_p,'_beta')]<-ans_A$coefficients['combined$A_binary','Estimate']\r\n output_p[i,paste0('A_top_',top_p,'_se')]<-ans_A$coefficients['combined$A_binary','Std. Error']\r\n output_p[i,paste0('R_beta')]<-ans_R$coefficients['combined$R','Estimate']\r\n output_p[i,paste0('R_se')]<-ans_R$coefficients['combined$R','Std. Error']\r\n }\r\n }\r\n \r\n #------liability-threshold model (probit) ---end-----\r\n \r\n }\r\n \r\n #write result liability-threshold (probit)\r\n write.table(output_p,paste0('/data/g***/z***/prslev/result/probit_',genetic_model,'/h2p_',h2_p,'_nsnp_','all_snps','_vr_',vr,'_freqr_',freq_r,'_k_',k,'_Nsample_',N_samples,'_pi0_',pi0),quote = F,row.names = F,sep='\\t')\r\n \r\n #write result logit model\r\n write.table(output_l,paste0('/data/g***/z***/prslev/result/logit_',genetic_model,'/h2p_',h2_p,'_nsnp_','all_snps','_vr_',vr,'_freqr_',freq_r,'_k_',k,'_Nsample_',N_samples,'_pi0_',pi0),quote = F,row.names = F,sep='\\t')\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": "895f4df283047410006de1d8b0392333f74bf435", "size": 11481, "ext": "r", "lang": "R", "max_stars_repo_path": "src/simulation_utility_power_and_OR_comparison_LEV_cSEV.r", "max_stars_repo_name": "gamazonlab/Polygenic_Background_Rare_Variant_Axis", "max_stars_repo_head_hexsha": "f86f3e385ae458e738ce9dcd0c0dbaa6e376fac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2021-08-05T14:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:58:29.000Z", "max_issues_repo_path": "src/simulation_utility_power_and_OR_comparison_LEV_cSEV.r", "max_issues_repo_name": "gamazonlab/Polygenic_Background_Rare_Variant_Axis", "max_issues_repo_head_hexsha": "f86f3e385ae458e738ce9dcd0c0dbaa6e376fac4", "max_issues_repo_licenses": ["MIT"], "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/simulation_utility_power_and_OR_comparison_LEV_cSEV.r", "max_forks_repo_name": "gamazonlab/Polygenic_Background_Rare_Variant_Axis", "max_forks_repo_head_hexsha": "f86f3e385ae458e738ce9dcd0c0dbaa6e376fac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-08-10T16:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T16:27:27.000Z", "avg_line_length": 40.426056338, "max_line_length": 240, "alphanum_fraction": 0.6475916732, "num_tokens": 3714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2923814378995846}} {"text": "\nreshape_res = function(out, nn = names(inits), \n\t\t cl = dimnames(Y)$country,\n\t\t n_years = hyp$Time, \n\t\t n_countries = hyp$N_countries, \n\t\t n_clust = hyp$H, pG = 2) {\n\n\t# I primi sono a posto così. Gli altri serve un po' di reshape manuale\n\t# prendiamo quelli bidimensionali\n\tnn_red = grep(\"^drift_|s_\", nn,invert=T,value=T)\n\tres = list()\n\n\t# actual Parameters, [nit x countries x years] format\n\tfor(i in 1:length(nn_red)) {\n\t\ttmp = out[,grep(paste0(\"^\",nn_red[i],\"\\\\[\"), colnames(out) )]\n\t\tres[[nn_red[i]]] = drop(array(tmp, dim = c(NROW(tmp), ncol(tmp)/n_years,n_years )))\n\t}\n\n\t# multivariate components: drift\n\tnn_dr = grep(\"drift\", nn,value=T)\n\tfor(i in 1:length(nn_dr)){\n\t\ttmp = out[,grep(paste0(\"^\",nn_dr[i],\"\\\\[\"), colnames(out) )]\n\t\tres[[nn_dr[i]]] = drop(array(tmp, dim = c(NROW(tmp), ncol(tmp)/n_countries,n_countries )))\n\t} \n\tnn_s = grep(\"s_\", nn,value=T)\n\tfor(i in 1:length(nn_dr)){\n\t\ttmp = out[,grep(paste0(\"^\",nn_s[i],\"\\\\[\"), colnames(out) )]\n\t\tres[[nn_s[i]]] = drop(array(tmp, dim = c(NROW(tmp), ncol(tmp)/n_countries,n_countries )))\n\t}\n\n\n\t\n\n\treturn(res)\n}\n\n## We use a different parametrisation\nadd_w = function(pl) {\n\tw0=w1=w2=array(NA, dim = dim(pl$eta1))\n\tfor(j in 1:dim(pl$eta1)[2]){\n\tfor(k in 1:dim(pl$eta1)[3]){\n\t\ttmp = t(apply(cbind(pl$eta1[,j,k], pl$eta2[,j,k]), 1, function(r) eta_to_w(eta1 = r[1], eta2 = r[2])))\n\t\tw2[,j,k] = tmp[,3] \n\t\tw1[,j,k] = tmp[,2]\n\t\tw0[,j,k] = tmp[,1]\n\t}\n\t}\n\treturn(c(pl, list(\"w0\" = w0,\"w1\" = w1,\"w2\" = w2)))\n}\n\n\nadd_skew_moments = function(pl) {\n\t# computes sn moments\n\ta2d = function(a) a / sqrt( 1 + a^2 )\n\tm = function(xi, omega, d) xi + omega * d * sqrt(2/pi)\n\tv = function(omega, d) omega^2 * (1 - 2 * d^2 / pi )\n\n\tsn_mean=sn_sd=array(NA, dim = dim(pl$xi))\n\tfor(j in 1:dim(pl$xi)[2]){\n\tfor(k in 1:dim(pl$xi)[3]){\n\t\tsn_mean[,j,k] = m(pl$xi[,j,k],sqrt(exp(pl$lomega[,j,k])), a2d(pl$alpha[,j,k]))\n\t\tsn_sd[,j,k] = sqrt(v(sqrt(exp(pl$lomega[,j,k])), a2d(pl$alpha[,j,k])))\n\t}}\n\treturn(c(pl, list(\"sn_mean\" = sn_mean, \"sn_sd\" = sn_sd)))\n\n\n}\n\n\n\neta_to_w = function(eta1,eta2) {\n\texpit = function(x) exp(x) / (1 + exp(x) )\n\t\tc(expit(-eta1) * expit(-eta2), expit(eta2) * expit(-eta1), expit(eta1))\n}\n\n\n\n# This function obtains predictions recursively\nget_rec_pred = function(nyears = 10, pl, hyp)\n{\n\tobj_size = c(NROW(pl$xi),hyp$N_countries, nyears)\n\n\ttmp = list()\n\ttmp$xi = array(NA, dim = obj_size)\n\ttmp$lomega = array(NA, dim = obj_size)\n\ttmp$alpha = array(NA, dim = obj_size)\n\n\ttmp$mu = array(NA, dim = obj_size)\n\ttmp$lsigma = array(NA, dim = obj_size)\n\n\ttmp$eta1 = array(NA, dim = obj_size)\n\ttmp$eta2 = array(NA, dim = obj_size)\n\n\n\tfor(it in 1:NROW(pl$mu)){\n\t\tfor(nc in 1:obj_size[2]) { # loop across countries\n\n\t\t\ttmp$xi[it,nc,1] = pl$xi[it,nc,hyp$Time] + pl$drift_xi[it,nc]\n\t\t\ttmp$lomega[it,nc,1] = pl$lomega[it,nc,hyp$Time] + pl$drift_lomega[it,nc]\n\t\t\ttmp$alpha[it,nc,1] = pl$alpha[it,nc,hyp$Time] + pl$drift_alpha[it,nc]\n\n\t\t\ttmp$mu[it,nc,1] = pl$mu[it,nc,hyp$Time] + pl$drift_mu[it,nc]\n\t\t\ttmp$lsigma[it,nc,1] = pl$lsigma[it,nc,hyp$Time] + pl$drift_lsigma[it,nc]\n\n\t\t\ttmp$eta1[it,nc,1] = pl$eta1[it,nc,hyp$Time] + pl$drift_eta1[it,nc]\n\t\t\ttmp$eta2[it,nc,1] = pl$eta2[it,nc,hyp$Time] + pl$drift_eta2[it,nc]\n\n\t\t\t# Now loop in time\n\t\t\tfor(tt in 2:obj_size[3]) { # loop in time and get recursive predictions\n\t\t\t\ttmp$xi[it,nc,tt] = tmp$xi[it,nc,tt-1] + pl$drift_xi[it,nc]\n\t\t\t\ttmp$lomega[it,nc,tt] = tmp$lomega[it,nc,tt-1] + pl$drift_lomega[it,nc]\n\t\t\t\ttmp$alpha[it,nc,tt] = tmp$alpha[it,nc,tt-1] + pl$drift_alpha[it,nc]\n\n\t\t\t\ttmp$mu[it,nc,tt] = tmp$mu[it,nc,tt-1] + pl$drift_mu[it,nc]\n\t\t\t\ttmp$lsigma[it,nc,tt] = tmp$lsigma[it,nc,tt-1] + pl$drift_lsigma[it,nc]\n\n\t\t\t\ttmp$eta1[it,nc,tt] = tmp$eta1[it,nc,tt-1] + pl$drift_eta1[it,nc]\n\t\t\t\ttmp$eta2[it,nc,tt] = tmp$eta2[it,nc,tt-1] + pl$drift_eta2[it,nc]\n\t\t\t}\n\t\t\t}\n\n\t\tif(it %% 50 == 0) cat(it, \" over \", obj_size[1], \"\\n\")\n\t}\n\treturn(tmp)\n}\n\n\n# This function obtains predictions recursively\nget_pred_ppd = function(nyears = 10, pl, hyp, seed = 1)\n{\n\tset.seed(seed)\n\tobj_size = c(NROW(pl$xi),hyp$N_countries, nyears)\n\n\ttmp = list()\n\ttmp$xi = array(NA, dim = obj_size)\n\ttmp$lomega = array(NA, dim = obj_size)\n\ttmp$alpha = array(NA, dim = obj_size)\n\n\ttmp$mu = array(NA, dim = obj_size)\n\ttmp$lsigma = array(NA, dim = obj_size)\n\n\ttmp$eta1 = array(NA, dim = obj_size)\n\ttmp$eta2 = array(NA, dim = obj_size)\n\n\tfor(it in 1:NROW(pl$mu)){\n\t\tfor(nc in 1:obj_size[2]) { # loop across countries\n\t\t\ttmp$xi[it,nc,1] = rnorm(1, mean = pl$xi[it,nc,hyp$Time] + pl$drift_xi[it,nc], sd = sqrt(pl$s_xi[it,nc]))\n\t\t\ttmp$lomega[it,nc,1] = rnorm(1, mean = pl$lomega[it,nc,hyp$Time] + pl$drift_lomega[it,nc], sd = sqrt(pl$s_lomega[it,nc]))\n\t\t\ttmp$alpha[it,nc,1] = rnorm(1, mean = pl$alpha[it,nc,hyp$Time] + pl$drift_alpha[it,nc], sd = sqrt(pl$s_alpha[it,nc]))\n\n\t\t\ttmp$mu[it,nc,1] = rnorm(1, mean = pl$mu[it,nc,hyp$Time] + pl$drift_mu[it,nc], sd = sqrt(pl$s_mu[it,nc]))\n\t\t\ttmp$lsigma[it,nc,1] = rnorm(1, mean = pl$lsigma[it,nc,hyp$Time] + pl$drift_lsigma[it,nc], sd = sqrt(pl$s_lsigma[it,nc]))\n\n\t\t\ttmp$eta1[it,nc,1] = rnorm(1, mean = pl$eta1[it,nc,hyp$Time] + pl$drift_eta1[it,nc], sd = sqrt(pl$s_eta1[it,nc]))\n\t\t\ttmp$eta2[it,nc,1] = rnorm(1, mean = pl$eta2[it,nc,hyp$Time] + pl$drift_eta2[it,nc], sd = sqrt(pl$s_eta2[it,nc]))\n\n\t\t\t# Now loop in time\n\t\t\tfor(tt in 2:obj_size[3]) { # loop in time and get recursive predictions\n\t\t\t\ttmp$xi[it,nc,tt] = rnorm(1, mean = tmp$xi[it,nc,tt-1] + pl$drift_xi[it,nc], sd = sqrt(pl$s_xi[it,nc]))\n\t\t\t\ttmp$lomega[it,nc,tt] = rnorm(1, mean = tmp$lomega[it,nc,tt-1] + pl$drift_lomega[it,nc], sd = sqrt(pl$s_lomega[it,nc]))\n\t\t\t\ttmp$alpha[it,nc,tt] = rnorm(1, mean = tmp$alpha[it,nc,tt-1] + pl$drift_alpha[it,nc], sd = sqrt(pl$s_alpha[it,nc]))\n\n\t\t\t\ttmp$mu[it,nc,tt] = rnorm(1, mean = tmp$mu[it,nc,tt-1] + pl$drift_mu[it,nc], sd = sqrt(pl$s_mu[it,nc]))\n\t\t\t\ttmp$lsigma[it,nc,tt] = rnorm(1, mean = tmp$lsigma[it,nc,tt-1] + pl$drift_lsigma[it,nc], sd = sqrt(pl$s_lsigma[it,nc]))\n\n\t\t\t\ttmp$eta1[it,nc,tt] = rnorm(1, mean = tmp$eta1[it,nc,tt-1] + pl$drift_eta1[it,nc], sd = sqrt(pl$s_eta1[it,nc]))\n\t\t\t\ttmp$eta2[it,nc,tt] = rnorm(1, mean = tmp$eta2[it,nc,tt-1] + pl$drift_eta2[it,nc], sd = sqrt(pl$s_eta2[it,nc]))\n\t\t\t}\n\n\t\t}\n\t\tif(it %% 50 == 0) cat(it, \" over \", obj_size[1], \"\\n\")\n\t}\n\treturn(tmp)\n}\n\n\n\nget_df_summ = function(pl,pred, countries = dimnames(dd$y)[[1]], \n\t\t log_scale = T, w = F, \n\t\t moments = F,\n\t\t func = \"mean\", ...) {\n\tdf_pl = list()\n\n\tfor(p in 1:length(countries)){\n\t\tcur_c = countries[p]\n\t\ttmp = data.frame(x=1:(hyp$Time+dim(pred$xi)[3]))\n\n\t\tif(w) {\n\t\t\ttmp$w0 = c(apply(pl$w0[,p,],2,get(func), ...), apply(pred$w0[,p,],2,get(func), ...))\n\t\t\ttmp$w1 = c(apply(pl$w1[,p,],2,get(func), ...), apply(pred$w1[,p,],2,get(func), ...))\n\t\t\ttmp$w2 = c(apply(pl$w2[,p,],2,get(func), ...), apply(pred$w2[,p,],2,get(func), ...))\n\t\t} else {\n\t\t\ttmp$eta1 = c(apply(pl$eta1[,p,],2,get(func), ...), apply(pred$eta1[,p,],2,get(func), ...))\n\t\t\ttmp$eta2 =c( apply(pl$eta2[,p,],2,get(func), ...), apply(pred$eta2[,p,],2,get(func), ...))\n\t\t}\n\n\t\ttmp$mu =c( apply(pl$mu[,p,],2,get(func), ...), apply(pred$mu[,p,],2,get(func), ...))\n\n\t\tif(log_scale){\n\t\t\ttmp$sigma =c( apply((pl$lsigma[,p,]),2,get(func), ...), apply((pred$lsigma[,p,]),2,get(func), ...))\n\t\t\ttmp$omega =c( apply((pl$lomega[,p,]),2,get(func), ...), apply((pred$lomega[,p,]),2,get(func), ...))\n\t\t} else {\n\t\t\ttmp$sigma =c( apply(exp(pl$lsigma[,p,]),2,get(func), ...), apply(exp(pred$lsigma[,p,]),2,get(func), ...))\n\t\t\ttmp$omega =c( apply(exp(pl$lomega[,p,]),2,get(func), ...), apply(exp(pred$lomega[,p,]),2,get(func), ...))\n\t\t}\n\n\t\ttmp$xi =c( apply(pl$xi[,p,],2,get(func), ...), apply(pred$xi[,p,],2,get(func), ...))\n\t\ttmp$alpha =c( apply(pl$alpha[,p,],2,get(func), ...), apply(pred$alpha[,p,],2,get(func), ...))\n\n\t\tif(moments) {\n\t\t\ttmp$sn_mean =c( apply(pl$sn_mean[,p,],2,get(func), ...), apply(pred$sn_mean[,p,],2,get(func), ...))\n\t\t\ttmp$sn_sd =c( apply(pl$sn_sd[,p,],2,get(func), ...), apply(pred$sn_sd[,p,],2,get(func), ...))\n\t\t\ttmp$xi = NULL\n\t\t\ttmp$omega = NULL\n\t\t}\n\n\t\tdf_pl[[cur_c]] = tmp\n\n\n\n\t}\n\treturn(df_pl)\n}\n\n\nget_df_ic = function(pl,pred, \n\t\t countries = dimnames(dd$y)[[1]],\n\t\t log_scale = T, \n\t\t w = F,\n\t\t moments = F,\n\t\t level = 0.05) {\n\tdf_pl = list()\n\n\tfor(p in 1:length(countries)){\n\t\tcur_c = countries[p]\n\t\ttmp = data.frame(x=1:(hyp$Time+dim(pred$xi)[3]))\n\n\n\t\tif(w) {\n\t\t\ttmp$w0 = c(apply(pl$w0[,p,],2,quantile, level), apply(pred$w0[,p,],2,quantile, level))\n\t\t\ttmp$w1 = c(apply(pl$w1[,p,],2,quantile, level), apply(pred$w1[,p,],2,quantile, level))\n\t\t\ttmp$w2 = c(apply(pl$w2[,p,],2,quantile, level), apply(pred$w2[,p,],2,quantile, level))\n\t\t} else {\n\t\t\ttmp$eta1 = c(apply(pl$eta1[,p,],2,quantile, level), apply(pred$eta1[,p,],2,quantile, level))\n\t\t\ttmp$eta2 = c(apply(pl$eta2[,p,],2,quantile, level), apply(pred$eta2[,p,],2,quantile, level))\n\t\t}\n\n\t\ttmp$mu =c( apply(pl$mu[,p,],2,quantile, level), apply(pred$mu[,p,],2,quantile, level))\n\n\t\tif(log_scale){\n\t\t\ttmp$sigma =c( apply((pl$lsigma[,p,]),2,quantile, level), apply((pred$lsigma[,p,]),2,quantile, level))\n\t\t\ttmp$omega =c( apply((pl$lomega[,p,]),2,quantile, level), apply((pred$lomega[,p,]),2,quantile, level))\n\t\t} else {\n\t\t\ttmp$sigma =c( apply(exp(pl$lsigma[,p,]),2,quantile, level), apply(exp(pred$lsigma[,p,]),2,quantile, level))\n\t\t\ttmp$omega =c( apply(exp(pl$lomega[,p,]),2,quantile, level), apply(exp(pred$lomega[,p,]),2,quantile, level))\n\t\t}\n\n\t\ttmp$xi =c( apply(pl$xi[,p,],2,quantile, level), apply(pred$xi[,p,],2,quantile, level))\n\t\ttmp$alpha =c( apply(pl$alpha[,p,],2,quantile, level), apply(pred$alpha[,p,],2,quantile, level))\n\t\tif(moments) {\n\t\t\ttmp$sn_mean =c( apply(pl$sn_mean[,p,],2,quantile, level), apply(pred$sn_mean[,p,],2,quantile, level))\n\t\t\ttmp$sn_sd =c( apply(pl$sn_sd[,p,],2,quantile, level), apply(pred$sn_sd[,p,],2,quantile, level))\n\t\t\ttmp$xi = NULL\n\t\t\ttmp$omega = NULL\n\t\t}\n\n\t\tdf_pl[[cur_c]] = tmp\n\t}\n\treturn(df_pl)\n}\n\n\n\n\nget_df_ic_h = function(pl,pred, \n\t\t countries = dimnames(dd$y)[[1]],\n\t\t log_scale = T, w = F, moments = F,\n\t\t level = 0.95, upper = T){\n\tdf_pl = list()\n\n\temp_hpd = function(x, level) TeachingDemos::emp.hpd(x, level)[ifelse(upper,2,1)]\n\n\tfor(p in 1:length(countries)){\n\t\tcur_c = countries[p]\n\t\ttmp = data.frame(x=1:(hyp$Time+dim(pred$xi)[3]))\n\n\t\tif(w) {\n\t\t\ttmp$w0 = c(apply(pl$w0[,p,],2,emp_hpd, level), apply(pred$w0[,p,],2,emp_hpd, level))\n\t\t\ttmp$w1 = c(apply(pl$w1[,p,],2,emp_hpd, level), apply(pred$w1[,p,],2,emp_hpd, level))\n\t\t\ttmp$w2 = c(apply(pl$w2[,p,],2,emp_hpd, level), apply(pred$w2[,p,],2,emp_hpd, level))\n\t\t} else {\n\t\t\ttmp$eta1 = c(apply(pl$eta1[,p,],2,emp_hpd, level), apply(pred$eta1[,p,],2,emp_hpd, level))\n\t\t\ttmp$eta2 = c(apply(pl$eta2[,p,],2,emp_hpd, level), apply(pred$eta2[,p,],2,emp_hpd, level))\n\t\t}\n\n\n\t\ttmp$mu =c( apply(pl$mu[,p,],2,emp_hpd, level), apply(pred$mu[,p,],2,emp_hpd, level))\n\n\t\tif(log_scale){\n\t\t\ttmp$sigma =c( apply((pl$lsigma[,p,]),2,emp_hpd, level), apply((pred$lsigma[,p,]),2,emp_hpd, level))\n\t\t\ttmp$omega =c( apply((pl$lomega[,p,]),2,emp_hpd, level), apply((pred$lomega[,p,]),2,emp_hpd, level))\n\t\t} else {\n\t\t\ttmp$sigma =c( apply(exp(pl$lsigma[,p,]),2,emp_hpd, level), apply(exp(pred$lsigma[,p,]),2,emp_hpd, level))\n\t\t\ttmp$omega =c( apply(exp(pl$lomega[,p,]),2,emp_hpd, level), apply(exp(pred$lomega[,p,]),2,emp_hpd, level))\n\t\t}\n\n\t\ttmp$xi =c( apply(pl$xi[,p,],2,emp_hpd, level), apply(pred$xi[,p,],2,emp_hpd, level))\n\t\ttmp$alpha =c( apply(pl$alpha[,p,],2,emp_hpd, level), apply(pred$alpha[,p,],2,emp_hpd, level))\n\n\t\tif(moments) {\n\t\t\ttmp$sn_mean =c( apply(pl$sn_mean[,p,],2,emp_hpd, level), apply(pred$sn_mean[,p,],2,emp_hpd, level))\n\t\t\ttmp$sn_sd =c( apply(pl$sn_sd[,p,],2,emp_hpd, level), apply(pred$sn_sd[,p,],2,emp_hpd, level))\n\t\t\ttmp$xi = NULL\n\t\t\ttmp$omega = NULL\n\t\t}\n\n\t\tdf_pl[[cur_c]] = tmp\n\t}\n\treturn(df_pl)\n}\n\n\n\n\n", "meta": {"hexsha": "39426af72049848ea0af90202bd05cafa850e880", "size": 11866, "ext": "r", "lang": "R", "max_stars_repo_path": "APPLICATION/post_proc_util.r", "max_stars_repo_name": "emanuelealiverti/dysm", "max_stars_repo_head_hexsha": "0c5b31194eade93b9740e87c0cad8503b1ff92ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "APPLICATION/post_proc_util.r", "max_issues_repo_name": "emanuelealiverti/dysm", "max_issues_repo_head_hexsha": "0c5b31194eade93b9740e87c0cad8503b1ff92ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APPLICATION/post_proc_util.r", "max_forks_repo_name": "emanuelealiverti/dysm", "max_forks_repo_head_hexsha": "0c5b31194eade93b9740e87c0cad8503b1ff92ff", "max_forks_repo_licenses": ["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.5107692308, "max_line_length": 123, "alphanum_fraction": 0.5927861116, "num_tokens": 4715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.29214692225283884}} {"text": "\n\n\n\n####################################################\n\n#This is the wrapper for running the LCM model for \n# Crozier, Burke, Chasco, Widener and Zabel 2020\n# Iconic salmon populations face perilous challenges from climate change across their life cycle\n# published in Communications Biology\n\n####################################################\n####################################################\n\n\nset.seed(10000)\nlibrary(plyr)\n\n# Model control parameters---------\n#1.Select which model you want to run. Models are defined by which freshwater and marine covariates they include\n #e.g., Model 1:\n # FW: p2TsuFfall\n # In-river: ersstArc.win + ersstWAcoast.sum\n # Transport: ersstArc.win \n\n model<-\"Model1\";filename<-\"p2TsuFfall\"; Fname=\"F.S3.ParrF\"; FW.name=\"Ffall\"\n # model<-\"Model2\"; filename<-\"p2Fsu\"; Fname=\"F.S2.ParrSu\"; FW.name=\"Fsu\"\n # model<-\"Model3\"; filename<-\"p2TsuFfall\"; Fname=\"F.S3.ParrF\"; FW.name=\"Ffall\"\n arrayname<-paste0(model,\".array\")\n load(file=paste(\"Input files/param\",arrayname,sep=\".\"),verbose=T) #param.array.1K\n\n \n#2. Decide how many simulations,populations and climate scenarios you want to run and build list of scenarios\n runs = 10\n years = 75 #2015:2089\n pop<-creeks<-\"bearvalley\"\n# pop<-creeks<-c(\"bearvalley\",\"big\",\"camas\",\"loon\",\"marsh\",\"secesh\",\"sulphur\",\"valley\")\n\n climate =c(\"stationary\",\"4.5\" , \"8.5\" )\n climateshort =c(\"1\",\"45\" , \"85\" )\n quant = c(\"25\", \"50\", \"75\")\n\n nsim<-length(pop)*length(model)*length(climate)*length(quant)#;nsim\n scenario<-length(model)*length(climate)*length(quant);scenario\n scenario.name<-vector(\"character\",length=scenario)\n cnt.scenario=0\n for(l in 1:length(model)){\n for(cc in 1:length(climate)){ \n for(qq in 1:length(quant)){ \n cnt.scenario=cnt.scenario+1\n scenario.name[cnt.scenario]=paste(climate[cc],quant[qq],model[l],sep=\".\");scenario.name\n }}}\n \n\n#Input files-------------------\n #FW\n source(\"LCM.fxn.r\") #functions for model relationships\n popinit<-read.csv(\"Input files/Ninit.csv\", header = T, row.names = 1)\n hydro<-read.csv(file=\"Input files/climategrid_survival_80yr_2020_PA.csv\",header=TRUE,row.names = NULL);hydro$gridYear<-rep(1:80,length=nrow(hydro))\n FW<-read.csv(file=\"Input files/SALM.Qflow.csv\",header=TRUE,row.names = NULL)#;head(FW)\n FW<-FW[FW$year>=2015,]\n scalefactors<-read.csv(file=\"Input files/scalefactors.corrected.May2019.csv\",row.names=1)#;scalefactors\n su<-read.csv(\"Input files/AprilJuneAndSurv_LoopsTransport.csv\",row.names = NULL,header=TRUE)#;head(su)\n su$LGRtemp<-round_any(su$LGrTempAJ,0.5)#;simtemp\n su$LGRflow<-round_any(su$LGrFlowAJ,20)#;simflow\n\n \n #SARs \n if(model==\"Model3\") sarfile<-\"Model3.SAR100.Rdata\" else sarfile<-\"Model1.Model2.SAR100.Rdata\"\n print(sarfile)\n load(paste0(\"Input files/\",sarfile),verbose=TRUE) \n \n #collect parameters used in each run\n param.marT<-as.data.frame(t(sarcoefT_rqvs[\"stationary\",\"50\",,]))\n names(param.marT)<-paste(\"T\",names(param.marT),sep=\".\")\n param.marI<-as.data.frame(t(sarcoefI_rqvs[\"stationary\",\"50\",,])) \n names(param.marI)<-paste(\"I\",names(param.marI),sep=\".\")\n\n# Set up temporary arrays to store data during model runs-----------\n N.new = N = array(0,5)\n surv.s1=surv.trib=surv.inriver=pt=pt.sar=pt.sup=surv.main=surv.s2=surv.s3=surv.sar=surv.sarI=surv.sarT=surv.sup=sup.spr.inriver=sup.spr.transport=sup.sum.inriver=sup.sum.transport=sup.spring=sup.summer=Spawners = Recruits = array(0,years) #indiv years within a run\n\n # Arrays to save output-----------\n spawner.array<-parrsmolt.array<-recruit.array<-array(0,dim=c(years,runs,length(pop),scenario),dimnames=list(2015:2089,paste0(\"sim\",1:runs),pop,scenario.name))#;dim(spawner.array)\n response<-c(\"yrQET50\",\"Mean2020\",\"Mean2040\",\"Mean2060\",\"Mean2080\",\"Meanallyears\")\n allparam<-c( names(param.marI),names(param.marT),dimnames(param.array.1K)[[2]],response)# ;allparam\n param.array<-array(0,dim=c(runs,length(allparam),length(pop),scenario),dimnames=list(paste0(\"sim\",1:runs),allparam,pop,scenario.name))#;dim(param.array)\n \n\n\n#START LOOPING THROUGH SIMULATIONS ========================\n print(Sys.time()) \n#k=1;l=1;m=1;cc=1;p=1;j=1;qq=1\ncnt=0\nfor(k in 1:length(pop)){ # loop across populations\n cnt.scenario=0\n print(paste(\"Pop\",k,pop[k],Sys.time()))\n ha= popinit[pop[k],\"ha\"]\n for(cc in 1:length(climate)){ \n for(qq in 1:length(quant)){ #loop across quantiles of each climate scenario\n cnt.scenario=cnt.scenario+1;print(scenario.name[cnt.scenario])\n for (j in 1:runs){\n jj<-sample(length(param.array.1K[,1,1]),1)\n jj.sar<-sample(length(sarI_rqys[1,1,1,]),1)\n param<-as.list(param.array.1K[jj,,pop[k]])#;unlist(param)\n\n #collect parameters used in each run\n param.marT<-as.data.frame(t(sarcoefT_rqvs[climate[cc],quant[qq],,jj.sar])) #;unlist(param.marT) #dimnames(sarcoefT_rqvs)\n param.marI<-as.data.frame(t(sarcoefI_rqvs[climate[cc],quant[qq],,jj.sar])) #dimnames(sarBeta_frqvs)[[1]][2]\n param.array[j,paste(\"T\",names(param.marT),sep=\".\"),k,scenario.name[cnt.scenario]]<-unlist(param.marT)\n param.array[j,paste(\"I\",names(param.marI),sep=\".\"),k,scenario.name[cnt.scenario]]<-unlist(param.marI)\n param.array[j,names(param),k,scenario.name[cnt.scenario]]<-unlist(param)\n\n #Load raw T and F projections from TMB model\n T1<- sc_envProj_rqvys[climate[cc],quant[qq],\"T.S2.ParrSu\",,jj.sar]#*env_sc[\"T.S2.ParrSu\"]+env_mu[\"T.S2.ParrSu\"]\n F1<- sc_envProj_rqvys[climate[cc],quant[qq],Fname,,jj.sar]#*env_sc[Fname]+env_mu[Fname]\n #Add trends\n if(cc>1) T1<-T1+FW[,paste0(\"Tsu.Q\",quant[qq],\".RCP\",climate[cc])]\n if(cc>1) F1<-F1+FW[,paste0(FW.name,quant[qq],\".RCP\",climateshort[cc])]\n #Scale for gompertz model coefficients\n T1<-(T1-scalefactors[\"mean\",\"T.S2.ParrSu\"])/scalefactors[\"sd\",\"T.S2.ParrSu\"]\n F1<-(F1-scalefactors[\"mean\",Fname])/scalefactors[\"sd\",Fname]\n \n \n#Initialize all age classes \n N[1:5] = c(0,0,0,0,0)\t\n for (i in 1:5){ \n xx<-sample(1:dim(envProj_rqvys)[5],1)\n N.new[1] = popinit[pop[k],\"stationaryMeanSp\"]*exp(param$p1+param$c1*log(popinit[pop[k],\"stationaryMeanSp\"]/ha))\t\n if(filename==\"p2Fsu\") surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BF*F1[i])\n if(length(grep(\"p2Tsu\",filename))>0) {surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BT*T1[i]+param$BF*F1[i])}\n if(length(grep(\"c2\",filename))>0) {surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BT*T1[i]*log(max(N[1]/ha,1))+param$BF*F1[i]*log(max(N[1]/ha,1)))}\n surv.inriver[i]= hydro[hydro$gridYear==envProj_rqvys[climate[cc],quant[qq],\"gridYear\",i,xx] & \n hydro$flow==envProj_rqvys[climate[cc],quant[qq],\"gridFlow\",i,xx]\n & hydro$temp==envProj_rqvys[climate[cc],quant[qq],\"gridTemp\",i,xx],\"surv\"]\n pt[i]=hydro[hydro$gridYear==envProj_rqvys[climate[cc],quant[qq],\"gridYear\",i,xx] & \n hydro$flow==envProj_rqvys[climate[cc],quant[qq],\"gridFlow\",i,xx]\n & hydro$temp==envProj_rqvys[climate[cc],quant[qq],\"gridTemp\",i,xx],\"proptrans\"]\n surv.main[i] =S2.mainstem(pt=pt[i], s.inriver=surv.inriver[i])\n pt.sar[i]<-pt[i]*0.98/((1-pt[i])*surv.inriver[i]+pt[i]*0.98)\n N.new[2] = N[1]*surv.trib[i]*surv.main[i]\n N.new[3] = N[2]*s3.fxn(pt=pt.sar[i],sarI=plogis(sarI_rqys[climate[cc],quant[qq],i,xx]),sarT=plogis(sarT_rqys[climate[cc],quant[qq],i,xx]),b3=param$b3,b4=param$b4,So=param$s0)$s3\n N.new[4] = N[3]*(1-param$b3)*param$s0\n N.new[5] = N[4]*(1-param$b4)*param$s0\n N = N.new\n };N\n\n for (i in 1:years){\n # Calculate effective spawners for recruit calculations\n #In the first year, we do not have pt.sup yet, so we are just using the average survival of upstream migrants\n if(i==1){\n myvar=\"aprmayjunetempLGR\";lgrtemp<-sc_envProj_rqvys[climate[cc],quant[qq],myvar,i,jj.sar]#*env_sc[myvar]+env_mu[myvar]\n myvar=\"aprmayjuneflowLGR\";lgrflow<-sc_envProj_rqvys[climate[cc],quant[qq],myvar,i,jj.sar]#*env_sc[myvar]+env_mu[myvar]\n simtemp<-round_any(lgrtemp,0.5)#;simtemp\n simflow<-round_any(lgrflow,20)#;simflow\n su.Temp.matches<-su[which(abs(simtemp-(su$LGRtemp))==min(abs(simtemp-(su$LGRtemp)))),]#;su.Temp.matches\n su.Flow.matches<-su.Temp.matches[which(abs(simflow-(su.Temp.matches$LGRflow))==min(abs(simflow-(su.Temp.matches$LGRflow)))),]#;su.Flow.matches\n surv.sup[i]<-sample(su.Flow.matches$SpringSurv_BoToLG,1) \n if(k %in% c(6,8)) surv.sup[i]<-sample(su.Flow.matches$SummerSurv_BoToLG,1)\n \n spawners = (param$b4*N[4] + param$f5*N[5])*surv.sup[i]*0.9\n }\n \n #In subsequent years, we use output from SARs in the previous year to determine the precent of upstream migrants that were transported as juveniles \n if(i>1){ spawners = (param$b4*N[4] + param$f5*N[5])*surv.sup[i-1]*0.9 }\n \n #Survival in each age class \n surv.s1[i]=exp(param$p1+param$c1*log(spawners/ha))\n if(filename==\"p2Fsu\") surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BF*F1[i])\n if(length(grep(\"p2Tsu\",filename))>0) {surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BT*T1[i]+param$BF*F1[i])}\n if(length(grep(\"c2\",filename))>0) {surv.trib[i] = exp(param$p2+param$c2*log(max(N[1]/ha,1))+param$BT*T1[i]*log(max(N[1]/ha,1))+param$BF*F1[i]*log(max(N[1]/ha,1)))}\n surv.inriver[i]= hydro[hydro$gridYear==envProj_rqvys[climate[cc],quant[qq],\"gridYear\",i,jj.sar] &\n hydro$flow==envProj_rqvys[climate[cc],quant[qq],\"gridFlow\",i,jj.sar] &\n hydro$temp==envProj_rqvys[climate[cc],quant[qq],\"gridTemp\",i,jj.sar],\"surv\"]\n pt[i]= hydro[hydro$gridYear==envProj_rqvys[climate[cc],quant[qq],\"gridYear\",i,jj.sar] & \n hydro$flow==envProj_rqvys[climate[cc],quant[qq],\"gridFlow\",i,jj.sar] &\n hydro$temp==envProj_rqvys[climate[cc],quant[qq],\"gridTemp\",i,jj.sar],\"proptrans\"]\n surv.main[i] =S2.mainstem(pt=pt[i], s.inriver=surv.inriver[i])\n pt.sar[i]<-pt[i]*0.98/((1-pt[i])*surv.inriver[i]+pt[i]*0.98)\n surv.s2[i] =surv.trib[i]*surv.main[i] \n s3 = s3.fxn(pt=pt.sar[i],sarI=plogis(sarI_rqys[climate[cc],quant[qq],i,jj.sar]),sarT=plogis(sarT_rqys[climate[cc],quant[qq],i,jj.sar]),b3=param$b3,b4=param$b4,So=param$s0)\n surv.s3[i] = s3$s3\n surv.sarI[i] = s3$sarI\n surv.sarT[i] = s3$sarT\n surv.sar[i] = s3$sar\n #tracking in-river and transported fish separately for upstream migration survival\n pt.sup[i]<-pt.sar[i]*surv.sarT[i]/surv.sar[i]\n\n myvar=\"aprmayjunetempLGR\";lgrtemp<-sc_envProj_rqvys[climate[cc],quant[qq],myvar,i,jj.sar]#*env_sc[myvar]+env_mu[myvar]\n myvar=\"aprmayjuneflowLGR\";lgrflow<-sc_envProj_rqvys[climate[cc],quant[qq],myvar,i,jj.sar]#*env_sc[myvar]+env_mu[myvar]\n simtemp<-round_any(lgrtemp,0.5)#;simtemp\n simflow<-round_any(lgrflow,20)#;simflow\n su.Temp.matches<-su[which(abs(simtemp-(su$LGRtemp))==min(abs(simtemp-(su$LGRtemp)))),]#;su.Temp.matches\n su.Flow.matches<-su.Temp.matches[which(abs(simflow-(su.Temp.matches$LGRflow))==min(abs(simflow-(su.Temp.matches$LGRflow)))),]#;su.Flow.matches\n xx<-sample(1:nrow(su.Flow.matches),size=1);xx\n sup.spr.inriver[i]<-su.Flow.matches$Spr_Pred_BOLG_inriver[xx] \n sup.spr.transport[i]<-su.Flow.matches$Spr_Pred_BOLG_transport[xx] \n sup.sum.inriver[i]<-su.Flow.matches$Sum_Pred_BOLG_inriver[xx] \n sup.sum.transport[i]<-su.Flow.matches$Sum_Pred_BOLG_transport[xx] \n \n sup.spring[i]<-pt.sup[i]* sup.spr.transport[i]+(1-pt.sup[i])* sup.spr.inriver[i] \n sup.summer[i]<-pt.sup[i]* sup.sum.transport[i]+(1-pt.sup[i])* sup.sum.inriver[i] \n surv.sup[i]<-sup.spring[i] \n if(k %in% c(6,8)) surv.sup[i]<-sup.summer[i]\n #Note that surv.sup[i] will be used in next year's calculation of spawners, not this year's N[1] \n \n N.new[1] = spawners*surv.s1[i]\t\n N.new[2] = N[1]*surv.s2[i]\n N.new[3] = N[2]*surv.s3[i]\n N.new[4] = N[3]*(1-param$b3)*param$s0\n N.new[5] = N[4]*(1-param$b4)*param$s0\n \n N = N.new\n \n # calculate spawners\n Spawners[i] = (param$b4*N[4] + N[5])*surv.sup[i]*0.9\n # calculate recruits referenced to brood year\n if (i > 4 && i <= (years-1))\n Recruits[i-4] = param$b4*N[4]*surv.sup[i]*0.9\n if (i > 5)\n Recruits[i-5] = Recruits[i-5] + N[5]*surv.sup[i]*0.9\n } #end years\n Spawners2<-Spawners[5:years]\n \n spawner.array[,j,k,cnt.scenario]<-Spawners\n parrsmolt.array[,j,k,cnt.scenario]<-surv.trib\n recruit.array[,j,k,cnt.scenario]<-Recruits\n } #end runs\n \n \n#Store spawner and recruit matrices and name them by scenario\n save(spawner.array,file=paste(\"output/spawner\",filename,arrayname,sep=\".\"))\n save(param.array,file=paste(\"output/param\",filename,arrayname,sep=\".\"))\n save(parrsmolt.array,file=paste(\"output/parrsmolt\",filename,arrayname,sep=\".\"))\n save(recruit.array,file=paste(\"output/recruit\",filename,arrayname,sep=\".\"))\n\n\n cnt=cnt+1\n \n \n } #end quantiles qq\n } #end climate cc\n} #end populations\n\n#Add response metrics to param.array-------------\n years<-2015:2089 #dimnames(spawner.array)[[1]]\n runs<-dim(spawner.array)[[2]]\n pop<-dimnames(spawner.array)[[3]]\n scenarios<-dimnames(spawner.array)[[4]]\n spQET<-spawner.array\n spQET[1:3,,,]<-NA\n for(k in 1:length(pop)){\n for(ss in 1:length(scenarios)){\n for ( j in 1:runs){\n spawners<-spawner.array[,j,k,scenarios[ss]];spawners\n for (i in 4:75){ifelse (sum(spawners[(i-3):i]) < 200,spQET[i,j,k,ss]<-1,spQET[i,j,k,ss]<-0) }\n param.array[j,\"yrQET50\",k,scenarios[ss]]<-ifelse(max(spQET[,j,k,scenarios[ss]],na.rm=TRUE)>0.5 , \n years[min(which(spQET[,j,k,scenarios[ss]]>0.5))] , 2115)\n param.array[j,\"Mean2020\",k,scenarios[ss]]<-exp(mean(log(spawners[6:15])))\n param.array[j,\"Mean2040\",k,scenarios[ss]]<-exp(mean(log(spawners[26:35])))\n param.array[j,\"Mean2060\",k,scenarios[ss]]<-exp(mean(log(spawners[46:55])))\n param.array[j,\"Mean2080\",k,scenarios[ss]]<-exp(mean(log(spawners[66:75])))\n param.array[j,\"Meanallyears\",k,scenarios[ss]]<-exp(mean(log(spawners)))\n } #end runs\n }#end scenarios\n }#end pop\n\n save(param.array,file=paste(\"output/param\",filename,arrayname,sep=\".\"))\n\n\n \n", "meta": {"hexsha": "a20fe3d84481e5610aba70e961d0bd310ed24d2c", "size": 16132, "ext": "r", "lang": "R", "max_stars_repo_path": "LCM.sim.CC.2020.r", "max_stars_repo_name": "lisa439/LCM", "max_stars_repo_head_hexsha": "4d6ab2fcba92ad1bf46cc899ba88478af918d4c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-18T20:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T20:19:45.000Z", "max_issues_repo_path": "LCM.sim.CC.2020.r", "max_issues_repo_name": "lisa439/LCM", "max_issues_repo_head_hexsha": "4d6ab2fcba92ad1bf46cc899ba88478af918d4c5", "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": "LCM.sim.CC.2020.r", "max_forks_repo_name": "lisa439/LCM", "max_forks_repo_head_hexsha": "4d6ab2fcba92ad1bf46cc899ba88478af918d4c5", "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": 59.3088235294, "max_line_length": 268, "alphanum_fraction": 0.5719067692, "num_tokens": 4985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.29105305864538766}} {"text": "#' Train HMM with model specificaiton provided in `model`\n#'\n#' @param x vector or matrix of data\n#' @param model model specification created by hmmspec.gen(..)\n#' @param lock.transition boolean, whether to fix the transition matrix\n#' @param tol numeric tolerance for convergence evaluation\n#' @param maxit maximum number of EM iterations\n#' @param verbose boolean, whether to print diagnostics\n#' @return list with elements that describe the trained model\n#' @details See example\n#' @export\nhextfit = function(x, model, lock.transition=FALSE, tol=1e-01, maxit=1000, verbose=TRUE) {\n K = model$K\n D = model$D # size of the alphabet sets, this is a vector!\n M = model$M # no. of gaussian mixtures\n if ( class(x)==\"numeric\" | class(x)==\"integer\") {\n warning('x is a primitive vector. Assuming single sequence.')\n TT = NROW(x)\n Nseq = 1\n } else {\n TT = x$TT\n Nseq = length(TT)\n x = x$x\n }\n mtype = model$mtype\n if ( length(mtype) != NCOL(x) ) stop(\"length of mtype differs from no of columns in x.\") \n if ( K < 2 ) stop(\"K must be larger than one.\")\n if( any(dim(model$ltransition)!=K) ) stop(\"dimensions of ltransition incorrect!\")\n if( length(model$linit)!=K ) stop(\"dimensions of linit incorrect!\")\n if( NROW(x)!=sum(TT) ) stop(\"no. of rows in x not equal sum(TT) !\")\n\n mstep = model$mstep\n # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n Emit.Prob.Func = model$dens.emission\n # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n loglik1 = numeric(maxit)\n loglik1[] = NA\n loglik1[1] = -1000\n loglik2 = numeric(maxit)\n loglik2[] = NA\n loglik2[1] = -1000\n\n # initialize gamma ===========\n lgam = rep(-1.0e100, K*sum(TT))\n # ============================\n lAlpha = rep(-1.0e300, (K+1)*sum(TT))\n lBeta = rep(-1.0e300, K*sum(TT))\n\n ll = c(0.0, 0.0)\n mu.it = rep(list(list()), maxit)\n \n for(i in 1:maxit) {\n if (verbose == TRUE) cat(\"\\niter:\",i,\" ====\")\n # calculate emission prob by state given model >>>>>>>>>>>>>>>>>>>>>>>>>>>>\n emit.p = sapply(1:K, fn <- function(state) Emit.Prob.Func(x, state, model))\n # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n \n # E-step <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n result = .C(\"mo_estep_hmm_ln\",\n lA=as.double(t(model$ltransition)),\n lPi=as.double(t(model$linit)),\n lP=as.double(t(emit.p)),\n TT=as.integer(TT),\n nsequences=as.integer(Nseq),\n K=as.integer(K),\n forward_p=lAlpha,\n backward_p=lBeta,\n lgam=lgam,\n ll=as.double(ll),\n PACKAGE='Hext')\n\n loglik1[i] = result$ll[1]\n loglik2[i] = result$ll[2]\n if (verbose == TRUE) { \n cat(\"loglikelihood(alpha) \", result$ll[1])\n cat(\".....(beta)\", result$ll[2])\n }\n if ( i > 1 ) {\n if(abs(loglik1[i]-loglik1[i-1]) < tol) {\n if (verbose == TRUE) cat(\"\\nConverged.\\n\")\n break\n }\n }\n # M-step >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n gam = matrix(exp(result$lgam), ncol=K)\n # simple check on gamma\n gamsum = rowSums(gam)\n \n model$parms.emission = mstep(x, gam, model)\n\n # write the optimized parameters back to model\n if(!lock.transition) {\n model$ltransition = matrix(result$lA, nrow=K, byrow=TRUE)\n model$linit = result$lPi\n }\n # save the means vector for output\n mu.it[[i]] = model$parms.emission$M5$mu.ll\n }\n \n LL = loglik1[i] # last iteration\n # Calculate no of parameters in the model >>>>>>>>>>>>>>>>>>>>>>>>>\n # 1 = discrete\n ix1 = which(mtype == 1)\n if ( length(ix1) > 0 ) {\n n.par1 = K*length(ix1)*(D - 1)\n } else {\n n.par1 = 0\n }\n # 2 = normal/multivariate\n ix2 = which(mtype == 2)\n if ( length(ix2) > 0 ) { \n # Zucchini & MacDonald (2009), p.186 \n # K*p(p+3)/2, where p is the dimension of the observation, and is equal\n # the number of 2s in mtype.\n n.par2 = K*length(ix2)*(length(ix2) + 3)/2\n } else {\n n.par2 = 0\n }\n # 3 = gamma\n ix3 = which(mtype == 3)\n if ( length(ix3) > 0 ) { \n # two free parameters for each component obeying the gamma distribution\n n.par3 = K * length(ix3) * 2\n } else {\n n.par3 = 0\n }\n # 4 = beta\n ix4 = which(mtype == 4)\n if ( length(ix4) > 0 ) { \n # two free parameters for each component obeying the beta distribution \n n.par4 = K * length(ix4) * 2\n } else {\n n.par4 = 0\n }\n # 5 = gaussian mixture\n ix5 = which(mtype == 5)\n if ( length(ix5) > 0 ) { \n # for each multivariate component, there are M mixtures, and each mixture \n # has p(p+3)/2 parameters, thus total :\n n.par5 = K * length(ix5)* M * (length(ix5) + 3) / 2\n } else {\n n.par5 = 0\n }\n np.trans = K * ( K - 1 )\n # Total number of parameters in the HMM\n N.param = np.trans + n.par1 + n.par2 + n.par3 + n.par4 + n.par5\n # Akaike information criterion (Ref : wiki on AIC)\n Aic = - 2*LL + 2*N.param \n # AIC with finite sample correction (see wiki on AIC)\n # Burnham, Anderson (2002) Model selection and multimodel inference: A Practical\n # Information-Theoretic Approach, 2nd ed, Springer.\n Aicc = Aic + 2*N.param*(N.param + 1)/(sum(TT) - N.param - 1)\n Bic = - 2*LL + N.param*log(sum(TT))\n \n ret = list(model=model,mstep=mstep, gam=gam, lgam=result$lgam, last.it=i,\n loglik1=loglik1, loglik2=loglik2, TT=TT, yhat=apply(gam,1,which.max),\n Aic=Aic, Aicc=Aicc, Bic=Bic, mu.it=mu.it)\n class(ret) <- \"Hext\"\n return(ret)\n}\n\n", "meta": {"hexsha": "d0db6d459618923703181cf879d20f3b68e202dc", "size": 5386, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Topcalls.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/Topcalls.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/Topcalls.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.2469135802, "max_line_length": 91, "alphanum_fraction": 0.5638692908, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2909959214857497}} {"text": "\n## * Assign number of children to each edge (from \"to\" node)\nnchild2edges <- function(tedges, from.node = NULL) {\n if (is.null(from.node))\n from.node <- setdiff(tedges$from, tedges$to)\n tedges[, nchildren := NA_integer_]\n\n children <- tedges[from %chin% from.node]\n while(nrow(children)) {\n nchild <- children[, .N, from]\n tedges[nchild, nchildren := i.N, on = c('to' = 'from')]\n children <- tedges[from %chin% children$to]\n }\n return(invisible(tedges))\n}\n\nget.root <- function(tedges) {\n setdiff(tedges$from, tedges$to)\n}\n\n## * Assign the distance to root to each edge\ndist2root <- function(tedges, from.node = NULL) {\n stopifnot(all(c('dist', 'from', 'to') %in% names(tedges)))\n\n if (is.null(from.node))\n from.node <- setdiff(tedges$from, tedges$to)\n\n if (is.null(key(tedges)) || key(tedges) != 'from')\n setkey(tedges, from)\n \n tedges[, cumdist := 0]\n i <- 1L\n children <- tedges[from %in% from.node]\n while(nrow(children)) {\n tedges[from %in% children$from, `:=`(cumdist = cumdist + dist, nthnode = i)]\n prevchildren <- tedges[from %in% children$from]\n children <- tedges[from %in% children$to]\n tedges[prevchildren, cumdist := i.cumdist, on = c('from' = 'to')]\n i <- i + 1L\n }\n return(invisible(tedges))\n \n}\n\nchildren_unique_vals <- function(tedges, var) {\n\n tedges[, cladevar := get(var)]\n tedges[, cladestart := F]\n ## if (is.null(key(tedges)) || key(tedges) != 'from')\n ## setkey(tedges, from)\n\n naval <- fcase(\n tedges[, is.character(get(var))], NA_character_,\n tedges[, is.integer(get(var))], NA_integer_,\n tedges[, is.numeric(get(var))], NA_real_,\n default = NA\n )\n \n getun <- function(x) {\n vs <- unique(setdiff(x, NA))\n if (length(vs) == 1L) {\n return(vs)\n } else return('multiple')\n }\n\n tedges[, uniquevals_children := get(var)]\n\n sel <- tedges[nthnode == max(nthnode)]\n uns <- sel[, .(uniquevals_children = getun(uniquevals_children)), from]\n tedges[uns, uniquevals_children := i.uniquevals_children, on = c('to' = 'from')]\n\n for (nn in (max(tedges$nthnode)-1):1L) {\n sel <- tedges[nthnode == nn]\n uns <- sel[, .(uniquevals_children = getun(uniquevals_children)), from]\n sel[uns, uniquevals_children_new := i.uniquevals_children, on = 'from']\n cladestarts <- sel[uniquevals_children_new == 'multiple' & uniquevals_children != 'multiple']\n tedges[cladestarts, cladestart := T, on = c('from' = 'to')]\n tedges[uns, uniquevals_children := i.uniquevals_children, on = c('to' = 'from')]\n }\n\n}\n\n\n## * Create edges data.table from phylo tree, and join tips data\nget.edges <- function(tree) {\n tedges <- as.data.table(tree$edge)\n setnames(tedges, c('from', 'to'))\n tedges[, eid := .I]\n tedges[, dist := tree$edge.length]\n ttips <- get.tips(tree)\n tedges[, to.tip := V2 %in% ttips$id]\n tedges <- merge(tedges, ttips, by.x = 'V2', by.y = 'id', all.x = T, all.y = F, sort = F)\n setnames(tedges, c('V1', 'V2'), c('from', 'to'))\n setcolorder(tedges, c('from', 'to'))\n nchild2edges(tedges)\n dist2root(tedges)\n tedges\n}\n\n\n## * Extract clade of same trait, given a tip id, from edges data.table\ncommon.trait.clade <- function(tedges, tip, var) {\n\n i <- 0L\n anc <- tedges[to == tip]\n val <- anc[, get(var)]\n if (is.na(val))\n stop('Need a tip with a non-NA value to start from')\n \n anc[, lvl := i]\n res <- anc\n\n sibs <- get.children(tedges, anc$from)\n cont <- sibs[, all(get(var) %in% c(NA, val))]\n\n while(cont) {\n sibs <- sibs[!res, on = 'to']\n sibs[, lvl := i]\n res <- rbind(res, sibs)\n i <- i + 1L\n anc <- tedges[to == anc$from]\n sibs <- get.children(tedges, anc$from)\n cont <- sibs[, all(get(var) %in% c(NA, val))]\n }\n\n return(res)\n}\n\n\n\nupdate.tree <- function(tedges) {\n tedges <- nchild2edges(tedges)\n tedges <- dist2root(tedges)\n tedges[, to.tip := fifelse(is.na(nchildren), T, F)]\n return(invisible(tedges))\n}\n\n\n\n## x=tree\n## type = \"fan\"; use.edge.length = TRUE; node.pos = NULL; \n## show.tip.label = FALSE; show.node.label = FALSE; edge.color = \"grey50\"; \n## edge.width = 1; edge.lty = 1; font = 3; cex = par(\"cex\"); \n## adj = NULL; srt = 0; no.margin = TRUE; root.edge = FALSE; \n## label.offset = 0; underscore = FALSE; x.lim = NULL; y.lim = NULL; \n## direction = \"rightwards\"; lab4ut = NULL; tip.color = \"red\"; \n## plot = TRUE; rotate.tree = 0; open.angle = 0; node.depth = 1; \n## align.tip.label = FALSE\n## * Adaptation of ape::plot.phylo() to return the coordinates\nplot2 <- function (x, type = \"phylogram\", use.edge.length = TRUE, node.pos = NULL, \n show.tip.label = TRUE, show.node.label = FALSE, edge.color = \"black\", \n edge.width = 1, edge.lty = 1, font = 3, cex = par(\"cex\"), \n adj = NULL, srt = 0, no.margin = FALSE, root.edge = FALSE, \n label.offset = 0, underscore = FALSE, x.lim = NULL, y.lim = NULL, \n direction = \"rightwards\", lab4ut = NULL, tip.color = \"black\", \n plot = TRUE, rotate.tree = 0, open.angle = 0, node.depth = 1, \n align.tip.label = FALSE, ...) {\n\n Ntip <- length(x$tip.label)\n\n if (Ntip < 2) {\n warning(\"found less than 2 tips in the tree\")\n return(NULL)\n }\n .nodeHeight <- function(edge, Nedge, yy) .C(node_height, \n as.integer(edge[, 1]), as.integer(edge[, 2]), as.integer(Nedge), \n as.double(yy))[[4]]\n .nodeDepth <- function(Ntip, Nnode, edge, Nedge, node.depth) .C(node_depth, \n as.integer(Ntip), as.integer(edge[, 1]), as.integer(edge[, \n 2]), as.integer(Nedge), double(Ntip + Nnode), as.integer(node.depth))[[5]]\n .nodeDepthEdgelength <- function(Ntip, Nnode, edge, Nedge, \n edge.length) .C(node_depth_edgelength, as.integer(edge[, \n 1]), as.integer(edge[, 2]), as.integer(Nedge), as.double(edge.length), \n double(Ntip + Nnode))[[5]]\n Nedge <- dim(x$edge)[1]\n Nnode <- x$Nnode\n if (any(x$edge < 1) || any(x$edge > Ntip + Nnode)) \n stop(\"tree badly conformed; cannot plot. Check the edge matrix.\")\n ROOT <- Ntip + 1\n type <- match.arg(type, c(\"phylogram\", \"cladogram\", \"fan\", \n \"unrooted\", \"radial\"))\n direction <- match.arg(direction, c(\"rightwards\", \"leftwards\", \n \"upwards\", \"downwards\"))\n if (is.null(x$edge.length)) {\n use.edge.length <- FALSE\n } else {\n if (use.edge.length && type != \"radial\") {\n tmp <- sum(is.na(x$edge.length))\n if (tmp) {\n warning(paste(tmp, \"branch length(s) NA(s): branch lengths ignored in the plot\"))\n use.edge.length <- FALSE\n }\n }\n }\n if (is.numeric(align.tip.label)) {\n align.tip.label.lty <- align.tip.label\n align.tip.label <- TRUE\n } else {\n if (align.tip.label) \n align.tip.label.lty <- 3\n }\n if (align.tip.label) {\n if (type %in% c(\"unrooted\", \"radial\") || !use.edge.length || \n is.ultrametric(x)) \n align.tip.label <- FALSE\n }\n if (type %in% c(\"unrooted\", \"radial\") || !use.edge.length || \n is.null(x$root.edge) || !x$root.edge) \n root.edge <- FALSE\n phyloORclado <- type %in% c(\"phylogram\", \"cladogram\")\n horizontal <- direction %in% c(\"rightwards\", \"leftwards\")\n xe <- x$edge\n if (phyloORclado) {\n phyOrder <- attr(x, \"order\")\n if (is.null(phyOrder) || phyOrder != \"cladewise\") {\n x <- reorder(x)\n if (!identical(x$edge, xe)) {\n ereorder <- match(x$edge[, 2], xe[, 2])\n if (length(edge.color) > 1) {\n edge.color <- rep(edge.color, length.out = Nedge)\n edge.color <- edge.color[ereorder]\n }\n if (length(edge.width) > 1) {\n edge.width <- rep(edge.width, length.out = Nedge)\n edge.width <- edge.width[ereorder]\n }\n if (length(edge.lty) > 1) {\n edge.lty <- rep(edge.lty, length.out = Nedge)\n edge.lty <- edge.lty[ereorder]\n }\n }\n }\n yy <- numeric(Ntip + Nnode)\n TIPS <- x$edge[x$edge[, 2] <= Ntip, 2]\n yy[TIPS] <- 1:Ntip\n }\n z <- reorder(x, order = \"postorder\")\n if (phyloORclado) {\n if (is.null(node.pos)) \n node.pos <- if (type == \"cladogram\" && !use.edge.length) \n 2\n else 1\n if (node.pos == 1) \n yy <- .nodeHeight(z$edge, Nedge, yy)\n else {\n ans <- .C(node_height_clado, as.integer(Ntip), as.integer(z$edge[, \n 1]), as.integer(z$edge[, 2]), as.integer(Nedge), \n double(Ntip + Nnode), as.double(yy))\n xx <- ans[[5]] - 1\n yy <- ans[[6]]\n }\n if (!use.edge.length) {\n if (node.pos != 2) \n xx <- .nodeDepth(Ntip, Nnode, z$edge, Nedge, \n node.depth) - 1\n xx <- max(xx) - xx\n }\n else {\n xx <- .nodeDepthEdgelength(Ntip, Nnode, z$edge, Nedge, \n z$edge.length)\n }\n } else {\n twopi <- 2 * pi\n rotate.tree <- twopi * rotate.tree/360\n if (type != \"unrooted\") {\n TIPS <- x$edge[which(x$edge[, 2] <= Ntip), 2]\n xx <- seq(0, twopi * (1 - 1/Ntip) - twopi * open.angle/360, \n length.out = Ntip)\n theta <- double(Ntip)\n theta[TIPS] <- xx\n theta <- c(theta, numeric(Nnode))\n }\n switch(type, fan = {\n theta <- .nodeHeight(z$edge, Nedge, theta)\n if (use.edge.length) {\n r <- .nodeDepthEdgelength(Ntip, Nnode, z$edge, \n Nedge, z$edge.length)\n } else {\n r <- .nodeDepth(Ntip, Nnode, z$edge, Nedge, node.depth)\n r <- 1/r\n }\n theta <- theta + rotate.tree\n if (root.edge) r <- r + x$root.edge\n xx <- r * cos(theta)\n yy <- r * sin(theta)\n }, unrooted = {\n nb.sp <- .nodeDepth(Ntip, Nnode, z$edge, Nedge, node.depth)\n XY <- if (use.edge.length) unrooted.xy(Ntip, Nnode, \n z$edge, z$edge.length, nb.sp, rotate.tree) else unrooted.xy(Ntip, \n Nnode, z$edge, rep(1, Nedge), nb.sp, rotate.tree)\n xx <- XY$M[, 1] - min(XY$M[, 1])\n yy <- XY$M[, 2] - min(XY$M[, 2])\n }, radial = {\n r <- .nodeDepth(Ntip, Nnode, z$edge, Nedge, node.depth)\n r[r == 1] <- 0\n r <- 1 - r/Ntip\n theta <- .nodeHeight(z$edge, Nedge, theta) + rotate.tree\n xx <- r * cos(theta)\n yy <- r * sin(theta)\n })\n }\n if (phyloORclado) {\n if (!horizontal) {\n tmp <- yy\n yy <- xx\n xx <- tmp - min(tmp) + 1\n }\n if (root.edge) {\n if (direction == \"rightwards\") \n xx <- xx + x$root.edge\n if (direction == \"upwards\") \n yy <- yy + x$root.edge\n }\n }\n if (no.margin) \n par(mai = rep(0, 4))\n if (show.tip.label) \n nchar.tip.label <- nchar(x$tip.label)\n max.yy <- max(yy)\n getLimit <- function(x, lab, sin, cex) {\n s <- strwidth(lab, \"inches\", cex = cex)\n if (any(s > sin)) \n return(1.5 * max(x))\n Limit <- 0\n while (any(x > Limit)) {\n i <- which.max(x)\n alp <- x[i]/(sin - s[i])\n Limit <- x[i] + alp * s[i]\n x <- x + alp * s\n }\n Limit\n }\n if (is.null(x.lim)) {\n if (phyloORclado) {\n if (horizontal) {\n xx.tips <- xx[1:Ntip]\n if (show.tip.label) {\n pin1 <- par(\"pin\")[1]\n tmp <- getLimit(xx.tips, x$tip.label, pin1, \n cex)\n tmp <- tmp + label.offset\n }\n else tmp <- max(xx.tips)\n x.lim <- c(0, tmp)\n }\n else x.lim <- c(1, Ntip)\n } else switch(type, fan = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.018 * max.yy * \n cex)\n x.lim <- range(xx) + c(-offset, offset)\n } else x.lim <- range(xx)\n }, unrooted = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.018 * max.yy * \n cex)\n x.lim <- c(0 - offset, max(xx) + offset)\n } else x.lim <- c(0, max(xx))\n }, radial = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.03 * cex)\n x.lim <- c(-1 - offset, 1 + offset)\n } else x.lim <- c(-1, 1)\n })\n } else if (length(x.lim) == 1) {\n x.lim <- c(0, x.lim)\n if (phyloORclado && !horizontal) \n x.lim[1] <- 1\n if (type %in% c(\"fan\", \"unrooted\") && show.tip.label) \n x.lim[1] <- -max(nchar.tip.label * 0.018 * max.yy * \n cex)\n if (type == \"radial\") \n x.lim[1] <- if (show.tip.label) \n -1 - max(nchar.tip.label * 0.03 * cex)\n else -1\n }\n if (phyloORclado && direction == \"leftwards\") \n xx <- x.lim[2] - xx\n if (is.null(y.lim)) {\n if (phyloORclado) {\n if (horizontal) \n y.lim <- c(1, Ntip)\n else {\n pin2 <- par(\"pin\")[2]\n yy.tips <- yy[1:Ntip]\n if (show.tip.label) {\n tmp <- getLimit(yy.tips, x$tip.label, pin2, \n cex)\n tmp <- tmp + label.offset\n }\n else tmp <- max(yy.tips)\n y.lim <- c(0, tmp)\n }\n } else switch(type, fan = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.018 * max.yy * \n cex)\n y.lim <- c(min(yy) - offset, max.yy + offset)\n } else y.lim <- c(min(yy), max.yy)\n }, unrooted = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.018 * max.yy * \n cex)\n y.lim <- c(0 - offset, max.yy + offset)\n } else y.lim <- c(0, max.yy)\n }, radial = {\n if (show.tip.label) {\n offset <- max(nchar.tip.label * 0.03 * cex)\n y.lim <- c(-1 - offset, 1 + offset)\n } else y.lim <- c(-1, 1)\n })\n } else if (length(y.lim) == 1) {\n y.lim <- c(0, y.lim)\n if (phyloORclado && horizontal) \n y.lim[1] <- 1\n if (type %in% c(\"fan\", \"unrooted\") && show.tip.label) \n y.lim[1] <- -max(nchar.tip.label * 0.018 * max.yy * \n cex)\n if (type == \"radial\") \n y.lim[1] <- if (show.tip.label) \n -1 - max(nchar.tip.label * 0.018 * max.yy * cex)\n else -1\n }\n if (phyloORclado && direction == \"downwards\") \n yy <- y.lim[2] - yy\n if (phyloORclado && root.edge) {\n if (direction == \"leftwards\") \n x.lim[2] <- x.lim[2] + x$root.edge\n if (direction == \"downwards\") \n y.lim[2] <- y.lim[2] + x$root.edge\n }\n asp <- fifelse(type %in% c(\"fan\", \"radial\", \"unrooted\"), 1, NA_integer_)\n plot.default(0, type = \"n\", xlim = x.lim, ylim = y.lim, xlab = \"\", \n ylab = \"\", axes = FALSE, asp = asp, ...)\n if (plot) {\n if (is.null(adj)) \n adj <- fifelse(phyloORclado && direction == \"leftwards\", 1, 0)\n if (phyloORclado && show.tip.label) {\n MAXSTRING <- max(strwidth(x$tip.label, cex = cex))\n loy <- 0\n if (direction == \"rightwards\") {\n lox <- label.offset + MAXSTRING * 1.05 * adj\n }\n if (direction == \"leftwards\") {\n lox <- -label.offset - MAXSTRING * 1.05 * (1 - adj)\n }\n if (!horizontal) {\n psr <- par(\"usr\")\n MAXSTRING <- MAXSTRING * 1.09 * (psr[4] - psr[3])/(psr[2] - psr[1])\n loy <- label.offset + MAXSTRING * 1.05 * adj\n lox <- 0\n srt <- 90 + srt\n if (direction == \"downwards\") {\n loy <- -loy\n srt <- 180 + srt\n }\n }\n }\n if (type == \"phylogram\") {\n phylogram.plot(x$edge, Ntip, Nnode, xx, yy, horizontal, \n edge.color, edge.width, edge.lty)\n } else {\n if (type == \"fan\") {\n ereorder <- match(z$edge[, 2], x$edge[, 2])\n if (length(edge.color) > 1) {\n edge.color <- rep(edge.color, length.out = Nedge)\n edge.color <- edge.color[ereorder]\n }\n if (length(edge.width) > 1) {\n edge.width <- rep(edge.width, length.out = Nedge)\n edge.width <- edge.width[ereorder]\n }\n if (length(edge.lty) > 1) {\n edge.lty <- rep(edge.lty, length.out = Nedge)\n edge.lty <- edge.lty[ereorder]\n }\n circular.plot(z$edge, Ntip, Nnode, xx, yy, theta, \n r, edge.color, edge.width, edge.lty)\n } else {\n cladogram.plot(x$edge, xx, yy, edge.color, edge.width, edge.lty)\n }\n }\n if (root.edge) {\n rootcol <- fifelse(length(edge.color) == 1, edge.color, 'black')\n rootw <- fifelse(length(edge.width) == 1, edge.width, 1)\n rootlty <- fifelse(length(edge.lty) == 1, edge.lty, 1)\n if (type == \"fan\") {\n tmp <- polar2rect(x$root.edge, theta[ROOT])\n segments(0, 0, tmp$x, tmp$y, col = rootcol, lwd = rootw, \n lty = rootlty)\n } else {\n switch(direction,\n rightwards = segments(0, yy[ROOT], \n x$root.edge, yy[ROOT], col = rootcol, lwd = rootw, \n lty = rootlty), leftwards = segments(xx[ROOT], \n yy[ROOT], xx[ROOT] + x$root.edge, yy[ROOT], \n col = rootcol, lwd = rootw, lty = rootlty), \n upwards = segments(xx[ROOT], 0, xx[ROOT], x$root.edge, \n col = rootcol, lwd = rootw, lty = rootlty), \n downwards = segments(xx[ROOT], yy[ROOT], xx[ROOT], \n yy[ROOT] + x$root.edge, col = rootcol, lwd = rootw, \n lty = rootlty))\n }\n }\n if (show.tip.label) {\n if (is.expression(x$tip.label)) \n underscore <- TRUE\n if (!underscore) \n x$tip.label <- gsub(\"_\", \" \", x$tip.label)\n if (phyloORclado) {\n if (align.tip.label) {\n xx.tmp <- switch(direction, rightwards = max(xx[1:Ntip]), \n leftwards = min(xx[1:Ntip]), upwards = xx[1:Ntip], \n downwards = xx[1:Ntip])\n yy.tmp <- switch(direction, rightwards = yy[1:Ntip], \n leftwards = yy[1:Ntip], upwards = max(yy[1:Ntip]), \n downwards = min(yy[1:Ntip]))\n segments(xx[1:Ntip], yy[1:Ntip], xx.tmp, yy.tmp, \n lty = align.tip.label.lty)\n }\n else {\n xx.tmp <- xx[1:Ntip]\n yy.tmp <- yy[1:Ntip]\n }\n text(xx.tmp + lox, yy.tmp + loy, x$tip.label, \n adj = adj, font = font, srt = srt, cex = cex, \n col = tip.color)\n } else {\n angle <- if (type == \"unrooted\") \n XY$axe\n else atan2(yy[1:Ntip], xx[1:Ntip])\n lab4ut <- if (is.null(lab4ut)) {\n if (type == \"unrooted\") \n \"horizontal\"\n else \"axial\"\n }\n else match.arg(lab4ut, c(\"horizontal\", \"axial\"))\n xx.tips <- xx[1:Ntip]\n yy.tips <- yy[1:Ntip]\n if (label.offset) {\n xx.tips <- xx.tips + label.offset * cos(angle)\n yy.tips <- yy.tips + label.offset * sin(angle)\n }\n if (lab4ut == \"horizontal\") {\n y.adj <- x.adj <- numeric(Ntip)\n sel <- abs(angle) > 0.75 * pi\n x.adj[sel] <- -strwidth(x$tip.label)[sel] * \n 1.05\n sel <- abs(angle) > pi/4 & abs(angle) < 0.75 * \n pi\n x.adj[sel] <- -strwidth(x$tip.label)[sel] * \n (2 * abs(angle)[sel]/pi - 0.5)\n sel <- angle > pi/4 & angle < 0.75 * pi\n y.adj[sel] <- strheight(x$tip.label)[sel]/2\n sel <- angle < -pi/4 & angle > -0.75 * pi\n y.adj[sel] <- -strheight(x$tip.label)[sel] * \n 0.75\n text(xx.tips + x.adj * cex, yy.tips + y.adj * \n cex, x$tip.label, adj = c(adj, 0), font = font, \n srt = srt, cex = cex, col = tip.color)\n } else {\n if (align.tip.label) {\n POL <- rect2polar(xx.tips, yy.tips)\n POL$r[] <- max(POL$r)\n REC <- polar2rect(POL$r, POL$angle)\n xx.tips <- REC$x\n yy.tips <- REC$y\n segments(xx[1:Ntip], yy[1:Ntip], xx.tips, \n yy.tips, lty = align.tip.label.lty)\n }\n if (type == \"unrooted\") {\n adj <- abs(angle) > pi/2\n angle <- angle * 180/pi\n angle[adj] <- angle[adj] - 180\n adj <- as.numeric(adj)\n } else {\n s <- xx.tips < 0\n angle <- angle * 180/pi\n angle[s] <- angle[s] + 180\n adj <- as.numeric(s)\n }\n font <- rep(font, length.out = Ntip)\n tip.color <- rep(tip.color, length.out = Ntip)\n cex <- rep(cex, length.out = Ntip)\n for (i in 1:Ntip) text(xx.tips[i], yy.tips[i], \n x$tip.label[i], font = font[i], cex = cex[i], \n srt = angle[i], adj = adj[i], col = tip.color[i])\n }\n }\n }\n if (show.node.label) \n text(xx[ROOT:length(xx)] + label.offset, yy[ROOT:length(yy)], \n x$node.label, adj = adj, font = font, srt = srt, \n cex = cex)\n }\n L <- list(type = type, use.edge.length = use.edge.length, \n node.pos = node.pos, node.depth = node.depth, show.tip.label = show.tip.label, \n show.node.label = show.node.label, font = font, cex = cex, \n adj = adj, srt = srt, no.margin = no.margin, label.offset = label.offset, \n x.lim = x.lim, y.lim = y.lim, direction = direction, \n tip.color = tip.color, Ntip = Ntip, Nnode = Nnode, root.time = x$root.time, \n align.tip.label = align.tip.label, coords = list(edge = xe, xx = xx, yy = yy))\n assign(\"last_plot.phylo\", c(L, list(edge = xe, xx = xx, yy = yy)), \n envir = .PlotPhyloEnv)\n invisible(L)\n}\n\n\n\nget.children <- function(tedges, from.node = NULL) {\n if (is.null(from.node))\n from.node <- setdiff(tedges$from , tedges$to)\n res <- NULL\n i <- 0L\n if (is.null(key(tedges)) || key(tedges) != 'from')\n setkey(tedges, from)\n children <- tedges[from %in% from.node]\n while(nrow(children)) {\n children[, lvl := i]\n res <- rbind(res, children)\n children <- tedges[from %in% children$to]\n i <- i + 1L\n }\n res\n}\n\nget.parents <- function(tedges, from.node) {\n i <- 0L\n res <- vector(\"list\", 1000)\n setkey(tedges, to)\n anc <- tedges[to %in% from.node]\n \n while(nrow(anc)) {\n anc[, lvl := i]\n i <- i + 1L\n res[[i]] <- anc\n anc <- tedges[to %in% anc$from]\n }\n rbindlist(res)\n}\n\n\n\n## * Convert subset of the edge data.table to phylo tree\nedges2phylo <- function(tedges, idcol = 'virus_name', update.first = T) {\n\n e <- copy(tedges)\n if (update.first | !('to.tip' %in% names(tedges)))\n update.tree(e)\n\n rt <- get.root(e)\n \n tps <- e[to.tip == T, sort(unique(to))]\n ntips <- length(tps)\n nds <- c(rt, setdiff(sort(setdiff(unlist(e[, .(from, to)]), tps)), rt))\n nnodes <- length(nds)\n\n ## ** Re-name nodes and tips\n lkup <- data.table(id = c(tps, nds), is.tip = c(rep(T, length.out = ntips), rep(F, length.out = nnodes)))\n lkup[, newid := .I]\n setnames(e, c('from', 'to'), c('from.ori', 'to.ori'))\n\n e[lkup, from := i.newid, on = c('from.ori' = 'id')]\n e[lkup, to := i.newid, on = c('to.ori' = 'id')]\n setorder(e, -to.tip, to, from)\n \n m <- as.matrix(e[, .(from, to)])\n dimnames(m) <- NULL\n\n cols <- c('to', idcol)\n t <- list(edge = m,\n edge.length = e$dist,\n Nnode = nnodes,\n node.label = NULL,\n tip.label = e[to.tip == T, ..cols][order(to)][, get(idcol)]\n )\n class(t) <- 'phylo'\n attr(t, 'order') <- 'cladewise'\n\n list(phylo = t,\n edges = e)\n}\n\n## * Prepare data to be plotted - extract coordinates and make edges square if required\nedges.plot.prep <- function(tedges, square.edges = T, id.col = 'vertex_id') {\n\n phy <- edges2phylo(tedges, idcol = id.col) # convert edges data.table back to phylo tree\n tt <- phy$phylo\n eds <- phy$edges\n\n ## checkValidPhylo(tt)\n\n ## ** Get coordinates without plotting\n p <- plot2(tt, type = 'phylogram', plot = F,\n show.tip.label = F, show.node.label = F,\n edge.color = 'black', tip.color = 'red', cex = 0,\n root.edge = F, use.edge.length = T,\n no.margin = T)\n\n ed <- data.table(p$coords$edge)\n xy <- data.table(x = p$coords$xx, y = p$coords$yy)\n xy[, id := .I]\n\n eds[xy, `:=`(from.x = i.x, from.y = i.y), on = c('from' = 'id')]\n eds[xy, `:=`(to.x = i.x, to.y = i.y), on = c('to' = 'id')]\n\n ## ** Make square segments\n if (square.edges) {\n e <- eds[from.x != to.x & from.y != to.y]\n ed <- e[, .(to.x = c(from.x, to.x), from.y = c(from.y, to.y), to.tip = c(F, first(to.tip)),\n extra = c(T, F))\n , .(from, to, eid)]\n \n ed <- merge(ed, e[, c('eid', setdiff(names(e), names(ed))), with=F], by = 'eid')\n ed <- rbind(ed, eds[!(from.x != to.x & from.y != to.y)], fill = T)\n } else ed <- copy(eds)\n\n return(ed)\n}\n\n\n\n## * Assign common trait within clades\n\nspread.clade.trait <- function(tedges, var, agg.var.name = 'children_common_trait') {\n\n if ('children_agg' %in% names(tedges))\n tedges[, children_agg := NULL]\n if (agg.var.name %in% names(tedges))\n tedges[, eval(agg.var.name) := NULL]\n tedges[, children_agg := get(var)]\n if ('curr_agg' %in% names(tedges))\n tedges[, curr_agg := NULL]\n \n ## aggval <- tedges[to.tip == T & !is.na(children_agg), mean(children_agg)]\n ## tedges[to.tip == T & is.na(children_agg), children_agg := aggval]\n \n mxnode <- tedges[, max(nthnode)]\n nod=mxnode-1\n for (nod in (mxnode-1):1L) {\n higher.lvl <- tedges[nthnode == nod+1L]\n higher.lvl[, curr_agg := fifelse(uniqueN(children_agg)==1, children_agg[1], 'multiple'), from]\n lower.lvl <- tedges[nthnode == nod]\n ## lower.lvl[higher.lvl, children_agg := mean(i.children_agg, na.rm=T), on = c('to' = 'from')]\n lower.lvl[higher.lvl, children_agg := i.curr_agg, on = c('to' = 'from')]\n ## lower.lvl[higher.lvl, curr_agg := mean(i.children_agg, na.rm=T), on = c('to' = 'from')]\n tedges[lower.lvl, children_agg := i.children_agg, on = 'eid']\n }\n\n if (agg.var.name %in% names(tedges)) {\n tedges[, eval(agg.var.name) := NULL]\n }\n setnames(tedges, 'children_agg', agg.var.name)\n return(invisible(tedges))\n}\n\nspread.stat <- function(tedges, var, progress = T, agg.var.name = 'children_agg', stat.fun = mean) {\n\n tedges[, children_agg := get(var)]\n if ('curr_agg' %in% names(tedges))\n tedges[, curr_agg := NULL]\n \n aggval <- tedges[to.tip == T & !is.na(children_agg), mean(children_agg)]\n tedges[to.tip == T & is.na(children_agg), children_agg := aggval]\n \n mxnode <- tedges[, max(nthnode)]\n nod=mxnode-1\n for (nod in (mxnode-1):1L) {\n higher.lvl <- tedges[nthnode == nod+1L]\n higher.lvl[, curr_agg := stat.fun(children_agg, na.rm=T), from]\n lower.lvl <- tedges[nthnode == nod]\n ## lower.lvl[higher.lvl, children_agg := mean(i.children_agg, na.rm=T), on = c('to' = 'from')]\n lower.lvl[higher.lvl, children_agg := i.curr_agg, on = c('to' = 'from')]\n ## lower.lvl[higher.lvl, curr_agg := mean(i.children_agg, na.rm=T), on = c('to' = 'from')]\n tedges[lower.lvl, children_agg := i.children_agg, on = 'eid']\n }\n\n setnames(tedges, 'children_agg', agg.var.name)\n\n}\n\n\n\n\n## points = NULL\n## width = 55.5; height = 50; square.edges = T;\n## edges.colour.by = 'children_trait'; points.colour.by = 'children_trait';\n## palette.fun = NULL; z.var = NULL; z.trans.fun = I; max.z = 2e6;\n## bgcol = '#EEEEEE'; tooltip = T;\n## edge.vars = c('accession_id', 'vertex_id', 'children_trait');\n## point.vars = c('accession_id', 'collection_date', 'continent',\n## 'country', 'host', 'clade', 'lineage', 'children_trait');\n## node.lab.glue = \"ID: {accession_id}
Continent: {continent}
country: {country}
Date: {collection_date}\";\n## edge.lab.glue = \"ID: {accession_id}
Vertex ID: {vertex_id}
{children_trait}\"\n\ntree2deck <- function(tedges, points = NULL, width = 55.5, height = 50, square.edges = T,\n edges.colour.by = 'children_trait', points.colour.by = 'children_trait',\n thickness.var = 'children_agg',\n palette.fun = NULL, z.var = NULL, z.trans.fun = I, max.z = 2e6,\n bgcol = '#EEEEEE', tooltip = T,\n edge.vars = c('eid', 'continent_spread', 'country_spread'),\n point.vars = c('eid', 'continent_spread', 'country_spread'),\n node.lab.glue = '{eid}
{continent_spread}
{country_spread}',\n edge.lab.glue = '{eid}
{continent_spread}
{country_spread}') {\n library(deckgl)\n\n in3D <- !is.null(z.var)\n if (in3D)\n tedges[, zval := get(z.var)]\n \n if (!('to.tip' %in% names(tedges)))\n tedges <- update.tree(tedges)\n\n e <- tedges\n\n if (is.null(points)) {\n t <- e[to.tip == T]\n } else t <- points\n\n if (!is.null(edges.colour.by) && !(edges.colour.by %in% names(e)))\n edges.colour.by <- NULL\n if (!is.null(points.colour.by) && !(points.colour.by %in% names(t)))\n points.colour.by <- NULL\n \n ## ** Colour\n if (!is.null(edges.colour.by)) {\n if (is.numeric(e[[edges.colour.by]])) {\n e[, colour := scales::cscale(get(edges.colour.by),\n scales::gradient_n_pal(colours = gplots::rich.colors(30)))]\n } else {\n if (e[!is.na(get(edges.colour.by)), all(grepl('^#', get(edges.colour.by)))]) {\n e[, colour := get(edges.colour.by)]\n } else {\n e[, colour := scales::dscale(factor(get(edges.colour.by)),\n pals::alphabet)]\n }\n }\n } else e[, colour := NA_character_]\n e[is.na(colour), colour := '#AAAAAA']\n\n if (!is.null(points.colour.by)) {\n if (points.colour.by %in% names(t)) {\n if (is.numeric(t[[points.colour.by]])) {\n t[, colour := scales::cscale(get(points.colour.by),\n scales::gradient_n_pal(colours = gplots::rich.colors(30)))]\n } else {\n if (t[!is.na(get(points.colour.by)), all(grepl('^#', get(points.colour.by)))]) {\n t[, colour := get(points.colour.by)]\n } else {\n t[, colour := scales::dscale(factor(get(points.colour.by)),\n gplots::rich.colors)]\n }\n }\n } else t[, colour := points.colour.by] # if colour var not a field, assume it's a colour\n } else t[, colour := NA_character_]\n t[is.na(colour), colour := '#AAAAAA']\n \n maxx <- max(e$to.x)\n maxy <- max(e$to.y)\n\n t[, x := scales::rescale(to.x, c(0, width) , c(0, maxx))]\n t[, y := scales::rescale(to.y, c(0, height), c(0, maxy))]\n\n e[, start_x := scales::rescale(from.x, c(0, width), c(0, maxx))]\n e[, start_y := scales::rescale(from.y, c(0, height), c(0, maxy))]\n e[, end_x := scales::rescale(to.x, c(0, width), c(0, maxx))]\n e[, end_y := scales::rescale(to.y, c(0, height), c(0, maxy))]\n if (!is.null(thickness.var) && thickness.var %in% names(e)) {\n e[, linewidth := scales::rescale(sqrt(get(thickness.var)), c(1, 20))]\n } else e[, linewidth := 1]\n \n if (in3D) {\n zrange <- e[, range(zval, na.rm=T)]\n t[, z := scales::rescale(z.trans.fun(zval) , c(0, max.z), z.trans.fun(zrange))]\n e[, start_z := scales::rescale(z.trans.fun(curr_agg), c(0, max.z), z.trans.fun(zrange))]\n e[, end_z := scales::rescale(z.trans.fun(zval) , c(0, max.z), z.trans.fun(zrange))]\n } else {\n t[, z := NA]\n e[, c('start_z', 'end_z') := NA]\n }\n\n vars <- c('x', 'y', 'z', 'colour', point.vars)\n pp <- t[, ..vars]\n vars <- c('start_x', 'start_y', 'start_z', 'end_x', 'end_y', 'end_z', 'colour', 'linewidth', edge.vars)\n ll <- e[, ..vars]\n\n root <- setdiff(tedges$from, tedges$to)\n rootpt <- e[from == root][1, .(start_x, start_y, start_z, end_x, end_y, end_z, eid)]\n\n pp[, label := glue::glue(node.lab.glue, envir = .SD)]\n ll[, label := as.character(glue::glue(edge.lab.glue, envir = .SD))]\n\n \n leg <- tedges[!is.na(colour), .N, c(edges.colour.by, 'colour')][order(get(edges.colour.by))]\n setnames(leg, edges.colour.by, 'val')\n\n if (in3D) {\n\n if (tooltip) {\n\n proplines <- list(\n getSourcePosition = ~ start_x + start_y + start_z,\n getTargetPosition = ~ end_x + end_y + end_z,\n getTooltip = JS(\"object =>`${object.label}`\"),\n getWidth = 1,\n pickable = T,\n opacity = 0.5,\n visible = T,\n getColor = get_color_to_rgb_array('colour')\n )\n \n proppoints <- list(\n getPosition = ~ x + y + z,\n getColor = get_color_to_rgb_array('colour'),\n getFillColor = get_color_to_rgb_array('colour'),\n getRadius = 1000,\n getTooltip = JS(\"object =>`${object.label}`\"),\n stroked = T,\n pointSize = 2,\n radiusScale = 8,\n radiusMinPixels = 1.5,\n radiusMaxPixels = 5,\n opacity = 0.8\n )\n\n proproot <- list(\n getPosition = ~ start_x + start_y + start_z,\n getColor = '#000000',\n getFillColor = '#FFFFFF',\n getRadius = 1000,\n getTooltip = \"Tree root
Epi-id: {{eid}}\",\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 5,\n radiusMaxPixels = 15,\n opacity = 1\n )\n \n\n deck <- deckgl(width='100vw', height='100vh', latitude = 25, longitude = 25, zoom = 3,\n pitch = fifelse(in3D, 60, 0), maxPitch = 89.9,\n style = list(background = bgcol)) %>%\n add_line_layer(data = ll[, .(start_x, start_y, start_z, end_x, end_y, end_z, colour, label)],\n properties = proplines) %>%\n add_scatterplot_layer(data = pp[, .(x, y, z, colour, label)], properties = proppoints) %>%\n add_scatterplot_layer(data = rootpt[, .(start_x, start_y, start_z, eid)], properties = proproot) %>%\n add_legend(\n colors = leg$colour,\n labels = leg$val,\n title = '',\n pos = 'top-left'\n )\n \n } else {\n \n proppoints <- list(\n getPosition = ~ x + y + z,\n getColor = get_color_to_rgb_array('colour'),\n getFillColor = get_color_to_rgb_array('colour'),\n getRadius = 1000,\n stroked = T,\n pointSize = 2,\n radiusScale = 8,\n radiusMinPixels = 1.5,\n radiusMaxPixels = 5,\n opacity = 0.8\n )\n \n proplines <- list(\n getSourcePosition = ~ start_x + start_y + start_z,\n getTargetPosition = ~ end_x + end_y + end_z,\n getWidth = 1,\n pickable = T,\n opacity = 0.5,\n visible = T,\n getColor = get_color_to_rgb_array('colour')\n )\n \n proproot <- list(\n getPosition = ~ start_x + start_y + start_z,\n getColor = '#000000',\n getFillColor = '#FFFFFF',\n getRadius = 1000,\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 5,\n radiusMaxPixels = 15,\n opacity = 1\n )\n \n deck <- deckgl(width='100vw', height='100vh', latitude = 25, longitude = 25, zoom = 3,\n pitch = fifelse(in3D, 60, 0), maxPitch = 89.9,\n style = list(background = bgcol)) %>%\n add_line_layer(data = ll[, .(start_x, start_y, start_z, end_x, end_y, end_z, colour)],\n properties = proplines) %>%\n add_scatterplot_layer(data = pp[, .(x, y, z, colour)], properties = proppoints) %>%\n add_scatterplot_layer(data = rootpt[, .(start_x, start_y, start_z)], properties = proproot) %>%\n add_legend(\n colors = leg$colour,\n labels = leg$val,\n title = '',\n pos = 'top-left'\n )\n\n }\n \n } else {\n\n if (tooltip) {\n \n proplines <- list(\n getSourcePosition = ~ start_x + start_y,\n getTargetPosition = ~ end_x + end_y,\n getTooltip = JS(\"object =>`${object.label}`\"),\n getWidth = ~ linewidth,\n widthScale = 1,\n pickable = T,\n opacity = 0.8,\n visible = T,\n getColor = get_color_to_rgb_array('colour')\n )\n\n proppoints <- list(\n getPosition = ~ x + y,\n getColor = get_color_to_rgb_array('colour'),\n getFillColor = get_color_to_rgb_array('colour'),\n getRadius = 1000,\n getTooltip = JS(\"object =>`${object.label}`\"),\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 1.5,\n radiusMaxPixels = 5,\n opacity = 0.8\n )\n\n proproot <- list(\n getPosition = ~ start_x + start_y,\n getColor = '#000000',\n getFillColor = '#FFFFFF',\n getRadius = 1000,\n getTooltip = \"Tree root
Epi-id: {{eid}}\",\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 5,\n radiusMaxPixels = 15,\n opacity = 1\n )\n\n deck <- deckgl(width='100vw', height='100vh', latitude = 25, longitude = 25, zoom = 3,\n pitch = fifelse(in3D, 60, 0), maxPitch = 89.9,\n style = list(background = bgcol)) %>%\n add_line_layer(data = ll[, .(start_x, start_y, end_x, end_y, colour, label, linewidth)],\n properties = proplines) %>%\n add_scatterplot_layer(data = pp[, .(x, y, colour, label)], properties = proppoints) %>%\n add_scatterplot_layer(data = rootpt[, .(start_x, start_y, eid)], properties = proproot) %>%\n add_legend(\n colors = leg$colour,\n labels = leg$val,\n title = '',\n pos = 'top-left'\n )\n \n } else {\n\n proppoints <- list(\n getPosition = ~ x + y,\n getColor = get_color_to_rgb_array('colour'),\n getFillColor = get_color_to_rgb_array('colour'),\n getRadius = 1000,\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 1.5,\n radiusMaxPixels = 5,\n opacity = 0.8\n )\n\n proproot <- list(\n getPosition = ~ start_x + start_y,\n getColor = '#000000',\n getFillColor = '#FFFFFF',\n getRadius = 1000,\n stroked = T,\n radiusScale = 8,\n radiusMinPixels = 5,\n radiusMaxPixels = 15,\n opacity = 1\n )\n\n proplines <- list(\n getSourcePosition = ~ start_x + start_y,\n getTargetPosition = ~ end_x + end_y,\n getWidth = 1,\n pickable = T,\n opacity = 0.8,\n visible = T,\n getColor = get_color_to_rgb_array('colour')\n )\n\n deck <- deckgl(width='100vw', height='100vh', latitude = 25, longitude = 25, zoom = 3,\n pitch = fifelse(in3D, 60, 0), maxPitch = 89.9,\n style = list(background = bgcol)) %>%\n add_line_layer(data = ll[, .(start_x, start_y, end_x, end_y, colour)],\n properties = proplines) %>%\n add_scatterplot_layer(data = pp[, .(x, y, colour)], properties = proppoints) %>%\n add_scatterplot_layer(data = rootpt[, .(start_x, start_y)], properties = proproot) %>%\n add_legend(\n colors = leg$colour,\n labels = leg$val,\n title = '',\n pos = 'top-left'\n )\n\n }\n \n }\n \n return(deck)\n}\n\ntree.from.edge <- function(tedges, sel.eid=123309) {\n from.node <- tedges[eid == sel.eid, to]\n pars <- get.parents(tedges, from.node)\n childs <- get.children(tedges, from.node)\n rbind(pars, childs)\n}\n\ntree.from.attribute <- function(tedges, attr.var = 'country', attr.val = 'Australia') {\n te <- tedges[get(attr.var) == attr.val]\n tetips <- te[to.tip == T]\n parents <- get.parents(tedges, tetips$to)\n parents <- unique(parents[, -'lvl'])\n parents\n}\n\n\nupper1st <- function (x, prelower = T) {\n if (is.factor(x)) {\n x0 <- levels(x)\n } else x0 <- as.character(x)\n if (prelower) x0 <- tolower(x0)\n nc <- nchar(x0)\n nc[is.na(nc)] <- 0\n x0[nc > 1] <- sprintf(\"%s%s\", toupper(substr(x0[nc > 1], 1, 1)),\n substr(x0[nc > 1], 2, nchar(x0[nc > 1])))\n x0[nc == 1] <- toupper(x0[nc == 1])\n if (is.factor(x)) {\n levels(x) <- x0\n } else x <- x0\n return(x)\n}\n\nhier.pal <- function(category, subcategory, spread.within = 0.3,\n chroma = 110, luminance = 70, alpha = 1) {\n\n cols0 <- data.table(id1 = category, id2 = subcategory)\n cols0[, i := .I]\n setkey(cols0, id1, id2)\n\n cols <- cols0[, .N, .(id1, id2)]\n\n ncats <- uniqueN(cols$id1)\n steps <- seq(0, 360, length.out = ncats + 1)\n diff <- steps[2]-steps[1]\n steps <- steps + diff / 2\n \n steps <- head(steps, ncats)\n names(steps) <- unique(cols$id1)\n cols[, step := steps[id1]]\n\n spread <- diff * spread.within / 2\n cols[, offset := seq(-spread, spread, length.out = .N), id1]\n cols[, hue := step + offset]\n \n cols[, c := chroma + offset]\n cols[, l := luminance + offset]\n\n cols[, col := hcl(h = hue, c = c, l = l, alpha = alpha)]\n\n setorder(cols0, i)\n return(cols[cols0, col, on = c('id1', 'id2')])\n}\n", "meta": {"hexsha": "28f9d4638f635bc996706acd5f90ebcb08b4b9da", "size": 45501, "ext": "r", "lang": "R", "max_stars_repo_path": "NLP/tree-functions.r", "max_stars_repo_name": "sarah-wilcox/dragonfly-website", "max_stars_repo_head_hexsha": "eba2106ded4a18e9260dcca389fa38d046ea8294", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 8, "max_stars_repo_stars_event_min_datetime": "2015-09-26T22:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T10:57:04.000Z", "max_issues_repo_path": "NLP/tree-functions.r", "max_issues_repo_name": "dragonfly-science/dragonfly-website", "max_issues_repo_head_hexsha": "eba2106ded4a18e9260dcca389fa38d046ea8294", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 151, "max_issues_repo_issues_event_min_datetime": "2015-09-20T23:27:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:33:56.000Z", "max_forks_repo_path": "NLP/tree-functions.r", "max_forks_repo_name": "sarah-wilcox/dragonfly-website", "max_forks_repo_head_hexsha": "eba2106ded4a18e9260dcca389fa38d046ea8294", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2015-09-20T22:57:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T22:49:42.000Z", "avg_line_length": 38.4949238579, "max_line_length": 126, "alphanum_fraction": 0.4677919167, "num_tokens": 12379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.2902211242444727}} {"text": "#-------------------------------------------------------------------------------\n# Licence:\n# Copyright (c) 2012-2017 Luzzi Valerio for Gecosistema S.r.l.\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n# Name:\n# Purpose: Kriging\n#\n# Author: Luzzi Valerio\n#\n# Created: 05/09/2017\n#-------------------------------------------------------------------------------\n\n#SRS = \"+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=500092 +y_0=-3999800 +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs\"\n#\n#Default SRS= epsg:3857 if not defined in shape\nSRS = \"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs\"\n#------------------------------------------------------------------------------\n#\tstring functions\n#------------------------------------------------------------------------------\nlen<-function(arr)length(arr)\ncontains<-function(text,search){return(length(grep(search,text))>0)}\nalltrim <- function (text) gsub(\"^\\\\s+|\\\\s+$\", \"\",text)\nupper<-function(text)toupper(text)\nlower<-function(text)tolower(text)\nleft<-function(text,n)substr(text,1,n)\njuststem<-function(text) sub(\"^([^.]*).*\", \"\\\\1\", basename(text)) \njustpath<-function(text)dirname(text)\njustext<-function(text) substr(text,nchar(text)-2,nchar(text))\nforceext<-function(text,ext) sub(\"^([^.]*).*\", paste(\"\\\\1\",ext,sep=\".\"), text) \nmkdirs<-function(text)dir.create(text,recursive=TRUE,showWarnings = FALSE)\nisDate<-function(text){res = tryCatch(length(as.Date(text))>0,error=function(e){return(FALSE)});return(res)}\nlogger<-function(text){f=file(\"log.txt\",open=\"at\");writeLines(text,f);print(text);close(f);}\nprogression<-function(text,perc){f=file(\"interp.progress\",open=\"at\");writeLines(text,f);print(text);close(f);}\n\n\n\n#------------------------------------------------------------------------------\n#\tCreateMask\n#------------------------------------------------------------------------------\nCreateMask<-function(piezo,buffer=200,pixelsize=10){\n\n\tbbox = bbox(piezo)\n\tminx = bbox[1]-buffer\n\tminy = bbox[2]-buffer\n\tmaxx = bbox[3]+buffer\n\tmaxy = bbox[4]+buffer\n\tx= seq(minx,maxx,pixelsize)\n\ty= seq(miny,maxy,pixelsize)\n\t\n\tgrid = expand.grid(X=x,Y=y)\n\tgrid$Z = 0.0\n\tgridded(grid)=~X+Y\n\tproj4string(grid)=proj4string(piezo)\n\t#writeGDAL(grid[\"Z\"],\"buffer.tif\")\n\treturn(grid)\n}\n\n#------------------------------------------------------------------------------\n#\tDetectFormulaUK - Formula for universal Kriging\n#------------------------------------------------------------------------------\nDetectFormulaUK <- function( prec ){\n\n\t#Creo la formula per l'Universal Kriging\n\t#Cerco il nome della variabile dipendente\n\tVALUE = \"VALUE\"\n\tcn = names( prec ) #Nomi dei campi \n\tcandidates = c(\"VALUE\",\"value\")\n\tfor(varname in candidates){\n\t\tif ( isTRUE(grep(varname,cn)) ){\n\t\t\tVALUE = varname\n\t\t\tbreak\n\t\t}\n\t}\n\t\n\t#Creo la formula per l'Universal Kriging\n\tcn = cn[cn!=VALUE] #Rimuovo \"VALUE\" non deve comparire a dx nella formula\n\tf = paste(cn,collapse=\"+\")\n\tf = paste(VALUE,\"~\",f)\n\tf = as.formula(f)\n\treturn(f)\n}\n\n\n#------------------------------------------------------------------------------\n#\tKriging | IDW\n#------------------------------------------------------------------------------\nKriging <- function( fileshp, filetif=\"\", sformula=\"VALUE~1\", type =\"AUTO\", pixelsize=100, psill=1, range=900, nugget=1, buffer=0, RemoveNegativeValues=FALSE)\n{\n prec = readOGR(fileshp,juststem(fileshp))\n if (is.na(proj4string(prec)))\n proj4string(prec) = CRS(SRS)\n\n\tprint(paste(\"Number of points to krige\",length(prec)))\n\n\tdem <- CreateMask(prec, buffer, pixelsize)\n\txy <- as.data.frame(coordinates(dem))\n\tdem@data$x<-xy$X\n\tdem@data$y<-xy$Y\n\n\t#Rinomino la banda1 in z \n\tcolnames(dem@data)[1]=\"z\"\n\n\t#fieldname (in genere VALUE)\n\tformula = as.formula(sformula)\n\tfieldname = alltrim(strsplit(sformula,\"~\")[[1]][1])\n\n\t#Remove na from prec$VALUE\n\tprec<-prec[!is.na(prec[[fieldname]]),]\n\n\t#Overlay prendo il valori nei punti delle stazioni\n\tov<-over(prec,dem)\n\tprec$x <- ov$x\n\tprec$y <- ov$y\n\tprec$z <- ov$z\t\n\t\n\t#print(prec)\n\t\n\t#UniversalKriging\n\tif (type ==\"UK\"){\n\t # trend model \n\t #sformula =\"VALUE~X+Y+Z\"\n\t #formula = as.formula(sformula) #else fm = DetectFormulaUK(prec@data)\n\t lm.prec <- lm(fm, prec)\n\t formula_optimal <-step(lm.prec)\n\t residui = residuals(fm)\n\t \n\t null.vgm <- vgm(var(residui), \"Sph\", sqrt(areaSpatialGrid(dem))/4, nugget=0) # initial parameters\n\t vgm_r <- fit.variogram(variogram(residui~1, prec) ,model=null.vgm)\n\t prec_ok <- krige(as.formula(formula_optimal), locations=prec, newdata=dem, model=vgm_r) \n\t prediction = prec_ok[1]\n\t}\n\t\n\t#Automap\n\tif (type == \"AUTO\"){\n\t library(automap)\n\t\tprec_ok <-autoKrige(formula,prec,dem)\n\t\tprec_ok = prec_ok$krige_output\t\t\n\t\tprediction = prec_ok[1]\n\t}\t\n\t#Ordinary Kriging\n\tif ( type ==\"OK\"){\n\t #psill,range,nugget are auto calculated by fitting the variogram\n\t \n\t #this are initial parameters to suggest an initial variogram model to fit.variogram algorithm\n psill = var(prec[[fieldname]]) #variance of prec$VALUE\n range = sqrt(areaSpatialGrid(dem))/4\n nugget = 0\n\t \n\t\tnull.vgm = vgm(psill, \"Sph\", range, nugget)\n\t\tvgm_optimal = fit.variogram(variogram(formula, prec), model=null.vgm )\n\t\t#vgm_optimal is the best variogram model that fit the empirical variogram data\n\t\t\n\t\t#print(vgm_optimal)\n\t\t#print(\"-----------------------\")\n\t\t\n\t\tprec_ok <- krige(formula, locations=prec, newdata=dem, model=vgm_optimal)\n\t\tprediction = prec_ok[1]\n\t}\n\t#Ordinary Kriging\n\tif ( type ==\"OK-ADVANCED\"){\n\t #psill,range,nugget are chosen from user passed by arg\n\t vgm_optimal<- vgm(psill, \"Sph\", range, nugget)\n\t \n\t print(vgm_optimal)\n\t print(\"-----------------------\")\n\t \n\t\tprec_ok <- krige(formula, locations=prec, newdata=dem, model=vgm_optimal)\n\t\tprediction = prec_ok[1]\n\t}\n\t#Inverse Distance\n\tif( type ==\"IDW2\"){\n prec_ok <- idw(formula, prec, dem,idp=2.0,maxdist=Inf)\n prediction = prec_ok[1]\n\t}\n\tmkdirs(justpath(filetif))\n\t\n\t#Remove negative values!!!!\n\tif (RemoveNegativeValues){\n\t\tprediction@data[prediction@data<0]=0}\n\t\n\twriteGDAL(prediction,filetif)\t\n\treturn(filetif)\n}\n\n#------------------------------------------------------------------------------\n#\tMain\n#------------------------------------------------------------------------------\nMain <- function(){\n #Suppress Warning\n options(warn=-1)\n\n\t#Getting command arguments\n\targs <- commandArgs(trailingOnly = TRUE)\n\tres = FALSE\n\n\t\n\t#load required libraries\n\tsuppressPackageStartupMessages(library(rgdal))\n\tlibrary(sp)\n\tlibrary(rgdal)\n\tlibrary(gstat)\n\t#library(tools)\n\t\n\n\t#Test\n\tfiletif = \"\"\n\tif (length(args)==0){\n\t\t\n\t\tsetwd(\"c:\\\\Users\\\\vlr20\\\\Dektop\\\\FeFlow\\\\results\")\n\t\tfileshp\t\t= \"okrige-759066-2015-08-01.shp\"\n\t\tfiletif = forceext(fileshp,\"tif\")\n\t\n\t\tmethod = \"OK\"\n\t\tsformula =\"value~1\"\n\t\tpsill = 1\n\t\trange = 900\n\t\tnugget = 1\n\t\tpixelsize=10\n\t\tbuffer = 5000\n\t\tfiletif = Kriging(fileshp, filetif, sformula, method, pixelsize, psill, range, nugget, buffer, RemoveNegativeValues=FALSE)\n\t}\n\tif (length(args)==10){\n\n\t\tSys.getenv()\n\n\t\tfileshp\t\t = Sys.getenv(\"FILESHP\")\n\t\tfiletif\t\t = Sys.getenv(\"FILETIF\")\n\t\tsformula = Sys.getenv(\"SFORMULA\")\n\t\tmethod\t\t = Sys.getenv(\"METHOD\") #AUTO|UK|UK-AutoKrige|OK|OK-ADVANCED|IDW2\n\t\tpixelsize = as.numeric(Sys.getenv(\"PIXELSIZE\"))\n\t\t\n\t\tpsill = as.numeric(Sys.getenv(\"PSILL\"))\n\t\trange = as.numeric(Sys.getenv(\"RANGE\"))\n\t\tnugget = as.numeric(Sys.getenv(\"NUGGET\"))\n\t\tbuffer = as.numeric(Sys.getenv(\"BUFFER\"))\n\t\tRemoveNegativeValues = as.logical(Sys.getenv(\"REMOVENEGATIVEVALUES\")) #remove non-sense negative values caused by interpolation\n\n\t\t#print(fileshp)\n\t\t#print(method)\n\t\t#print(pixelsize)\n\t\t#print(sformula)\n\t\t#print(RemoveNegativeValues)\n\t\t#comment next 2 lines\n\t\t# ...\n\t\t#pixelsize\t=50\t \n\t\t#Pay attention here!!\n\t\tfiletif = Kriging(fileshp, filetif, sformula, method, pixelsize, psill, range, nugget, buffer, RemoveNegativeValues)\n\t}\n\t\n\t#res = paste('{\"success\":TRUE,\"filename\":\"',filetif,'\"}',sep=\"\")\n\treturn(filetif)\n}\n\n#------------------------------------------------------------------------------\n#\tMain-loop launch\n#------------------------------------------------------------------------------\n##libray = \"D:\\\\Program Files (x86)\\\\SICURA\\\\apps\\\\common\\\\bin\\\\R\\\\R-3.3.2\\\\library\"\n##install.packages(\"sp\", lib=libray)\n##install.packages(\"rgdal\", lib=libray)\n##install.packages(\"gstat\", lib=libray)\n##install.packages(\"automap\", lib=libray)\n##install.packages(\"tools\", lib=libray)\nprint(Main())\n\n\n\n\n", "meta": {"hexsha": "85bcd19ffc943bb5ec0293f2d64c9f2b7a9d0637", "size": 9044, "ext": "r", "lang": "R", "max_stars_repo_path": "gecosistema_krige/R/qkrige_v4.1.r", "max_stars_repo_name": "valluzzi/gecosistema_krige", "max_stars_repo_head_hexsha": "9c1f43e2d95afdb85aa0e6c7ec6479d9c8f840ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gecosistema_krige/R/qkrige_v4.1.r", "max_issues_repo_name": "valluzzi/gecosistema_krige", "max_issues_repo_head_hexsha": "9c1f43e2d95afdb85aa0e6c7ec6479d9c8f840ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gecosistema_krige/R/qkrige_v4.1.r", "max_forks_repo_name": "valluzzi/gecosistema_krige", "max_forks_repo_head_hexsha": "9c1f43e2d95afdb85aa0e6c7ec6479d9c8f840ad", "max_forks_repo_licenses": ["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.3, "max_line_length": 158, "alphanum_fraction": 0.5986289253, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.28937793727907074}} {"text": "# 3. faza: Vizualizacija podatkov\n\n# Funkcija za prikaz napredka discipline\n\nGraf_napredka <- function(razdalja, bazen){\n ggplot(podatki %>% filter(Distance == razdalja, Pool == bazen) %>%\n mutate(zaokrozeni_datumi=Swim_date-day(Swim_date)+1) %>%\n group_by(zaokrozeni_datumi) %>% summarise(Time=min(Time)),\n aes(x=zaokrozeni_datumi, y=Time)) +\n geom_line() + ylab(\"Čas plavanja\") + xlab(\"Datum\")\n}\n\n\n# Funkcija za prikaz napredka plavalca pri neki disciplini\n\nGraf_plavalca <- function(razdalja, bazen, ime){\n ggplot(podatki %>% filter(Distance == razdalja, Pool == bazen, Name == ime) %>%\n mutate(zaokrozeni_datumi=Swim_date-day(Swim_date)+1) %>%\n group_by(zaokrozeni_datumi) %>% summarise(Time=min(Time)),\n aes(x=zaokrozeni_datumi, y=Time), colour = \"steelblue\", size = 1) +\n geom_line() + ylab(\"Swim Time\") + xlab(\"Date\")\n}\n\n\n# Primerjava kratkih in dolgih bazenov\n\nGraf_LCM_vs_SCM <- function(razdalja){\n SCM_podatki <- podatki %>% filter(Distance == razdalja, Pool == \"SCM\") %>%\n mutate(zaokrozeni_datumi=Swim_date-day(Swim_date)+1) %>%\n group_by(zaokrozeni_datumi) %>% summarise(Time=min(Time)) %>%\n mutate(Pool=\"SCM\")\n \n LCM_podatki <- podatki %>% filter(Distance == razdalja, Pool == \"LCM\") %>%\n mutate(zaokrozeni_datumi=Swim_date-day(Swim_date)+1) %>%\n group_by(zaokrozeni_datumi) %>% summarise(Time=min(Time)) %>%\n mutate(Pool=\"LCM\")\n \n ime_grafa <- paste(\"Primerjava dolgih in kratkih bazenov pri\", as.character(razdalja), \"metrov delfin\")\n \n LCM_vs_SCM <- rbind(SCM_podatki, LCM_podatki)\n \n ggplot(LCM_vs_SCM) +\n geom_line() +\n aes(x = zaokrozeni_datumi, y = Time, col = Pool) +\n ylab(\"Čas plavanja [sekunde]\") + xlab(\"Datum\") + labs(title = ime_grafa)\n} \n\n\n# Osebni rekordi plavalca\n\nOsebni_rekordi_plavalca <- function(ime){\n vsi_casi <- podatki %>% filter(Name == ime)\n osebni_rekordi <- vsi_casi %>% group_by(Distance, Pool) %>% summarise(Time=min(Time))\n osebni_rekordi\n}\n\n\n# Najboljse tekme (stevilo novih casov na tekmi) po disciplini\n\nNajboljse_tekme <- function(dolzina, bazen){\n ggplot(as.data.frame(table((podatki %>% \n filter(Distance == dolzina, Pool == bazen)) %>%\n group_by(Meet_name)%>% \n summarise(Meet_name))), \n aes(x=reorder(Var1, Freq), y=Freq)) + \n geom_bar(stat = \"identity\", fill=\"steelblue\") +\n coord_flip() +\n labs(x = \"Meet name\", y = \"Number of top 200 results\")\n}\n\n\n# Koliko tekem je bilo kje\n\ntekme_na_drzavo <- as.data.frame(table(dogodki %>% group_by(Meet_country) %>% summarise(Meet_country)))\n\ngraf_tekme_na_drzavo <- ggplot(tekme_na_drzavo, \n aes(x=reorder(Var1, -Freq), y=Freq)) + \n geom_bar(stat = \"identity\", fill=\"steelblue\") +\n labs(x = \"Country\", y = \"Number of competitions\")\n \n# Uvozim zemljevid za število tekem\n\nzemljevid <- uvozi.zemljevid(\"https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/110m_cultural.zip\",\n \"ne_110m_admin_0_countries\", encoding=\"UTF-8\") %>%\n fortify()\n\ncolnames(zemljevid)[12] <- \"Var1\"\n\nzemljevid$Var1 <- gsub(\"US1\", \"USA\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"AU1\", \"AUS\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"COG\", \"CGO\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"CH1\", \"CHN\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"HRV\", \"CRO\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"DN1\", \"DEN\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"FI1\", \"FIN\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"FR1\", \"FRA\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"GB1\", \"GBR\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"DEU\", \"GER\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"GRC\", \"GRE\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"IDN\", \"INA\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"IS1\", \"ISN\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"MYS\", \"MAS\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"NL1\", \"NED\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"NZ1\", \"NZL\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"ZAF\", \"RSA\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"CHE\", \"SUI\", zemljevid$Var1)\nzemljevid$Var1 <- gsub(\"ARE\", \"UAE\", zemljevid$Var1)\n\nzemljevid_tekem <- ggplot() +\n geom_polygon(data=right_join(tekme_na_drzavo, zemljevid, by=\"Var1\"), \n aes(x=long, y=lat, group=group, fill=Freq)) +\n xlab(\"\") +\n ylab(\"\") + \n ggtitle(\"Zemljevid tekem po državah\") + \n theme(axis.title=element_blank(), axis.text=element_blank(), \n axis.ticks=element_blank(), panel.background = element_blank()) + \n scale_fill_gradient(low = '#FCDADA', high='#970303', limits=c(1,35)) +\n labs(fill=\"Število tekem\")\n\n# plot(zemljevid_tekem)\n\n\n# Najštevilčnejše reprezentance delfinistov\n\nstevilo_plavalcev_iz_posamicnih_drzav <- as.data.frame(table(plavalci %>% group_by(Country) %>% summarise(Country)))\n\ngraf_stevila_plavalcev_iz_posamicnih_drzav <- ggplot(stevilo_plavalcev_iz_posamicnih_drzav, \n aes(x=reorder(Var1, Freq), y=Freq)) + \n geom_bar(stat = \"identity\", fill=\"steelblue\") +\n geom_text(aes(label=Freq)) +\n labs(x = \"Country\", y = \"Number of top 200 swimmers\") +\n coord_flip()\n\n# Uvozim zemljevid za število najboljših delfinistov\n\nzemljevid2 <- uvozi.zemljevid(\"https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/cultural/110m_cultural.zip\",\n \"ne_110m_admin_0_countries\", encoding=\"UTF-8\") %>%\n fortify()\n\ncolnames(zemljevid2)[11] <- \"Var1\"\n\nzemljevid2$Var1 <- gsub(\"United Kingdom\", \"Great Britain\", zemljevid2$Var1)\nzemljevid2$Var1 <- gsub(\"Russia\", \"Russian Federation\", zemljevid2$Var1)\nzemljevid2$Var1 <- gsub(\"Republic of Serbia\", \"Serbia\", zemljevid2$Var1)\n\nzemljevid_stevilo_delfinistov <- ggplot() +\n geom_polygon(data=right_join(stevilo_plavalcev_iz_posamicnih_drzav, zemljevid2, by=\"Var1\"), \n aes(x=long, y=lat, group=group, fill=Freq)) +\n xlab(\"\") +\n ylab(\"\") + \n ggtitle(\"Zemljevid števila delfinistov iz držav\") + \n theme(axis.title=element_blank(), axis.text=element_blank(), \n axis.ticks=element_blank(), panel.background = element_blank()) + \n scale_fill_gradient(low = '#FCDADA', high='#970303', limits=c(1,20)) +\n labs(fill=\"Število delfinistov\")\n\n# Starost rekorderjev\n\nt <- ((right_join(podatki, plavalci, by=\"Name\")) %>% \n filter(Points>=1000)) %>% \n select(Name, Swim_date, Birth_date)\n\ngraf_starosti_rekorderjev <- ggplot(as.data.frame(table(floor((t$Swim_date - t$Birth_date)/365.25))),\n aes(x=Var1, y=Freq)) +\n geom_bar(stat = \"identity\", fill = \"steelblue\") +\n labs(x = \"Starost\", y = \"Število plavalcev\") +\n labs(title = \"Graf starosti plavalcev ko so odplavali svetovni rekord\")\n\n\n", "meta": {"hexsha": "bc08c34f594d6ab3ddb466d70478e8389c181558", "size": 6749, "ext": "r", "lang": "R", "max_stars_repo_path": "vizualizacija/vizualizacija.r", "max_stars_repo_name": "JakaSvetek/APPR-2020-21", "max_stars_repo_head_hexsha": "7704b2906b3e1995c725f489237752b3bc324635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizualizacija/vizualizacija.r", "max_issues_repo_name": "JakaSvetek/APPR-2020-21", "max_issues_repo_head_hexsha": "7704b2906b3e1995c725f489237752b3bc324635", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-11-05T07:45:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-22T09:18:09.000Z", "max_forks_repo_path": "vizualizacija/vizualizacija.r", "max_forks_repo_name": "JakaSvetek/APPR-2020-21", "max_forks_repo_head_hexsha": "7704b2906b3e1995c725f489237752b3bc324635", "max_forks_repo_licenses": ["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.7, "max_line_length": 137, "alphanum_fraction": 0.6621721737, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.28937793727907074}} {"text": "# W SA i GA jest inna filozofia funkcji_oceniajacej: w SA ma byc jak najmniejsza, w GA ma byc jak najwieksza\n\n# Zeby to zadzialalo, wczesniej trzeba zrobic:\n# install.packages(\"GenSA\")\nlibrary(GenSA)\n\n\n# Do zmiennej \"poznan\" wczytujemy dane z pliku CSV\nsetwd('/')\npoznan <- read.csv(file = 'poznan.csv')\n\n#liczba obos\nN <- 65\n\n#plec i wiek\nN_WOMAN18 <- 2\nN_MAN18 <- 2\nN_WOMAN25 <- 9\nN_MAN25 <- 8\nN_WOMAN40 <- 14\nN_MAN40 <- 12\nN_WOMAN65 <- 11\nN_MAN65 <- 7\n\n\n#wyksztalcenie\nN_PRIMARY <- 9\nN_MEDIUM <- 35\nN_HIGHER <- 21\n\n#stosunek do zmian kliematu skala 5-stopniowa\nNC_1 <- 10\nNC_2 <- 2\nNC_3 <- 14\nNC_4 <- 11\nNC_5 <- 28\n\n#osiedle\nN_A_1 <- 1\nN_A_2 <- 2\nN_A_3 <- 1\nN_A_4 <- 1\nN_A_5 <- 1\nN_A_6 <- 2\nN_A_7 <- 3\nN_A_8 <- 2\nN_A_9 <- 1\nN_A_10 <- 2\nN_A_11 <- 1\nN_A_12 <- 1\nN_A_13 <- 1\nN_A_14 <- 1\nN_A_15 <- 1\nN_A_16 <- 1\nN_A_17 <- 1\nN_A_18 <- 2\nN_A_19 <- 2\nN_A_20 <- 2\nN_A_21 <- 1\nN_A_22 <- 1\nN_A_23 <- 1\nN_A_24 <- 3\nN_A_25 <- 1\nN_A_26 <- 3\nN_A_27 <- 1\nN_A_28 <- 3\nN_A_29 <- 1\nN_A_30 <- 1\nN_A_31 <- 1\nN_A_32 <- 1\nN_A_33 <- 1\nN_A_34 <- 3\nN_A_35 <- 2\nN_A_36 <- 1\nN_A_37 <- 1\nN_A_38 <- 3\nN_A_39 <- 2\nN_A_40 <- 1\nN_A_41 <- 2\nN_A_42 <- 2\n\n# ROZMIAR_DANYCH (dla zbioru poznan)\nROZMIAR_DANYCH <- nrow(poznan)\n\nfunkcja_oceniajaca <- function(v,b) {\n \n ret <- 0\n \n #zapobieganie duplikatom\n if(any(duplicated(poznan$ID[v]))){\n ret <- 99999999\n }else{\n \n \n \n \n # Liczymy ile jest \"man/woman\" i zakresy wiekowe\n man18 <- 0\n woman18 <- 0\n man25 <- 0\n woman25 <- 0\n man40 <- 0\n woman40 <- 0\n man65 <- 0\n woman65 <- 0\n \n #liczniki wyksztalcenia\n primary <- 0\t\n medium <- 0\n higher <- 0\n \n #liczniki stosunku klimatu\n c1 <- 0\n c2 <- 0\n c3 <- 0\n c4 <- 0\n c5 <- 0\n \n #liczniki osiedla\n a1 <- 0\n a2 <- 0\n a3 <- 0\n a4 <- 0\n a5 <- 0\n a6 <- 0\n a7 <- 0\n a8 <- 0\n a9 <- 0\n a10 <- 0\n a11 <- 0\n a12 <- 0\n a13 <- 0\n a14 <- 0\n a15 <- 0\n a16 <- 0\n a17 <- 0\n a18 <- 0\n a19 <- 0\n a20 <- 0\n a21 <- 0\n a22 <- 0\n a23 <- 0\n a24 <- 0\n a25 <- 0\n a26 <- 0\n a27 <- 0\n a28 <- 0\n a29 <- 0\n a30 <- 0\n a31 <- 0\n a32 <- 0\n a33 <- 0\n a34 <- 0\n a35 <- 0\n a36 <- 0\n a37 <- 0\n a38 <- 0\n a39 <- 0\n a40 <- 0\n a41 <- 0\n a42 <- 0\n \n for (i in 1:length(v)) {\n \n if (poznan$GenderAge[v[i]] == \"man18-24\") {\n man18 <- man18+1\n } else if (poznan$GenderAge[v[i]] == \"woman18-24\") {\n woman18 <- woman18+1\n } else if (poznan$GenderAge[v[i]] == \"man25-39\") {\n man25 <- man25+1\n } else if (poznan$GenderAge[v[i]] == \"woman25-39\") {\n woman25 <- woman25+1\n } else if (poznan$GenderAge[v[i]] == \"man40-64\") {\n man40 <- man40+1\n } else if (poznan$GenderAge[v[i]] == \"woman40-64\") {\n woman40 <- woman40+1\n } else if (poznan$GenderAge[v[i]] == \"man65+\") {\n man65 <- man65+1\n } else if (poznan$GenderAge[v[i]] == \"woman65+\") {\n woman65 <- woman65+1\n } else {\n \n }\t\t\n \n if (poznan$Education[v[i]] == \"primary\") {\n primary <- primary+1\n } else if (poznan$Education[v[i]] == \"medium\") {\n medium <- medium+1\n } else if (poznan$Education[v[i]] == \"higher\") {\n higher <- higher+1\n } else {\n \n }\n \n if (poznan$climate[v[i]] == \"1\") {\n c1 <- c1+1\n } else if (poznan$climate[v[i]] == \"2\") {\n c2 <- c2+1\n } else if (poznan$climate[v[i]] == \"3\") {\n c3 <- c3+1\n } else if (poznan$climate[v[i]] == \"4\") {\n c4 <- c4+1\n } else if (poznan$climate[v[i]] == \"5\") {\n c5 <- c5+1\n } \n \n if (poznan$area[v[i]] == \"1\") {\n a1 <- a1+1\n }else if(poznan$area[v[i]] == \"2\") {\n a2 <- a2+1\n }else if(poznan$area[v[i]] == \"3\") {\n a3 <- a3+1\n }else if(poznan$area[v[i]] == \"4\") {\n a4 <- a4+1\n }else if(poznan$area[v[i]] == \"5\") {\n a5 <- a5+1\n }else if(poznan$area[v[i]] == \"6\") {\n a6 <- a6+1\n }else if(poznan$area[v[i]] == \"7\") {\n a7 <- a7+1\n }else if(poznan$area[v[i]] == \"8\") {\n a8 <- a8+1\n }else if(poznan$area[v[i]] == \"9\") {\n a9 <- a9+1\n }else if(poznan$area[v[i]] == \"10\") {\n a10 <- a10+1\n }else if(poznan$area[v[i]] == \"11\") {\n a11 <- a11+1\n }else if(poznan$area[v[i]] == \"12\") {\n a12 <- a12+1\n }else if(poznan$area[v[i]] == \"13\") {\n a13 <- a13+1\n }else if(poznan$area[v[i]] == \"14\") {\n a14 <- a14+1\n }else if(poznan$area[v[i]] == \"15\") {\n a15 <- a15+1\n }else if(poznan$area[v[i]] == \"16\") {\n a16 <- a16+1\n }else if(poznan$area[v[i]] == \"17\") {\n a17 <- a17+1\n }else if(poznan$area[v[i]] == \"18\") {\n a18 <- a18+1\n }else if(poznan$area[v[i]] == \"19\") {\n a19 <- a19+1\n }else if(poznan$area[v[i]] == \"20\") {\n a20 <- a20+1\n }else if(poznan$area[v[i]] == \"21\") {\n a21 <- a21+1\n }else if(poznan$area[v[i]] == \"22\") {\n a22 <- a22+1\n }else if(poznan$area[v[i]] == \"23\") {\n a23 <- a23+1\n }else if(poznan$area[v[i]] == \"24\") {\n a24 <- a24+1\n }else if(poznan$area[v[i]] == \"25\") {\n a25 <- a25+1\n }else if(poznan$area[v[i]] == \"26\") {\n a26 <- a26+1\n }else if(poznan$area[v[i]] == \"27\") {\n a27 <- a27+1\n }else if(poznan$area[v[i]] == \"28\") {\n a28 <- a28+1\n }else if(poznan$area[v[i]] == \"29\") {\n a29 <- a29+1\n }else if(poznan$area[v[i]] == \"30\") {\n a30 <- a30+1\n }else if(poznan$area[v[i]] == \"31\") {\n a31 <- a31+1\n }else if(poznan$area[v[i]] == \"32\") {\n a32 <- a32+1\n }else if(poznan$area[v[i]] == \"33\") {\n a33 <- a33+1\n }else if(poznan$area[v[i]] == \"34\") {\n a34 <- a34+1\n }else if(poznan$area[v[i]] == \"35\") {\n a35 <- a35+1\n }else if(poznan$area[v[i]] == \"36\") {\n a36 <- a36+1\n }else if(poznan$area[v[i]] == \"37\") {\n a37 <- a37+1\n }else if(poznan$area[v[i]] == \"38\") {\n a38 <- a38+1\n }else if(poznan$area[v[i]] == \"39\") {\n a39 <- a39+1\n }else if(poznan$area[v[i]] == \"40\") {\n a40 <- a40+1\n }else if(poznan$area[v[i]] == \"41\") {\n a41 <- a41+1\n }else if(poznan$area[v[i]] == \"42\") {\n a42 <- a42+1\n }\n }\n \n #do wieku i plci dodana jest waga aby zwiekszyc nacisk na te kryteria\n ret <- ret + (N_MAN18-man18)^2*10 + (N_WOMAN18-woman18)^2*10 + (N_MAN25-man25)^2*10 + (N_WOMAN25-woman25)^2*10 + (N_MAN40-man40)^2*10 + (N_WOMAN40-woman40)^2*10 + (N_MAN65-man65)^2*10 + (N_WOMAN65-woman65)^2*10 + (N_PRIMARY-primary)^2 + (N_MEDIUM-medium)^2 + (N_HIGHER-higher)^2 + (NC_1 -c1)^2 +(NC_2-c2)^2+(NC_3-c3)^2+(NC_4-c4)^2+(NC_5-c5)^2+(N_A_1-a1)^2+(N_A_2-a2)^2+(N_A_3-a3)^2+(N_A_4-a4)^2+(N_A_5-a5)^2+(N_A_6-a6)^2+(N_A_7-a7)^2+(N_A_8-a8)^2+(N_A_9-a9)^2+(N_A_10-a10)^2+(N_A_11-a11)^2+(N_A_12-a12)^2+(N_A_13-a13)^2+(N_A_14-a14)^2+(N_A_15-a15)^2+(N_A_16-a16)^2+(N_A_17-a17)^2+(N_A_18-a18)^2+(N_A_19-a19)^2+(N_A_20-a20)^2+(N_A_21-a21)^2+(N_A_22-a22)^2+(N_A_23-a23)^2+(N_A_24-a24)^2+(N_A_25-a25)^2+(N_A_26-a26)^2+(N_A_27-a27)^2+(N_A_28-a28)^2+(N_A_29-a29)^2+(N_A_30-a30)^2+(N_A_31-a31)^2+(N_A_32-a32)^2+(N_A_33-a33)^2+(N_A_34-a34)^2+(N_A_35-a35)^2+(N_A_36-a36)^2+(N_A_37-a37)^2+(N_A_38-a38)^2+(N_A_39-a39)^2+(N_A_40-a40)^2+(N_A_41-a41)^2+(N_A_42-a42)^2\n \n }\n \n if (b) {\n #prezentacja wynikow\n print( poznan$Code[v] )\n print( cat('man18=', man18, ' woman18=', woman18,'man25=', man25, ' woman25=', woman25,'man40=', man40, ' woman40=', woman40,'man65=', man65, ' woman65=', woman65, ' primary=', primary, ' medium=', medium, ' higher=', higher,' climate1=',c1,' climate2=',c2,' climate3=',c3, ' cliamte4=',c4, ' climate5=',c5,' area1=',a1,' area2=',a2,' area3=',a3,' area4=',a4,' area5=',a5,' area6=',a6,' area7=',a7,' area8=',a8,' area9=',a9,' area10=',a10,' area11=',a11,' area12=',a12,' area13=',a13,' area14=',a14,' area15=',a15,' area16=',a16,' area17=',a17,' area18=',a18,' area19=',a19,' area20=',a20,' area21=',a21,' area22=',a22,' area23=',a23,' area24=',a24,' area25=',a25,' area26=',a26,' are27=',a27,' area28=',a28,' area29=',a29,' area30=',a30,' area31=',a31,' area32=',a32,' area33=',a33,' area34=',a34,' area35=',a35,' area36=',a36,' area37=',a37,' area38=',a38,' area39=',a39,' area40=',a40,' area41=',a41,' area42=',a42) )\n #zapis wynikow do pliku\n write.csv(cbind(poznan$ID[v],poznan$Code[v]),'wynik.csv',row.names = FALSE)\n }\n \n ret\n}\n\n\n# Funkcja oceniajaca bedzie sluzyla do optymalizacji rozwiazania. Chcemy, zeby miala jak najnizsza wartosc.\n# Argumentem jest wektor danych (lista ID osob) - poniewaz nam chodzi o zbior 65 osob, wiec poprzez wartosc funkcji\n# musimy wykluczyc wektory, gdzie ID sie powtarzaja (damy im bardzo wysoka wartosc). \n# Przyjmiemy, ze ciag elementow wektora (czyli ID osob) musi byc rosnacy (co nam zapewnia roznowartosciowosc).\n\n# Bez \"as.numeric\" wywraca sie z komunikatem \"REAL() can only be applied...\"\nWYNIK <- GenSA(par=as.numeric(sample(1:N)*ROZMIAR_DANYCH/N), fn=funkcja_oceniajaca, lower=as.numeric(seq(1,N)), upper=as.numeric(seq(ROZMIAR_DANYCH-N+1,ROZMIAR_DANYCH)), FALSE, control=list(max.time=1440,smooth=FALSE,verbose=TRUE,temperature=50.0))\nprint(WYNIK)\n\n#wynik\nfunkcja_oceniajaca(WYNIK$par, TRUE)\n", "meta": {"hexsha": "1292de21f2d32132659dc1232c661ad7a080a98c", "size": 9345, "ext": "r", "lang": "R", "max_stars_repo_path": "panel_poznan.r", "max_stars_repo_name": "tecladopl/panelobywatelskipoznan", "max_stars_repo_head_hexsha": "a6d3eb55d0a1a318d6172acb1f40b97b04165b3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "panel_poznan.r", "max_issues_repo_name": "tecladopl/panelobywatelskipoznan", "max_issues_repo_head_hexsha": "a6d3eb55d0a1a318d6172acb1f40b97b04165b3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "panel_poznan.r", "max_forks_repo_name": "tecladopl/panelobywatelskipoznan", "max_forks_repo_head_hexsha": "a6d3eb55d0a1a318d6172acb1f40b97b04165b3c", "max_forks_repo_licenses": ["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.0217391304, "max_line_length": 958, "alphanum_fraction": 0.5261637239, "num_tokens": 4048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2887758489809229}} {"text": "#\n# Exemplo 3\n#\n\n# atribui valores para x1 e x2\nx1 <- 0.3815\nx2 <- 123456789015\n# cálculo 1\nresultado1 <- (x1 + x2) - x2\nresultado1\n# cálculo 2\nresultado2 <- x1 + (x2 - x2)\nresultado2", "meta": {"hexsha": "101083efa2d537dae68a15631e6c9e6d6894540c", "size": 183, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/aula1/exemplo3.r", "max_stars_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_stars_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/aula1/exemplo3.r", "max_issues_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_issues_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/aula1/exemplo3.r", "max_forks_repo_name": "EduardoJM/anotacoes-matematica-aplicada", "max_forks_repo_head_hexsha": "75eaa8548ec01cc596e40dc4699fbef06001f20d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.0769230769, "max_line_length": 30, "alphanum_fraction": 0.6557377049, "num_tokens": 83, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.2871522673399509}} {"text": "#==============================================================================#\n# This function will place any list of files with any pattern into a vector\n# in an object. The way it should be used for the functions on this page\n# is to search for .dat files. \n#==============================================================================#\ngetfile <- function(multFile=NULL, pattern=NULL){\n# the default option is to grab all of the files in a directory matching a \n# specified pattern. If no pattern is set, all files will be listed.\n\tif (is.null(multFile) || toupper(multFile) == \"YES\"){\n\t\t# this sets the path variable that the user can use to set the path\n\t\t# to the files with setwd(x$path), where x is the datastructure \n\t\t# this function dumped into.\n\t\tpath <- sub(\"(^.+?/).+?\\\\.[a-z]{3}$\", \"\\\\1\", file.path(file.choose()))\t\t\n\t\tif (!is.null(pattern)){\n\t\t\tpat <- pattern\n\t\t\tx <- list.files(path, pattern=pat)\n\t\t}\n\t\telse {\n\t\t\tx <- list.files(path)\n\t\t}\n\t}\n\telse {\n\t\t# if the user chooses to analyze only one file, a pattern is not needed\n\t\tcsv <- file.choose()\n\t\tpath <- sub(\"(^.+?/).+?\\\\.[a-z]{3}$\", \"\\\\1\", file.path(csv))\n\t\tcsv <- sub(\"^.+?/(.+?\\\\.[a-z]{3})$\", \"\\\\1\", csv)\n\t\tx <- csv\n\t}\n\tfilepath <- list(files=x, path=path)\n\treturn(filepath)\n}\n#==============================================================================#\n# The calculation of the Index of Association and standardized Index of \n# Association.\n#==============================================================================#\nstdIa <- function(x){\n#------------------------------------------------------------------------------#\n# Testing for valid filetypes\n#------------------------------------------------------------------------------#\n\tif (toupper(.readExt(x)) == \"DAT\") {\n\t\tpop <- read.fstat(x, missing = 0, quiet=T) \n\t}\n\telse if (toupper(.readExt(x)) %in% c(\"STR\", \"STRU\")) {\n\t\tpop <- read.structure(x, missing = 0, ask=FALSE, quiet=TRUE)\n\t}\n\telse if (toupper(.readExt(x)) == \"GTX\") {\n\t\tpop <- read.genetix(x, missing = 0, quiet=T) \n\t}\n\telse if (toupper(.readExt(x)) == \"GEN\") {\n\t\tpop <- read.genepop(x, missing = 0, quiet=T) \n\t}\n\telse {\n\t\tstop(\"File ext .dat, .str, .gtx, or .gen expected\")\n\t}\t\t\n\tnumAlleles <- length(pop@loc.names)\n\tnumIsolates <- length(pop@ind.names)\n\t# Creating this number is necessary because it is how the variance is\n\t# calculated.\n\tnp <- (numIsolates*(numIsolates-1))/2\n\t# Creation of the datastructures\n\tif (!exists(\"Ia.vector\")){\n\t\tIa.vector <- NULL\n\t\trbarD.vector <- NULL\n\t\tfile.vector <- NULL\n\t}\n\tD.matrix <- matrix(0, nrow=numIsolates, ncol=numIsolates)\n\td.matrix <- D.matrix\n\td.vector <- NULL\n\td2.vector <- NULL\n\tvard.vector <- NULL\n\tvardpair.vector <- NULL\n\tcount <- 0\n#--------------------------------------------------------------------------#\n# This is the loop for analyzing the pairwise distances at each locus,\n# also known as d. These values will be placed into two vectors representing\n# the sum of d for each locus and the sum of d^2 for each locus. \n# \n# This will also calculate D, the pairwise comparison of all isolates over\n# all loci. \n#--------------------------------------------------------------------------#\n\tfor (loc in names(pop@loc.nall)){\n\t\tn <- count + 1\n\t\tcount <- pop@loc.nall[loc] + count\n\t\tm <- count\n\t\t#print(paste(n, m, sep=\":\"))\n\t\tfor(j in 1:numIsolates){\n\t\t\t# Loop for the rows of the distance matrix\n\t\t\tfor(i in 1:numIsolates){\n\t\t\t\tz <- 0\n\t\t\t\t# Setting the contraint for the pairwise comparisons by the\n\t\t\t\t# equation (n(n-1))/2 where n = numIsolates \n\t\t\t\tif(j < i && i <= numIsolates){\n\t\t\t\t\tz <- sum(abs(pop@tab[j,m:n] \n\t\t\t\t\t\t\t\t-pop@tab[i,m:n]))\n\t\t\t\t}\n\t\t\t\t# The value of z (0, 1, or 2) is pushed into the matrix\n\t\t\t\td.matrix[i,j] <- d.matrix[i,j]+z\n\t\t\t\t# This value is added to the matrix for pairwise comparison\n\t\t\t\t# of all the isolates over all loci as opposed to each locus\n\t\t\t\tD.matrix[i,j] <- D.matrix[i,j]+d.matrix[i,j]\n\t\t\t}\n\t\t}\n\t\td.vector <- append(d.vector, sum(d.matrix))\n\t\td2.vector <- append(d2.vector, sum(d.matrix^2))\n\t\td.matrix[1:numIsolates,1:numIsolates] <- 0\n\t}\n\trm(d.matrix)\n#--------------------------------------------------------------------------#\n# Now to begin the calculations. First, set the variance of D\n#--------------------------------------------------------------------------#\n\tvarD <- ((sum(D.matrix^2)-((sum(D.matrix))^2)/np))/np\n#--------------------------------------------------------------------------#\n# Next is to create a vector containing all of the variances of d (there\n# will be one for each locus)\n#--------------------------------------------------------------------------#\n\tvard.vector <- ((d2.vector-((d.vector^2)/np))/np)\n#--------------------------------------------------------------------------#\n# Here the roots of the products of the variances are being produced and\n# the sum of those values is taken.\n#--------------------------------------------------------------------------#\n\tfor (b in 1:length(d.vector)){\n\t\tfor (d in 1:length(d.vector)){\n\t\t\tif(b < d && d <= length(d.vector)){\n\t\t\t\tvardpair <- sqrt(vard.vector[b]*vard.vector[d])\n\t\t\t\tvardpair.vector <- append(vardpair.vector, vardpair)\n\t\t\t}\n\t\t}\n\t}\n#--------------------------------------------------------------------------#\n# The sum of the variances necessary for the calculation of Ia is calculated\n#--------------------------------------------------------------------------#\n\tsigVarj <- sum(vard.vector)\n\trm(vard.vector)\n#--------------------------------------------------------------------------#\n# Finally, the Index of Association and the standardized Index of associati-\n# on are calculated.\n#--------------------------------------------------------------------------#\n\tIa <- (varD/sigVarj)-1\n\trbarD <- (varD - sigVarj)/(2*sum(vardpair.vector))\n\t# Prints to screen as loop progresses\n\tprint(paste(\"File Name:\", x, sep=\" \"))\n\tprint(paste(\"Index of Association:\", Ia, sep=\" \"))\n\tprint(paste(\"Standardized Index of Association (rbarD):\", rbarD, sep=\" \"))\n\t# Saves the values of Ia, rbarD, and the filename into datastructures\n\t# that will be listed in a dataframe\n\tfile.vector <- append(file.vector, x)\n\tIa.vector <- append(Ia.vector, Ia)\n\trbarD.vector <- append(rbarD.vector, rbarD)\n\tIout <- list(Ia=Ia.vector, rbarD=rbarD.vector, File=file.vector)\n\treturn(as.data.frame(Iout))\n}\n\n#==============================================================================#\n# This function allows the user to analyze many separate files automatically\n#==============================================================================#\nstdIa.all <- function(x) {\n\tIout <- NULL\n\tfor(a in x){\n\t\tIout <- rbind(Iout, stdIa(a))\n\t}\n\treturn(Iout)\n}\n\nextract.info <- function(x) {\n\tx$clone <- as.factor(sub(\"^clone.(\\\\d{3}.\\\\d{2}).+?$)\",\"\\\\1\", x$File))\n\tx$rep <- as.numeric(sub(\"^clone.+?rep.(\\\\d{2}).+?$)\",\"\\\\1\", x$File))\n\tx$pop.size <- as.numeric(sub(\"^clone.+?pop.(\\\\d+?).+?$)\",\"\\\\1\", x$File))\n\tx$sex.rate <- (100-x$clone)/100\n\treturn(x)\n}", "meta": {"hexsha": "0212eaa1d609f1f83d07780dc7a82194f26d9fbc", "size": 6892, "ext": "r", "lang": "R", "max_stars_repo_path": "the_horror/MATRIXmlFunk.r", "max_stars_repo_name": "zkamvar/PiG_Multitool", "max_stars_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "the_horror/MATRIXmlFunk.r", "max_issues_repo_name": "zkamvar/PiG_Multitool", "max_issues_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "the_horror/MATRIXmlFunk.r", "max_forks_repo_name": "zkamvar/PiG_Multitool", "max_forks_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "max_forks_repo_licenses": ["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.5411764706, "max_line_length": 80, "alphanum_fraction": 0.5005803831, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.28649189443153006}} {"text": "### Seq-Gen output analysis\n### CIR Project\n### Advisors: Steve Freedberg, Matthew Richey\n### Code by: Suzie Hoops\n\n#######installing packages:\nif (!require('seqinr')) {\n\tinstall.packages('seqinr', repos=\"http://cran.rstudio.com/\")\n\tlibrary('seqinr')\n}\nif (!require('mosaic')) {\n\tinstall.packages('mosaic', repos=\"http://cran.rstudio.com/\")\n\tinstall.packages('mosaicData', repos=\"http://cran.rstudio.com/\")\n\tlibrary('mosaic')\n}\n\n\nprintf <- function(...) cat(sprintf(...))\n\n\n##################################################\n# We want to compare the two individuals to find a Hamming\n# distance between them. That is, how many base pairs differ\n# between the two sequences.\n\n# To do this, we must compare each base pair, one at a time.\n# Let's make a function for comparing the pieces of the string:\nHammingDistance <- function (x, y) {\n # note that the parameters x and y should be\n counter <- 0 # to track the number of base pairs different\n index <- 1 # to keep track of indices in for loop\n xVector <- strsplit(x, \"\")[[1]]\n yVector <- strsplit(y, \"\")[[1]]\n for (i in xVector) {\n if (i != yVector[index]) {\n counter <- counter + 1\n }\n index <- index + 1\n }\n return(counter) # returns number of base pairs that differ\n}\n\n\nHammingDistanceTwoSequences <- function (file1, file2) {\n x <- LoadFileIntoString(file1)\n y <- LoadFileIntoString(file2)\n distance <- HammingDistance(x, y)\n print(distance)\n}\n\nLoadFileIntoString <- function (fileName) {\n return(readChar(fileName, file.info(fileName)$size))\n}\n\n\nLoadDataFromFile <- function(fname) {\n ##################################################\n # Generalizing to Larger Files\n # The above code works for a file of only two individuals, but\n # we wish to generalize this so that it can be used for multiple\n # pairs of individuals and store the appropriate data.\n\n # Note that for now, we will assume that all sequences in a\n # single file have the same length.\n\n ### First Steps\n # read in the data:\n data <- read.fasta(file=fname, as.string=TRUE)\n\n # get the number of sequences included in the data\n len <- length(data)\n\n # create a vector of every other integer up to len for the loop\n list <- seq(1, len, 2)\n\n # store the original names of the sequences:\n orig_names <- names(data)\n\n\n ##################################################\n # We create a for loop to cycle through the pairs and compare\n # each one. The loop will record its findings in a list called `out`.\n\n # out is initialized with fillers\n out <- seq(1:(len/2))\n\n # print(data)\n # printf(\"end\\n\")\n\n for (i in list) {\n names(data)[i] <- \"indiv1\"\n names(data)[i+1] <- \"indiv2\"\n length <- nchar(data$indiv1[1])\n taxon1 <- substring(data$indiv1[1], seq(1,length,1), seq(1,length,1))\n taxon2 <- substring(data$indiv2[1], seq(1,length,1), seq(1,length,1))\n index <- (i-1)/2 + 1\n out[index] <- HammingDistance(taxon1, taxon2)\n }\n\n # Now \"out\" is filled with Hamming distances of all pairs\n\n\n ##################################################\n # Simple Statistics from the data:\n avgOfRange <- mean(out) # average\n minOfRange <- min(out) # minimum of range\n maxOfRange <- max(out) # maximum of range\n percent <- (avgOfRange / len)\n\n\n printf(\"avg=%d\\n\", avgOfRange)\n printf(\"min=%d\\n\", minOfRange)\n printf(\"max=%d\\n\", maxOfRange)\n printf(\"percent=%f\\n\", percent)\n\n printf(\"start data\\n\")\n print(out) # desired output\n}\n\n\n\nEstimateGenerations <- function(genlength, percent) {\n ##################################################\n ##################################################\n # Estimating Generations:\n # Assume 2% per million years (standard for cytochrome B)\n # mutation rate. This allows us to calculate a likely divergence\n # time, from which we can estimate generations:\n\n # divergence time in million years\n divtime <- percent/0.02\n printf(\"divtime=%d\\n\", divtime)\n\n # number of generations (used for seq gen parameters)\n gen <- divtime*1000000/genlength\n printf(\"gen=%d\\n\", gen)\n}\n\n\n\n\nPrintUsage <- function() {\n write(\"usage: Rscript hamdis.r \", stdout())\n write(\"commands:\", stdout())\n write(\" estimate \", stdout())\n write(\" calculate \", stdout())\n write(\" distance-between \", stdout())\n quit()\n}\n\n\nargs <- commandArgs(trailingOnly = TRUE)\nif (length(args) != 3) {\n PrintUsage()\n}\n\ncommand <- args[1]\nif (command == \"estimate\") {\n genlength <- as.numeric(args[2])\n percent <- as.numeric(args[3])\n EstimateGenerations(genlength, percent)\n} else if (command == \"calculate\") {\n filename <- args[2]\n other <- args[3]\n LoadDataFromFile(filename)\n} else if (command == \"distance-between\") {\n xfilename <- args[2]\n yfilename <- args[3]\n HammingDistanceTwoSequences(xfilename, yfilename)\n} else {\n PrintUsage()\n}\n", "meta": {"hexsha": "57d774cd1d9665810d4abe8a0fe7fefb3883231e", "size": 4873, "ext": "r", "lang": "R", "max_stars_repo_path": "server/hamdis/legacy/hamdis.r", "max_stars_repo_name": "hybsearch/hybsearch", "max_stars_repo_head_hexsha": "67b06b35406f0b19ac9c0b482c662c3ce6364e33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-03-22T01:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-22T01:11:35.000Z", "max_issues_repo_path": "server/hamdis/legacy/hamdis.r", "max_issues_repo_name": "hybsearch/hybsearch", "max_issues_repo_head_hexsha": "67b06b35406f0b19ac9c0b482c662c3ce6364e33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 124, "max_issues_repo_issues_event_min_datetime": "2018-02-20T21:57:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T22:44:14.000Z", "max_forks_repo_path": "server/hamdis/legacy/hamdis.r", "max_forks_repo_name": "hybsearch/hybsearch", "max_forks_repo_head_hexsha": "67b06b35406f0b19ac9c0b482c662c3ce6364e33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-03-19T17:10:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-14T19:54:49.000Z", "avg_line_length": 28.1676300578, "max_line_length": 73, "alphanum_fraction": 0.6269238662, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2862607791529429}} {"text": "inch2Millimeter <- function(val, ...) {\n\n val_new <- val * 25.4\n val_new <- round(val_new, ...)\n\n return(val_new)\n}\n\nknots2mps <- function(val, ...) {\n\n val_new <- val * 0.514444\n val_new <- round(val_new, ...)\n\n return(val_new)\n}\n\n\n\nknots2ms <- function(val, ...) {\n\n kmperhour = val*1.8535\n val_new = kmperhour*(1000/3600)\n val_new <- round(val_new, ...)\n\n return(val_new)\n}\n\n\n\nretrieve_GSOD=function(usaf,WBAN=\"99999\",start_year = NA, end_year = NA, dsn = \".\")\n{\n\n fls_gz <- sapply(start_year:end_year, function(year) {\n dlbase <- paste0(as.character(usaf), \"-\", WBAN, \"-\", year, \".op.gz\")\n dlurl <- paste0(\"ftp://ftp.ncdc.noaa.gov/pub/data/gsod/\",year, \"/\", dlbase)\n dlfile <- paste0(dsn, \"/\", dlbase)\n\n if (file.exists(dlfile)) {\n cat(\"File\", dlfile, \"already exists. Proceeding to next file... \\n\")\n }\n else {\n try(download.file(dlurl, dlfile), silent = FALSE)\n }\n return(dlfile) })\n\n}\n\n\nis.leapyear=function(year){\n return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0))\n}\n\n\n\n\nfindindexes = function(x,window=15) {\n j = window+x\n indexdayj = c(c(365-window):365,c(1:365),c(1:window))\n indexdayj[(j-window+1):(j+window-1)]\n}\n\n####################################################\n#' firenze_peretola_gsod_1979_2015\n#'\n#' @description Firenze Peretola 1979-2015 16700 GSOD daily weather data.\n#'\n#' @references Data are obtained from GSOD NOAA site. \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @format data.frame\n#'\n#' @source \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso crisci \\email{a.crisci@@ibimet.cnr.it}\n#'\n\n####################################################\n#' selected_italian_weather\n#'\n#' @description Main features of a selected GSOD italian weather station.\n#'\n#' @references Data are obtained from GSOD NOAA site. \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @format data.frame\n#'\n#' @source \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso crisci \\email{a.crisci@@ibimet.cnr.it}\n#'\n\n####################################################\n#' geo_selected_italian_weather\n#'\n#' @description Geographical information of a selected GSOD italian weather station.\n#'\n#' @references Data are obtained from GSOD NOAA site. \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @format SpatialPointDataframe\n#'\n#' @source \\url{https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod}\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords meteo spatial\n#'\n\n####################################################\n#' calculate_HWdays\n#'\n#' Calculate HWdays days and Critical ones adding some columns at data.frame.\n#' Mean air temperature, mean relative humidity and extreme thermal values are required.\n#'\n#'\n#' @param data data.frame Daily time series with colums' names: date(YYYY-MM-DD),tmed,tmax,tmin,rhum,vmed.\n#' @param clim_array data.frame Name of location or the time series analized.\n#' @param method character Method to assess critical and heatwave days. Default is \"EuroHeat\" and other are \"TMAX\",\"TMED\",\"TMIN\".\n#' @param index character Biometerological index to calculate apparent temperature with ATI or UTCI. Default is \"ATI\" corresponding to the shaded version of ATI Steadman (2004).\n#' @param wind logical If TRUE the wind in biometeorological index are considered.\n#' @param months numeric The month her HW days are calculated. Default are c(5:9) corresponding to May-Dec.\n#' @param P_intesity numeric If one of the \"TMAX\",\"TMED\",\"TMIN\" methods was selected is the level of intensity in term of percentiles.Default are c(95),\n#' @param duration numeric Minimum spell of critical days to be considered for heatave definition. Default is 2.\n#' @param time_reference numeric Temporal format of the referenced climatology: DAY (daily) or MON (monthly).Default is \"DAY\".\n#' @return Return a list of data.frame respectively with monthly and daily values.\n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords heat wave\n#'\n#' @export\n#'\n#'\n#'\n#'\n#'\n#'\n\n\ncalculate_HWdays=function(data,\n clim_array,\n method=\"EuroHeat\",\n index=\"ATI\",\n wind=T,\n P_intesity=c(95),\n duration=2,\n time_reference=\"DAY\"\n) {\n\n if (class(data) != \"data.frame\") {stop(paste(\"data argument must be a daily data.frame object with column's names equal to:\",\n \"date( %Y-%m-%d ),tmed,tmax,tmin,rhum,vmed\"))\n }\n\n if (time_reference==\"DAY\") {if (nrow(clim_array)!=365) {stop(paste(\"Valid climatology is needed!\")) } }\n if (time_reference==\"MONTH\") {if (nrow(clim_array)!=12) {stop(paste(\"Valid climatology is needed!\")) } }\n if (wind==T ) { if (length(grep(\"vmed\",names(data)))==0) {stop(paste(\"Wind data are needed!\")) } }\n if (length(grep(P_intesity,names(clim_array)))<1) {stop(paste(\"Valid P_intesity Percentile intensity value is needed!\"))}\n\n temp_mat=data;\n temp_mat$yday=strptime(as.Date(data$date), format = \"%Y-%m-%d\")$yday+1\n temp_mat$yday365=temp_mat$yday\n temp_mat$yday365[grep(\"-02-29\",temp_mat$date)]=28\n temp_mat$yday365[which(temp_mat$yday==366)]=365\n temp_mat$CritDay=0\n temp_mat$HWDay=0\n temp_matTappmax=NA\n temp_mat$Tappmed=NA\n temp_mat$mese=as.numeric(format(as.Date(temp_mat$date),\"%m\"))\n\n if ( index==\"ATI\")\n {\n temp_mat$Tappmax=round(steadman_indoor(temp_mat$tmax,temp_mat$rhum),1)\n temp_mat$Tappmed=round(steadman_indoor(temp_mat$tmed,temp_mat$rhum),1)\n\n if ( wind == T)\n { temp_mat$Tappmax=round(steadman_outdoor_shade(temp_mat$tmax,temp_mat$rhum,temp_mat$vmed),1)\n temp_mat$Tappmed=round(steadman_outdoor_shade(temp_mat$tmed,temp_mat$rhum,temp_mat$vmed),1)\n }\n }\n\n if ( index==\"UTCI\")\n\n {\n temp_mat$Tappmax=round(UTCI(temp_mat$tmax,temp_mat$rhum,rep(0.1,nrow(temp_mat)),temp_mat$tmax),1)\n temp_mat$Tappmed=round(UTCI(temp_mat$tmed,temp_mat$rhum,rep(0.1,nrow(temp_mat)),temp_mat$tmed),1)\n\n\n if ( wind == T)\n { temp_mat$Tappmax=round(UTCI(temp_mat$tmax,temp_mat$rhum,temp_mat$vmed,temp_mat$tmax),1)\n temp_mat$Tappmed=round(UTCI(temp_mat$tmed,temp_mat$rhum,temp_mat$vmed,temp_mat$tmed),1)\n }\n }\n\n #####################################################################################################################\n if ( time_reference == \"DAY\") {\n\n if (method == \"EuroHeat\" & wind==T)\n\n {\n for (i in 1:nrow(temp_mat))\n { iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$Tappmax[i])) {temp_mat$CritDay[i]=0;next}\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$Tappmax[i] >= clim_array$TmaxApp_V_P90_DAY[temp_mat$yday365[i]],1,0)\n b=ifelse(temp_mat$tmin[i] >= clim_array$Tmin_P90_DAY[temp_mat$yday365[i]] && temp_mat$Tappmax[i] >= clim_array$TmaxApp_V_P50_DAY[temp_mat$yday365[i]],1,0)\n if(a==1 || b==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"EuroHeat\" & wind==F)\n\n {\n for (i in 1:nrow(temp_mat))\n { iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$Tappmax[i])) {temp_mat$CritDay[i]=0;next}\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$Tappmax[i] >= clim_array$TmaxApp_P90_DAY[temp_mat$yday365[i]],1,0)\n b=ifelse(temp_mat$tmin[i] >= clim_array$Tmin_P90_DAY[temp_mat$yday365[i]] && temp_mat$Tappmax[i] >= clim_array$TmaxApp_P50_DAY[temp_mat$yday365[i]],1,0)\n if(a==1 || b==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"TMED\" )\n\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmed[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmed[i] >= clim_array[temp_mat$yday365[i],paste0(\"Tmax_P\",P_intesity,\"_DAY\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"TMAX\" )\n\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmax[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmax[i] >= clim_array[temp_mat$yday365[i],paste0(\"Tmax_P\",P_intesity,\"_DAY\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n if (method == \"TMIN\" )\n\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmin[i] >= clim_array[temp_mat$yday365[i],paste0(\"Tmin_P\",P_intesity,\"_DAY\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n ########################################################################################################################\n\n } # day loop\n ########################################################################################################################\n\n if ( time_reference == \"MON\") {\n\n if (method == \"EuroHeat\" & wind==T)\n\n {\n for (i in 1:nrow(temp_mat))\n { iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$Tappmax[i])) {temp_mat$CritDay[i]=0;next}\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$Tappmax[i] >= clim_array$TmaxApp_V_P90_MON[temp_mat$mese[i]],1,0)\n b=ifelse(temp_mat$tmin[i] >= clim_array$Tmin_P90_MON[temp_mat$mese[i]] && temp_mat$Tappmax[i] >= clim_array$TmaxApp_V_P50_MON[temp_mat$mese[i]],1,0)\n if(a==1 || b==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"EuroHeat\" & wind==F)\n\n {\n for (i in 1:nrow(temp_mat))\n { iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$Tappmax[i])) {temp_mat$CritDay[i]=0;next}\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$Tappmax[i] >= clim_array$TmaxApp_P90_MON[temp_mat$mese[i]],1,0)\n b=ifelse(temp_mat$tmin[i] >= clim_array$Tmin_P90_MON[temp_mat$mese[i]] && temp_mat$Tappmax[i] >= clim_array$TmaxApp_P50_MON[temp_mat$mese[i]],1,0)\n if(a==1 || b==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"TMED\" )\n\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmed[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmed[i] >= clim_array[temp_mat$mese[i],paste0(\"Tmax_P\",P_intesity,\"_MON\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"TMAX\" )\n\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmax[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmax[i] >= clim_array[temp_mat$mese[i],paste0(\"Tmax_P\",P_intesity,\"_MON\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n\n if (method == \"TMIN\" )\n {\n for (i in 1:nrow(temp_mat))\n {\n iHW=ifelse(i-(duration-1)>0,i-(duration-1),1)\n if (is.na(temp_mat$tmin[i])) {temp_mat$CritDay[i]=0;next}\n a=ifelse(temp_mat$tmin[i] >= clim_array[temp_mat$mese[i],paste0(\"Tmin_P\",P_intesity,\"_MON\")],1,0)\n if( a==1) {temp_mat$CritDay[i]=1}\n if (sum(temp_mat$CritDay[iHW:i]) == duration) {temp_mat$HWDay[i]=1}\n }\n }\n }\n # MON Loop\n\n #######################################################################################################################\n res_HW=temp_mat[c(\"date\",\"mese\",\"yday365\",\"CritDay\",\"HWDay\")]\n \n if ( method == \"EuroHeat\") {res_HW=temp_mat[c(\"date\",\"mese\",\"yday365\",\"CritDay\",\"HWDay\",\"Tappmax\",\"Tappmed\")]}\n \n return(res_HW)\n\n}\n\n\n#' create_clim_param_HW\n#'\n#' Calculate the parameters to assess heat-wave daily status from a climatic time series monthly.\n#' Mean air temperature , mean relative humidity and extreme thermal values are required.\n#' Parameters\n#'\n#'\n#' @param data data.frame Daily time series with colums' names: date(YYYY-MM-DD),tmed,tmax,tmin,rhum,vmed.\n#' @param name character Name of location or ID of time series.\n#' @param index character Biometerological index to calculate apparent temperature.\n#' @param iniclim character Initial year of climatological reference time period, Default is \"1981\".\n#' @param yfinclim character Final year of climatological reference time period, Default is \"2010\".\n#' @param PT numeric Three levels of percentile used as thresholds for intensity. Default are c(90, 95, 98).\n#' @param window_days numeric Half Day span to calculate daily climatology. Default is 15.\n#' @param save_clim logical If True save file daily and montly in RDS and CSV format. Default is F.\n#' @return Return a list of data.frame respectively with monthly and daily values.\n#'\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords heat wave\n#'\n#' @export\n#'\n#'\n#'\n#'\n\n\ncreate_clim_param_HW=function(data,\n name,\n index=\"ATI\",\n yiniclim=\"1981\",\n yfinclim=\"2010\",\n PT=c(90,95,98),\n window_days=15,\n save_clim=F) {\n\n if (class(data) != \"data.frame\") {stop(paste(\"data argument must be a daily data.frame object with column's names equal to:\",\n \"date( %Y-%m-%d ),tmed,tmax,tmin,rhum,vmed\"))\n }\n if (length(PT) != 3 ) {stop(paste(\"Please three values of PT parameter are required!\"))}\n\n dates=seq(as.Date(paste0(yiniclim,\"-01-01\")),as.Date(paste0(yfinclim,\"-12-31\")),1)\n indexday=which(as.character(data$date) %in% as.character(dates) ==T)\n anni=unique(as.numeric(format(as.Date(data$date),\"%Y\")))\n if (length(which(anni %in% yiniclim:yfinclim==T)) < length(yiniclim:yfinclim) ) {stop(paste(\"Please refine year climate range!\"))}\n\n ##########################################################################################################################################################################\n\n\n\n PTD=PT/100\n temp_mat=data;\n temp_mat$yday=strptime(as.Date(data$date), format = \"%Y-%m-%d\")$yday+1\n temp_mat$yday365=temp_mat$yday\n temp_mat$yday365[grep(\"-02-29\",temp_mat$date)]=28\n temp_mat$yday365[which(temp_mat$yday==366)]=365\n\n ##########################################################################################################################################################################\n\n temp_mat$Tappmax=NA\n temp_mat$Tappmed=NA\n temp_mat$Tappmax_v=NA\n temp_mat$Tappmed_v=NA\n\n if ( index==\"ATI\")\n {\n temp_mat$Tappmax=round(steadman_indoor(temp_mat$tmax,temp_mat$rhum),1)\n temp_mat$Tappmed=round(steadman_indoor(temp_mat$tmed,temp_mat$rhum),1)\n\n if ( length(grep(\"vmed\",names(temp_mat)))>0)\n { temp_mat$Tappmax_v=round(steadman_outdoor_shade(temp_mat$tmax,temp_mat$rhum,temp_mat$vmed),1)\n temp_mat$Tappmed_v=round(steadman_outdoor_shade(temp_mat$tmed,temp_mat$rhum,temp_mat$vmed),1)\n }\n }\n\n if ( index==\"UTCI\")\n {\n temp_mat$Tappmax=round(UTCI(temp_mat$tmax,temp_mat$rhum,rep(0.1,nrow(temp_mat)),temp_mat$tmax),1)\n temp_mat$Tappmed=round(UTCI(temp_mat$tmed,temp_mat$rhum,rep(0.1,nrow(temp_mat)),temp_mat$tmed),1)\n\n\n if ( length(grep(\"vmed\",names(temp_mat)))>0)\n { temp_mat$Tappmax_v=round(UTCI(temp_mat$tmax,temp_mat$rhum,temp_mat$vmed,temp_mat$tmax),1)\n temp_mat$Tappmed_v=round(UTCI(temp_mat$tmed,temp_mat$rhum,temp_mat$vmed,temp_mat$tmed),1)\n }\n }\n\n ##########################################################################################################################################################################\n\n\n temp_mat_climdata=temp_mat[indexday,]\n temp_mat_climdata$mese=as.numeric(format(as.Date(temp_mat_climdata$date),\"%m\"))\n\n ##########################################################################################################################################################################\n\n temp_clim=data.frame(Tmax_P50=NA,Tmax_PT1=NA,Tmax_PT2=NA,Tmax_PT3=NA,\n TmaxApp_P50=NA,TmaxApp_PT1=NA,TmaxApp_PT2=NA,TmaxApp_PT3=NA,\n TmaxApp_V_P50=NA, TmaxApp_V_PT1=NA,TmaxApp_V_PT2=NA,TmaxApp_V_PT3=NA,\n Tmin_P50=NA,Tmin_PT1=NA,Tmin_PT2=NA,Tmin_PT3=NA,\n Tmed_P50=NA,Tmed_PT1=NA,Tmed_PT2=NA,Tmed_PT3=NA)\n\n temp_clim_daily=cbind(id=1:365,temp_clim)\n temp_clim_monthly=cbind(id=1:12,temp_clim)\n\n #######################################################################################################################################################à\n\n for ( i in 1:365) {\n\n temp_clim_daily$Tmax_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmax,na.rm=T))\n temp_clim_daily$Tmax_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmax,PTD[1],na.rm=T)[1])\n temp_clim_daily$Tmax_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmax,PTD[2],na.rm=T)[1])\n temp_clim_daily$Tmax_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmax,PTD[3],na.rm=T)[1])\n\n temp_clim_daily$TmaxApp_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax,na.rm=T))\n temp_clim_daily$TmaxApp_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax,PTD[1],na.rm=T)[1])\n temp_clim_daily$TmaxApp_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax,PTD[2],na.rm=T)[1])\n temp_clim_daily$TmaxApp_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax,PTD[3],na.rm=T)[1])\n\n temp_clim_daily$TmaxApp_V_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax_v,na.rm=T))\n temp_clim_daily$TmaxApp_V_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax_v,PTD[1],na.rm=T)[1])\n temp_clim_daily$TmaxApp_V_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax_v,PTD[2],na.rm=T)[1])\n temp_clim_daily$TmaxApp_V_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$Tappmax_v,PTD[3],na.rm=T)[1])\n\n\n temp_clim_daily$Tmed_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmed,na.rm=T))\n temp_clim_daily$Tmed_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmed,PTD[1],na.rm=T)[1])\n temp_clim_daily$Tmed_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmed,PTD[2],na.rm=T)[1])\n temp_clim_daily$Tmed_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmed,PTD[3],na.rm=T)[1])\n\n temp_clim_daily$Tmin_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmin,na.rm=T))\n temp_clim_daily$Tmin_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmin,PTD[1],na.rm=T)[1])\n temp_clim_daily$Tmin_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmin,PTD[2],na.rm=T)[1])\n temp_clim_daily$Tmin_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$yday365 %in% findindexes(i,window_days))==TRUE),]$tmin,PTD[3],na.rm=T)[1])\n\n }\n\n\n\n for ( i in 1:12) {\n\n temp_clim_monthly$Tmax_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,na.rm=T))\n temp_clim_monthly$Tmax_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,PTD[1],na.rm=T)[1])\n temp_clim_monthly$Tmax_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,PTD[2],na.rm=T)[1])\n temp_clim_monthly$Tmax_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,PTD[3],na.rm=T)[1])\n\n temp_clim_monthly$TmaxApp_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax,na.rm=T))\n temp_clim_monthly$TmaxApp_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax,PTD[1],na.rm=T)[1])\n temp_clim_monthly$TmaxApp_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,PTD[2],na.rm=T)[1])\n temp_clim_monthly$TmaxApp_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmax,PTD[3],na.rm=T)[1])\n\n temp_clim_monthly$TmaxApp_V_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax_v,na.rm=T))\n temp_clim_monthly$TmaxApp_V_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax_v,PTD[1],na.rm=T)[1])\n temp_clim_monthly$TmaxApp_V_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax_v,PTD[2],na.rm=T)[1])\n temp_clim_monthly$TmaxApp_V_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$Tappmax_v,PTD[3],na.rm=T)[1])\n\n\n temp_clim_monthly$Tmed_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmed,na.rm=T))\n temp_clim_monthly$Tmed_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmed,PTD[1],na.rm=T)[1])\n temp_clim_monthly$Tmed_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmed,PTD[2],na.rm=T)[1])\n temp_clim_monthly$Tmed_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmed,PTD[3],na.rm=T)[1])\n\n temp_clim_monthly$Tmin_P50[i]=as.numeric(median(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmin,na.rm=T))\n temp_clim_monthly$Tmin_PT1[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmin,PTD[1],na.rm=T)[1])\n temp_clim_monthly$Tmin_PT2[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmin,PTD[2],na.rm=T)[1])\n temp_clim_monthly$Tmin_PT3[i]=as.numeric(quantile(temp_mat_climdata[which((temp_mat_climdata$mese == i)),]$tmin,PTD[3],na.rm=T)[1])\n\n }\n\n\n #######################################################################################################################################################################\n\n names(temp_clim_daily)=gsub(\"T1\",PT[1],names(temp_clim_daily))\n names(temp_clim_daily)=gsub(\"T2\",PT[2],names(temp_clim_daily))\n names(temp_clim_daily)=gsub(\"T3\",PT[3],names(temp_clim_daily))\n names(temp_clim_monthly)=gsub(\"T1\",PT[1],names(temp_clim_monthly))\n names(temp_clim_monthly)=gsub(\"T2\",PT[2],names(temp_clim_monthly))\n names(temp_clim_monthly)=gsub(\"T3\",PT[3],names(temp_clim_monthly))\n\n names(temp_clim_daily)=paste0(names(temp_clim_daily),\"_DAY\")\n names(temp_clim_monthly)=paste0(names(temp_clim_monthly),\"_MON\")\n\n if ( save_clim == T) {\n saveRDS(temp_clim_daily,paste0(name,\"_DAYCLIM.rds\"))\n write.csv(temp_clim_daily,paste0(name,\"_DAYCLIM.csv\"))\n saveRDS(temp_clim_monthly,paste0(name,\"_MONCLIM.rds\"))\n write.csv(temp_clim_monthly,paste0(name,\"_MONCLIM.csv\"))\n\n }\n\n\n\n return(list(MONCLIM=temp_clim_monthly,\n DAYCLIM=temp_clim_daily))\n}\n\n\n\n\n\n\n\n#############################################################################################################################################\n#' manage_GSOD\n#'\n#' Download and build a specific data.frame for heatwave analisys from a GSOD NOAA repository station based on its unique USAF code.\n#'\n#'\n#' @param id character USAF code of weather station.\n#' @param name character Name of location or ID of time series.\n#' @param ini_year character Initial year of data time period, Default is \"1979\".\n#' @param last_year character Final year of climatological reference time period, Default is \"2016\".\n#' @param save_files logical If True save GSOD data file in RDS and CSV format. Default is F.\n#' @return Return data.frame ready to use for heat-wave analitics.\n#'\n#' @author Istituto di Biometeorologia Firenze Italy Alfonso Crisci \\email{a.crisci@@ibimet.cnr.it}\n#' @keywords GSOD\n#' @importFrom GSODTools gzGsodStations\n#' @importFrom lubridate ymd\n#' @export\n#'\n#'\n#'\n\nmanage_GSOD=function(id,name,ini_year = 1979, last_year = 2015, missing=NA,save_files=T) {\n retrieveGSOD(usaf=id,start_year = ini_year, end_year = last_year)\n temp_daily<- gzGsodStations(x,start_year = ini_year, end_year = last_year)\n temp_daily$Date=as.Date(ymd(temp_daily$YEARMODA))\n temp_daily$YEARMODA=NULL\n temp_daily$tmed <- toCelsius(temp_daily$TEMP, digits = 1)\n temp_daily$tmax <- toCelsius(temp_daily$MAX, digits = 1)\n temp_daily$tmin <- toCelsius(temp_daily$MIN, digits = 1)\n temp_daily$prec <-inch2Millimeter(temp_daily$PRCP, digits = 1)\n temp_daily$DEWP <- toCelsius(temp_daily$DEWP, digits = 1)\n temp_daily$rhum <- 100*(exp((17.625*temp_daily$DEWP)/(243.04+temp_daily$DEWP))/exp((17.625*temp_daily$tmed)/(243.04+temp_daily$tmed)))\n temp_daily$slp=temp_daily$SLP\n temp_daily$prec[which(temp_daily$PRCPFLAG==\"I\")]=missing\n temp_daily$vmed=knots2ms(temp_daily$WDSP,1)\n temp_daily$vmax=knots2ms(temp_daily$MXSPD,1)\n temp_daily=temp_daily[c(\"date\",\"tmed\",\"tmax\",\"tmin\",\"rhum\",\"DEWP\",\"vmed\",\"vmax\",\"prec\",\"slp\")]\n if ( save_files == T) {\n saveRDS(temp_daily,paste0(name,\"_DAYCLIM.rds\"))\n write.csv(temp_daily,paste0(name,\"_DAYCLIM.csv\"))\n\n }\n return(temp_daily)\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6acf3485f5370fd23dd86f6df35e0e22655913af", "size": 27069, "ext": "r", "lang": "R", "max_stars_repo_path": "R/heatwave.r", "max_stars_repo_name": "alfcrisci/rHeatWave", "max_stars_repo_head_hexsha": "0ff94cc337cd63ad7a8638bab653dd37bdb05bc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:42.000Z", "max_issues_repo_path": "R/heatwave.r", "max_issues_repo_name": "alfcrisci/rHeatWave", "max_issues_repo_head_hexsha": "0ff94cc337cd63ad7a8638bab653dd37bdb05bc3", "max_issues_repo_licenses": ["MIT"], "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/heatwave.r", "max_forks_repo_name": "alfcrisci/rHeatWave", "max_forks_repo_head_hexsha": "0ff94cc337cd63ad7a8638bab653dd37bdb05bc3", "max_forks_repo_licenses": ["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.6475548061, "max_line_length": 179, "alphanum_fraction": 0.6361889985, "num_tokens": 8390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2838406397121608}} {"text": "subroutine lo0(x,y,w,n,d,p,nvmax,span,degree,match,nef,dof,s,var,\n\t\tbeta,iv,liv,lv,v,iwork,work)\ninteger n,d,p,nvmax,degree,match(*),nef,liv,lv,iv(liv),iwork(*)\ndouble precision x(n,d),y(n),w(n),span,dof,s(n),var(n),v(lv),work(*)\ndouble precision beta(p+1)\n#work should be nef*(p+d+8) + 2*p + n +8 \ninteger qrank\n\tcall lo1(x,y,w,n,d,p,nvmax,span,degree,match,nef,0,dof,s,var,beta,\n#\txin,win,sqwin,sqwini,\n\twork(1),work(nef*d+1),work(nef*(d+1)+2),work(nef*(d+2)+2),\n#\txqr,qrank,qpivot,qraux,\t\n\twork(nef*(d+3)+2),qrank,iwork(1),work(nef*(p+d+4)+3+p),\n\tiv,liv,lv,v,\t\n\twork(nef*(p+d+4)+4+2*p) )\nreturn\nend\n\t\nsubroutine lo1(x,y,w,n,d,p,nvmax,span,degree,match,nef,nit,dof,s,var,beta,\n\txin,win,sqwin,sqwini,xqr,qrank,qpivot,qraux,\n\tiv,liv,lv,v,\t\n\twork)\ninteger n,d,p,nvmax,degree,match(*),nef,nit,qrank,qpivot(p+1)\ninteger iv(liv),liv,lv\ndouble precision x(n,d),y(n),w(n),span,dof,s(n),var(n),beta(p+1),\n\txin(nef,d),win(nef+1),sqwin(nef),sqwini(nef),xqr(nef,p+1),\n\tqraux(p+1),v(lv),\n\twork(*)\n#work should have size n +4*(nef+1)\ncall lo2(x,y,w,n,d,p,nvmax,span,degree,match,nef,nit,dof,s,var,beta,\n\txin,win,sqwin,sqwini,xqr,qrank,qpivot,qraux,\n\tiv,liv,lv,v,\t\n\twork(1),work(nef+2),work(2*nef+3),work(3*nef+4))\nreturn\nend\n\n\n\nsubroutine lo2(x,y,w,n,d,p,nvmax,span,degree,match,nef,nit,dof,s,var,beta,\n\txin,win,sqwin,sqwini,xqr,qrank,qpivot,qraux,\n\tiv,liv,lv,v,\t\n\tlevout,sout,yin,work)\ninteger n,d,p,nvmax,degree,match(*),nef,nit,qrank,qpivot(p+1)\ninteger iv(liv),liv,lv\ndouble precision x(n,d),y(n),w(n),span,dof,s(n),var(n),beta(p+1),\n\txin(nef,d),win(nef+1),sqwin(nef),sqwini(nef),xqr(nef,p+1),\n\tqraux(p+1),v(lv),\n\tlevout(nef+1), sout(nef+1),yin(nef+1),work(*)\n#work should be length n\ndouble precision junk, onedm7\ninteger job, info\nlogical setLf, ifvar\njob=110;info=1\nifvar=.true.\nonedm7=1d-7\nif(nit<=1){\n\tcall pck(n,nef,match,w,win)\n\tdo i=1,nef{\n\t\tif(win(i)>0d0){\n\t\t\tsqwin(i)=dsqrt(win(i))\n\t\t\tsqwini(i)=1d0/sqwin(i)\n\t\t}\n\t\telse{\n\t\t\tsqwin(i)=1d-5\n\t\t\tsqwini(i)=1d5\n\t\t\t}\n\t\t}\n\tdo i=1,n{\n\t\tk=match(i)\n\t\tif(k<=nef){\n\t\t\tdo j=1,d\n\t\t\t\txin(k,j)=x(i,j)\n\t\t\tfor(j=d+1;j<=p;j=j+1)\n\t\t\t\txqr(k,j+1)=x(i,j)\n\t\t\t\n\t\t\t}\n\t\t}\n\tdo i=1,nef{\n\t\txqr(i,1)=sqwin(i)\n\t\tdo j=1,d\n\t\t\txqr(i,j+1)=xin(i,j)*sqwin(i)\n\t\tfor(j=d+2;j<=p+1;j=j+1)\n\t\t\t\txqr(i,j)=xqr(i,j)*sqwin(i)\n\t\t}\n\tfor(j=1;j<=p+1;j=j+1)\n\t\tqpivot(j)=j\n\tcall dqrdca(xqr,nef,nef,p+1,qraux,qpivot,work,qrank,onedm7)\n\tsetLf = (nit==1)\n\tcall lowesd(106,iv,liv,lv,v,d,nef,span,degree,nvmax,setLf)\n\tv(2)=span/5d0\n\t}\ndo i=1,n\n\twork(i)=y(i)*w(i)\ncall pck(n,nef,match,work,yin)\n\tdo i=1,nef\n\t\tyin(i)=yin(i)*sqwini(i)*sqwini(i)\n\n\nif(nit<=1)call lowesb(xin,yin,win,levout,ifvar,iv,liv,lv,v)\n\telse call lowesr(yin,iv,liv,lv,v)\ncall lowese(iv,liv,lv,v,nef,xin,sout)\n\n#now remove the parametric piece\ndo i=1,nef\n\tsout(i)=sout(i)*sqwin(i)\ncall dqrsl(xqr,nef,nef,qrank,qraux,sout,work(1),work(1),beta,\n\t\tsout,work(1),job,info)\n#####dqrsl(x,ldx,n,k,qraux,y,qy,qty,b,rsd,xb,job,info)\ndo i=1,nef\n\tsout(i)=sout(i)*sqwini(i)\n\n#now clean up \n\nif(nit<=1){\n#get rid of the parametric component of the leverage\n\tjob=10000\n\tfor(j=1;j<=p+1;j=j+1){\n\t\tdo i=1,nef\n\t\t\twork(i)=0d0\n\t\twork(j)=1d0\n\t\tcall dqrsl(xqr,nef,nef,qrank,qraux,work,var,junk,junk,\n\t\t\tjunk,junk,job,info)\n\t\tdo i=1,nef\n\t\t\tlevout(i)=levout(i) - var(i)**2\n\t\t}\n\tdof=0d0\n\tdo i=1,nef {\n\t\tif(win(i)>0d0) {\n\t\t\tlevout(i)=levout(i)/win(i)\n\t\t\t}\n\t\telse {levout(i)=0d0}\n\t\t}\n\tdo i=1,nef {dof=dof+levout(i)*win(i)}\n\tcall unpck(n,nef,match,levout,var)\n\tfor(j=1;j<=p+1;j=j+1){work(j)=beta(j)}\n\tfor(j=1;j<=p+1;j=j+1){beta(qpivot(j))=work(j)}\n\t}\ncall unpck(n,nef,match,sout,s)\nreturn\nend\nsubroutine pck(n,p,match,x,xbar)\ninteger match(n),p,n\ndouble precision x(n),xbar(n)\n\tdo i=1,p\n\t\txbar(i)=0d0\n\tdo i=1,n\n\t\txbar(match(i))=xbar(match(i))+x(i)\nreturn\nend\n\nsubroutine suff(n,p,match,x,y,w,xbar,ybar,wbar,work)\ninteger match(n),p,n\ndouble precision x(n),xbar(n),y(n),ybar(n),w(n),wbar(n),work(n)\ncall pck(n,p,match,w,wbar)\ndo i=1,n\n\txbar(match(i))=x(i)\ndo i=1,n\n\twork(i)=y(i)*w(i)\ncall pck(n,p,match,work,ybar)\n\tdo i=1,p{\n\t\tif(wbar(i)>0d0) \n\t\t\tybar(i)=ybar(i)/wbar(i) \n\t\telse ybar(i)=0d0\n\n\t}\nreturn\nend\nsubroutine unpck(n,p,match,xbar,x)\ninteger match(n),p,n\ndouble precision x(n),xbar(p+1)\nif(p 0d0) {dwrss=wsum/wtot} else {dwrss=0d0}\nreturn\nend\n", "meta": {"hexsha": "b73d52e297b3545ffd7ba71916af6509c1230047", "size": 4442, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/lo.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/lo.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/lo.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": 23.6276595745, "max_line_length": 74, "alphanum_fraction": 0.6463304818, "num_tokens": 2042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2836788891028571}} {"text": "score <- function(input) {\n return((subroutine0(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.0351) - (input[1])) ^ (2.0)) + (((95.0) - (input[2])) ^ (2.0))) + (((2.68) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.4161) - (input[5])) ^ (2.0))) + (((7.853) - (input[6])) ^ (2.0))) + (((33.2) - (input[7])) ^ (2.0))) + (((5.118) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((224.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((392.78) - (input[12])) ^ (2.0))) + (((3.81) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine0 <- function(input) {\n return((subroutine1(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((18.0846) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.679) - (input[5])) ^ (2.0))) + (((6.434) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.8347) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((27.25) - (input[12])) ^ (2.0))) + (((29.05) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine1 <- function(input) {\n return((subroutine2(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.98843) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.813) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((4.0952) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((394.54) - (input[12])) ^ (2.0))) + (((19.88) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine2 <- function(input) {\n return((subroutine3(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((10.8342) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.679) - (input[5])) ^ (2.0))) + (((6.782) - (input[6])) ^ (2.0))) + (((90.8) - (input[7])) ^ (2.0))) + (((1.8195) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((21.57) - (input[12])) ^ (2.0))) + (((25.79) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine3 <- function(input) {\n return((subroutine4(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.22358) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.605) - (input[5])) ^ (2.0))) + (((6.943) - (input[6])) ^ (2.0))) + (((97.4) - (input[7])) ^ (2.0))) + (((1.8773) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((363.43) - (input[12])) ^ (2.0))) + (((4.59) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine4 <- function(input) {\n return((subroutine5(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((6.53876) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.631) - (input[5])) ^ (2.0))) + (((7.016) - (input[6])) ^ (2.0))) + (((97.5) - (input[7])) ^ (2.0))) + (((1.2024) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((392.05) - (input[12])) ^ (2.0))) + (((2.96) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine5 <- function(input) {\n return((subroutine6(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.18337) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((27.74) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.609) - (input[5])) ^ (2.0))) + (((5.414) - (input[6])) ^ (2.0))) + (((98.3) - (input[7])) ^ (2.0))) + (((1.7554) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((711.0) - (input[10])) ^ (2.0))) + (((20.1) - (input[11])) ^ (2.0))) + (((344.05) - (input[12])) ^ (2.0))) + (((23.97) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine6 <- function(input) {\n return((subroutine7(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.03578) - (input[1])) ^ (2.0)) + (((20.0) - (input[2])) ^ (2.0))) + (((3.33) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.4429) - (input[5])) ^ (2.0))) + (((7.82) - (input[6])) ^ (2.0))) + (((64.5) - (input[7])) ^ (2.0))) + (((4.6947) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((216.0) - (input[10])) ^ (2.0))) + (((14.9) - (input[11])) ^ (2.0))) + (((387.31) - (input[12])) ^ (2.0))) + (((3.76) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine7 <- function(input) {\n return((subroutine8(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((45.7461) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((4.519) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.6582) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((88.27) - (input[12])) ^ (2.0))) + (((36.98) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine8 <- function(input) {\n return((subroutine9(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((2.01019) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.605) - (input[5])) ^ (2.0))) + (((7.929) - (input[6])) ^ (2.0))) + (((96.2) - (input[7])) ^ (2.0))) + (((2.0459) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((369.3) - (input[12])) ^ (2.0))) + (((3.7) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine9 <- function(input) {\n return((subroutine10(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((7.67202) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.747) - (input[6])) ^ (2.0))) + (((98.9) - (input[7])) ^ (2.0))) + (((1.6334) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((393.1) - (input[12])) ^ (2.0))) + (((19.92) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine10 <- function(input) {\n return((subroutine11(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.46336) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.605) - (input[5])) ^ (2.0))) + (((7.489) - (input[6])) ^ (2.0))) + (((90.8) - (input[7])) ^ (2.0))) + (((1.9709) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((374.43) - (input[12])) ^ (2.0))) + (((1.73) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine11 <- function(input) {\n return((subroutine12(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.61282) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((6.096) - (input[6])) ^ (2.0))) + (((96.9) - (input[7])) ^ (2.0))) + (((3.7598) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((248.31) - (input[12])) ^ (2.0))) + (((20.34) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine12 <- function(input) {\n return((subroutine13(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((67.9208) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.683) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.4254) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((384.97) - (input[12])) ^ (2.0))) + (((22.98) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine13 <- function(input) {\n return((subroutine14(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((22.5971) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.7) - (input[5])) ^ (2.0))) + (((5.0) - (input[6])) ^ (2.0))) + (((89.5) - (input[7])) ^ (2.0))) + (((1.5184) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((31.99) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine14 <- function(input) {\n return((subroutine15(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((14.2362) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((6.343) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.5741) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((20.32) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine15 <- function(input) {\n return((subroutine16(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.25387) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((6.91) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.448) - (input[5])) ^ (2.0))) + (((5.399) - (input[6])) ^ (2.0))) + (((95.3) - (input[7])) ^ (2.0))) + (((5.87) - (input[8])) ^ (2.0))) + (((3.0) - (input[9])) ^ (2.0))) + (((233.0) - (input[10])) ^ (2.0))) + (((17.9) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((30.81) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine16 <- function(input) {\n return((subroutine17(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.01501) - (input[1])) ^ (2.0)) + (((90.0) - (input[2])) ^ (2.0))) + (((1.21) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.401) - (input[5])) ^ (2.0))) + (((7.923) - (input[6])) ^ (2.0))) + (((24.8) - (input[7])) ^ (2.0))) + (((5.885) - (input[8])) ^ (2.0))) + (((1.0) - (input[9])) ^ (2.0))) + (((198.0) - (input[10])) ^ (2.0))) + (((13.6) - (input[11])) ^ (2.0))) + (((395.52) - (input[12])) ^ (2.0))) + (((3.16) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine17 <- function(input) {\n return((subroutine18(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((9.91655) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.852) - (input[6])) ^ (2.0))) + (((77.8) - (input[7])) ^ (2.0))) + (((1.5004) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((338.16) - (input[12])) ^ (2.0))) + (((29.97) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine18 <- function(input) {\n return((subroutine19(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.31533) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((6.2) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.504) - (input[5])) ^ (2.0))) + (((8.266) - (input[6])) ^ (2.0))) + (((78.3) - (input[7])) ^ (2.0))) + (((2.8944) - (input[8])) ^ (2.0))) + (((8.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((17.4) - (input[11])) ^ (2.0))) + (((385.05) - (input[12])) ^ (2.0))) + (((4.14) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine19 <- function(input) {\n return((subroutine20(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.83377) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.605) - (input[5])) ^ (2.0))) + (((7.802) - (input[6])) ^ (2.0))) + (((98.2) - (input[7])) ^ (2.0))) + (((2.0407) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((389.61) - (input[12])) ^ (2.0))) + (((1.92) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine20 <- function(input) {\n return((subroutine21(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.38799) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.95) - (input[6])) ^ (2.0))) + (((82.0) - (input[7])) ^ (2.0))) + (((3.99) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((232.6) - (input[12])) ^ (2.0))) + (((27.71) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine21 <- function(input) {\n return((subroutine22(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.01538) - (input[1])) ^ (2.0)) + (((90.0) - (input[2])) ^ (2.0))) + (((3.75) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.394) - (input[5])) ^ (2.0))) + (((7.454) - (input[6])) ^ (2.0))) + (((34.2) - (input[7])) ^ (2.0))) + (((6.3361) - (input[8])) ^ (2.0))) + (((3.0) - (input[9])) ^ (2.0))) + (((244.0) - (input[10])) ^ (2.0))) + (((15.9) - (input[11])) ^ (2.0))) + (((386.34) - (input[12])) ^ (2.0))) + (((3.11) - (input[13])) ^ (2.0))))) * (0.7500000000002167)))\n}\nsubroutine22 <- function(input) {\n return((subroutine23(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.01381) - (input[1])) ^ (2.0)) + (((80.0) - (input[2])) ^ (2.0))) + (((0.46) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.422) - (input[5])) ^ (2.0))) + (((7.875) - (input[6])) ^ (2.0))) + (((32.0) - (input[7])) ^ (2.0))) + (((5.6484) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((255.0) - (input[10])) ^ (2.0))) + (((14.4) - (input[11])) ^ (2.0))) + (((394.23) - (input[12])) ^ (2.0))) + (((2.97) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine23 <- function(input) {\n return((subroutine24(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((2.77974) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.871) - (input[5])) ^ (2.0))) + (((4.903) - (input[6])) ^ (2.0))) + (((97.8) - (input[7])) ^ (2.0))) + (((1.3459) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((29.29) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine24 <- function(input) {\n return((subroutine25(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((9.2323) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.631) - (input[5])) ^ (2.0))) + (((6.216) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.1691) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((366.15) - (input[12])) ^ (2.0))) + (((9.53) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine25 <- function(input) {\n return((subroutine26(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.06129) - (input[1])) ^ (2.0)) + (((20.0) - (input[2])) ^ (2.0))) + (((3.33) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.4429) - (input[5])) ^ (2.0))) + (((7.645) - (input[6])) ^ (2.0))) + (((49.7) - (input[7])) ^ (2.0))) + (((5.2119) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((216.0) - (input[10])) ^ (2.0))) + (((14.9) - (input[11])) ^ (2.0))) + (((377.07) - (input[12])) ^ (2.0))) + (((3.01) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine26 <- function(input) {\n return((subroutine27(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.25179) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.57) - (input[6])) ^ (2.0))) + (((98.1) - (input[7])) ^ (2.0))) + (((3.7979) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((376.57) - (input[12])) ^ (2.0))) + (((21.02) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine27 <- function(input) {\n return((subroutine28(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((4.89822) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.631) - (input[5])) ^ (2.0))) + (((4.97) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.3325) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((375.52) - (input[12])) ^ (2.0))) + (((3.26) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine28 <- function(input) {\n return((subroutine29(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.13081) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.713) - (input[6])) ^ (2.0))) + (((94.1) - (input[7])) ^ (2.0))) + (((4.233) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((360.17) - (input[12])) ^ (2.0))) + (((22.6) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine29 <- function(input) {\n return((subroutine30(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.33147) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((6.2) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.507) - (input[5])) ^ (2.0))) + (((8.247) - (input[6])) ^ (2.0))) + (((70.4) - (input[7])) ^ (2.0))) + (((3.6519) - (input[8])) ^ (2.0))) + (((8.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((17.4) - (input[11])) ^ (2.0))) + (((378.95) - (input[12])) ^ (2.0))) + (((3.95) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine30 <- function(input) {\n return((subroutine31(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.52693) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((6.2) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.504) - (input[5])) ^ (2.0))) + (((8.725) - (input[6])) ^ (2.0))) + (((83.0) - (input[7])) ^ (2.0))) + (((2.8944) - (input[8])) ^ (2.0))) + (((8.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((17.4) - (input[11])) ^ (2.0))) + (((382.0) - (input[12])) ^ (2.0))) + (((4.63) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine31 <- function(input) {\n return((subroutine32(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.35472) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((6.072) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((4.175) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((376.73) - (input[12])) ^ (2.0))) + (((13.04) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine32 <- function(input) {\n return((subroutine33(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.57834) - (input[1])) ^ (2.0)) + (((20.0) - (input[2])) ^ (2.0))) + (((3.97) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.575) - (input[5])) ^ (2.0))) + (((8.297) - (input[6])) ^ (2.0))) + (((67.0) - (input[7])) ^ (2.0))) + (((2.4216) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((264.0) - (input[10])) ^ (2.0))) + (((13.0) - (input[11])) ^ (2.0))) + (((384.54) - (input[12])) ^ (2.0))) + (((7.44) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine33 <- function(input) {\n return((subroutine34(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.08187) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((2.89) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.445) - (input[5])) ^ (2.0))) + (((7.82) - (input[6])) ^ (2.0))) + (((36.9) - (input[7])) ^ (2.0))) + (((3.4952) - (input[8])) ^ (2.0))) + (((2.0) - (input[9])) ^ (2.0))) + (((276.0) - (input[10])) ^ (2.0))) + (((18.0) - (input[11])) ^ (2.0))) + (((393.53) - (input[12])) ^ (2.0))) + (((3.57) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine34 <- function(input) {\n return((subroutine35(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.02009) - (input[1])) ^ (2.0)) + (((95.0) - (input[2])) ^ (2.0))) + (((2.68) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.4161) - (input[5])) ^ (2.0))) + (((8.034) - (input[6])) ^ (2.0))) + (((31.9) - (input[7])) ^ (2.0))) + (((5.118) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((224.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((390.55) - (input[12])) ^ (2.0))) + (((2.88) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine35 <- function(input) {\n return((subroutine36(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.61154) - (input[1])) ^ (2.0)) + (((20.0) - (input[2])) ^ (2.0))) + (((3.97) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.647) - (input[5])) ^ (2.0))) + (((8.704) - (input[6])) ^ (2.0))) + (((86.9) - (input[7])) ^ (2.0))) + (((1.801) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((264.0) - (input[10])) ^ (2.0))) + (((13.0) - (input[11])) ^ (2.0))) + (((389.7) - (input[12])) ^ (2.0))) + (((5.12) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine36 <- function(input) {\n return((subroutine37(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((3.32105) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.871) - (input[5])) ^ (2.0))) + (((5.403) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.3216) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((26.82) - (input[13])) ^ (2.0))))) * (-0.400989603367655)))\n}\nsubroutine37 <- function(input) {\n return((subroutine38(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.29819) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((6.2) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.504) - (input[5])) ^ (2.0))) + (((7.686) - (input[6])) ^ (2.0))) + (((17.0) - (input[7])) ^ (2.0))) + (((3.3751) - (input[8])) ^ (2.0))) + (((8.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((17.4) - (input[11])) ^ (2.0))) + (((377.51) - (input[12])) ^ (2.0))) + (((3.92) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine38 <- function(input) {\n return((subroutine39(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.51902) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((19.58) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.605) - (input[5])) ^ (2.0))) + (((8.375) - (input[6])) ^ (2.0))) + (((93.9) - (input[7])) ^ (2.0))) + (((2.162) - (input[8])) ^ (2.0))) + (((5.0) - (input[9])) ^ (2.0))) + (((403.0) - (input[10])) ^ (2.0))) + (((14.7) - (input[11])) ^ (2.0))) + (((388.45) - (input[12])) ^ (2.0))) + (((3.32) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine39 <- function(input) {\n return((subroutine40(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((5.66998) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.631) - (input[5])) ^ (2.0))) + (((6.683) - (input[6])) ^ (2.0))) + (((96.8) - (input[7])) ^ (2.0))) + (((1.3567) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((375.33) - (input[12])) ^ (2.0))) + (((3.73) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine40 <- function(input) {\n return((subroutine41(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((8.26725) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))) + (((0.668) - (input[5])) ^ (2.0))) + (((5.875) - (input[6])) ^ (2.0))) + (((89.6) - (input[7])) ^ (2.0))) + (((1.1296) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((347.88) - (input[12])) ^ (2.0))) + (((8.88) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine41 <- function(input) {\n return((subroutine42(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((25.0461) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.987) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.5888) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((26.77) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine42 <- function(input) {\n return((subroutine43(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.05602) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((2.46) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.488) - (input[5])) ^ (2.0))) + (((7.831) - (input[6])) ^ (2.0))) + (((53.6) - (input[7])) ^ (2.0))) + (((3.1992) - (input[8])) ^ (2.0))) + (((3.0) - (input[9])) ^ (2.0))) + (((193.0) - (input[10])) ^ (2.0))) + (((17.8) - (input[11])) ^ (2.0))) + (((392.63) - (input[12])) ^ (2.0))) + (((4.45) - (input[13])) ^ (2.0))))) * (1.0)))\n}\nsubroutine43 <- function(input) {\n return((subroutine44(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.38735) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((25.65) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.581) - (input[5])) ^ (2.0))) + (((5.613) - (input[6])) ^ (2.0))) + (((95.6) - (input[7])) ^ (2.0))) + (((1.7572) - (input[8])) ^ (2.0))) + (((2.0) - (input[9])) ^ (2.0))) + (((188.0) - (input[10])) ^ (2.0))) + (((19.1) - (input[11])) ^ (2.0))) + (((359.29) - (input[12])) ^ (2.0))) + (((27.26) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine44 <- function(input) {\n return((subroutine45(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((41.5292) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.531) - (input[6])) ^ (2.0))) + (((85.4) - (input[7])) ^ (2.0))) + (((1.6074) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((329.46) - (input[12])) ^ (2.0))) + (((27.38) - (input[13])) ^ (2.0))))) * (-0.3490103966325617)))\n}\nsubroutine45 <- function(input) {\n return((subroutine46(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((24.8017) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.349) - (input[6])) ^ (2.0))) + (((96.0) - (input[7])) ^ (2.0))) + (((1.7028) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((19.77) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine46 <- function(input) {\n return((subroutine47(input)) + ((exp((-0.0000036459736698188483) * (((((((((((((((1.15172) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.701) - (input[6])) ^ (2.0))) + (((95.0) - (input[7])) ^ (2.0))) + (((3.7872) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((358.77) - (input[12])) ^ (2.0))) + (((18.35) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\nsubroutine47 <- function(input) {\n return((((25.346480984077544) + ((exp((-0.0000036459736698188483) * (((((((((((((((16.8118) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.7) - (input[5])) ^ (2.0))) + (((5.277) - (input[6])) ^ (2.0))) + (((98.1) - (input[7])) ^ (2.0))) + (((1.4261) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((30.81) - (input[13])) ^ (2.0))))) * (-1.0))) + ((exp((-0.0000036459736698188483) * (((((((((((((((38.3518) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((18.1) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.693) - (input[5])) ^ (2.0))) + (((5.453) - (input[6])) ^ (2.0))) + (((100.0) - (input[7])) ^ (2.0))) + (((1.4896) - (input[8])) ^ (2.0))) + (((24.0) - (input[9])) ^ (2.0))) + (((666.0) - (input[10])) ^ (2.0))) + (((20.2) - (input[11])) ^ (2.0))) + (((396.9) - (input[12])) ^ (2.0))) + (((30.59) - (input[13])) ^ (2.0))))) * (-1.0))) + ((exp((-0.0000036459736698188483) * (((((((((((((((0.84054) - (input[1])) ^ (2.0)) + (((0.0) - (input[2])) ^ (2.0))) + (((8.14) - (input[3])) ^ (2.0))) + (((0.0) - (input[4])) ^ (2.0))) + (((0.538) - (input[5])) ^ (2.0))) + (((5.599) - (input[6])) ^ (2.0))) + (((85.7) - (input[7])) ^ (2.0))) + (((4.4546) - (input[8])) ^ (2.0))) + (((4.0) - (input[9])) ^ (2.0))) + (((307.0) - (input[10])) ^ (2.0))) + (((21.0) - (input[11])) ^ (2.0))) + (((303.42) - (input[12])) ^ (2.0))) + (((16.51) - (input[13])) ^ (2.0))))) * (-1.0)))\n}\n", "meta": {"hexsha": "3323ae17bfcb02a8b76873de6a9ffd70680305c3", "size": 30230, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/regression/svm.r", "max_stars_repo_name": "Symmetry-International/m2cgen", "max_stars_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2161, "max_stars_repo_stars_event_min_datetime": "2019-01-13T02:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:24:09.000Z", "max_issues_repo_path": "generated_code_examples/r/regression/svm.r", "max_issues_repo_name": "Symmetry-International/m2cgen", "max_issues_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 380, "max_issues_repo_issues_event_min_datetime": "2019-01-17T15:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:59:20.000Z", "max_forks_repo_path": "generated_code_examples/r/regression/svm.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": 204.2567567568, "max_line_length": 1613, "alphanum_fraction": 0.3864042342, "num_tokens": 14154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2833101815616768}} {"text": "## Plot simulations for Mincerian Wage equation\n## Load libraries\nlibrary(tidyverse)\nlibrary(texreg)\nlibrary(cowplot)\nlibrary(ggsci)\nlibrary(ggpubr)\nlibrary(vtable)\n\n## Make descriptipve table\ndf <- read.csv(\"data/edit/analysis_df.csv\") %>%\n dplyr::select(-X.1)\n\nlabs <- data.frame(\n age = \"Age\",\n S = \"Schooling (years)\",\n X = \"Work experience (years)\",\n ln_y_I = \"Log wages (linear-I)\",\n ln_y_II = \"Log wages (linear-II)\",\n ln_y_III = \"Log wages (linear-III)\",\n ln_y_IV = \"Log wages (linear-IV)\",\n gender = \"Sex (1 = female, 0 = male)\"\n)\n\ndf %>%\n select(age, S, X, gender, ln_y_I, ln_y_II, ln_y_III, ln_y_IV) %>%\n mutate(gender = ifelse(gender == 1, \"Female\", \"Male\")) %>%\n vtable::sumtable(\n labels = labs, out = \"latex\",\n file = \"tex/tables/desc_mincerian.tex\"\n )\n\n## Plot OOS performance\nsource(\"mincerian/functions.R\")\ndata <- readRDS(\"data/final/simul_4models_100.rds\")\n\ndf <- data %>%\n mutate(\n lm_1_1 = 1 - (lm_1_1 / lm_1_bench),\n lm_1_2 = 1 - (lm_1_2 / lm_1_bench),\n lm_1_3 = 1 - (lm_1_3 / lm_1_bench),\n lm_1_4 = 1 - (lm_1_4 / lm_1_bench),\n lm_2_1 = 1 - (lm_2_1 / lm_2_bench),\n lm_2_2 = 1 - (lm_2_2 / lm_2_bench),\n lm_2_3 = 1 - (lm_2_3 / lm_2_bench),\n lm_2_4 = 1 - (lm_2_4 / lm_2_bench),\n lm_3_1 = 1 - (lm_3_1 / lm_3_bench),\n lm_3_2 = 1 - (lm_3_2 / lm_3_bench),\n lm_3_3 = 1 - (lm_3_3 / lm_3_bench),\n lm_3_4 = 1 - (lm_3_4 / lm_3_bench),\n lm_4_1 = 1 - (lm_4_1 / lm_4_bench),\n lm_4_2 = 1 - (lm_4_2 / lm_4_bench),\n lm_4_3 = 1 - (lm_4_3 / lm_4_bench),\n lm_4_4 = 1 - (lm_4_4 / lm_4_bench),\n gb_1 = 1 - (gb_1 / lm_1_bench),\n gb_2 = 1 - (gb_2 / lm_2_bench),\n gb_3 = 1 - (gb_3 / lm_3_bench),\n gb_4 = 1 - (gb_4 / lm_4_bench)\n ) %>%\n dplyr::select(-lm_1_bench, -lm_2_bench, -lm_3_bench, -lm_4_bench)\n\ndf_melt <- df %>%\n reshape2::melt() %>%\n mutate(\n dataset = ifelse(grepl(\"lm_1|gb_1\", variable), \"Dataset I\",\n ifelse(grepl(\"lm_2|gb_2\", variable), \"Dataset II\",\n ifelse(grepl(\"lm_3|gb_3\", variable), \"Dataset III\",\n ifelse(grepl(\"lm_4|gb_4\", variable), \"Dataset IV\",\n \"Else\"\n )\n )\n )\n ),\n model = ifelse(grepl(\"\\\\d{1}_1\", variable), \"Linear I\",\n ifelse(grepl(\"\\\\d{1}_2\", variable), \"Linear II\",\n ifelse(grepl(\"\\\\d{1}_3\", variable), \"Linear III\",\n ifelse(grepl(\"\\\\d{1}_4\", variable), \"Linear IV\",\n ifelse(grepl(\"gb\", variable), \"XGBoost\",\n \"Other\"\n )\n )\n )\n )\n )\n )\n\ndf_summ <- df_melt %>%\n group_by(variable) %>%\n summarise(\n mean = mean(value),\n sd = sd(value),\n model = unique(model),\n dataset = unique(dataset)\n )\n\ndf_plot <- df_summ %>%\n filter(!grepl(\"rf\", variable))\n\ncustom_pal <- c(\n ggsci::pal_aaas()(6)[6],\n RColorBrewer::brewer.pal(4, \"Blues\")\n)\n\ndf_plot$model <- factor(df_plot$model, levels = c(\n \"XGBoost\", \"Linear I\", \"Linear II\",\n \"Linear III\", \"Linear IV\"\n))\ntext_size <- 20\n\n\nggplot(df_plot, aes(y = mean, x = model, group = dataset, fill = model)) +\n geom_bar(stat = \"identity\", color = \"black\") +\n geom_text(aes(label = paste0(as.character(round(mean, 2) * 100), \"%\")),\n vjust = -0.5\n ) +\n geom_hline(yintercept = 0.9, linetype = \"dashed\") +\n scale_fill_manual(values = custom_pal, name = \"\") +\n ylim(0, 1) +\n scale_y_continuous(\n limits = c(0.5, 1.05), oob = scales::rescale_none,\n labels = scales::percent\n ) +\n geom_errorbar(aes(ymin = mean - sd, ymax = mean + sd), width = 0.5) +\n facet_wrap(~dataset, nrow = 1) +\n cowplot::theme_cowplot() +\n xlab(\"Model\") +\n ylab(\"Out-of-sample R-squared\") +\n theme(\n panel.grid.minor.x = element_line(size = 0.25), # linetype = 'dotted'),\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.5),\n legend.position = \"top\",\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n text = element_text(size = 20)\n ) +\n theme(\n axis.text.x = element_text(angle = 45, hjust = 1, size = (text_size - 1)),\n axis.text.y = element_text(size = (text_size - 1)),\n axis.title.y = element_text(size = 16.3)\n ) +\n scale_y_continuous(labels = scales::percent, limits = c(0, 1))\n\nggsave(\"tex/figs/fig1_mincerian.pdf\", last_plot(), width = 12, height = 6)\n\n## Plot in-sample regression results\n\nanalysis_df <- read.csv(\"data/edit/analysis_df.csv\")\n\nform_0 <- as.formula(\"ln_y ~ 1\")\nform_1 <- as.formula(\"ln_y ~ 1 + S + X\")\nform_2 <- as.formula(\"ln_y ~ 1 + S + X + X_sq\")\nform_3 <- as.formula(\n \"ln_y ~ 1 + S_0_8 + S_9_10 + S_11_12 + S_13_14 + S_15p + X + X_sq\"\n)\nform_4 <- as.formula(\n \"ln_y ~ 1 + S_0_8 + S_9_10 + S_11_12 + S_13_14 + S_15p + X + X_sq + gender\"\n)\n\nformulas <- list(form_0, form_1, form_2, form_3, form_4)\n\nvars <- list(\"ln_y_I\", \"ln_y_II\", \"ln_y_III\", \"ln_y_IV\")\n\ncoef_dfs <- lapply(vars, FUN = function(x) {\n make_coef_df(formulas, analysis_df, var = x)\n})\n\ntotal_df <- data.frame()\n\nfor (i in coef_dfs) {\n total_df <- rbind(total_df, i)\n}\n\ntotal_df <- total_df[total_df$model_no != \"Null\", ]\nplot_df <- total_df[total_df$coefficient != \"(Intercept)\", ]\nplot_df$dataset <- as.factor(plot_df$dataset)\n\nplot_df <- plot_df %>%\n mutate(var_type = ifelse(grepl(\"X\", coefficient), \"Years Work Experience\",\n ifelse(grepl(\"S\", coefficient), \"Years Schooling\", \"Sex\")\n )) %>%\n mutate(coefficient = gsub(\"gender\", \"Female\", coefficient)) %>%\n mutate(\n coefficient = gsub(\"S_|S\", \"School years: \", coefficient),\n coefficient = gsub(\"_\", \" to \", coefficient),\n coefficient = gsub(\"p$\", \"+\", coefficient),\n coefficient = gsub(\"X to sq\", \"Work years (squared)\", coefficient),\n coefficient = gsub(\"X\", \"Work years\", coefficient),\n dataset = gsub(\"ln_y_\", \"Dataset \", dataset)\n ) %>%\n mutate(\n sig = ifelse(`p-value` < 0.01, \"*\", \"\"),\n sig_pos = estimate + 0.05\n )\n\nggplot(\n plot_df,\n aes(x = estimate, y = coefficient, fill = model_no)\n) +\n geom_point(\n size = 2.5, position = position_dodge(width = 0.5),\n color = \"black\", pch = 21\n ) +\n facet_wrap(~dataset, nrow = 1) +\n geom_vline(xintercept = 0, linetype = \"dashed\") +\n theme_cowplot() +\n scale_fill_manual(\n values = custom_pal[2:5],\n name = \"Model type\"\n ) +\n theme(legend.position = \"top\") +\n xlab(\"Coefficient Estimate\") +\n ylab(\"Coefficient\") +\n geom_text(\n data = plot_df, aes(x = sig_pos, y = coefficient, label = sig),\n color = \"black\",\n position = position_dodge(width = 0.5),\n vjust = 0.7\n ) +\n theme(\n panel.grid.major.x = element_line(\n size = 0.5, linetype = \"dotted\",\n colour = \"lightgrey\"\n ),\n panel.grid.minor.x = element_line(\n size = 0.25, linetype = \"dotted\",\n colour = \"lightgrey\"\n ),\n strip.placement = \"outside\",\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.2),\n legend.position = \"top\",\n panel.spacing.x = unit(1, \"lines\"),\n panel.spacing.y = unit(0.1, \"lines\"),\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n plot.margin = grid::unit(c(0.5, 0.5, 0.1, 0.1), \"mm\")\n )\n\nggsave(\"tex/figs/fig2_mincerian.pdf\", last_plot(), width = 12, height = 8)\n\n## -- Shapley plots\n\ndf <- read.csv(\"data/edit/mincerian_shap.csv\") %>%\n rowwise() %>%\n mutate(\n S1 = as.numeric(S1),\n S_0_8 = min(S1, 8),\n S_9_10 = min(max(S1 - 8, 0), 2),\n S_11_12 = min(max(S1 - 10, 0), 2),\n S_13_14 = min(max(S1 - 12, 0), 2),\n S_15p = max(S1 - 14, 0),\n ) %>%\n ungroup()\n\ndf$X1_1_predict <- predict_XSQ(df, total_df, \"Linear I\", \"ln_y_I\")\ndf$X1_2_predict <- predict_XSQ(df, total_df, \"Linear II\", \"ln_y_I\")\ndf$X1_3_predict <- predict_XSQ(df, total_df, \"Linear III\", \"ln_y_I\")\ndf$X1_4_predict <- predict_XSQ(df, total_df, \"Linear IV\", \"ln_y_I\")\n\ndf$X2_1_predict <- predict_XSQ(df, total_df, \"Linear I\", \"ln_y_II\")\ndf$X2_2_predict <- predict_XSQ(df, total_df, \"Linear II\", \"ln_y_II\")\ndf$X2_3_predict <- predict_XSQ(df, total_df, \"Linear III\", \"ln_y_II\")\ndf$X2_4_predict <- predict_XSQ(df, total_df, \"Linear IV\", \"ln_y_II\")\n\ndf$X3_1_predict <- predict_XSQ(df, total_df, \"Linear I\", \"ln_y_III\")\ndf$X3_2_predict <- predict_XSQ(df, total_df, \"Linear II\", \"ln_y_III\")\ndf$X3_3_predict <- predict_XSQ(df, total_df, \"Linear III\", \"ln_y_III\")\ndf$X3_4_predict <- predict_XSQ(df, total_df, \"Linear IV\", \"ln_y_III\")\n\ndf$X4_1_predict <- predict_XSQ(df, total_df, \"Linear I\", \"ln_y_IV\")\ndf$X4_2_predict <- predict_XSQ(df, total_df, \"Linear II\", \"ln_y_IV\")\ndf$X4_3_predict <- predict_XSQ(df, total_df, \"Linear III\", \"ln_y_IV\")\ndf$X4_4_predict <- predict_XSQ(df, total_df, \"Linear IV\", \"ln_y_IV\")\n\ndf$S1_1_predict <- predict_S(df, total_df, \"Linear I\", \"ln_y_I\")\ndf$S1_2_predict <- predict_S(df, total_df, \"Linear II\", \"ln_y_I\")\ndf$S1_3_predict <- predict_S(df, total_df, \"Linear III\", \"ln_y_I\")\ndf$S1_4_predict <- predict_S(df, total_df, \"Linear IV\", \"ln_y_I\")\n\ndf$S2_1_predict <- predict_S(df, total_df, \"Linear I\", \"ln_y_II\")\ndf$S2_2_predict <- predict_S(df, total_df, \"Linear II\", \"ln_y_II\")\ndf$S2_3_predict <- predict_S(df, total_df, \"Linear III\", \"ln_y_II\")\ndf$S2_4_predict <- predict_S(df, total_df, \"Linear IV\", \"ln_y_II\")\n\ndf$S3_1_predict <- predict_S(df, total_df, \"Linear I\", \"ln_y_III\")\ndf$S3_2_predict <- predict_S(df, total_df, \"Linear II\", \"ln_y_III\")\ndf$S3_3_predict <- predict_S(df, total_df, \"Linear III\", \"ln_y_III\")\ndf$S3_4_predict <- predict_S(df, total_df, \"Linear IV\", \"ln_y_III\")\n\ndf$S4_1_predict <- predict_S(df, total_df, \"Linear I\", \"ln_y_IV\")\ndf$S4_2_predict <- predict_S(df, total_df, \"Linear II\", \"ln_y_IV\")\ndf$S4_3_predict <- predict_S(df, total_df, \"Linear III\", \"ln_y_IV\")\ndf$S4_4_predict <- predict_S(df, total_df, \"Linear IV\", \"ln_y_IV\")\n\ndf_melt_X <- df %>%\n sample_n(250) %>%\n dplyr::select(\n X1, X1_shap, X2_shap, X3_shap, X4_shap,\n contains(\"_predict\"),\n -starts_with(\"S\"), sex\n ) %>%\n reshape2::melt(id.vars = c(\"X1\", \"sex\")) %>%\n mutate(\n model = ifelse(grepl(\"shap\", variable), \"Shapley Value\",\n ifelse(grepl(\"_1\", variable), \"Linear I\",\n ifelse(grepl(\"_2\", variable), \"Linear II\",\n ifelse(grepl(\"_3\", variable), \"Linear III\",\n ifelse(grepl(\"_4\", variable), \"Linear IV\", \"None\")\n )\n )\n )\n ),\n dataset = gsub(\"_.*\", \"\", variable),\n dataset = gsub(\"X\", \"Dataset \", dataset),\n sex = as.factor(ifelse(sex == 1, \"Female\", \"Male\"))\n ) %>%\n rename(Sex = sex) %>%\n group_by(variable) %>%\n mutate(value = scale(value)) %>%\n ungroup()\n\ndf_melt_S <- df %>%\n sample_n(250) %>%\n dplyr::select(\n S1, S1_shap, S2_shap, S3_shap, S4_shap,\n contains(\"_predict\"), sex\n ) %>%\n dplyr::select(-contains(\"X\"), sex) %>%\n reshape2::melt(id.vars = c(\"S1\", \"sex\")) %>%\n mutate(\n model = ifelse(grepl(\"shap\", variable), \"Shapley Value\",\n ifelse(grepl(\"_1\", variable), \"Linear I\",\n ifelse(grepl(\"_2\", variable), \"Linear II\",\n ifelse(grepl(\"_3\", variable), \"Linear III\",\n ifelse(grepl(\"_4\", variable), \"Linear IV\", \"None\")\n )\n )\n )\n ),\n dataset = gsub(\"_.*\", \"\", variable),\n dataset = gsub(\"S\", \"Dataset \", dataset),\n S1 = as.numeric(S1),\n sex = as.factor(ifelse(sex == 1, \"Female\", \"Male\"))\n ) %>%\n rename(Sex = sex) %>%\n group_by(variable) %>%\n mutate(value = scale(value)) %>%\n ungroup()\n\nX_shap_plot <- ggplot(\n df_melt_X %>% filter(!grepl(\"shap\", variable)),\n aes(y = value, x = X1, color = Sex)\n) +\n geom_point(\n data = df_melt_X %>% filter(grepl(\"shap\", variable)),\n alpha = 0.5, size = 3.5\n ) +\n geom_line(aes(linetype = model), color = \"black\", size = 0.8) +\n ggsci::scale_color_aaas() +\n xlab(\"Work experience (years)\") +\n ylab(\"Implied effect on log wages\") +\n scale_linetype_manual(values = c(\"solid\", \"dashed\", \"twodash\", \"dotted\")) +\n theme_cowplot() +\n guides(color = guide_legend(override.aes = list(fill = NA))) +\n facet_wrap(~dataset, nrow = 1) +\n theme(\n panel.grid.minor.y = element_line(size = 0.25, linetype = \"dotted\"),\n panel.grid.major.y = element_line(size = 0.25, linetype = \"dotted\"),\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.5),\n legend.position = \"top\",\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n text = element_text(size = 20),\n legend.title = element_blank()\n )\n\nS_shap_plot <- ggplot(\n df_melt_S %>% filter(!grepl(\"shap\", variable)),\n aes(y = value, x = S1, color = Sex)\n) +\n geom_point(\n data = df_melt_S %>% filter(grepl(\"shap\", variable)),\n size = 3.5, alpha = 0.5\n # color = ggsci::pal_aaas(\"default\")(4)[1], size = 3.5\n ) +\n ggsci::scale_color_aaas() +\n geom_line(aes(linetype = model), color = \"black\", size = 0.8) +\n xlab(\"Schooling (years)\") +\n ylab(\"Implied effect on log wages\") +\n scale_linetype_manual(values = c(\"solid\", \"dashed\", \"twodash\", \"dotted\")) +\n theme_cowplot() +\n theme(\n panel.grid.minor.y = element_line(size = 0.25, linetype = \"dotted\"),\n panel.grid.major.y = element_line(size = 0.25, linetype = \"dotted\"),\n strip.text.y = element_text(face = \"bold\", hjust = 0.5, vjust = 0.5),\n strip.background = element_rect(fill = NA, color = \"black\", size = 1.5),\n legend.position = \"top\",\n panel.border = element_rect(color = \"lightgrey\", fill = NA, size = 0.5),\n text = element_text(size = 20),\n legend.title = element_blank()\n ) +\n guides(color = guide_legend(override.aes = list(fill = NA))) +\n facet_wrap(~dataset, nrow = 1)\n\nggarrange(X_shap_plot + theme(legend.position = \"none\"),\n S_shap_plot + theme(legend.position = \"none\"),\n nrow = 2, common.legend = TRUE, legend = \"top\"\n)\n\nggsave(\"tex/figs/fig3_mincerian.pdf\", last_plot(), width = 12, height = 8)", "meta": {"hexsha": "7c52f2e369f8799b10d6f0d28c4ad44e57a476fc", "size": 13777, "ext": "r", "lang": "R", "max_stars_repo_path": "mincerian/04_plot.r", "max_stars_repo_name": "MarkDVerhagen/functional_form_complexity", "max_stars_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mincerian/04_plot.r", "max_issues_repo_name": "MarkDVerhagen/functional_form_complexity", "max_issues_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mincerian/04_plot.r", "max_forks_repo_name": "MarkDVerhagen/functional_form_complexity", "max_forks_repo_head_hexsha": "9938723621396ec217b4295d90f13ef98f75e528", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.684596577, "max_line_length": 78, "alphanum_fraction": 0.6160267112, "num_tokens": 4846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2832842077228008}} {"text": " XIFUpixelFracs <- function(ctrate, deltat, t0, t1, t2, tolsep){\n #\n # Calculate (Quality) Fractions of photons for XIFU pixels, using photon simulation AND\n # Poisson statistics\n #\n # Poissonian Distribution of Photons\n # tp = Tprevious\n # tn = Tnext\n # L : event with \"Low\" Quality\n # M : event with \"Medium\" Quality\n # H : event with \"High\" Quality\n # I : event \"Invalid\"\n # P2 : secondary events piled-up (same arrival time) (preceeded by close pulses)\n # P1: first pulse in pile-up (followed by close pulses but no pulse close before)\n # P : Pile-up = P1+P2\n #===================================================\n # | tolsep>tp tolsept0 =\n # -------------------------------------------------=\n # tnt2 | P2 I H =\n # tn0)\n N.real.photons <- rpois(1,N.mean.photons)\n #cat(\"psfrac=\",psf, \"N.mean.photons=\", N.mean.photons,\"\\n\")\n points <- runif(N.real.photons,0.,deltat)\n points <- sort(points)\n \n # Calculate fractions by photon counting (points in plots)\n # ----------------------------------------------------------\n Frac.HQ <- 0.\n Frac.MQ <- 0.\n Frac.LQ <- 0.\n Frac.IQ <- 0.\n Frac.PL <- 0.\n Frac.P1L <- 0.\n Frac.P2L <- 0.\n \n N.HQ.photons <- 0.\n N.MQ.photons <- 0.\n N.LQ.photons <- 0.\n N.IQ.photons <- 0.\n N.PL.photons <- 0.\n N.P1L.photons <- 0.\n N.P2L.photons <- 0.\n \n if(N.real.photons < 2){ # if less than 2 photons in total\n Frac.HQ <- 1.\n Frac.MQ <- 0.\n Frac.LQ <- 0.\n Frac.IQ <- 0.\n Frac.PL <- 0.\n Frac.P1L <- 0.\n Frac.P2L <- 0.\n }else{\n for (i in 1:N.real.photons){\n if(i==1){ # first photon case\n if((points[i+1]-points[i])>t2){ # HQ\n N.HQ.photons <- N.HQ.photons +1\n }else if((points[i+1]-points[i])>t1 && (points[i+1]-points[i])t0){ # HQ\n N.HQ.photons <- N.HQ.photons +1\n }else if((points[i]-points[i-1])t0 && (points[i+1]-points[i])>t2){ # HQ\n N.HQ.photons <- N.HQ.photons +1 \n }else if((points[i]-points[i-1])>t0 && (points[i+1]-points[i])>t1 && \n (points[i+1]-points[i])t0 && ((points[i+1]-points[i])tolsep){ # LQ\n N.LQ.photons <- N.LQ.photons +1\n }else if((points[i+1]-points[i])tolsep){\n N.P1L.photons <- N.P1L.photons +1 # P1L\n }else if((points[i]-points[i-1])2 photons\n \n # Calculate fractions from Expression by Poissonian theory: given a photon...\n #----------------------------------------------------------------------------\n # HQ => pH: exp(-ctrate*t0) * exp(-ctrate*t2)\n # Prob of having 0 prev. photons in t0 and 0 next photons in t2\n pH <- dpois(0,lambda*t0)*dpois(0,lambda*t2)\n \n # MQ => pM: exp(-ctrate*t1) * exp(-ctrate*t1)- pH\n # Prob of having 0 prev. photons in t1 and 0 next photons in t1 - pH\n pM <- dpois(0,lambda*t0)*dpois(0,lambda*t1)-pH\n \n # LQ => pL: exp(-ctrate*t0) -pH - pM\n pL <- dpois(0,lambda*t0)-pH-pM\n \n # PL => pP: two pulses arriving at tti\n # + (1- exp(-ctrate*ti))*(1- exp(-ctrate*ti)) : tp and tn closer than ti\n pP <- 1-dpois(0,2*lambda*tolsep) \n # also = ppois(0,2*lambda*tolsep, lower.tail=FALSE) -> given 1 photon, which is the prob of finding >0 ph in the double interval?\n pP2 <- 1-dpois(0,lambda*tolsep) \n pP1 <- pP - pP2\n # IQ => pI\n pI <- 1-pH-pM-pL-pP\n \n return(list(\"HQ_ph\"=Frac.HQ, \"MQ_ph\"=Frac.MQ, \"LQ_ph\"=Frac.LQ, \"IQ_ph\"=Frac.IQ,\n \"PL_ph\"=Frac.PL, \"P1L_ph\"=Frac.P1L, \"P2L_ph\"=Frac.P2L,\n \"HQ_Ps\"=pH, \"MQ_Ps\"=pM, \"LQ_Ps\"=pL, \"IQ_Ps\"=pI, \n \"PL_Ps\"=pP, \"P1L_Ps\"=pP1, \"P2L_Ps\"=pP2))\n }\n", "meta": {"hexsha": "78ff79bb2973ae95bd73e7b03b88b1e5f5cb859c", "size": 6885, "ext": "r", "lang": "R", "max_stars_repo_path": "XIFUpixelFracs.r", "max_stars_repo_name": "mtceballos/myRfunctions", "max_stars_repo_head_hexsha": "7b292c5af68bafd04fe7eece84c921dc6f5ec8e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "XIFUpixelFracs.r", "max_issues_repo_name": "mtceballos/myRfunctions", "max_issues_repo_head_hexsha": "7b292c5af68bafd04fe7eece84c921dc6f5ec8e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "XIFUpixelFracs.r", "max_forks_repo_name": "mtceballos/myRfunctions", "max_forks_repo_head_hexsha": "7b292c5af68bafd04fe7eece84c921dc6f5ec8e8", "max_forks_repo_licenses": ["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.1468531469, "max_line_length": 137, "alphanum_fraction": 0.4213507625, "num_tokens": 2149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2778077253027184}} {"text": "## Descriptive statistics for questionnaire data\n# Copyright 2021 Enrico Glerean\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License. \n\n\n# Data description\n# filetype: CSV, first row list of column names with format C[1-4]_Q[1-40]\n# 40 items (Q*) arranged in columns, divided in 4 subscales (C*)\n# The four subscales: \n# C1_Q1, C1_Q5, C1_Q9, C1_Q11, C1_Q13, C1_Q16, C1_Q19, C1_Q25, C1_Q27, C1_Q29, C1_Q31, C1_Q35, \n# C2_Q4, C2_Q6, C2_Q8, C2_Q10, C2_Q14, C2_Q21, C2_Q22, C2_Q23, C2_Q30, C2_Q34, \n# C3_Q3, C3_Q12, C3_Q17, C3_Q20, C3_Q24, C3_Q26, C3_Q28, C3_Q32, C3_Q33, C3_Q37, C3_Q38, C3_Q39, \n# C4_Q2, C4_Q7, C4_Q15, C4_Q18, C4_Q36, C4_Q40 \n#\n# each row contains the scored answer of a participant:\n# -1: the participant answered wrongly\n# 0: the participant answered \"I am unsure\"\n# 1: the participant answered correctly\n# Missing values were replaced with median (see python code for preprocessing)\n\n# In this script we report classical descriptive summaries for the dataset\n# The script should be run from the terminal prompt as an R-script\n# - without input argument: descriptive statistics for the whole scale\n# - with input argument 1,2,3,4: descriptive statistics for one of the 4 subscales\n\n# We use the descriptive function from the ltm package\nlibrary(\"ltm\")\n\n\ndfA <- read.table(\"../results/scores/scores_sorted.csv\",header=TRUE, sep=',', colClasses = \"integer\")\ndfA <- dfA + 1 # We have values from 0 to 2 as required in other R packages with polytomous data\n\n\n#!/usr/bin/env Rscript\nargs = commandArgs(trailingOnly=TRUE)\n\n\n\nif (length(args)==0) {\n print(\"Running for all items\")\n plotlabel=\"allItems.pdf\"\n df <- dfA\n} else if (length(args)==1) {\n if (args==1){\n itemssub <- c(1,2,3,4,5,6,7,8,9,10,11,12);\n df <- subset(dfA, select = c(\"C1_Q1\", \"C1_Q5\", \"C1_Q9\", \"C1_Q11\", \"C1_Q13\", \"C1_Q16\", \"C1_Q19\", \"C1_Q25\", \"C1_Q27\", \"C1_Q29\", \"C1_Q31\", \"C1_Q35\"));\n plotlabel=\"Subscale1.pdf\";\n print(\"Running for Subscale 1\")\n }\n if (args==2){\n itemssub <- c(13,14,15,16,17,18,19,20,21,22);\n df <- subset(dfA, select = c(C2_Q4, C2_Q6, C2_Q8, C2_Q10, C2_Q14, C2_Q21, C2_Q22, C2_Q23, C2_Q30, C2_Q34));\n plotlabel=\"Subscale2.pdf\";\n print(\"Running for Subscale 2\")\n }\n if (args==3){\n itemssub <- c(23,24,25,26,27,28,29,30,31,32,33,34)\n df <- subset(dfA, select = c(C3_Q3, C3_Q12, C3_Q17, C3_Q20, C3_Q24, C3_Q26, C3_Q28, C3_Q32, C3_Q33, C3_Q37, C3_Q38, C3_Q39));\n plotlabel=\"Subscale3.pdf\"\n }\n if (args==4){\n itemssub <- c(35,36,37,38,39,40)\n df <- subset(dfA, select = c(C4_Q2, C4_Q7, C4_Q15, C4_Q18, C4_Q36, C4_Q40))\n plotlabel=\"Subscale4.pdf\"\n }\n}\n\n\n\nd <- descript(df)\nd\n\n\n## Item Response Theory equivalent of reliability\n# - Item Separation Reliability (ISR)\n# - Person Separation Reliability (PSR)\n# IMPORTANT NOTE:\n# ISR and PSR can also be computed from the standard error of the model fit\n# See for example implementation in package eRm. \n# Here we follow the formulas from Chapter 18 of:\n# Wright, B. D., & Stone, M. (1999). Measurement Essentials, Wide Range. INC. Wilmington, Delaware.\n# https://www.rasch.org/measess/met-18.pdf\n\n# item separation reliability code from https://bookdown.org/chua/new_rasch_demo2/PC-model.html\n# Based on formulas from https://www.rasch.org/measess/met-18.pdf\n# Get Item scores\nItemScores <- colSums(df)\n# Get Item SD\nItemSD <- apply(df,2,sd)\n# Calculate the se of the Item\nItemSE <- ItemSD/sqrt(length(ItemSD))\n# compute the Observed Variance (also known as Total Person Variability or Squared Standard Deviation)\nSSD.ItemScores <- var(ItemScores)\n# compute the Mean Square Measurement error (also known as Model Error variance)\nItem.MSE <- sum((ItemSE)^2) / length(ItemSE)\n# compute the Item Separation Reliability\nitem.separation.reliability <- (SSD.ItemScores-Item.MSE) / SSD.ItemScores\n\nprint(\"Item separation reliability: \")\nitem.separation.reliability\n\n\n# person separation reliability code from https://bookdown.org/chua/new_rasch_demo2/PC-model.html\n# Based on formulas from https://www.rasch.org/measess/met-18.pdf\n# Get Person scores\nPersonScores <- rowSums(df)\n# Get Person SD\nPersonSD <- apply(df,1,sd)\n# Calculate the se of the Person\nPersonSE <- PersonSD/sqrt(length(PersonSD))\n# compute the Observed Variance (also known as Total Person Variability or Squared Standard Deviation)\nSSD.PersonScores <- var(PersonScores)\n# compute the Mean Square Measurement error (also known as Model Error variance)\nPerson.MSE <- sum((PersonSE)^2) / length(PersonSE)\n# compute the Person Separation Reliability\nperson.separation.reliability <- (SSD.PersonScores-Person.MSE) / SSD.PersonScores\n\n\nprint(\"Person separation reliability: \")\nperson.separation.reliability\n\n", "meta": {"hexsha": "e23bac024e85b794ce215880783f32d31f9cc05c", "size": 5190, "ext": "r", "lang": "R", "max_stars_repo_path": "r01_descriptives.r", "max_stars_repo_name": "eglerean/sulo", "max_stars_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r01_descriptives.r", "max_issues_repo_name": "eglerean/sulo", "max_issues_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r01_descriptives.r", "max_forks_repo_name": "eglerean/sulo", "max_forks_repo_head_hexsha": "989411c9ffd84144e95548d583242ff80b3ac9f3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6183206107, "max_line_length": 151, "alphanum_fraction": 0.7231213873, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.2777921560835902}} {"text": "#######################\n# R script for the Treeweb #\n# cross-community analysis #\n# SI analysis #\n#######################################\n\n# load libraries\nlibrary(vegan)\nlibrary(plyr)\nlibrary(reshape2)\nlibrary(boot)\nlibrary(dplyr)\nlibrary(UpSetR)\nlibrary(DHARMa)\nlibrary(ade4)\nlibrary(ggplot2)\nlibrary(gridExtra)\n\n# set working directory\nsetwd(\"~/PostDoc_Ghent/Synthesis_3/treeweb_community/\")\n\n# load plot data\nplot_info <- read.csv(\"data/synthesis_expldata_raw.csv\", stringsAsFactors = FALSE)\nplot_xy <- read.csv(\"data/plot_xy.csv\")\n\n# load community data\ncomms <- c(\"bird\", \"bat\", \"spider\", \"opiliones\", \"carabid\", \"isopods\", \"diplopod\", \"herb\", \"vegetation\")\ncomm_l <- lapply(comms, function(x) read.csv(paste0(\"data/treeweb_\", x, \"_format.csv\")))\nnames(comm_l) <- comms\n\n# remove the species with no record in the bird table\ncomm_l$bird <- comm_l$bird[,-which(colSums(comm_l$bird) == 0)]\n# divide herbivore by sampling effort\ncomm_l$herb <- cbind(comm_l$herb[,1], comm_l$herb[,-1] / plot_info$specrich)\n# remove genus level id in isopods\ncomm_l$isopods <- comm_l$isopods[,-ncol(comm_l$isopods)]\n\n########### Part 1: RDA per trophic group ###########\n\n# an helper function to run the RDA\n# arguments are:\n# @comm: a character, the name of the taxa\n# @interaction: a logical, whether the include an interaction term between species composition and fragmentation\n# @decostand: a logical, whether to hellinger-standardize the community data\n# @species: a character, the tree species in focus\n# @...: further argument to pass to the RDA, see ?rda\n\nfit_rda <- function(comm, interaction = TRUE, decostand = TRUE, species = \"qrob\",...){\n \n print(species)\n # grab the plot index for the focal tree species\n ids <- eval(as.name(paste0(\"id_\",species)))\n # if needed standardize\n if(decostand){\n comm <- decostand(comm, method = \"hellinger\", MARGIN = 1)\n }\n \n # compute PCNM\n rs <- rowSums(comm) / sum(comm) # the site weights\n pcnmw <- pcnm(dist(plot_xy[,c(\"X\", \"Y\")]), w = rs) # PCNM based on plot coordinates\n # add the PCNM scores to the dataset\n dat <- cbind(plot_info[,c(\"speccomb\", \"fragm_std\")], scores(pcnmw))\n # NA for opiliones, fix by putting PCNM to 0\n dat[is.na(dat)] <- 0\n # fit the RDA with or without interaction\n if(interaction){\n rr <- rda(comm[ids,] ~ . + speccomb : fragm_std, dat[ids,], ...)\n } else {\n rr <- rda(comm[ids,] ~ ., dat[ids,],...)\n }\n \n return(rr)\n}\n\n### fit the RDA\n## plot id for the specific tree composition changes\nid_qrob <- which(plot_info$speccomb %in% c(\"qrob\", \"fsyl_qrob\",\"qrob_qrub\", \"all\"))\nid_qrub <- which(plot_info$speccomb %in% c(\"qrub\", \"fsyl_qrub\",\"qrob_qrub\", \"all\"))\nid_fsyl <- which(plot_info$speccomb %in% c(\"fsyl\", \"fsyl_qrob\",\"fsyl_qrub\", \"all\"))\n## the different tree species code\nspp <- c(\"qrob\", \"qrub\", \"fsyl\")\n\n# go through the different communities\n# with interaction\nrda_l <- lapply(comm_l, function(comm) sapply(spp, function(sp) fit_rda(comm[,-1], interaction = TRUE, decostand = TRUE, species = sp), \n simplify = FALSE))\n### analyze the results\n## first table of effects\n# grab the RDA results for the Table\n## an helper function that grab p-values of the effects and R-square per taxa\neff_rda <- function(taxa = \"bird\"){\n rr <- rda_l[[taxa]]\n tmp <- ldply(rr, function(x) as.data.frame(anova(x, by = \"terms\", permutations = how(nperm = 9999))))\n tmp$terms <- rep(c(\"composition\", \"fragmentation\", paste0(\"P\", 1:14), \"interaction\", \"residual\"), 3)\n tmp <- filter(tmp, terms %in% c(\"composition\", \"fragmentation\", \"interaction\"))\n tmp$taxa <- taxa\n \n # add R2\n tmp2 <- ldply(rr, function(x) as.data.frame(RsquareAdj(x)$adj.r.squared))\n tmp2$terms <- \"R2\"\n names(tmp2)[2] <- names(tmp)[5]\n tmp2$taxa <- taxa\n \n tmp <- rbind(tmp2, tmp[,c(1,5,6,7)])\n \n return(tmp) \n}\n\n# apply to all taxa\ntabb <- rbind.fill(sapply(comms, function(sp) eff_rda(sp), simplify = FALSE))\n# some data wraggling\ntabb_w <- dcast(tabb, taxa ~ .id + terms, value.var = \"Pr(>F)\")\nxtable(tabb_w[c(1:3,8, 7,6,4:5,9),c(1,5,2,3,4,9,6,7,8, 13, 10:12)], digits = 3)\n\n## second, effect size of composition / fragmentation effects\n# per tree diversification pathways develop indices of tree composition changes\nchange_qrob <- c(\"qrob -> qrob_fsyl\", \"qrob -> qrob_qrub\",\n \"qrob_fsyl -> all\", \"qrob_qrub -> all\", \"qrob -> all\")\n\nchange_qrub <- c(\"qrub -> fsyl_qrub\", \"qrub -> qrob_qrub\",\n \"fsyl_qrub -> all\", \"qrob_qrub -> all\", \"qrub -> all\")\n\nchange_fsyl <- c(\"fsyl -> qrob_fsyl\", \"fsyl -> fsyl_qrub\",\n \"qrob_fsyl -> all\", \"fsyl_qrub -> all\", \"fsyl -> all\")\n\n# an helper function to get the distance between centroids of different tree composition\n# and also to get the distance of changes due to the fragmentation effect\n# the arguments are:\n# @rr: an object of class rda, the fitted RDA from vegan\n# @tree: a character, the focal tree species, like \"qrob\"\nget_length_rda <- function(rr, tree){\n # define the composition changes\n change_comp <- eval(as.name(paste0(\"change_\", tree)))\n # define the different composition\n change_fragm <- c(grep(tree, unique(plot_info$speccomb), value = TRUE), \"all\")\n # a new data frame to compute predicted shifts along the gradient of fragmentation\n newdat <- expand.grid(speccomb = change_fragm, fragm_std = c(-1.69, 2.42),\n PCNM1 = 0, PCNM2 = 0, PCNM3 = 0, PCNM4 = 0,\n PCNM5 = 0, PCNM6 = 0, PCNM7 = 0, PCNM8 = 0,\n PCNM9 = 0, PCNM10 = 0, PCNM11 = 0, PCNM12 = 0,\n PCNM13 = 0, PCNM14 = 0)\n # get the RDA centroid scores\n sc_cn <- scores(rr, choices = c(1,2), display = \"cn\", scaling = 0)\n # depeding on the focal tree compute the shifts in centroids\n if(tree == \"qrob\"){\n c1 <- dist(rbind(sc_cn[3,], sc_cn[2,]))\n c2 <- dist(rbind(sc_cn[3,], sc_cn[4,]))\n c3 <- dist(rbind(sc_cn[2,], sc_cn[1,]))\n c4 <- dist(rbind(sc_cn[4,], sc_cn[1,]))\n c5 <- dist(rbind(sc_cn[3,], sc_cn[1,]))\n }\n if(tree == \"qrub\"){\n c1 <- dist(rbind(sc_cn[4,], sc_cn[2,]))\n c2 <- dist(rbind(sc_cn[4,], sc_cn[3,]))\n c3 <- dist(rbind(sc_cn[2,], sc_cn[1,]))\n c4 <- dist(rbind(sc_cn[3,], sc_cn[1,]))\n c5 <- dist(rbind(sc_cn[4,], sc_cn[1,]))\n }\n if(tree == \"fsyl\"){\n c1 <- dist(rbind(sc_cn[2,], sc_cn[3,]))\n c2 <- dist(rbind(sc_cn[2,], sc_cn[4,]))\n c3 <- dist(rbind(sc_cn[3,], sc_cn[1,]))\n c4 <- dist(rbind(sc_cn[4,], sc_cn[1,]))\n c5 <- dist(rbind(sc_cn[2,], sc_cn[1,]))\n }\n # compute the shift along the fragmentation gradient\n sc_fragm <- predict(rr, newdata = newdat, type = \"lc\")\n fragm <- c(dist(sc_fragm[c(1, 5),1:2]), \n dist(sc_fragm[c(2, 6),1:2]),\n dist(sc_fragm[c(3, 7),1:2]),\n dist(sc_fragm[c(4, 8),1:2])) # if we do not restrict the dist to the first two axis we always get the same dist: 0.76\n \n data.frame(effect = rep(c(\"composition\", \"fragmentation\"), times = c(5, 4)), change = c(change_comp, change_fragm), length = c(c1, c2, c3, c4, c5, fragm))\n \n}\n\n# an helper function to compute the bootstrapped shifts\n# arguments are:\n# @dat: a data.frame or matrix, the community data\n# @id: internal argument for boot\n# @N: an integer, the number of species\n# @tree: a character, the focal tree species like \"qrob\"\nboot_rda <- function(dat, id, N, tree){\n # the community data\n comm <- dat[,1:N]\n # the predicotrs\n plot_info <- dat[,(N+1):ncol(dat)]\n # standardize the community\n comm <- decostand(comm[,-1], \"hellinger\", MARGIN = 1)\n # run the RDA with interaction\n rr <- rda(comm[id,] ~ speccomb * fragm_std, plot_info[id,])\n # grab the effect sizes\n out <- get_length_rda(rr, tree)\n return(out$length)\n}\n\n# an helper function combining the effect computation with the bootstrapped computation\n# the arguments are:\n# @taxa: a character, the name of the focal taxa like \"bird\"\n# @tree: a character, the name of the focal tree species like \"qrob\"\n# @R: an integer, the number of bootstrap samples\nget_length_df <- function(taxa = \"bird\", tree = \"qrob\", R = 10){\n print(taxa) # for debug purposes\n # grab the relevant RDA\n rr <- rda_l[[taxa]]\n # grab the relevant community matrix\n comm <- comm_l[[taxa]]\n # grab the plot index for the tree diversification pathways\n ids <- eval(as.name(paste0(\"id_\", tree)))\n # the species numer\n n_sp <- ncol(comm)\n # put together the community and the predictor data\n boot_dat <- cbind(comm[ids,], plot_info[ids,])\n # compute the effect size\n tab <- get_length_rda(rr[[tree]], tree)\n # compute the bootstrapped effect size\n bb <- boot(data = boot_dat, statistic = boot_rda, R = R, N = n_sp, tree = tree, strata = factor(boot_dat$speccomb))\n # the bootstrapped standard deviation\n tab$std_err <- apply(bb$t, 2, sd)\n \n return(tab)\n}\n\n# run this for all taxa and trees\nc_rob <- rbind.fill(sapply(comms, function(taxa) get_length_df(taxa = taxa, tree = \"qrob\", R = 10000), simplify = FALSE))\nc_rub <- rbind.fill(sapply(comms, function(taxa) get_length_df(taxa = taxa, tree = \"qrub\", R = 10000), simplify = FALSE))\nc_syl <- rbind.fill(sapply(comms, function(taxa) get_length_df(taxa = taxa, tree = \"fsyl\", R = 10000), simplify = FALSE))\n# put everything together\nc_all <- rbind(c_rob, c_rub, c_syl)\n# some re-naming for the plots\nc_all$tree <- rep(c(\"qrob\", \"qrub\", \"fsyl\"), each = 81)\nc_all$taxa <- rep(comms, each = 9)\nc_all$taxa[c_all$taxa==\"herb\"] <- \"herbivore\"\nc_all$taxa <- factor(c_all$taxa, \n levels = c(comms[1:7], \"herbivore\", \"vegetation\"))\nc_all$change <- factor(c_all$change, levels = c(change_qrob[1:2], change_qrub[1:2], change_fsyl[1:2], change_qrob[3:4], change_qrub[3], change_qrob[5], change_qrub[5], change_fsyl[5], \"qrob\", \"fsyl\", \"qrub\", \"fsyl_qrob\", \"fsyl_qrub\", \"qrob_qrub\", \"all\"))\n\n# first plot on the fragmentation effect\nc_fragm <- subset(c_all, effect == \"fragmentation\")\n# the position of the bars in the graph\nc_fragm$X <- c(rep(c(3, 2, 1, 4), 9), rep(c(8, 7, 6, 9), 9), rep(c(11, 12, 13, 14), 9))\n\n# compute the average per taxa and div paths\nc_fragm %>%\n group_by(taxa, tree) %>%\n summarise(avg = mean(length)) -> avg_eff\n# end of the dotted average line on the graphs\navg_eff$x_start <- rep(c(10.5, 0.5, 5.5), times = 9)\navg_eff$x_end <- rep(c(14.5, 4.5, 9.5), times = 9)\n\n# nicer name for the facets\nfacet_n <- c(\"bird\" = \"birds\", \"bat\" = \"bats\", \"spider\" = \"spiders\",\n \"opiliones\" = \"harvestmen\", \"carabid\" = \"carabids\",\n \"isopods\" = \"woodlice\", \"diplopod\" = \"millipedes\",\n \"herbivore\" = \"herbivores\", \"vegetation\" = \"vegetation\")\n\n# the plot\ngg_f <- ggplot(c_fragm,aes(x=X, y=length, color=tree))+\n geom_bar(stat = \"identity\", fill = \"white\")+\n geom_linerange(aes(ymin=length, ymax = length + 2 * std_err))+\n scale_x_continuous(breaks = c(1:4, 6:9, 11:14), labels = c(\"qrob\", \"fsyl_qrob\", \"qrob_qrub\", \"all\", \n \"qrub\", \"fsyl_qrub\", \"qrob_qrub\", \"all\",\n \"fsyl\", \"fsyl_qrub\", \"fsyl_qrob\", \"all\")) +\n facet_wrap(~taxa, labeller = as_labeller(facet_n)) +\n geom_segment(data = avg_eff, aes(x = x_start, xend = x_end, y = avg, yend = avg),\n size = 1, linetype = \"dashed\") +\n labs(x = \"Diversification pathway\",\n y = \"Strength of fragmentation effect (95% bootstraped CI)\"\n ) +\n theme(legend.position = \"none\", axis.text.x = element_text(angle = 90))\n\nggsave(\"figures/fragmentation_rda.png\", gg_f, width = 22.77,\n height = 14.71, units = \"cm\")\n\n# now the compositional change in a similar graph\nc_comp <- subset(c_all, effect == \"composition\")\nc_comp$X <- c(rep(1:5, 9), rep(7:11, 9), rep(13:17, 9))\n\ngg_c <- ggplot(subset(c_comp, change != \"fragmentation\"), \n aes(x=X, y=length, group = paste0(change, tree), color = tree)) +\n geom_bar(stat = \"identity\", position = position_dodge(width = 0.9), fill = \"white\")+\n geom_linerange(aes(ymin=length, ymax = length + 2* std_err), position = position_dodge(width = 0.9))+\n facet_wrap(~taxa, labeller = as_labeller(facet_n)) + \n theme(axis.text.x = element_text(angle = 45, hjust = 0.9), \n legend.position = \"none\") +\n scale_x_continuous(breaks= c(1:5, 7:11, 13:17), labels = subset(c_comp, taxa == \"bird\")$change) +\n labs(x = \"Diversification pathway\",\n y = \"Strength of diversification effect (95% bootstraped CI)\")\n\nggsave(\"figures/composition_rda.png\", gg_c, width = 22.77,\n height = 14.71, units = \"cm\")\n\n########### Part 2: compositional turnover across groups, using upset graphs #####\n\n# an helper function formatting the comminty data and outputting the desired plots\nupset_comm <- function(comm){\n \n if(names(comm)[1] != \"id_plot\"){\n names(comm)[1]<- \"id_plot\"\n }\n \n #format the community\n comm %>%\n pivot_longer(cols = 2:ncol(comm), names_to = \"species\", values_to = \"abundance\") %>%\n #rename(id_plot = plot) %>%\n left_join(plot_info, by = \"id_plot\") %>%\n group_by(speccomb, species) %>%\n summarise(Present = sum(abundance, na.rm = TRUE)) %>%\n mutate(Present = ifelse(Present > 0, 1, 0)) %>%\n pivot_wider(names_from = speccomb, values_from = Present) -> comm_dd\n \n comm_dd <- as.data.frame(comm_dd)\n # one plot per diversification pathways\n u_rob <- upset(comm_dd, sets = c(\"qrob\", \"fsyl_qrob\", \"qrob_qrub\", \"all\"), order.by = \"freq\",\n mainbar.y.label = \"Number of (shared) species\", sets.x.label = \"Total species\\nnumber\",\n main.bar.color=\"#1b9e77\", matrix.color=\"#1b9e77\",\n sets.bar.color=\"#d95f02\")\n \n \n u_robc <- cowplot::plot_grid(NULL, u_rob$Main_bar, u_rob$Sizes, u_rob$Matrix,\n nrow=2, align='hv', rel_heights = c(3,1),\n rel_widths = c(2,3))\n \n u_rub <- upset(comm_dd, sets = c(\"qrub\", \"fsyl_qrub\", \"qrob_qrub\", \"all\"), order.by = \"freq\",\n mainbar.y.label = \"Number of (shared) species\", sets.x.label = \"Total species\\nnumber\",\n main.bar.color=\"#1b9e77\", matrix.color=\"#1b9e77\",\n sets.bar.color=\"#d95f02\")\n \n \n u_rubc <- cowplot::plot_grid(NULL, u_rub$Main_bar, u_rub$Sizes, u_rub$Matrix,\n nrow=2, align='hv', rel_heights = c(3,1),\n rel_widths = c(2,3))\n \n u_syl <- upset(comm_dd, sets = c(\"fsyl\", \"fsyl_qrub\", \"fsyl_qrob\", \"all\"), order.by = \"freq\",\n mainbar.y.label = \"Number of (shared) species\", sets.x.label = \"Total species\\nnumber\",\n main.bar.color=\"#1b9e77\", matrix.color=\"#1b9e77\",\n sets.bar.color=\"#d95f02\")\n \n \n u_sylc <- cowplot::plot_grid(NULL, u_syl$Main_bar, u_syl$Sizes, u_syl$Matrix,\n nrow=2, align='hv', rel_heights = c(3,1),\n rel_widths = c(2,3))\n \n \n gga <- grid.arrange(u_robc, u_rubc, u_sylc, ncol = 3)\n \n \n return(gga)\n}\n\n# run this for all taxa\nggsave(\"figures/upset_bird.png\", upset_comm(comm_l$bird), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_bat.png\", upset_comm(comm_l$bat), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_carabid.png\", upset_comm(comm_l$carabid), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_spider.png\", upset_comm(comm_l$spider), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_isopod.png\", upset_comm(comm_l$isopods), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_diplopod.png\", upset_comm(comm_l$diplopod), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_herbivore.png\", upset_comm(comm_l$herb), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_vegetation.png\", upset_comm(comm_l$vegetation), width = 11, height = 5, units = \"in\")\nggsave(\"figures/upset_opiliones.png\", upset_comm(comm_l$opiliones), width = 11, height = 5, units = \"in\")\n\n\n########### Part 3: testing additional community webs ########\n\n# an helper function to run the mcoa\n# the arguments are:\n# @web: a character, the web of interaction to quantify like \"bird_bat_spider\"\n# @nf: an integer, the number of axis to keep\n# @option: a character, the weighing used, see ?mcoa for the different options\n# @std: a logical, whether to hellinger-standardize the data\nmcoa_run <- function(web, nf = 2, option = \"inertia\", std = TRUE){\n comm_name <- strsplit(web, \"_\")[[1]]\n \n comms <- lapply(comm_name, function(x) comm_l[[x]])\n \n if(std){\n comms <- lapply(comms, function(comm) decostand(comm[,-1], \"hellinger\"))\n }\n \n # grab number of columns\n nb_col <- sapply(comms, function(x) ncol(x))\n \n # put all together\n comms_all <- do.call(cbind, comms)\n # create ktab object\n kt <- ktab.data.frame(comms_all, nb_col,\n tabnames = comm_name)\n \n # run mcoa\n m <- mcoa(kt, option = option, nf = nf, scannf = FALSE)\n \n return(m)\n}\n\n##full web of interaction: all groups:\nweb_2 <- \"bird_bat_spider_opiliones_carabid_isopods_diplopod_herb_vegetation\"\nn_taxa <- 9\nm_2 <- mcoa_run(web_2)\n\n## compute the distance of each group from the plot synthetic scores\nplot_info$x <- plot_xy$X\nplot_info$y <- plot_xy$Y\nvhb_xy <- m_2$Tl1\nvhb_xy$id_plot <- rep(1:53, n_taxa)\nvhb_xy$ref_x <- m_2$SynVar[rep(1:53, n_taxa),1]\nvhb_xy$ref_y <- m_2$SynVar[rep(1:53, n_taxa),2]\nvhb_xy$d <- with(vhb_xy, sqrt((Axis1-ref_x) ** 2 + (Axis2-ref_y) ** 2))\nvhb_xy %>%\n group_by(id_plot) %>%\n summarise(d = sum(d)) %>%\n left_join(plot_info[,c(1,13,14,15, 16, 17)], by = \"id_plot\") -> vhb_dd\n\n# fit a glm to this\nm_vhb <- glm(d ~ fragm_std * speccomb, vhb_dd, family = Gamma(link=\"log\"), contrasts = list(speccomb = \"contr.sum\"))\n\n## look at residuals\nss <- simulateResiduals(m_vhb)\nplot(ss) # good\ntestSpatialAutocorrelation(ss, x = plot_info$x, y = plot_info$y) # no spatial autocorrelation\n\n## anova\nanova(m_vhb, test = \"Chisq\") # species composition effect\n\n## make plot of predicted distance for the different tree composition\n### a new data frame to derive the model predictions\nnewdat <- expand.grid(speccomb = unique(plot_info$speccomb), fragm_std = 0)\n\n# augment per diversification path\nnewdat2 <- newdat[c(2, 5, 3, 4, 7, 5, 1, 4, 6, 3, 1, 4),]\nnewdat2$tree <- rep(c(\"fsyl\", \"qrob\", \"qrub\"), each = 4)\n# compute the model predictions\nnewdat2$pred <- predict(m_vhb, newdata = newdat2, type = \"response\")\nnewdat2$se <- predict(m_vhb, newdata = newdat2, type = \"response\", se.fit = TRUE)$se.fit\n\n# some refinments for ordering the species somposition as we want them\nnewdat2$speccomb <- factor(newdat2$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\nvhb_dd$speccomb <- factor(vhb_dd$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\n\n# the plots\ngg_syl <- ggplot(subset(vhb_dd, speccomb %in% c(\"fsyl\", \"fsyl_qrob\", \"fsyl_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"beech\", \"beech +\\nped. oak\", \"beech +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(a)\") +\n ylim(c(3.8, 10.1))\n\ngg_rob <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrob\", \"fsyl_qrob\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrob\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrob\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"ped. oak\", \"beech +\\nped. oak\", \"ped. oak +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(b)\") +\n ylim(c(3.8, 10.1))\n\ngg_rub <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrub\", \"fsyl_qrub\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrub\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrub\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n labs(x = \"\", y = \"\", title = \"(c)\") +\n scale_x_discrete(labels = c(\"red oak\", \"beech +\\nred oak\", \"ped. oak +\\nred oak\", \"all\")) +\n ylim(c(3.8, 10.1))\n\n\ngg_all <- grid.arrange(gg_syl, gg_rob, gg_rub, nrow = 3, bottom = \"Tree species composition\", left = \"Community distance\")\n\nggsave(\"figures/mcoa_composition_web2.png\", gg_all, width = 4, height = 8)\n\n\n## now only vegetation - bird - carabid - spider\nweb_3 <- \"bird_carabid_spider_vegetation\"\nn_taxa <- 4\nm_3 <- mcoa_run(web_3)\n\n## compute the distance of each group from the plot synthetic scores\nplot_info$x <- plot_xy$X\nplot_info$y <- plot_xy$Y\nvhb_xy <- m_3$Tl1\nvhb_xy$id_plot <- rep(1:53, n_taxa)\nvhb_xy$ref_x <- m_3$SynVar[rep(1:53, n_taxa),1]\nvhb_xy$ref_y <- m_3$SynVar[rep(1:53, n_taxa),2]\nvhb_xy$d <- with(vhb_xy, sqrt((Axis1-ref_x) ** 2 + (Axis2-ref_y) ** 2))\nvhb_xy %>%\n group_by(id_plot) %>%\n summarise(d = sum(d)) %>%\n left_join(plot_info[,c(1,13,14,15, 16, 17)], by = \"id_plot\") -> vhb_dd\n\n# fit a glm to this\nm_vhb <- glm(d ~ fragm_std * speccomb, vhb_dd, family = Gamma(link=\"log\"), contrasts = list(speccomb = \"contr.sum\"))\n\n## look at residuals\nss <- simulateResiduals(m_vhb)\nplot(ss) # good\ntestSpatialAutocorrelation(ss, x = plot_info$x, y = plot_info$y) # no spatial autocorrelation\n\n## anova\nanova(m_vhb, test = \"Chisq\") # species composition effect\n\n## make plot of predicted distance for the different tree composition\n### a new data frame to derive the model predictions\nnewdat <- expand.grid(speccomb = unique(plot_info$speccomb), fragm_std = 0)\n\n# augment per diversification path\nnewdat2 <- newdat[c(2, 5, 3, 4, 7, 5, 1, 4, 6, 3, 1, 4),]\nnewdat2$tree <- rep(c(\"fsyl\", \"qrob\", \"qrub\"), each = 4)\n# compute the model predictions\nnewdat2$pred <- predict(m_vhb, newdata = newdat2, type = \"response\")\nnewdat2$se <- predict(m_vhb, newdata = newdat2, type = \"response\", se.fit = TRUE)$se.fit\n\n# some refinments for ordering the species somposition as we want them\nnewdat2$speccomb <- factor(newdat2$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\nvhb_dd$speccomb <- factor(vhb_dd$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\n\n# the plots\ngg_syl <- ggplot(subset(vhb_dd, speccomb %in% c(\"fsyl\", \"fsyl_qrob\", \"fsyl_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"beech\", \"beech +\\nped. oak\", \"beech +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(a)\") +\n ylim(c(0.5, 5.2))\n\ngg_rob <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrob\", \"fsyl_qrob\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrob\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrob\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"ped. oak\", \"beech +\\nped. oak\", \"ped. oak +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(b)\") +\n ylim(c(0.5, 5.2))\n\ngg_rub <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrub\", \"fsyl_qrub\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrub\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrub\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n labs(x = \"\", y = \"\", title = \"(c)\") +\n scale_x_discrete(labels = c(\"red oak\", \"beech +\\nred oak\", \"ped. oak +\\nred oak\", \"all\")) +\n ylim(c(0.5, 5.2))\n\n\ngg_all <- grid.arrange(gg_syl, gg_rob, gg_rub, nrow = 3, bottom = \"Tree species composition\", left = \"Community distance\")\n\nggsave(\"figures/mcoa_composition_web3.png\", gg_all, width = 4, height = 8)\n\n##### Part 4: Co-inertia analysis with new groupings ######\n\n# define 5 groups, herbivores, primary producers, predators, detritivores and omnivores\ncomm_l$primary <- comm_l$vegetation\ncomm_l$herbivore <- comm_l$herb\ncomm_l$detritivore <- cbind(comm_l$isopods, comm_l$diplopod[,-1])\ncomm_l$omnivore <- cbind(comm_l$carabid, comm_l$opiliones[,-1], comm_l$bird[,-1])\ncomm_l$predator <- cbind(comm_l$bat, comm_l$spider[,-1])\n\n# all potential pairs of communities\ncomms2 <- c(\"primary\", \"herbivore\", \"detritivore\", \"omnivore\", \"predator\")\npairs2 <- outer(comms2, comms2, paste, sep = \"_\")\npairs_u2 <- pairs2[upper.tri(pairs2)]\n\n# define the trophic levels\ntl2 <- data.frame(taxa = comms2,\n tl = c(1, 2, 2, 3, 4))\n\n# put all pairs in a data frame together with their trophic distance\npairs_d2 <- data.frame(pairs = pairs_u2, stringsAsFactors = FALSE)\npairs_d2 <- separate(pairs_d2, \"pairs\", c(\"from\", \"to\"), sep = \"_\", remove = FALSE)\n\npairs_d2 <- merge(pairs_d2, tl2, by.x = \"from\", by.y = \"taxa\", sort = FALSE)\npairs_d2 <- merge(pairs_d2, tl2, by.x = \"to\", by.y = \"taxa\", sort=FALSE)\npairs_d2$dist <- with(pairs_d2, sqrt((tl.x - tl.y)**2))\n\n\n## get percent explained variation of the first two axis in the coinertia\ntt2 <- sapply(pairs_u2, function(x) get_percent_explained(x))\n\n# RV value between each comms\nrv_all2 <- sapply(pairs_u2, function(x) get_coia_rv(x, nrepet = 9999), simplify = FALSE) # this can take time to run depending on the number of repetitions\n# some data wraggling to put te results in a plotable format\nrv_all2 <- rbind.fill(rv_all2)\nrv_all2$pair <- pairs_u2\nrv_all2 <- merge(rv_all2, pairs_d2, by.x = \"pair\", by.y = \"pairs\")\nrv_all2 <- arrange(rv_all2, dist, pair)\n\n# plot\nrv_all2 <- unite(rv_all2, \"pair\", c(to, from), sep =\":\")\nrv_all2$pair <- factor(rv_all2$pair)\nrv_all2$x <- 1:10\n\n# the plot (figure X in the manuscript)\ngg_rv2 <- ggplot(rv_all2, aes(x=x, y=rv, fill=col)) +\n geom_bar(stat = \"identity\", width = 0.75) +\n scale_fill_brewer(type = \"qual\",palette = \"Set1\",\n labels = c(\"no sig. relation\", \"sig. relation\"),\n name = \"RV permutation\\ntest:\") +\n scale_x_continuous(breaks = 1:10, labels = rv_all2$pair, expand = c(0, 0)) +\n scale_y_continuous(limits = c(0, 0.6), expand = c(0, 0)) +\n coord_flip() +\n theme(axis.text.x = element_text(hjust = 0),\n axis.text.y = element_text(vjust = 0.25)) +\n labs(x = \"Pairwise community comparison\",\n y = \"RV value\") +\n theme_bw()\n\nggsave(\"figures/coin_rv_feeding.png\", gg_rv2)\n\n\n# multiple COIA\n\n## first web of interaction: all groups except for the bats:\nweb_1 <- \"primary_herbivore_detritivore_omnivore_predator\"\nm_1 <- mcoa_run(web_1)\n\n## compute the distance of each group from the plot synthetic scores\nplot_info$x <- plot_xy$X\nplot_info$y <- plot_xy$Y\nvhb_xy <- m_1$Tl1\nvhb_xy$id_plot <- rep(1:53, length(web_1))\nvhb_xy$ref_x <- m_1$SynVar[rep(1:53, length(web_1)),1]\nvhb_xy$ref_y <- m_1$SynVar[rep(1:53, length(web_1)),2]\nvhb_xy$d <- with(vhb_xy, sqrt((Axis1-ref_x) ** 2 + (Axis2-ref_y) ** 2))\nvhb_xy %>%\n group_by(id_plot) %>%\n summarise(d = sum(d)) %>%\n left_join(plot_info[,c(1,13,14,15, 16, 17)], by = \"id_plot\") -> vhb_dd\n\n# fit a glm to this\nm_vhb <- glm(d ~ fragm_std * speccomb, vhb_dd, family = Gamma(link=\"log\"), contrasts = list(speccomb = \"contr.sum\"))\n\n## look at residuals\nss <- simulateResiduals(m_vhb)\nplot(ss) # good\ntestSpatialAutocorrelation(ss, x = plot_info$x, y = plot_info$y) # no spatial autocorrelation\n\n## anova\nanova(m_vhb, test = \"Chisq\")\n## the plot of composition effects\nnewdat <- expand.grid(speccomb = unique(plot_info$speccomb), fragm_std = 0)\n\n# augment per diversification path\nnewdat2 <- newdat[c(2, 5, 3, 4, 7, 5, 1, 4, 6, 3, 1, 4),]\nnewdat2$tree <- rep(c(\"fsyl\", \"qrob\", \"qrub\"), each = 4)\n# compute the model predictions\nnewdat2$pred <- predict(m_vhb, newdata = newdat2, type = \"response\")\nnewdat2$se <- predict(m_vhb, newdata = newdat2, type = \"response\", se.fit = TRUE)$se.fit\n\n# some refinments for ordering the species somposition as we want them\nnewdat2$speccomb <- factor(newdat2$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\nvhb_dd$speccomb <- factor(vhb_dd$speccomb, levels = c(\"fsyl\",\"qrob\",\"qrub\",\"fsyl_qrob\",\"fsyl_qrub\",\"qrob_qrub\",\"all\"))\n\n# the plots\ngg_syl <- ggplot(subset(vhb_dd, speccomb %in% c(\"fsyl\", \"fsyl_qrob\", \"fsyl_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"fsyl\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"beech\", \"beech +\\nped. oak\", \"beech +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(a)\") +\n ylim(c(1.6, 6.2))\n\ngg_rob <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrob\", \"fsyl_qrob\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrob\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrob\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n scale_x_discrete(labels = c(\"ped. oak\", \"beech +\\nped. oak\", \"ped. oak +\\nred oak\", \"all\")) +\n labs(x = \"\", y = \"\", title = \"(b)\") +\n ylim(c(1.6, 6.2))\n\ngg_rub <- ggplot(subset(vhb_dd, speccomb %in% c(\"qrub\", \"fsyl_qrub\", \"qrob_qrub\", \"all\"))) +\n geom_jitter(aes(x=speccomb, y = d), width = 0.1) +\n geom_point(data=subset(newdat2, tree == \"qrub\"), aes(x=speccomb, y=pred), color=\"red\", size = 2.5) +\n geom_linerange(data = subset(newdat2, tree == \"qrub\"), aes(x=speccomb, ymin = pred-2*se, ymax=pred+2*se), color=\"red\") +\n geom_hline(yintercept = exp(coef(m_vhb)[1]), linetype = \"dashed\", color = \"red\") +\n labs(x = \"\", y = \"\", title = \"(c)\") +\n scale_x_discrete(labels = c(\"red oak\", \"beech +\\nred oak\", \"ped. oak +\\nred oak\", \"all\")) +\n ylim(c(1.6, 6.2))\n\n\ngg_all <- grid.arrange(gg_syl, gg_rob, gg_rub, nrow = 3, bottom = \"Tree species composition\", left = \"Community distance\")\n\nggsave(\"figures/mcoa_composition_feeding.png\", gg_all, width = 4, height = 8)\n\n##### Part 5: Fourth corner analysis #######\n\n# explore trait-environment relation via a fourth corner analysis\n# load traits data\nff <- list.files(\"data/\", pattern = \"_trait\")\ntraits_l <- lapply(ff, function(x) read.csv(paste0(\"data/\", x)))\nnames(traits_l) <- gsub(\"_traits.csv\", \"\", ff)\n\n# some refinments, per taxa especiallymaking sure that species order is the\n# same between the trait table and the community matrix\ntraits_l$bat$body_size <- with(traits_l$bat, (body_size_min + body_size_max) / 2)\ntraits_l$bat$forest_affinity <- factor(traits_l$bat$forest_affinity)\ntraits_l$bat <- traits_l$bat[,c(1, 5, 4)]\ntraits_l$bird$forest_affinity <- factor(traits_l$bird$forest_affinity)\ntraits_l$bird <- traits_l$bird[traits_l$bird$species %in%colnames(comm_l$bird),]\ntraits_l$carabid <- traits_l$carabid[order(traits_l$carabid$species),]\ntraits_l$carabid$dispersal <- factor(traits_l$carabid$dispersal)\ncomm_l$carabid <- comm_l$carabid[,c(1, order(colnames(comm_l$carabid[,-1])) + 1)]\ncomm_l$spider <- comm_l$spider[,c(1, order(colnames(comm_l$spider[,-1])) + 1)]\ntraits_l$diplopod <- traits_l$diplopod[order(traits_l$diplopod$species),]\ntraits_l$diplopod$forest_affinity <- factor(traits_l$diplopod$forest_affinity)\ncomm_l$diplopod <- comm_l$diplopod[,c(1, order(colnames(comm_l$diplopod[,-1])) + 1)]\ntraits_l$vegetation <- traits_l$vegetation[which(!is.na(traits_l$vegetation$height) & traits_l$vegetation$forest_affinity != \"\"),]\nfor(i in 2:ncol(comm_l$vegetation)){\n colnames(comm_l$vegetation)[i] <- as.character(tt_d$species_scientific[colnames(comm_l$vegetation)[i] == tt_d$n])\n}\ncomm_l$vegetation <- comm_l$vegetation[,c(1, order(colnames(comm_l$vegetation[,-1])) + 1)]\ncomm_l$vegetation <- comm_l$vegetation[,c(1, which(colnames(comm_l$vegetation) %in% traits_l$vegetation$species))]\nnames(comm_l)[6] <- \"isopod\"\n\n## an helper function\ndo_fourthcorner <- function(comm, ...){\n spe <- comm_l[[comm]][,-1]\n \n trait <- traits_l[[comm]][,2:3]\n \n envs <- plot_info[,c(\"speccomb\", \"fragm_std\")]\n envs$speccomb <- factor(envs$speccomb)\n \n four <- fourthcorner(envs, spe, trait, ...)\n \n cat(paste0(comm, \" is done!\\n\"))\n \n return(four)\n}\n\n\nfourth_l <- lapply(names(traits_l), function(comm) do_fourthcorner(comm,\n modeltype = 6,\n nrepet = 9999))\npng(\"figures/fourth_corner.png\", width = 800, height = 800)\npar(mfrow = c(3, 3))\nfor(i in 1:8){\n plot(fourth_l[[i]])\n mtext(names(traits_l)[i], line = 2, adj = 0)\n}\ndev.off()\n\n############ Part 6: compute sample coverage and diversity metrics\n\n# compute sample coverage\nlibrary(iNEXT)\n\nget_coverage <- function(comm){\n \n cc <- comm_l[[comm]]\n # remove plot id\n cc <- cc[,-1]\n # remove plots with no species\n cc <- cc[rowSums(cc) > 0,]\n # remove plots with only one species\n cc <- cc[apply(cc, 1, function(x) sum(x > 0)) != 1,]\n \n # get iNext\n ii <- iNEXT(t(cc), q = 0, datatype = \"abundance\", knots = 2)\n \n return(mean(ii$DataInfo$SC))\n \n}\n\nlapply(comms[-c(2, 9)], function(x) get_coverage(x))\n\n\n# get plot of tightness vs diversity\nlibrary(tidyr)\nget_div <- function(x){\n \n rich <- sum(x > 0, na.rm = TRUE)\n p <- x / sum(x, na.rm = TRUE)\n sha <- exp(- sum(p * log(p), na.rm = TRUE))\n simp <- 1 / sum(p ** 2)\n \n out <- data.frame(rich = rich, sha = sha, simp = simp)\n \n return(out)\n}\n\n\ndd <- ldply(comm_l, function(x) {\n out <- adply(x, 1, get_div, .expand = FALSE)\n})\n\ndd %>%\n pivot_longer(3:5, names_to = \"index\") %>%\n rename(id_plot = X1) %>%\n left_join(vhb_dd[,1:2]) -> dd_d\n\nggplot(dd_d, aes(x=d, y=value)) +\n stat_smooth(method = \"lm\", se = FALSE) +\n geom_point() +\n facet_grid(.id ~ index) \n\ndd_d %>%\n group_by(.id, index) %>%\n summarise(R = cor(value, d)) %>%\n arrange(desc(R)) -> cc\n\n\n", "meta": {"hexsha": "75cd419bab8f269c194b288f06e938536cac69c8", "size": 34799, "ext": "r", "lang": "R", "max_stars_repo_path": "script/si_analysis.r", "max_stars_repo_name": "TerrestrialEcology-ugent/treeweb_community", "max_stars_repo_head_hexsha": "52d642997d743fc33c575230d66259bf8afe1606", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/si_analysis.r", "max_issues_repo_name": "TerrestrialEcology-ugent/treeweb_community", "max_issues_repo_head_hexsha": "52d642997d743fc33c575230d66259bf8afe1606", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/si_analysis.r", "max_forks_repo_name": "TerrestrialEcology-ugent/treeweb_community", "max_forks_repo_head_hexsha": "52d642997d743fc33c575230d66259bf8afe1606", "max_forks_repo_licenses": ["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.2285714286, "max_line_length": 254, "alphanum_fraction": 0.6442713871, "num_tokens": 11772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290152, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2752225465621391}} {"text": "#CIEISP 2007\n#http://www.pfp.gob.mx/portalWebApp/ShowBinary?nodeId=/BEA%20Repository/368010//archivo\n\n#CIESIP 2006\n#http://www.ssp.gob.mx/portalWebApp/ShowBinary?nodeId=/BEA%20Repository/368009//archivo\n\n#CIEISP 2005\n#http://www.ssp.gob.mx/portalWebApp/ShowBinary?nodeId=/BEA%20Repository/368008//archivo\n\nm07 <- c(44, 33, 61, 50, 41, 40, 51, 38, 42, 47, 38, 42)\nm06 <- c(47, 36, 40, 46, 55, 44, 55, 88, 58, 65, 60, 67)\nm05 <- c(33, 37, 40, 35, 38, 32, 39, 22, 34, 37, 39, 41)\n\nsource(\"library/utilities.r\")\nsource(\"timelines/constants.r\")\nhom <- read.csv(bzfile(\"timelines/data/county-month-gue-oax.csv.bz2\"))\nhom <- cleanHom(hom)\nhom$County <- factor(cleanNames(hom, \"County\"))\nhom <- subset(hom, County == \"Michoacán\" &\n Year.of.Murder >= 2005 &\n Year.of.Murder <= 2007)\n\nmich.hom <- data.frame(tot = c(m05,m06,m07, hom$Total.Murders),\n type = rep(c(\"SNSP\", \"INEGI\"), each=12*3),\n month = rep(1:12),\n year = rep(2005:2007, each = 12))\nmich.hom$Date <- as.Date(paste(mich.hom$year, mich.hom$month, \"15\"),\n \"%Y%m%d\")\n\nCairo(file = \"CIEISP/output/michoacan.png\", width=700, height=400)\nprint(ggplot(mich.hom, aes(as.Date(Date), tot, group = type,\n color = type)) +\n geom_line(size = 1.2) +\n scale_x_date() +\n xlab(\"\") + ylab(\"Monthly number of homicides\") +\n opts(title=\"Differences in homicides in Michoacan\") +\n geom_vline(aes(xintercept = op.mich), alpha = .7) +\n annotate(\"text\", x = op.mich, y = 20, hjust = 1.01, vjust = 0,\n label=\"Joint Operation Michoacan\", ))\ndev.off()\n", "meta": {"hexsha": "c3502d9c0ce2051d0b75df408ad56d4cbbe9062b", "size": 1622, "ext": "r", "lang": "R", "max_stars_repo_path": "CIEISP/michoacan.r", "max_stars_repo_name": "diegovalle/Homicide-MX-Drug-War", "max_stars_repo_head_hexsha": "6b1a5257420c4d444324672503c03237c4fca543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2015-05-14T01:06:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T12:52:10.000Z", "max_issues_repo_path": "CIEISP/michoacan.r", "max_issues_repo_name": "diegovalle/Homicide-MX-Drug-War", "max_issues_repo_head_hexsha": "6b1a5257420c4d444324672503c03237c4fca543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CIEISP/michoacan.r", "max_forks_repo_name": "diegovalle/Homicide-MX-Drug-War", "max_forks_repo_head_hexsha": "6b1a5257420c4d444324672503c03237c4fca543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2015-02-05T15:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T02:19:40.000Z", "avg_line_length": 39.5609756098, "max_line_length": 87, "alphanum_fraction": 0.6115906289, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.2752225396311443}} {"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#' To perform GWAS with GLM and MLM model and get the P value of SNPs\n#'\n#' Build date: Aug 30, 2016\n#' Last update: Aug 30, 2016\n#' \n#' @author Lilin Yin and Xiaolei Liu\n#' \n#' @param phe phenotype, n * 2 matrix\n#' @param geno genotype, m * n, m is marker size, n is population size\n#' @param K Kinship, Covariance matrix(n * n) for random effects; must be positive semi-definite\n#' @param eigenK list of eigen Kinship\n#' @param CV covariates\n#' @param REML a list that contains ve and vg\n#' @param cpu number of cpus used for parallel computation\n#' @param vc.method the methods for estimating variance component(\"emma\" or \"he\" or \"brent\")\n#' @param verbose whether to print detail.\n#' \n#' @return\n#' results: a m * 2 matrix, the first column is the SNP effect, the second column is the P values\n#' @export\n#'\n#' @examples\n#' phePath <- system.file(\"extdata\", \"07_other\", \"mvp.phe\", package = \"rMVP\")\n#' phenotype <- read.table(phePath, header=TRUE)\n#' idx <- !is.na(phenotype[, 2])\n#' idx <- !is.na(phenotype[, 2])\n#' phenotype <- phenotype[idx, ]\n#' print(dim(phenotype))\n#' genoPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.desc\", package = \"rMVP\")\n#' genotype <- attach.big.matrix(genoPath)\n#' genotype <- deepcopy(genotype, cols=idx)\n#' print(dim(genotype))\n#' K <- MVP.K.VanRaden(genotype)\n#' \n#' mlm <- MVP.MLM(phe=phenotype, geno=genotype, K=K)\n#' str(mlm)\n#' \n\nMVP.MLM <-\nfunction(\n phe, \n geno, \n K=NULL,\n eigenK=NULL,\n CV=NULL, \n REML=NULL,\n cpu=1,\n vc.method=c(\"BRENT\", \"EMMA\", \"HE\"),\n verbose=TRUE\n){\n # R.ver <- Sys.info()[['sysname']]\n # r.open <- eval(parse(text = \"!inherits(try(Revo.version,silent=TRUE),'try-error')\"))\n \n # if (R.ver == 'Windows') cpu <- 1\n # if (r.open && cpu > 1 && R.ver == 'Darwin') {\n # Sys.setenv(\"VECLIB_MAXIMUM_THREADS\" = \"1\")\n # }\n\n vc.method <- match.arg(vc.method)\n n <- ncol(geno)\n m <- nrow(geno)\n ys <- as.numeric(as.matrix(phe[,2]))\n\n if(!is.big.matrix(geno)) stop(\"genotype should be in 'big.matrix' format.\")\n if(sum(is.na(ys)) != 0) stop(\"NAs are not allowed in phenotype.\")\n if(nrow(phe) != ncol(geno)) stop(\"number of individuals not match in phenotype and genotype.\")\n \n if(is.null(K)){\n if(vc.method == \"EMMA\" | vc.method == \"he\") stop(\"Kinship must be provided!\")\n if(vc.method == \"BRENT\"){\n if(is.null(eigenK)) stop(\"eigenK must be provided!\")\n }\n }else{\n # convert K to base:matrix\n K <- K[, ]\n if(is.null(eigenK)){\n logging.log(\"Eigen Decomposition on GRM\", \"\\n\", verbose = verbose)\n eigenK <- eigen(K, symmetric=TRUE)\n }\n }\n\n if (is.null(CV)) {\n X0 <- matrix(1, n)\n } else {\n CV.index <- apply(CV, 2, function(x) length(table(x)) > 1)\n CV <- CV[, CV.index, drop=FALSE]\n X0 <- cbind(matrix(1, n), CV)\n }\n X0 <- as.matrix(X0)\n\n if(is.null(REML)) {\n logging.log(paste(\"Variance components using: \", vc.method, sep=\"\"), \"\\n\", verbose = verbose) \n if (vc.method == \"EMMA\") REML <- MVP.EMMA.Vg.Ve(y=ys, X=X0, K=K)\n if (vc.method == \"HE\") REML <- MVP.HE.Vg.Ve(y=ys, X=X0, K=K)\n if (vc.method == \"BRENT\") REML <- MVP.BRENT.Vg.Ve(y=ys, X=X0, eigenK=eigenK)\n logging.log(paste(\"Estimated Vg and Ve: \", sprintf(\"%.6f\", REML$vg), \" \", sprintf(\"%.6f\", REML$ve), sep=\"\"), \"\\n\", verbose = verbose)\n }else{\n logging.log(paste(\"Provided Vg and Ve: \", sprintf(\"%.6f\", REML$vg), \" \", sprintf(\"%.6f\", REML$ve), sep=\"\"), \"\\n\", verbose = verbose)\n }\n if(!is.null(K)){rm(K); gc()}\n\n ves <- REML$ve\n vgs <- REML$vg\n lambda <- ves/vgs\n\n U <- eigenK$vectors * matrix(sqrt(1/(eigenK$values + lambda)), n, length(eigenK$values), byrow=TRUE); rm(eigenK); gc()\n \n logging.log(\"scanning...\\n\", verbose = verbose)\n mkl_env({\n results <- mlm_c(y = ys, X = X0, U = U, vgs = vgs, geno@address, verbose = verbose, threads = cpu)\n })\n\n return(results)\n}#end of MVP.MLM function\n", "meta": {"hexsha": "374e83a04af121c82d901bf3d6d3bfa6eae8b151", "size": 4567, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.MLM.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.MLM.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.MLM.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": 35.6796875, "max_line_length": 141, "alphanum_fraction": 0.6052112984, "num_tokens": 1396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.27413187815409645}} {"text": "#MR id -> complications\r\n#ml GCC/8.2.0 OpenMPI/3.1.4 Intel/2019.1.144 IntelMPI/2018.4.274 R/3.6.0\r\n\r\nlibrary('MendelianRandomization')\r\nlibrary('ggplot2')\r\n\r\nanno<-read.table('/data/c***/z***/anno/gencode/37/gencode.v32.GRCh37.txt',header = T,stringsAsFactors = F)\r\n\r\ninfo<-read.table('/data/g***/z***/hihost_gwas/mr_id_complications/top.txt',header = T,stringsAsFactors = F,sep='\\t')\r\n\r\ninfo<-merge(info,anno[,c('genename','chr','left','right')],by=1)\r\ninfo$chr=sub('chr','',info$chr)\r\n\r\n\r\n\r\np_cutoff=1e-5 \r\n\r\n#top ranked genes \r\ninfo<-read.table('/data/g***/z***/hihost_gwas/mr_id_complications/top.txt',header = T,stringsAsFactors = F,sep='\\t')\r\ninfo<-merge(info,anno[,c('genename','chr','left','right')],by=1)\r\ninfo$chr=sub('chr','',info$chr)\r\n\r\nfor(i in 1:nrow(info)){\r\n exp_phecode=paste0('X',info[i,'exp_phecode'])\r\n outcome_phecode=paste0('X',info[i,'outcome_phecode'])\r\n \r\n #plink clumping\r\n cmd=paste0('plink --bfile /data/g***/z***/biovu/23k/geno/ea --clump /data/g***/z***/hihost_gwas/asso/',exp_phecode,'.txt.gz --clump-field P --clump-p1 ',p_cutoff,' --clump-r2 0.01 --out /data/g***/z***/hihost_gwas/mr_id_complications/tmp/',exp_phecode,'_',p_cutoff)\r\n #system(cmd,wait = T)\r\n \r\n #load clumped snps\r\n clumped<-read.table(paste0('/data/g***/z***/hihost_gwas/mr_id_complications/tmp/',exp_phecode,'_',p_cutoff,'.clumped'),header = T,stringsAsFactors = F)\r\n \r\n #load exp gwas\r\n exp<-read.table(paste0('/data/g***/z***/hihost_gwas/asso/',exp_phecode,'.txt.gz'),header = T,stringsAsFactors = F)\r\n exp<-exp[(exp$SNP %in% clumped$SNP),]\r\n exp$beta_exp=log(exp$OR,2.718)\r\n exp$se_exp=exp$beta_exp/exp$Z_STAT\r\n exp<-exp[,c('SNP','A1','beta_exp','se_exp')]\r\n colnames(exp)<-c('SNP','eff_exp','beta_exp','se_exp')\r\n \r\n #load outcome gwas\r\n outcome<-read.table(paste0('/data/g***/z***/hihost_gwas/asso/',outcome_phecode,'.txt.gz'),header = T,stringsAsFactors = F)\r\n outcome$beta_outcome=log(outcome$OR,2.718)\r\n outcome$se_outcome=outcome$beta_outcome/outcome$Z_STAT\r\n outcome<-outcome[,c('SNP','A1','beta_outcome','se_outcome')]\r\n \r\n df<-merge(exp,outcome,by='SNP')\r\n \r\n #rm na\r\n df<-df[!is.na(df$beta_exp+df$beta_outcome),]\r\n \r\n #harmonize\r\n df$beta_outcome=ifelse(df$eff_exp==df$A1,df$beta_outcome,df$beta_outcome*-1)\r\n \r\n #flip the allele\r\n df$beta_outcome=ifelse(df$beta_exp>0,df$beta_outcome,df$beta_outcome*-1)\r\n df$beta_exp=abs(df$beta_exp)\r\n \r\n \r\n info[i,paste0('n_SNPs_allgenes_p_cutoff_',p_cutoff)]<-nrow(df)\r\n if(nrow(df)<3){next}\r\n \r\n #mr weighted median\r\n ans_median_weighted<-mr_median(mr_input(bx = df$beta_exp, bxse = df$se_exp, by = df$beta_outcome, byse = df$se_outcome),weighting = \"weighted\", iterations = 100)\r\n \r\n info[i,paste0('median_weighted_allgenes_p_cutoff_',p_cutoff,'_beta')]<-ans_median_weighted@Estimate\r\n info[i,paste0('median_weighted_allgenes_p_cutoff_',p_cutoff,'_pvalue')]<-ans_median_weighted@Pvalue\r\n \r\n #mr egger\r\n ans_egger<-try(mr_egger(mr_input(bx = df$beta_exp, bxse = df$se_exp, by = df$beta_outcome, byse = df$se_outcome),alpha=0.05))\r\n if('try-error' %in% class(ans_egger)){next} \r\n info[i,paste0('egger_allgenes_p_cutoff_',p_cutoff,'_beta')]<-ans_egger@Estimate\r\n info[i,paste0('egger_allgenes_p_cutoff_',p_cutoff,'_pvalue')]<-ans_egger@Pvalue.Est\r\n \r\n \r\n #generate scatter plot\r\n \r\n png(paste0('/data/g***/z***/hihost_gwas/mr_id_complications/plot/expo_',info[i,'exp_phecode'],'_outcome_',info[i,'outcome_phecode'],'.png'),width = 1500,height = 1500,res=400)\r\n \r\n scatter_p<-ggplot(df, aes(x=beta_exp, y=beta_outcome)) +\r\n geom_errorbar(aes(ymin=beta_outcome-se_outcome*1.96, ymax=beta_outcome+se_outcome*1.96),size=0.05,color='ivory3') +\r\n geom_errorbarh(aes(xmin=beta_exp-se_exp*1.96, xmax=beta_exp+se_exp*1.96),size=0.05,color='ivory3') +\r\n geom_point(size=1.5,color='dodgerblue4') +\r\n xlab(paste0(\"Effect size of SNP-Exposure \\n\",info[i,'exp_trait'])) +\r\n ylab(paste0(\"Effect size of SNP-Outcome \\n\",info[i,'outcome_trait']))+\r\n theme_classic()\r\n #xlim(-0.5,3)\r\n print(scatter_p)\r\n dev.off()\r\n \r\n}\r\n\r\n\r\nwrite.table(info,paste0('/data/g***/z***/hihost_gwas/mr_id_complications/result/allgenes_',p_cutoff,'.txt'),quote = F,sep='\\t',row.names = F)\r\n\r\n", "meta": {"hexsha": "d84452134d99660e73a2d7bf7c93a3a7f72c3376", "size": 4189, "ext": "r", "lang": "R", "max_stars_repo_path": "src/MR_Egger_ID_complications_BioVUEA23K.r", "max_stars_repo_name": "egamazon/InfectiousDiseaseResource", "max_stars_repo_head_hexsha": "2dc0636ed73ae7f0e67ac3e81ddc2a43c76fd107", "max_stars_repo_licenses": ["MIT"], "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/MR_Egger_ID_complications_BioVUEA23K.r", "max_issues_repo_name": "egamazon/InfectiousDiseaseResource", "max_issues_repo_head_hexsha": "2dc0636ed73ae7f0e67ac3e81ddc2a43c76fd107", "max_issues_repo_licenses": ["MIT"], "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/MR_Egger_ID_complications_BioVUEA23K.r", "max_forks_repo_name": "egamazon/InfectiousDiseaseResource", "max_forks_repo_head_hexsha": "2dc0636ed73ae7f0e67ac3e81ddc2a43c76fd107", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-01T03:48:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T03:48:01.000Z", "avg_line_length": 43.1855670103, "max_line_length": 268, "alphanum_fraction": 0.6841728336, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.272972516948216}} {"text": "# Yuan Yuan, 2015-02-06\n# This script check balance after propensity weighting\n\ncheck.balance <- function(index.tr,index.ctr, X1, wt, printout=FALSE)\n {\n mean.tr <- sum(wt[index.tr]*X1[index.tr])/sum(wt[index.tr])\n sd.tr <- sum(wt[index.tr]*(X1[index.tr]-mean(X1[index.tr]))^2)/(sum(wt[index.tr])-1)\n mean.ctr <- sum(wt[index.ctr]*X1[index.ctr])/sum(wt[index.ctr])\n sd.ctr <- sum(wt[index.ctr]*(X1[index.ctr]-mean(X1[index.ctr]))^2)/(sum(wt[index.ctr])-1)\n\n std.diff <- abs(mean.tr-mean.ctr)/sqrt((sd.tr+sd.ctr)/2)\n if(printout)\n {\n print(std.diff)\n }\n return(std.diff)\n }\n", "meta": {"hexsha": "676d7580e0897f0a713b7ff18b44990889e6feb9", "size": 665, "ext": "r", "lang": "R", "max_stars_repo_path": "13.afh-vs-afl/yy_code/check_balance.r", "max_stars_repo_name": "zhangyupisa/autophagy-in-cancer", "max_stars_repo_head_hexsha": "7510611e742ba451c9741ff3ca767c84bfce66f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "13.afh-vs-afl/yy_code/check_balance.r", "max_issues_repo_name": "zhangyupisa/autophagy-in-cancer", "max_issues_repo_head_hexsha": "7510611e742ba451c9741ff3ca767c84bfce66f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "13.afh-vs-afl/yy_code/check_balance.r", "max_forks_repo_name": "zhangyupisa/autophagy-in-cancer", "max_forks_repo_head_hexsha": "7510611e742ba451c9741ff3ca767c84bfce66f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-05-25T07:07:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-25T07:07:00.000Z", "avg_line_length": 36.9444444444, "max_line_length": 97, "alphanum_fraction": 0.5669172932, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2723887262933196}} {"text": "full_algorithm <- function(Kc, Kr, S0, S1, MW, wt, minimum_threshold) {\n # Two-way Tanimoto Algorithm\n # ===========================\n\n # Parameters:\n # Kc Integer, how many neighbors to select for consumers\n # Kr Integer, how many neighbors to select for resources\n # S0 A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']\n # S1 The subset of S0 where we want to predict new preys, string vector with taxa name\n # MW Mimimum weight to accept a candidate as a prey\n\n # Output\n # A vector of sets (the preys for each species)\n\n predictions <- matrix(nrow = length(S1), ncol = 3, data = \"\", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions\n predictions[, 'consumer'] <- S1\n\n pb <- txtProgressBar(min = 0,max = length(S1), style = 3)\n for(i in 1:length(S1)) { # loop through each taxon in S1\n candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight\n resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], \" \\\\|\\\\ \")) # resources of S1[i]\n\n # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or\n # Find similar resources to resources for S1[i] in S1\n if(length(resources.S1) > 0) {\n empirical <- character()\n for(j in 1:length(resources.S1)) { #loop through empirical resources for S1\n if(resources.S1[j] %in% S1) {\n empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical\n } else { # selecting Kr most similar resources in S1\n # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.\n\n similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == resources.S1[j]), ]), # S1 in S0 + resource for which similarity has to be measured\n S1 = resources.S1[j], # resource for which similarity has to be measured\n wt = wt,\n taxa = 'resource')\n\n similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources\n similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])\n similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]\n to.remove <- which(similar.resource[,'resource'] == resources.S1[j])\n if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)\n similar.resource <- similar.resource[-which(similar.resource[,'resource'] == resources.S1[j]), ]\n }\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {\n same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])\n similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]\n similar.resource <- similar.resource[1:Kr, ]\n } else {\n similar.resource <- similar.resource[1:Kr, ]\n }# if for random draw\n\n for(l in 1:Kr) { # extracting resource candidates\n if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed\n } else if(similar.resource[l, 'similarity'] < minimum_threshold) {\n NULL\n } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight\n candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])\n } else {\n candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight\n }#if3\n }#l\n }#if\n }#j\n predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')\n }#if1\n\n # Identify similar consumers to S1[i]\n\n similarity.consumers <- similarity_full_algorithm(S0 = S0,\n S1 = S1[i],\n wt = wt,\n taxa = 'consumer')\n\n similar.consumer <- matrix(nrow = nrow(similarity.consumers), ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # importing K nearest neighbors consumers\n similar.consumer[, 'consumer'] <- names(similarity.consumers[order(similarity.consumers, decreasing = TRUE), ])\n similar.consumer[, 'similarity'] <- similarity.consumers[order(similarity.consumers, decreasing = TRUE)]\n to.remove <- which(similar.consumer[,'consumer'] == S1[i])\n if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)\n similar.consumer <- similar.consumer[-which(similar.consumer[,'consumer'] == S1[i]), ]\n }\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {\n same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])\n similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]\n similar.consumer <- similar.consumer[1:Kc, ]\n } else {\n similar.consumer <- similar.consumer[1:Kc, ]\n }# if for random draw\n\n\n # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?\n # If yes, we could add an argument call wt_predator.\n # if(wt_predator == FALSE) {\n # resources <- unique of all prey species of all similar predators\n # } else {}\n\n for(j in 1:Kc) { #loop through consumers\n\n if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n } else if(similar.consumer[j, 'similarity'] < minimum_threshold) {\n NULL\n } else {\n\n # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource\n candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], \" \\\\|\\\\ \")) # list of resources for consumer j\n # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment\n\n for(k in 1:length(candidate.resource)) { # loop through resources of consumer j\n if(length(candidate.resource) == 0) { # if candidate resource list is empty, break\n break\n } else if(candidate.resource[1] == \"\") { # if candidate list is an empty vector \"\", break\n break\n } else if(candidate.resource[k] == S1[i]) {\n # #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not\n NULL\n } else if((candidate.resource[k] %in% S1) == TRUE) {\n if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight\n candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1\n } else {\n candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight\n }#if2\n\n } else {\n similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == candidate.resource[k]), ]), # S1 in S0 + resource for which similarity has to be measured\n S1 = candidate.resource[k], # resource for which similarity has to be measured\n wt = wt,\n taxa = 'resource')\n\n similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources\n similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])\n similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]\n to.remove <- which(similar.resource[,'resource'] == candidate.resource[k])\n if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)\n similar.resource <- similar.resource[-which(similar.resource[,'resource'] == candidate.resource[k]), ]\n }\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {\n same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])\n similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]\n similar.resource <- similar.resource[1:Kr, ]\n } else {\n similar.resource <- similar.resource[1:Kr, ]\n }# if for random draw\n\n for(l in 1:Kr) { # extracting resource candidates\n if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed\n } else if(similar.resource[l, 'similarity'] < minimum_threshold) {\n NULL\n } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight\n candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])\n } else {\n candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity\n }#if3\n }#l\n } #if1\n }#k\n }#if\n }#j\n\n candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW\n if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order\n candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight\n predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')\n } else {\n predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')\n }#if\n setTxtProgressBar(pb, i)\n }#i\n close(pb)\n return(predictions)\n}#full algorithm function\n", "meta": {"hexsha": "0a916ea840d29754ec1e3974ded78406925dbbe8", "size": 14266, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/full_algorithm.r", "max_stars_repo_name": "david-beauchesne/predicting_interactions", "max_stars_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-08-12T11:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-09T18:16:12.000Z", "max_issues_repo_path": "Script/full_algorithm.r", "max_issues_repo_name": "david-beauchesne/predicting_interactions", "max_issues_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-12T14:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T15:25:21.000Z", "max_forks_repo_path": "Script/full_algorithm.r", "max_forks_repo_name": "david-beauchesne/predicting_interactions", "max_forks_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-12T10:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-12T10:46:53.000Z", "avg_line_length": 75.8829787234, "max_line_length": 246, "alphanum_fraction": 0.5610542549, "num_tokens": 2972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.26893506011160756}} {"text": "subroutine trifnd(j,tau,nedge,nadj,madj,x,y,ntot,eps,ntri,nerror)\n\n# Find the triangle of the extant triangulation in which\n# lies the point currently being added.\n# Called by initad.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot), xt(3), yt(3)\ndimension itmp(1)\ninteger tau(3)\nlogical adjace, anticl\n\nnerror = -1\n\n# The first point must be added to the triangulation before\n# calling trifnd.\nif(j==1) {\n\tnerror = 11\n\treturn\n}\n\n# Get the previous triangle:\nj1 = j-1\ntau(1) = j1\ntau(3) = nadj(j1,1)\ncall pred(tau(2),j1,tau(3),nadj,madj,ntot,nerror)\nif(nerror > 0) return\ncall adjchk(tau(2),tau(3),adjace,nadj,madj,ntot,nerror)\nif(nerror>0) {\n return\n}\nif(!adjace) {\n tau(3) = tau(2)\n\tcall pred(tau(2),j1,tau(3),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n}\n\n# Move to the adjacent triangle in the direction of the new\n# point, until the new point lies in this triangle.\nktri = 0\n1 continue\n\n# Check that the vertices of the triangle listed in tau are\n# in anticlockwise order. (If they aren't then reverse the order;\n# if they are *still* not in anticlockwise order, theh alles\n# upgefucken ist; throw an error.)\ncall acchk(tau(1),tau(2),tau(3),anticl,x,y,ntot,eps)\nif(!anticl) {\n call acchk(tau(3),tau(2),tau(1),anticl,x,y,ntot,eps)\n if(!anticl) {\n itmp(1) = j\n call intpr(\"Point number =\",-1,itmp,1)\n call intpr(\"Previous triangle:\",-1,tau,3)\n call rexit(\"Both vertex orderings are clockwise. See help for deldir.\")\n } else {\n ivtmp = tau(3)\n tau(3) = tau(1)\n tau(1) = ivtmp\n }\n}\n\nntau = 0 # This number will identify the triangle to be moved to.\nnedge = 0 # If the point lies on an edge, this number will identify that edge.\ndo i = 1,3 {\n ip = i+1\n if(ip==4) ip = 1 # Take addition modulo 3.\n\n# Get the coordinates of the vertices of the current side,\n# and of the point j which is being added:\n\txt(1) = x(tau(i))\n\tyt(1) = y(tau(i))\n\txt(2) = x(tau(ip))\n\tyt(2) = y(tau(ip))\n\txt(3) = x(j)\n\tyt(3) = y(j)\n\n# Create indicator telling which of tau(i), tau(ip), and j\n# are ideal points. (The point being added, j, is ***never*** ideal.)\n\tif(tau(i)<=0) i1 = 1\n\telse i1 = 0\n\tif(tau(ip)<=0) j1 = 1\n\telse j1 = 0\n\tk1 = 0\n\tijk = i1*4+j1*2+k1\n\n# Calculate the ``normalized'' cross product; if this is positive\n# then the point being added is to the left (as we move along the\n# edge in an anti-clockwise direction). If the test value is positive\n# for all three edges, then the point is inside the triangle. Note\n# that if the test value is very close to zero, we might get negative\n# values for it on both sides of an edge, and hence go into an\n# infinite loop.\n\tcall cross(xt,yt,ijk,cprd)\n\tif(cprd >= eps) continue\n\telse if(cprd > -eps) nedge = ip\n\telse {\n\t\tntau = ip\n\t\tbreak\n\t}\n}\n\n# We've played ring-around-the-triangle; now figure out the\n# next move:\n\n# case 0: All tests >= 0.; the point is inside; return.\nif(ntau==0) return\n\n# The point is not inside; work out the vertices of the triangle to which\n# to move. Notation: Number the vertices of the current triangle from 1 to 3,\n# anti-clockwise. Then \"triangle i+1\" is adjacent to the side from vertex i to\n# vertex i+1, where i+1 is taken modulo 3 (i.e. \"3+1 = 1\").\n\n# case 1: Move to \"triangle 1\"\nif(ntau==1) {\n\t#tau(1) = tau(1)\n\ttau(2) = tau(3)\n\tcall succ(tau(3),tau(1),tau(2),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n}\n\n# case 2: Move to \"triangle 2\"\nif(ntau==2) {\n\t#tau(1) = tau(1)\n\ttau(3) = tau(2)\n\tcall pred(tau(2),tau(1),tau(3),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n}\n\n# case 3: Move to \"triangle 3\"\nif(ntau==3) {\n\ttau(1) = tau(3)\n\t#tau(2) = tau(2)\n\tcall succ(tau(3),tau(1),tau(2),nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n}\n\n# We've moved to a new triangle; check if the point being added lies\n# inside this one.\nktri = ktri + 1\nif(ktri > ntri) {\n itmp(1) = j\n call intpr(\"Point being added:\",-1,itmp,1)\n call rexit(\"Cannot find an enclosing triangle. See help for deldir.\")\n}\ngo to 1\n\nend\n", "meta": {"hexsha": "ffc169dd436c68d7d3b5035bd96e8feef9f312b1", "size": 4025, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/ratfor/trifnd.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/ratfor/trifnd.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/ratfor/trifnd.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": 27.1959459459, "max_line_length": 79, "alphanum_fraction": 0.6539130435, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2686331518300428}} {"text": "# ================================================================ #\n# | *** Implementation of CV\n# | 1. Sequential implementation \n# | 1.a local shrinkage\n# | 1.b global shrinkage\n# | 2. Distributed/Parallel implementation for global shrinkage\n# ================================================================ # \nlibrary(lars) #, lib=\"/home/dabid/R/x86_64-unknown-linux-gnu-library/3.2/\")\n\n\n# ================================================================ #\n# | **** Helper functions **** | #\n# ================================================================ #\nlars.multi <- function(tdata,rdata,pert,prior,allowed)\n{\n lars.paths <- list()\n targets <- seq(dim(tdata)[1])\n \n \n cat(\"Building path for target: \")\n for (i in targets)\n {\n cat(i,\"\")\n mindices <- which(pert[i,]==0)\n \n x <- rdata[,mindices] * prior[,i] \n x[which(allowed[,i]==0),]<-0; \n \n ##### YK patch 05-23-2017\n # results.lars <- lars(t(x),tdata[i,mindices],trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,use.Gram=FALSE);\n y <- tdata[i,mindices];\n results.lars.flag <- TRUE;\n sample.indx <- length(y); \n while (results.lars.flag) {\n results.lars <- try(lars(t(x[,1:sample.indx]),y[1:sample.indx],trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,use.Gram=FALSE));\n results.lars.flag <- class(results.lars) =='try-error';\n if (results.lars.flag) { cat(' *no soln* '); }\n sample.indx <- sample.indx-1; \n }\n #####\n #lars.paths[[i]] <- list(beta=results.lars$beta, mu=results.lars$mu, meanx=results.lars$meanx, C.Max=c(results.lars$C.Max,0))\n lars.paths[[i]] <- list(beta=results.lars$beta, mu=results.lars$mu, meanx=results.lars$meanx, C.Max=c(results.lars$lambda,0)) # for support in lars 1.2\n }\n cat(\"\\n\")\n \n cat(\"Building combined C.Max ranking\\n\")\n all.C.lars <- c()\n for (i in targets)\n {\n all.C.lars <- rbind(all.C.lars, cbind(lars.paths[[i]]$C.Max,rep(i,times=length(lars.paths[[i]]$C.Max)),1:length(lars.paths[[i]]$C.Max)))\n }\n R <- all.C.lars[sort.list(all.C.lars[,1],decreasing=TRUE),]\n lars.paths$R <- R\n lars.paths$targets <- targets\n lars.paths\n}\n\n# ================================================================ #\n# | **** END Helper functions **** | #\n# ================================================================ #\n\n\n\n# ================================================================ #\n# | **** Lochal Shrinkage functions **** | #\n# ================================================================ #\n\n# ================================================================ #\n# | **** END Lochal Shrinkage functions **** | #\n# ================================================================ #\nlars.multi.optimize <- function(tdata,rdata,pert,prior,allowed)\n{\n\tcat(as.character(Sys.time()),\"\\n\")\n\tlars.paths.cv <- lars.multi.cv(tdata,rdata,pert,prior,allowed,10)\n\t\n\tlars.paths <- lars.multi(tdata,rdata,pert,prior,allowed)\n\tB <- lars.multi.path.step(lars.paths,lars.paths.cv[[2]])\n\n\tB.adj <- matrix(0,nrow=dim(rdata)[1],ncol=dim(tdata)[1])\n\n\tfor (i in seq(dim(tdata)[1]))\n\t{\n\t\t#Scale B.adj according to prior\n\t\tB.adj[,i] <- B[[i]] * prior[,i]\n\t}\n\trval <- list()\n\trval[[1]] <- B.adj\n\trval[[2]] <- lars.paths\n\trval[[3]] <- lars.paths.cv\n\tcat(as.character(Sys.time()),\"\\n\")\n\trval\n}\n\nlars.multi.cv <- function(tdata,rdata,pert,prior,allowed,fold)\n{\t\n\tall.folds <- cv.folds(dim(tdata)[2], fold)\n\tlars.cv.paths <- list()\n\tcMax <- 0;\n\tfor (f in 1:fold)\n\t{\n\t\tcat(\"Building path for cv\",f,\"of\",fold,\"\\n\")\n\t\tomit <- all.folds[[f]]\n\t\tlars.cv.paths[[f]] <- lars.multi(tdata[,-omit], rdata[,-omit], pert[,-omit],prior,allowed)\n\t\tif (lars.cv.paths[[f]]$R[1,1]>cMax)\n\t\t{\n\t\t\tcMax <- lars.cv.paths[[f]]$R[1,1]\n\t\t}\n\t\t\n\t}\n\n\tcSteps <- c()\n\tmse <- c()\n\tbnorm <- c()\n\t\n\tconverged <- FALSE\n\tP <- c(cMax/10,0)\n\tFP <- c(lars.multi.cv.eval(P[1],fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed),lars.multi.cv.eval(P[2],fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed))\n\n\twhile (!converged)\n\t{\n\t\tImin <- which.min(FP)\n\t\tImax <- which.max(FP)\n\t\tif (Imin==Imax)\n\t\t\tconverged=TRUE\n\n\t\tcat(\"P:\",P,\"F(P):\",FP,\"Max/Min\",Imax,Imin,\"\\n\")\n\t\tPhat <- P[Imin]\n\t\tPref <- 2*Phat - P[Imax]\n\n\t\tif (Pref>cMax)\n\t\t\tFPref <- max(FP) + (Pref-cMax)^2\n\t\telse if (Pref<0)\n\t\t\tFPref <- max(FP) + Pref^2\n\t\telse\n\t\t\tFPref <- lars.multi.cv.eval(Pref,fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed)\n\t\t\n\t\t\tif (FPref < FP[Imin])\t\t\n\t\t\t{\n\t\t\t\t#Attempt expansion\n\t\t\t\tPexp <- 2*Pref - Phat\n\t\t\t\tFPexp <- lars.multi.cv.eval(Pexp,fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed)\n\t\t\t\tif (FPexp < FPref) #Expand\n\t\t\t\t{\n\t\t\t\t\tcat(\"Expand\\n\")\n\t\t\t\t\tP[Imax] <- Pexp\n\t\t\t\t\tFP[Imax] <- FPexp\n\t\t\t\t}\n\t\t\t\telse #Reflect\n\t\t\t\t{\n\t\t\t\t\tcat(\"Reflect\\n\")\n\t\t\t\t\tP[Imax] <- Pref\n\t\t\t\t\tFP[Imax] <- FPref\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t#Contract\n\t\t\t\tif (FP[Imax] < FPref)\n\t\t\t\t{\n\t\t\t\t\tcat(\"Contract (1)\\n\")\n\t\t\t\t\tP[Imax] <- (P[Imax] + Phat)/2\n\t\t\t\t\tFP[Imax] <- lars.multi.cv.eval(P[Imax],fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed)\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcat(\"Contract (2)\\n\")\n\t\t\t\t\tP[Imax] <- (Pref + Phat)/2\n\t\t\t\t\tFP[Imax] <- lars.multi.cv.eval(P[Imax],fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed)\n\t\t\t\t}\n\t\t\t}\n\t}\n\trval <- list()\n\trval[[1]] <- lars.cv.paths\n\trval[[2]] <- P[which.min(FP)]\n\trval[[3]] <- min(FP)\n\trval[[4]] <- all.folds\n\trval\n}\n\nlars.multi.cv.eval <- function(cVal,fold,lars.cv.paths,all.folds,tdata,rdata,pert,prior,allowed,targets=NULL)\n{\n\t\tif (is.null(targets))\n\t\t\ttargets <- seq(dim(tdata)[1])\n\t\tmse <- rep(0,times=fold)\n\t\tfor (f in 1:fold)\n\t\t{\n\t\t\tB <- lars.multi.path.step(lars.cv.paths[[f]],cVal)\n\t\t\tfor (i in targets)\n\t\t\t{\n\t\t\t\tomit <- all.folds[[f]]\n\t\t\t\tomit <- setdiff(omit,which(pert[i,]!=0))\n\t\t\t\t\n\t\t\t\ttestx <- rdata[,omit]\n\t\t\t\ttesty <- tdata[i,omit]\n\t\t\t\ttestx[which(allowed[,i]==0),] <- 0\n\t\t\t\ttestx <- testx * prior[,i]\n\n\t\t\t\ttestp <- scale(t(testx) , lars.cv.paths[[f]][[i]]$meanx, FALSE) %*% matrix(B[[i]]) + lars.cv.paths[[f]][[i]]$mu\n\t\t\t\ttestr <- apply((testp - testy)^2,2,mean)\n\t\t\t\tmse[f] <- mse[f] + testr\n\t\t\t}\n\t\t\tmse[f] <- mse[f]/length(targets)\n\t\t}\n\t\ttotalmse <- sum(mse) / fold\n\t\ttotalmse\n}\n\n\n\n\nlars.multi.path.step <- function(lars.paths,stepC)\n{\n\tk <- 1\n\tif (length(which(lars.paths$R[,1]>stepC))>0)\n\t{\n\t\tk<-max(which(lars.paths$R[,1]>stepC))\n\t}\n\n\tB <- list()\n\tA <- c()\n\tAi <- unique(lars.paths$R[1:k,2])\n\tfor (i in Ai)\n\t{\t\n\t\tA <- rbind(A,c(i,lars.paths$R[max(which(lars.paths$R[1:k,2]==i)),3]))\n\t}\n\n\tfor (i in lars.paths$targets)\n\t{\n\t\tindx <- which(A[,1]==i)\n\t\tif (length(indx)==0)\n\t\t{\n\t\t\tB[[i]] <- rep(0,times=dim(lars.paths[[i]]$beta)[2])\n\t\t}\n\t\telse\n\t\t{\n\t\t\tplen <- dim(lars.paths[[i]]$beta)[1]\n\t\t\tif (A[indx,2]==plen)\n\t\t\t{\n\t\t\t\tB[[i]] <- lars.paths[[i]]$beta[plen,]\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ( lars.paths$R[k,1] < lars.paths[[i]]$C.Max[A[indx,2]+1] )\n\t\t\t\t{\n\t\t\t\t\tif (A[indx,2] < plen)\n\t\t\t\t\t\tA[indx,2] <- A[indx,2] + 1\n\t\t\t\t}\n\t\t\t\tgamma <- (lars.paths[[i]]$C.Max[A[indx,2]] - lars.paths$R[k,1]) / (lars.paths[[i]]$C.Max[A[indx,2]] - lars.paths[[i]]$C.Max[A[indx,2]+1])\n\t\t\t\tu <- (lars.paths[[i]]$beta[A[indx,2]+1,] - lars.paths[[i]]$beta[A[indx,2],])\n\t\t\t\tB[[i]] <- lars.paths[[i]]$beta[A[indx,2],] + u * gamma\n\t\t\t}\n\t\t}\n\t}\n\tB\n}\n\n###\n\nlars.multi.cv.singlefold <- function(tdata,rdata,pert,prior,allowed,nbr_cv_fold,seed,f)\n{\n\tset.seed(seed)\n\tall.folds <- cv.folds(dim(tdata)[2], nbr_cv_fold)\n\tcat(\"Building path for cv\",f,\"of\",nbr_cv_fold,\"\\n\")\n\tomit <- all.folds[[f]]\n\tlars.cv.paths <- lars.multi(tdata[,-omit], rdata[,-omit], pert[,-omit],prior,allowed)\n\tlars.cv.paths\n}\n\nlars.single.cv <- function(tdata,rdata,pert,prior,allowed,fold,seed)\n{\n\ttargets <- seq(dim(tdata)[1])\n\tlars.paths.cv <- list()\n\tlars.paths <- list()\n\tB <- matrix(0,nrow=dim(rdata)[1],ncol=dim(tdata))\n\n\tminFrac <- c()\n cat(\"Building path for target: \")\n for (i in targets)\n {\n cat(i,\"\")\n mindices <- which(pert[i,]==0)\n x <- rdata[,mindices] * prior[,i]\n x[which(allowed[,i]==0),]<-0;\n set.seed(seed)\n lars.paths.cv[[i]] <- cv.lars(t(x),tdata[i,mindices],K=fold,plot.it=FALSE,trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,se=FALSE);\n\t\tminFrac[i] <- lars.paths.cv[[i]]$index[which.min(lars.paths.cv[[i]]$cv)]\n\t\tlars.paths[[i]] <- lars(t(x),tdata[i,mindices],trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE);\n\t\tB[,i] <- predict(lars.paths[[i]],s=minFrac[i],type=\"coefficients\",mode=\"fraction\")$coefficients\n }\t\n\tcat(\"\\n\")\n\tB\n}\n\nlars.local <- function(tdata,rdata,pert,prior,allowed,skip_reg,skip_gen)\n{\n cat(as.character(Sys.time()),\"\\n\")\n B.adj <- matrix(0,nrow=dim(rdata)[1],ncol=dim(tdata)[1])\n\t\n cat(\"Working on Gene:\")\n\tfor(i in 1:dim(tdata)[1]) {\n\t\tif (skip_gen[i] == 0) {\n\t\t \tcat(i,\",\")\n\t\t\tmindices <- which(pert[i,]==0)\n\t\t\tx <- rdata[,mindices] * prior[,i]\n\t\t\tx[which(allowed[,i]==0),]<-0;\n\t\t\tnindices <- which(skip_reg==0)\n\t\t\tx <- x[nindices,]\n\t\t\tlars.paths.cv <- cv.lars(t(x),tdata[i,mindices],K=3,trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,se=FALSE, plot.it=FALSE,use.Gram=FALSE);\n\t\t\tminFrac <- lars.paths.cv$index[which.min(lars.paths.cv$cv)]\n\t\t\tlars.paths <- lars(t(x),tdata[i,mindices],trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,use.Gram=FALSE);\n\t\t\t# lars.paths <- lars(t(x),tdata[i,mindices],trace=FALSE,max.steps=600,type=\"lasso\",normalize=FALSE,intercept=TRUE,use.Gram=TRUE);\n\t\t\ttempVec <- predict(lars.paths,s=minFrac,type=\"coefficients\",mode=\"fraction\")$coefficients\n\t\t\t# tempVec <- lars.paths$beta\n\t\t\t# print(tempVec)\n\t\t\tnindices <- which(skip_reg==1)\n tempCol <- c(tempVec, rep(0,length(nindices)))\n tempIndices <- c(seq_along(tempVec), nindices+.5)\n B.adj[,i] <- tempCol[order(tempIndices)]\n #Scale B.adj according to prior\t\t\n\t\t\tB.adj[,i] <- B.adj[,i] * prior[,i]\n\t\t}\n\t}\n\tcat(\"\\n\")\n\n\trval <- list()\n rval[[1]] <- B.adj\n rval\n}\n\n\n# ====================================================================== #\n# | **** Distributed/Parallel Implementation **** | #\n# ====================================================================== #\n\ncreate_lasso_global_shrinkage_parallel = function(df_expr_target\n , df_expr_reg\n , df_allowed\n , df_perturbed\n , df_prior\n , seed\n , p_out_dir\n , nbr_cv_fold\n , p_src_code){\n library(\"Rmpi\")\n mpi.spawn.Rslaves(nslaves = nbr_cv_fold)\n mpi.bcast.Robj2slave(df_expr_target)\n mpi.bcast.Robj2slave(df_expr_reg)\n mpi.bcast.Robj2slave(df_prior)\n mpi.bcast.Robj2slave(df_allowed)\n mpi.bcast.Robj2slave(df_perturbed)\n mpi.bcast.Robj2slave(p_out_dir)\n mpi.bcast.Robj2slave(p_src_code)\n mpi.bcast.Robj2slave(seed)\n mpi.bcast.Robj2slave(nbr_cv_fold)\n mpi.remote.exec(source(paste(p_src_code, \"src/build_np1/code/netprophet1/run_netprophet_parallel_single_process.r\", sep=\"\")))\n mpi.remote.exec(get_fold_nbr())\n # all.folds = cv.folds(dim(df_expr_target)[2], nbr_cv_fold)\n df_lasso_net = lars.multi.optimize.parallel(df_expr_target,df_expr_reg,df_perturbed,df_prior,df_allowed)[[1]]\n \n \n mpi.close.Rslaves()\n \n df_lasso_net\n}\n\nlars.multi.optimize.parallel <- function(df_expr_target,df_expr_reg,df_perturbed,df_prior,df_allowed)\n{\n prior=df_prior\n allowed=df_allowed\n pert=df_perturbed\n tdata=df_expr_target\n rdata=df_expr_reg\n targets=seq(dim(tdata)[1])\n cat(as.character(Sys.time()),\"\\n\")\n c.cvmin <- lars.multi.cv.parallel()\n \n # lars.paths <- lars.multi(tdata,rdata,pert,prior,allowed)\n lars.paths <- lars.multi(df_expr_target,df_expr_reg,df_perturbed,df_prior,df_allowed)\n B <- lars.multi.path.step(lars.paths,c.cvmin)\n \n B.adj <- matrix(0,nrow=dim(rdata)[1],ncol=dim(tdata)[1])\n \n for (i in seq(dim(tdata)[1]))\n {\n #Scale B.adj according to prior\n B.adj[,i] <- B[[i]] * prior[,i] \n }\n rval <- list()\n rval[[1]] <- B.adj\n rval[[2]] <- lars.paths\n cat(as.character(Sys.time()),\"\\n\")\n rval\n}\n\nlars.multi.cv.cmax.parallel <- function()\n{\n cat(cv.obj$R[1,1],\"\\n\")\n cv.obj$R[1,1]\n}\n\nlars.multi.cv.parallel <- function()\n{\t\n cMax <- max(as.numeric(mpi.remote.exec(lars.multi.cv.cmax.parallel())))\n cat(\"cMax: \", cMax, \"\\n\")\n converged <- FALSE\n P <- c(cMax/10,0)\n \n FP <- c(mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,P[1]))),mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,P[2]))))\n \n while (!converged)\n {\n Imin <- which.min(FP)\n Imax <- which.max(FP)\n if (Imin==Imax)\n converged=TRUE\n \n cat(\"P:\",P,\"F(P):\",FP,\"Max/Min\",Imax,Imin,\"\\n\")\n Phat <- P[Imin]\n Pref <- 2*Phat - P[Imax]\n \n if (Pref>cMax)\n FPref <- max(FP) + (Pref-cMax)^2\n else if (Pref<0)\n FPref <- max(FP) + Pref^2\n else\n FPref <- mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,Pref)))\n \n if (FPref < FP[Imin])\t\t\n {\n #Attempt expansion\n Pexp <- 2*Pref - Phat\n FPexp <- mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,Pexp)))\n if (FPexp < FPref) #Expand\n {\n cat(\"Expand\\n\")\n P[Imax] <- Pexp\n FP[Imax] <- FPexp\n }\n else #Reflect\n {\n cat(\"Reflect\\n\")\n P[Imax] <- Pref\n FP[Imax] <- FPref\n }\n }\n else\n {\n #Contract\n if (FP[Imax] < FPref)\n {\n cat(\"Contract (1)\\n\")\n P[Imax] <- (P[Imax] + Phat)/2\n FP[Imax] <- mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,P[Imax])))\n }\n else\n {\n cat(\"Contract (2)\\n\")\n P[Imax] <- (Pref + Phat)/2\n FP[Imax] <- mean(as.numeric(mpi.remote.exec(cmd=lars.multi.cv.eval.parallel,P[Imax])))\n }\n }\n }\n \n cat(P[which.min(FP)],min(FP),\"\\n\")\n \n P[which.min(FP)]\n}\n\nlars.multi.cv.eval.parallel <- function(cVal)\n{\n mse <- 0;\n B <- lars.multi.path.step(cv.obj,cVal)\n prior=df_prior\n allowed=df_allowed\n pert=df_perturbed\n tdata=df_expr_target\n rdata=df_expr_reg\n targets=seq(dim(tdata)[1])\n # all.folds <- cv.folds(dim(tdata)[2], nbr_cv_fold)\n for (i in targets)\n {\n omit <- all.folds[[fold]]\n omit <- setdiff(omit,which(pert[i,]!=0))\n \n testx <- rdata[,omit]\n testy <- tdata[i,omit]\n testx[which(allowed[,i]==0),] <- 0\n testx <- testx * prior[,i]\n \n testp <- scale(t(testx) , cv.obj[[i]]$meanx, FALSE) %*% matrix(B[[i]]) + cv.obj[[i]]$mu\n testr <- apply((testp - testy)^2,2,mean)\n mse <- mse + testr\n }\n mse <- mse/length(targets)\n mse\n}\n\n\n\n# ====================================================================== #\n# | **** END Distributed/Parallel Implementation **** | #\n# ====================================================================== #\n", "meta": {"hexsha": "fcce31ec1802160237f540830e7305b6d3a5396c", "size": 14999, "ext": "r", "lang": "R", "max_stars_repo_path": "src/build_np1/code/netprophet1/global.lars.regulators.r", "max_stars_repo_name": "yiming-kang/NetProphet_2.0", "max_stars_repo_head_hexsha": "3245693eb4e6afe799a1948852dac6f1b22711f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2017-11-10T22:02:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-05T20:47:09.000Z", "max_issues_repo_path": "src/build_np1/code/netprophet1/global.lars.regulators.r", "max_issues_repo_name": "yiming-kang/NetProphet_2.0", "max_issues_repo_head_hexsha": "3245693eb4e6afe799a1948852dac6f1b22711f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-07-11T08:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T17:33:02.000Z", "max_forks_repo_path": "src/build_np1/code/netprophet1/global.lars.regulators.r", "max_forks_repo_name": "yiming-kang/NetProphet_2.0", "max_forks_repo_head_hexsha": "3245693eb4e6afe799a1948852dac6f1b22711f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2017-11-03T16:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T04:11:34.000Z", "avg_line_length": 29.8190854871, "max_line_length": 179, "alphanum_fraction": 0.5445029669, "num_tokens": 4807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2677492309189948}} {"text": "#' @title Parametric bootstraps of confidence intervals of model estimates and potentially fitted values for\n#' (G)LMMs fitted with lmer or glmmTMB functions.\n#' @description Derive Bootstrapped confidence intervals of model estimates and potentially fitted values for\n#' (G)LMMs fitted with lmer or glmmTMB functions and using a parametric bootstrap.\n#' @param m fitted model object as obtained from \\code{lmer}, \\code{glmer}, \\code{glmer.nb}, or \\code{glmmTMB}.\n#' @param data data frame comprising all variables needed to fit the model (only \\code{boot.glmmtmb}).\n#' @param discard.warnings logical (function \\code{boot.lmer}); determines whether bootstraps that failed\n#' with an error or issued a warning should be discarded (\\code{T}; a 'dangerous' option; see datails) or not (\\code{F}; default).\n#' @param discard.non.conv logical (function \\code{boot.glmmtmb}); determines whether bootstraps that failed\n#' with an error should be discarded (\\code{T}; a 'dangerous' option; see datails) or not (\\code{F}; default).\n#' @param nboots number of bootstraps to be conducetd (default: 1000).\n#' @param para logical; determines whether bootstraps should be parallellized (\\code{T}) or not (\\code{F};\n#' default; see details).\n#' @param n.cores number cores to be used when \\code{para=T}. Can be one of \"all-1\" (the default), \"all\",\n#' or an integer.\n#' @param resol resolution with which confidence limits of fitted values for the effects of covariates should be\n#' determined (default: 1000; see details).\n#' @param level confidence level (default: 0.95).\n#' @param use, character vector or list of character vectors indicating the names of the predictors for which\n#' confidence intervals of fitted values should be obtained. Defaults to \\code{NULL} in which case no\n#' confidence intervals of fitted values are returned (see details).\n#' @param circ.var.name character; name of a potential circular variable present in the model (only relevant\n#' when \\code{use} is not left at its default).\n#' @param circ.var numeric vector with the values of the circular variable as handed over to the model fitting\n#' function.\n#' @param use.u logical; determines whether bootstraps should be conditional on the particular levels of the\n#' random effects present in the data \\code{T} or not (\\code{F}; default; see \\code{\\link{bootMer}} for details).\n#' @param save.path path in which results of individual bootstraps should be saved (defaults to \\code{NULL} in\n#' which case results of individual bootstraps aren't saved).\n#' @param load.lib logical determining whether the package needed to conduct the bootstrap should be loaded\n#' (\\code{T}) or not (\\code{F}; default).\n#' @param lib.loc path from where the package should be loaded (defaults to \\code{.libPaths()}; usually one\n#' dosn't need to bother about; see details).\n#' @param set.all.effects.2.zero don't know what this is doing (just leave it at its default; \\code{F}).\n#' @details\n#' Both functions are actually wrappers of the functions \\code{bootMer{lme4}} and\n#' \\code{simulate.glmmTMB{glmmTMB}}, respectively, making their use more convenient, allowing to obtain\n#' bootstrapped confidence intervals of fitted values, keep track of warnings issued, and avoid boostraps\n#' failing with an error.\n#'\n#' Note that these functions try to fit many models (at least as many as indicated to the argument\n#' \\code{n.boots}). As a consequence, it can take a while until they finish. For instance, for a complex GLMM\n#' with, e.g., binomial, negative binomial, Poisson, or beta error distribution, it can easily take days\n#' for the function to complete, even when it runs parallelized on on, say, 16 or 64 cores.\n#'\n#' Use parallelisation (i.e., \\code{para=T}) on dedicated machines, and I suggest to not use it on laptops to avoid\n#' over heating. The default for the number cores (\\code{n.cores=\"all-1\"}) keeps some capacity for the OS,\n#' allowing to easier have a look at what's going on.\n#'\n#' Excluding bootstraps which issued a warning or failed with an error (\\code{discard.warnings=T} or\n#' \\code{discard.non.conv=T}, respectively) is pretty 'dangerous' since in case this likely happens many models will\n#' tried to be fitted and then discarded. Hence, getting, say, 1,000 bootstraps may take ages...\n#'\n#' When the argument \\code{use} is not left at its default, the function will return confidence intervals\n#' of fitted values. When a vector is handed over to \\code{use} which includes a single covariate and the model doesn't\n#' include any factors, the function will return a data frame with one column for each term in the model with all\n#' except the intercept and the particular covariate(s) set to zero, as well as columns with the fitted value\n#' (\"fitted\") and its confidence limits (\"lwr\", \"upr\"). The number rows will be equal to \\code{resol} whereby the\n#' covariate will range from its minimum to its maximum with as many values as \\code{resol}, equally spaced.\n#' When the vector handed over to \\code{use} comprises two or more covariates, confidence intervals of fitted\n#' values will be determined for each combination of their values (i.e., all will range from their minimum to\n#' their maximum with \\code{resol} values and the resulting data frame will have \\code{resol}^n rows, with n\n#' being the numbe of covariates). When the model\n#' comprises factors, these will automatically be included in each vector handed over to use. For instance, if a model\n#' comprises the factors 'sex' and 'species' and a covariate 'age' and one runs the function with use=\"sex\", then one\n#' will get fitted values with confidence intervals for each combination of sex, species, and age.\n#'\n#' When a list of vectors is handed over to \\code{use} then a data frame ass described in the previous para is generated\n#' for each element of the list.\n#'\n#' When the model comprises a circular variable fitted by including its sine and cosine into the model\n#' (Stolwijk et al. 1999) and one wants to get confidence intervals of fitted values, then it is important\n#' that the vector with the circular variable (as handed over to the model fitting function is handed over to\n#' \\code{circ.var} and its name (as present in the model to \\code{to circ.var.name}.\n#'\n#' Caution, the function \\code{boot.glmmtmb} is somewhat premature. For instance, it likely fails if the fitted\n#' model doesn't contain random effects...\n#'\n#' @return Returns a list with the following objects:\n#' \\item{ci.estimates}{bootsrapped confidence intervals of model estimates (together with original estimate). In case of\n#' the function \\code{boot.lmer} this is a date frame, and in case of the function \\code{boot.glmmtmb} this\n#' is a named list comprising confidence intervals separately for fixed effects (\\code{ci.estimates$fe}) and\n#' random effects (\\code{ci.estimates$re}).}\n#' \\item{ci.fitted}{confidence intervals of fitted model with regard to what was handed over to \\code{use}. When \\code{use} was\n#' a single vector it will be a single data frame in case of the function \\code{boot.lmer} with one column for\n#' each term in the model (with all covariates not present in \\code{use} set to zero), the fitted value, and\n#' its confidence intervals (columns headed \"lwr\", and \"upr\"). In case of the function \\code{boot.glmmtmb}, it\n#' will be three such data frames, one for each of the conditional, the dispersion, and the zero-inflation model\n#' (given these were present in the model). In case one handed over a list to \\code{use}, \\code{ci.fitted}\n#' will be a list with one object as described so far for each entry in the list.}\n#'\n#' \\item{warnings}{list with the warnings issued by the models fitted to the individual bootstraps (only\n#' present when \\code{boot.lmer} was used).}\n#'\n#' \\item{all.boots}{Data frame with model estimates for each individual bootstrap.}\n#'\n#' @seealso\n#' \\code{\\link[lme4]{bootMer}}, \\code{\\link[glmmTMB]{simulate.glmmTMB}}, \\code{\\link[kyotil]{keepWarnings}} (which I borrowed)\n#' @references\n#' Stolwijk, AM, Straatman H, & Zielhuis GA. 1999. Studying seasonality by using sine and cosine functions in regression analysis. J Epidemiol Community Health, 53:235–238.\n#' @examples\n#' ##examples for \\code{boot.lmer}\n#' \\donttest{\n#' ##minimal examlpe with 10 boostraps for testing:\n#' library(lme4)\n#' data(sleepstudy)\n#' m = lmer(Reaction ~ Days + (Days | Subject), sleepstudy)\n#' boot.m=boot.lmer(m=m, nboots=10)\n#' boot.m$ci.estimates\n#' #obtain confidence intervals of fitted values (low resolution for testing):\n#' boot.m=boot.lmer(m=m, nboots=10, use=\"Days\", resol=10)\n#' boot.m$ci.fitted\n#' }\n#' \\donttest{\n#' ##with factor in model:\n#' data(Orthodont, package=\"nlme\")\n#' m=lmer(distance ~ age + Sex + (1|Subject), data=Orthodont)\n#' boot.m=boot.lmer(m=m, nboots=10, use=\"age\", resol=10)\n#' boot.m$ci.fitted\n#' #comprises a range of age values for each of females and males\n#' boot.m=boot.lmer(m=m, nboots=10, use=\"Sex\", resol=10)\n#' boot.m$ci.fitted\n#' ##age is set to zero in the data frame for which confidence intervals of fitted values are determined\n#'\n#' ##with a list handed over to argument use:\n#' boot.m=boot.lmer(m=m, nboots=10, use=list(\"Sex\", \"age\"), resol=10)\n#' names(boot.m$ci.fitted)\n#' #comprises two data frames; have a look:\n#' boot.m$ci.fitted$Sex\n#' boot.m$ci.fitted$age\n#' }\n#'\n#' ##examples for boot.glmmtmb\n#' \\donttest{\n#' library(glmmTMB)\n#' m = glmmTMB(count ~ mined + (1|site), zi=~mined, family=poisson, data=Salamanders)\n#' boot.m=boot.glmmtmb(m=m, nboots=10, resol=10, data=Salamanders, para=T)\n#' boot.m$ci.estimates$fe\n#' boot.m$ci.estimates$re\n#'\n#' ##bootstrap fitted values, too:\n#' boot.m=boot.glmmtmb(m=m, nboots=10, resol=10, data=Salamanders, use=\"mined\")\n#' names(boot.m$ci.fitted)\n#' boot.m$ci.fitted$cond\n#' boot.m$ci.fitted$zi\n#' boot.m$ci.fitted$disp##null because there is no dispersion part\n#'\n#' ##bootstrap fitted values for combinations of pedictors and zero-inflated part:\n#' m = glmmTMB(count ~ spp + mined + DOP + (1|site), zi=~mined, family=poisson, data=Salamanders)\n#' boot.m=boot.glmmtmb(m=m, nboots=10, resol=10, data=Salamanders, use=c(\"mined\", \"DOP\"))\n#' boot.m$ci.estimates$fe\n#' head(boot.m$ci.fitted$cond)\n#' head(boot.m$ci.fitted$zi)\n#' boot.m$ci.fitted$disp##null because there is no dispersion part\n#'\n#' ##with use being a list:\n#' boot.m=boot.glmmtmb(m=m, nboots=10, resol=10, data=Salamanders, use=list(\"mined\", \"DOP\"))\n#' names(boot.m$ci.fitted)\n#' boot.m$ci.fitted$mined$cond\n#' boot.m$ci.fitted$mined$zi\n#' }\n#'\n#' @rdname boot.lmer\n#' @export\nboot.lmer<-function(m, discard.warnings=F, nboots=1000, para=F, resol=1000, level=0.95,\n use=NULL, circ.var.name=NULL, circ.var=NULL, use.u=F,\n n.cores=c(\"all-1\", \"all\"), save.path=NULL, load.lib=F, lib.loc=.libPaths(), set.all.effects.2.zero=F){\n if(load.lib){library(lme4, lib.loc=lib.loc)}\n n.cores=n.cores[1]\n if(!is.null(use)){\n if(is.list(use)){use.list=use}else{use.list=list(use)}\n }else{\n use.list=NULL\n }\n #keepWarnings<-function(expr){##from package kyotil\n # localWarnings <- list()\n # value <- withCallingHandlers(expr,\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t warning = function(w) {\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t localWarnings[[length(localWarnings)+1]] <<- w\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #invokeRestart(r=\"muffleWarnings\")\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t }\n # )\n # list(value=value, warnings=localWarnings)\n #}\n ##define function extracting all estimated coefficients (fixed and random effects) and also the model summary wrt random effects:\n extract.all<-function(mres, use.u.=use.u){\n ##extract random effects model summary:\n vc.mat=as.data.frame(summary(mres)$varcor)##... and prepare/extract variance covariance matrix from the model handed over\n xx=lapply(summary(mres)$varcor, function(x){attr(x, \"stddev\")})##append residual variance\n ##create vector with names of the terms in the model\n xnames=c(names(fixef(mres)), paste(rep(names(xx), unlist(lapply(xx, length))), unlist(lapply(xx, names)), sep=\"@\"))\n if(class(mres)[1]==\"lmerMod\"){xnames=c(xnames, \"Residual\")}##append \"Residual\" to xnames in case of Gaussian model\n if(class(mres)[1]==\"lmerMod\"){res.sd=vc.mat[vc.mat$grp==\"Residual\", \"sdcor\"]}##extract residual sd i case of Gaussian model\n #if(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat=vc.mat[-nrow(vc.mat), ]}##and drop residuals-row from vc.mat in case of Gaussisn model\n ##deal with names in vc.mat which aren't exactly the name of the resp. random effect\n r.icpt.names=names(ranef(mres))##extract names of random intercepts...\n not.r.icpt.names=setdiff(vc.mat$grp, r.icpt.names)##... and names of the random effects having random slopes\n not.r.icpt.names=unlist(lapply(strsplit(not.r.icpt.names, split=\".\", fixed=T), function(x){paste(x[1:(length(x)-1)], collapse=\".\")}))\n vc.mat$grp[!vc.mat$grp%in%r.icpt.names]=not.r.icpt.names\n if(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat$var1[nrow(vc.mat)]=\"\"}\n xnames=paste(vc.mat$grp, vc.mat$var1, sep=\"@\")\n re.summary=unlist(vc.mat$sdcor)\n names(re.summary)=xnames\n ranef(mres)\n ##extract random effects model summary: done\n ##extract random effects details:\n if(use.u.){\n\t\t\tre.detail=ranef(mres)\n\t\t\txnames=paste(\n\t\t\t\trep(x=names(re.detail), times=unlist(lapply(re.detail, function(x){nrow(x)*ncol(x)}))),\n\t\t\t\tunlist(lapply(re.detail, function(x){rep(colnames(x), each=nrow(x))})),\n\t\t\t\tunlist(lapply(re.detail, function(x){rep(rownames(x), times=ncol(x))})),\n\t\t\t\tsep=\"@\")\n\t\t\tre.detail=unlist(lapply(re.detail, function(x){\n\t\t\t\treturn(unlist(c(x)))\n\t\t\t}))\n\t\t\tnames(re.detail)=xnames\n\t\t}else{\n\t\t\txnames=NULL; re.detail=NULL\n\t\t}\n #deal with negative binomial model to extract theta:\n xx=as.character(summary(mres)$call)\n if(any(grepl(x=xx, pattern=\"negative.binomial\"))){\n xx=xx[grepl(x=xx, pattern=\"negative.binomial\")]\n xx=gsub(x=xx, pattern=\"MASS::negative.binomial(theta = \", replacement=\"\", fixed=T)\n theta=as.numeric(gsub(x=xx, pattern=\")\", replacement=\"\", fixed=T))\n #re.detail=c(re.detail, as.numeric(xx))\n #xnames=c(xnames, \"theta\")\n }else{\n\t\t\ttheta=NULL\n\t\t}\n ns=c(length(fixef(mres)), length(re.summary), length(re.detail), length(theta))\n names(ns)=c(\"n.fixef\", \"n.re.summary\", \"n.blups\", \"n.theta\")\n return(c(fixef(mres), re.summary, re.detail, theta=theta, ns))\n }\n if(discard.warnings){\n boot.fun<-function(x, m., keepWarnings., use.u., save.path.){\n xdone=F\n while(!xdone){\n i.res=keepWarnings.(bootMer(x=m., FUN=extract.all, nsim=1, use.u=use.u.)$t)\n if(length(unlist(i.res$warnings))==0){\n xdone=T\n }\n }\n est.effects=i.res\n i.warnings=NULL\n if(length(save.path.)>0){save(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))}\n return(list(ests=i.res$value, warns=i.warnings))\n }\n }else{\n boot.fun<-function(y, m., keepWarnings., use.u., save.path.){\n #keepWarnings.(bootMer(x=m., FUN=fixef, nsim=1)$t)\n i.res=keepWarnings.(bootMer(x=m., FUN=extract.all, nsim=1, use.u=use.u.)$t)\n if(length(save.path.)>0){\n est.effects=i.res$t\n i.warnings=i.res$warnings\n save(file=paste(c(save.path., \"/b_\", y, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))\n }\n return(list(ests=i.res$value, warns=unlist(i.res$warnings)))\n }\n }\n #browser()\n if(para){\n on.exit(expr = parLapply(cl=cl, X=1:length(cl), fun=function(x){rm(list=ls())}), add = FALSE)\n on.exit(expr = stopCluster(cl), add = T)\n library(parallel)\n cl <- makeCluster(getOption(\"cl.cores\", detectCores()))\n if(n.cores!=\"all\"){\n if(n.cores!=\"all-1\"){n.cores=length(cl)-1}\n if(n.cores0)\n for(i in 1:length(model.terms)){\n if(is.factor(ii.data[, model.terms[i]])){\n new.data[[i]]=levels(ii.data[, model.terms[i]])\n }else if(!is.factor(ii.data[, model.terms[i]]) & usel[i] & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n new.data[[i]]=seq(from=min(ii.data[, model.terms[i]]), to=max(ii.data[, model.terms[i]]), length.out=resol)\n }else if(!is.factor(ii.data[, model.terms[i]]) & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n new.data[[i]]=mean(ii.data[, model.terms[i]])\n }\n }\n names(new.data)=model.terms\n if(length(circ.var.name)==1){\n new.data=new.data[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n if(sum(grepl(pattern=circ.var.name, x=use))>0){\n new.data=c(new.data, list(seq(min(circ.var, na.rm=T), max(circ.var, na.rm=T), length.out=resol)))\n names(new.data)[length(new.data)]=circ.var.name\n }else{\n new.data=c(new.data, list(0))\n }\n model.terms=model.terms[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n }\n xnames=names(new.data)\n #browser()\n new.data=data.frame(expand.grid(new.data))\n names(new.data)=xnames\n if(length(circ.var.name)==1){\n names(new.data)[ncol(new.data)]=circ.var.name\n }\n if(set.all.effects.2.zero){\n for(iterm in setdiff(colnames(new.data), c(\"(Intercept)\", use))){\n new.data[, iterm]=0\n }\n }\n m.mat=model.matrix(object=as.formula(paste(c(\"~\", model), collapse=\"\")), data=new.data)\n if(set.circ.var.to.zero){\n m.mat[,paste(c(\"sin(\", circ.var.name, \")\"), collapse=\"\")]=0\n m.mat[,paste(c(\"cos(\", circ.var.name, \")\"), collapse=\"\")]=0\n }\n #get CIs for fitted values:\n ci=lapply(all.res, function(x){\n #return(apply(m.mat[names(fixef(m)), , drop=F]*as.vector(x[, names(fixef(m))]), 2, sum))\n return(as.vector(m.mat[, names(fixef(m)), drop=F]%*%as.vector(x[, names(fixef(m))])))\n })\n ci=matrix(unlist(ci), ncol=nboots, byrow=F)\n ci=t(apply(ci, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n colnames(ci)=c(\"lwr\", \"upr\")\n fv=m.mat[, names(fixef(m))]%*%fixef(m)\n if(class(m)[[1]]!=\"lmerMod\"){\n if(m@resp$family$family==\"binomial\"){\n ci=exp(ci)/(1+exp(ci))\n fv=exp(fv)/(1+exp(fv))\n }else if(m@resp$family$family==\"poisson\" | substr(x=m@resp$family$family, start=1, stop=17)==\"Negative Binomial\"){\n ci=exp(ci)\n fv=exp(fv)\n }\n }\n return(data.frame(new.data, fitted=fv, ci))\n })\n result=all.fitted\n if(length(use.list)==1){\n\t\t\tresult=as.data.frame(result[[1]])\n\t\t}else{\n\t\t\tnames(result)=unlist(lapply(use.list, paste, collapse=\"@\"))\n\t\t}\n }else{\n result=NULL\n }\n all.boots=matrix(unlist(all.res), nrow=nboots, byrow=T)\n colnames(all.boots)=colnames(all.res[[1]])\n ci.est=apply(all.boots, 2, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T)\n if(length(fixef(m))>1){\n ci.est=data.frame(orig=fixef(m), t(ci.est)[1:length(fixef(m)), ])\n }else{\n ci.est=data.frame(orig=fixef(m), t(t(ci.est)[1:length(fixef(m)), ]))\n }\n return(list(ci.estimates=ci.est, ci.fitted=result, warnings=all.warns, all.boots=all.boots))\n}\n\n#' @rdname boot.lmer\n#' @export\nboot.glmmtmb<-function(m, data, discard.non.conv=F, nboots=1000, para=F, resol=100, level=0.95,\n use=NULL, circ.var.name=NULL, circ.var=NULL,\n n.cores=c(\"all-1\", \"all\"), save.path=NULL, load.lib=T, lib.loc=.libPaths(), set.all.effects.2.zero=F){\n if(!summary(m)$link%in%c(\"log\", \"logit\", \"identity\")){\n stop(\"link functions other than log, logit, or identity aren't supported yet; please contact Roger\")\n }\n if(load.lib){library(lme4, lib.loc=lib.loc)}\n if(!is.null(use)){\n if(is.list(use)){use.list=use}else{use.list=list(use)}\n }else{\n use.list=NULL\n }\n print(\"doesn't account for circular variables in the zero-inflated model\")\n print(\"haven't tested it yet with a cbind response\")\n n.cores=n.cores[1]\n #if(is.null(getCall(m)$control)){\n # contr=glmmTMBControl()\n #}\n ##does the model comprise any random effects?\n has.RE=any(!unlist(lapply(summary(m)$varcor, is.null)))\n extract.BLUPs.from.glmmTB<-function(m){\n to.do=lapply(c(\"cond\", \"zi\"), function(x){\n if(length(ranef(m)[[x]])>0){\n lapply(ranef(m)[[x]], function(y){\n return(list(\n what=rep(x, prod(dim(as.matrix(y)))),\n blup=unlist(c(as.matrix(y))),\n level=rep(rownames(y), times=ncol(y)),\n Name=rep(colnames(y), each=nrow(y))\n ))\n })\n }else{\n return(list(list(what=NULL, blup=NULL, level=NULL, Name=NULL)))\n }\n })\n xc=sapply(lapply(to.do[[1]], \"[[\", \"what\"), length)\n xz=sapply(lapply(to.do[[2]], \"[[\", \"what\"), length)\n res=data.frame(\n what=as.vector(unlist(lapply(to.do, function(x){lapply(x, \"[[\", \"what\")}))),\n Grp=c(rep(names(xc), times=xc), rep(names(xz), times=xz)),\n Name=as.vector(unlist(lapply(to.do, function(x){lapply(x, \"[[\", \"Name\")}))),\n level=as.vector(unlist(lapply(to.do, function(x){lapply(x, \"[[\", \"level\")}))),\n blup=as.vector(unlist(lapply(to.do, function(x){lapply(x, \"[[\", \"blup\")})))\n )\n res=res[order(res$what, res$Grp, res$Name, res$level), ]\n return(res)\n }\n extract.all<-function(mres){\n if(has.RE){\n\t\t\t##extract random effects model summary:\n\t\t\tm=extract.ranef.glmmTMB(m=mres)\n\t\t\t##extract random effects, BLUPs:\n\t\t\tBLUPs=extract.BLUPs.from.glmmTB(m=mres)\n\t\t}else{\n\t\t\tm=NULL\n\t\t\tBLUPs=NULL\n\t\t}\n ##dispersion parameter:\n dp=summary(mres)$sigma\n ##fixed effects\n xx=fixef(mres)\n fe=data.frame(\n what=rep(names(xx), times=sapply(xx, length)),\n term=unlist(lapply(xx, names)),\n est=unlist(xx)\n )\n fe=fe[order(fe$what, fe$term), ]\n return(list(fe=fe, sigma=dp, m=m, BLUPs=BLUPs))\n }\n ##prepare for new calls:\n xcall=as.character(m$call)\n names(xcall)=names(m$call)\n xcall=list(cond.form=xcall[\"formula\"], zi.form=xcall[\"ziformula\"], disp.form=xcall[\"dispformula\"], xfam=xcall[\"family\"])\n if(grepl(xcall[[\"xfam\"]], pattern=\"(\", fixed=T)){\n xfam=xcall[[\"xfam\"]]\n xfam=unlist(strsplit(xfam, split=\"(\", fixed=T))\n xfam[2]=gsub(x=xfam[2], pattern=\")\", replacement=\"\", fixed=T)\n xfam[2]=gsub(x=xfam[2], pattern=\"link = \", replacement=\"\", fixed=T)\n xfam[2]=gsub(x=xfam[2], pattern=\"\\\"\", replacement=\"\", fixed=T)\n if(substr(xcall[[\"xfam\"]], start=1, stop=5)!=\"Gamma\"){\n xcall[[\"xfam\"]]=get(xfam[1])(xfam[2])\n }else{\n if(xfam[2]==\"log\"){\n xcall[[\"xfam\"]]=Gamma(link=\"log\")\n }else if(xfam[2]==\"inverse\"){\n xcall[[\"xfam\"]]=Gamma(link=\"inverse\")\n }else if(xfam[2]==\"identity\"){\n xcall[[\"xfam\"]]=Gamma(link=\"identity\")\n }else{\n stop(\"Error: family not supported\")\n\t\t\t\t}\n }\n }\n\n #xweights=try(m$frame[, \"(weights)\"], silent=T)\n #if(class(xweights)[[1]]==\"try-error\"){\n # xweights=rep(1, nrow(m$frame))\n #}\n #data$xweights.X.=xweights\n rv.name=gsub(unlist(strsplit(xcall[[\"cond.form\"]], split=\"~\"))[1], pattern=\" \", replacement=\"\", fixed=T)\n ##define function doing the bootstrap:\n boot.fun<-function(x, xcall., data., rv.name., m., discard.non.conv., save.path., extract.all.){\n xdone=F\n while(!xdone){\n done2=F\n while(!done2){\n data.[, rv.name.]=simulate(object=m.)[, 1]\n if(xcall[[\"xfam\"]][[\"family\"]]!=\"beta\" |\n (xcall[[\"xfam\"]][[\"family\"]]==\"beta\" & min(data.[, rv.name.])>0 & max(data.[, rv.name.])<1)){\n done2=T\n }\n }\n i.res=try(update(m., data=data.), silent=T)\n #return(update(m., data=data.))\n #i.res=try(glmmTMB(formula=as.formula(xcall.[[\"cond.form\"]]), ziformula=as.formula(xcall.[[\"zi.form\"]]), dispformula=as.formula(xcall.[[\"disp.form\"]]),\n # data=data., control=contr., family=xcall[[\"xfam\"]], weights=xweights.X.), silent=T)\n if(class(i.res)[[1]]!=\"try-error\"){\n\t\t\t\tif(i.res$sdr$pdHess | !discard.non.conv.){\n\t\t\t\t\txdone=T\n\t\t\t\t}\n\t\t\t}\n }\n\t\tif(class(i.res)[[1]]!=\"try-error\"){\n\t\t\tconv=i.res$sdr$pdHess\n\t\t\ti.res=extract.all.(mres=i.res)\n\t\t\tif(length(save.path.)>0){save(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=c(\"i.res\", \"conv\"))}\n\t\t\treturn(list(boot.res=i.res, conv=conv))\n\t\t}else{\n\t\t\treturn(NULL)\n\t\t}\n }\n ##do bootstrap:\n if(para){\n library(parallel)\n cl <- makeCluster(getOption(\"cl.cores\", detectCores()))\n if(n.cores!=\"all\"){\n if(n.cores==\"all-1\"){n.cores=length(cl)-1}\n if(n.cores0){\n ci.fitted.cond=NULL\n ci.fitted.zi=NULL\n ci.fitted.disp=NULL\n #extract fixed effects terms from the model:\n model.terms=c(attr(terms(as.formula(xcall[[\"cond.form\"]])), \"term.labels\"),\n attr(terms(as.formula(xcall[[\"zi.form\"]])), \"term.labels\"),\n attr(terms(as.formula(xcall[[\"disp.form\"]])), \"term.labels\"))\n #exclude random effects:\n model.terms=model.terms[!grepl(x=model.terms, pattern=\"|\", fixed=T)]\n #exclude random effects, interactions and squared terms from model.terms:\n model.terms=model.terms[!grepl(x=model.terms, pattern=\"I(\", fixed=T)]\n model.terms=model.terms[!grepl(x=model.terms, pattern=\":\", fixed=T)]\n model.terms=unique(model.terms)\n\n all.fitted=lapply(use.list, function(use){\n #create new data to be used to determine fitted values:\n if(length(use)==0){use=model.terms}\n new.data=vector(\"list\", length(model.terms))\n if(length(circ.var.name)==1){\n set.circ.var.to.zero=sum(circ.var.name%in%use)==0\n }else{\n set.circ.var.to.zero=F\n }\n usel=model.terms%in%use\n #if(length(use)>0)\n for(i in 1:length(model.terms)){\n if(is.factor(data[, model.terms[i]])){\n new.data[[i]]=levels(data[, model.terms[i]])\n }else if(!is.factor(data[, model.terms[i]]) & usel[i] & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n new.data[[i]]=seq(from=min(data[, model.terms[i]]), to=max(data[, model.terms[i]]), length.out=resol)\n }else if(!is.factor(data[, model.terms[i]]) & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n new.data[[i]]=mean(data[, model.terms[i]])\n }\n }\n names(new.data)=model.terms\n\n if(length(circ.var.name)==1){\n new.data=new.data[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n if(sum(grepl(pattern=circ.var.name, x=use))>0){\n new.data=c(new.data, list(seq(min(circ.var, na.rm=T), max(circ.var, na.rm=T), length.out=resol)))\n names(new.data)[length(new.data)]=circ.var.name\n }else{\n new.data=c(new.data, list(0))\n }\n model.terms=model.terms[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n }\n xnames=names(new.data)\n #browser()\n new.data=data.frame(expand.grid(new.data))\n names(new.data)=xnames\n #browser()\n if(length(circ.var.name)==1){\n names(new.data)[ncol(new.data)]=circ.var.name\n }\n if(set.all.effects.2.zero){\n for(iterm in setdiff(colnames(new.data), c(\"(Intercept)\", use))){\n new.data[, iterm]=0\n }\n }\n ##prepare model frame for conditional model for prediction:\n model=attr(terms(as.formula(xcall[[\"cond.form\"]])), \"term.labels\")\n model=model[!grepl(x=model, pattern=\"|\", fixed=T)]\n if(length(model)==0){model=\"1\"}\n cond.m.mat=model.matrix(object=as.formula(paste(c(\"~\", paste(model, collapse=\"+\")), collapse=\"\")), data=new.data)\n if(set.circ.var.to.zero){\n cond.m.mat[,paste(c(\"sin(\", circ.var.name, \")\"), collapse=\"\")]=0\n cond.m.mat[,paste(c(\"cos(\", circ.var.name, \")\"), collapse=\"\")]=0\n }\n ##get bootstrapped fitted values for the conditional part:\n ests=all.ind.boots$fe[, substr(colnames(all.ind.boots$fe), start=1, stop=5)==\"cond@\", drop=F]\n est.names=gsub(colnames(ests), pattern=\"cond@\", replacement=\"\")\n ci.cond=lapply(1:nrow(ests), function(x){\n return(cond.m.mat[, est.names, drop=F]%*%as.vector(ests[x, ]))\n })\n ci.cond=matrix(unlist(ci.cond), ncol=length(all.res), byrow=F)\n ci.cond=t(apply(ci.cond, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n colnames(ci.cond)=c(\"lower.cl\", \"upper.cl\")\n ##get fitted value for the conditional part:\n ests=ci.estimates$fe\n ests=ests[substr(rownames(ests), start=1, stop=5)==\"cond@\", , drop=F]\n est.names=gsub(rownames(ests), pattern=\"cond@\", replacement=\"\")\n fv.cond=cond.m.mat[, est.names, drop=F]%*%ests$orig\n if(summary(m)$link==\"log\"){\n ci.fitted.cond=data.frame(fitted=exp(fv.cond), exp(ci.cond))\n }else if(summary(m)$link==\"logit\"){\n ci.fitted.cond=data.frame(fitted=plogis(fv.cond), plogis(ci.cond))\n }else if(summary(m)$link==\"identity\"){\n ci.fitted.cond=data.frame(fitted=fv.cond, ci.cond)\n }\n ci.fitted.cond=data.frame(new.data, ci.fitted.cond)\n\n ##prepare model frame for ZI model for prediction:\n if(!is.null(summary(m)$coefficients$zi)){\n model=attr(terms(as.formula(xcall[[\"zi.form\"]])), \"term.labels\")\n model=model[!grepl(x=model, pattern=\"|\", fixed=T)]\n if(length(model)==0){model=\"1\"}\n zi.m.mat=model.matrix(object=as.formula(paste(c(\"~\", paste(model, collapse=\"+\")), collapse=\"\")), data=new.data)\n ##get bootstrapped fitted values for the conditional part:\n ests=all.ind.boots$fe[, substr(colnames(all.ind.boots$fe), start=1, stop=3)==\"zi@\", drop=F]\n est.names=gsub(colnames(ests), pattern=\"zi@\", replacement=\"\")\n ci.zi=lapply(1:nrow(ests), function(x){\n return(zi.m.mat[, est.names, drop=F]%*%as.vector(ests[x, ]))\n })\n ci.zi=matrix(unlist(ci.zi), ncol=length(all.res), byrow=F)\n ci.zi=t(apply(ci.zi, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n colnames(ci.zi)=c(\"lower.cl\", \"upper.cl\")\n ##get fitted value for the conditional part:\n ests=ci.estimates$fe\n ests=ests[substr(rownames(ests), start=1, stop=3)==\"zi@\", , drop=F]\n est.names=gsub(rownames(ests), pattern=\"zi@\", replacement=\"\")\n fv.zi=zi.m.mat[, est.names, drop=F]%*%ests$orig\n ci.fitted.zi=data.frame(fitted=plogis(fv.zi), plogis(ci.zi))\n #ci.fitted.zi=ci.fitted*(1-ci.fitted.zi)\n ci.fitted.zi=data.frame(new.data, ci.fitted.zi)\n }\n\n ##prepare model frame for disp model for prediction:\n if(!is.null(summary(m)$coefficients$disp)){\n model=attr(terms(as.formula(xcall[[\"disp.form\"]])), \"term.labels\")\n model=model[!grepl(x=model, pattern=\"|\", fixed=T)]\n if(length(model)==0){model=\"1\"}\n disp.m.mat=model.matrix(object=as.formula(paste(c(\"~\", paste(model, collapse=\"+\")), collapse=\"\")), data=new.data)\n ##get bootstrapped fitted values for the conditional part:\n ests=all.ind.boots$fe[, substr(colnames(all.ind.boots$fe), start=1, stop=5)==\"disp@\", drop=F]\n est.names=gsub(colnames(ests), pattern=\"disp@\", replacement=\"\")\n ci.disp=lapply(1:nrow(ests), function(x){\n return(disp.m.mat[, est.names, drop=F]%*%as.vector(ests[x, ]))\n })\n ci.disp=matrix(unlist(ci.disp), ncol=length(all.res), byrow=F)\n ci.disp=t(apply(ci.disp, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n colnames(ci.disp)=c(\"lwr\", \"upr\")\n ##get fitted value for the dispersion part:\n ests=ci.estimates$fe\n ests=ests[substr(rownames(ests), start=1, stop=5)==\"disp@\", , drop=F]\n est.names=gsub(rownames(ests), pattern=\"disp@\", replacement=\"\")\n fv.disp=disp.m.mat[, est.names, drop=F]%*%ests$orig\n ci.fitted.disp=data.frame(fitted=exp(fv.disp), exp(ci.disp))\n #ci.fitted.disp=ci.fitted*(1-ci.fitted.disp)\n ci.fitted.disp=data.frame(new.data, ci.fitted.disp)\n }\n ci.fitted=list(\n cond=ci.fitted.cond,\n zi=ci.fitted.zi,\n disp=ci.fitted.disp\n )\n return(ci.fitted)\n })\n if(length(use.list)>1){\n names(all.fitted)=unlist(lapply(use.list, paste, collapse=\"@\"))\n }else{\n all.fitted=all.fitted[[1]]\n }\n }else{\n all.fitted=NULL\n }\n return(list(ci.estimates=ci.estimates, ci.fitted=all.fitted, all.boots=all.ind.boots))\n}\n", "meta": {"hexsha": "2234f0015c635f76978801a23c0bfa40b6a05f71", "size": 36846, "ext": "r", "lang": "R", "max_stars_repo_path": "R_scripts/boot_glmm.r", "max_stars_repo_name": "dagdpz/fmri-reach-decision", "max_stars_repo_head_hexsha": "0840a1a63b73603a8980b6c0bdcec6c51d15680c", "max_stars_repo_licenses": ["MIT"], "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_scripts/boot_glmm.r", "max_issues_repo_name": "dagdpz/fmri-reach-decision", "max_issues_repo_head_hexsha": "0840a1a63b73603a8980b6c0bdcec6c51d15680c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R_scripts/boot_glmm.r", "max_forks_repo_name": "dagdpz/fmri-reach-decision", "max_forks_repo_head_hexsha": "0840a1a63b73603a8980b6c0bdcec6c51d15680c", "max_forks_repo_licenses": ["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.6094986807, "max_line_length": 172, "alphanum_fraction": 0.6420506975, "num_tokens": 10861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2674016342650133}} {"text": "#--------------------------------------------------------------------------------\n# Name: IBM_MonteCarlo.r\n# Purpose: MonteCarlo Simulation. Stand-alone script. \n# Author: Francesco Tonini\n# Email: \t f_tonini@hotmail.com\n# Created: 11/10/2011\n# Copyright: (c) 2011 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##Make sure to specify the appropriate path using either / or \\\\ to specify the path \nmainDir <- '~/Desktop/Temp'\n\n##Let's set the working directory\nsetwd(file.path(mainDir))\n\n#Path to folders in which you want to save all your vector & raster files\nworkdir_Raster <- 'Raster'\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, workdir_Raster), 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('myfunctionsMC.R')\n\n##Load all required libraries\nprint('Loading required libraries...')\nload.packages()\n\n###Let's set all simulation parameters:\n\n##Number of Monte Carlo runs\ncat('\\nHow many MonteCarlo simulation runs?\\n')\nNRuns <- scan(n=1)\n\n##First Year of Simulation (input from terminal console)\ncat('\\nWhat is the first year of simulation?\\n')\nstart_time <- scan(n=1)\n\n##Last Year of Simulation (input from terminal console)\ncat('\\nWhat Is The Last Year Of Simulation?\\n')\nend_time <- scan(n=1)\nwhile(end_time < start_time) {\n\ttkmessageBox(title = \"Warning\", message = 'The last year of simulation cannot be inferior to the first year!...Please type again'\n\t\t\t\t, icon = \"warning\", type = \"ok\")\n\tend_time <- scan(n=1)\n}\n\n##Set the age at which colonies start producing first swarmers\ncat('\\nAt what age do colonies generate the first swarmers?\\n')\nColAge_swarmers <- scan(n=1)\n\n##Set the maximum life expectancy for a colony (input from terminal console)\ncat('\\nWhat is the maximum life expectancy of a colony (in years)?\\n')\nMaxAge <- scan(n=1)\n\n##Apply a radius representing the max attraction distance btw Males & Females\ncat('\\nType max attraction distance between males & females (in meters)?\\n')\nradius <- scan(n=1)\nwhile(radius == 0) {\n\ttkmessageBox(title = \"Warning\", message = 'The attraction distance must be > 0!...Please type again'\n\t\t\t\t, icon = \"warning\", type = \"ok\")\n\tradius <- scan(n=1)\n}\n \n##Read background non-suitable habitat layer\nhabitat_block <- read.NSHabitat()\n\n##Read the Input File w/ Starting Points (colonies)\n##By default it assigns a random age to all input colonies\nstarting_colonies <- read.file(random.age = 'random')\n\n##Check habitat suitability and remove colonies falling within non-suitable habitat\nstarting_colonies <- habitat.survival(starting_colonies)\n\n##Define a Simulation Extent\nextent <- simulation.extent()\n\n##Check for max density of source colonies, based on the user input \n##This module returns a list (to access list elements use $ sign)\ncat('\\nType the maximum colony density in colonies per hectare (1ha = 100 sq. meters)\\n')\nmaxdensity <- scan(n=1)\nlst <- max.density.source()\n\n##lst is a list with outputs returned by the max.density.source() module\nstarting_colonies <- lst$starting_colonies\nmaxdensity <- lst$maxdensity \n\n##Create a database to store occupied areas over time & across all MC simulation runs\narea.dataset <- as.data.frame(matrix(0,ncol=1,nrow=NRuns))\ncolnames(area.dataset) <- start_time\nrownames(area.dataset) <- paste('Run',seq(NRuns),sep='')\n\n##If we only have ONE source of invasion, define an empty vector in which we will store the \n##mean Eucl. dist. of all existing colonies from it, at each time step\nif (nrow(starting_colonies) == 1) {\n\tavgdistSource <- as.data.frame(matrix(0,ncol=1,nrow=NRuns))\n\tcolnames(avgdistSource) <- start_time\n\trownames(avgdistSource) <- paste('Run',seq(NRuns),sep='')\n}\n\n##Create a Tk window element as a container\nroot <- tktoplevel()\ntktitle(root) <- 'MonteCarlo Simulation'\n\n##Define the label of the first progress bar\nl1 <- tk2label(root)\n##Define the length of the first progress bar\npb1 <- tk2progress(root, length = 300)\n##Configure the first progress bar's max value (min is always = 0)\n##Max will be the number of MC simulation runs - 1 (since index starts at 0)\ntkconfigure(pb1, value=0, maximum = NRuns-1)\n\n##Define the label of the second progress bar\nl2 <- tk2label(root)\n##Define the length of the second progress bar\npb2 <- tk2progress(root, length = 300)\n##Configure the second progress bar's max value (min is always = 0)\n##Max will be the number of subdivisions - 1 (since index starts at 0)\ntkconfigure(pb2, value=0, maximum = 2)\n\n##Pack all labels and progress bars inside the Tk container\ntkpack(l1)\ntkpack(pb1)\ntkpack(l2)\ntkpack(pb2)\n\n##Refresh the Tk window\ntcl('update')\n\n##LOOP for each MC simulation run\nfor (run in seq(NRuns)){\n\t\n\t##Configure the MC Runs progress bar by updating its label and current value\n\ttkconfigure(l1, text = paste('Run', run))\n tkconfigure(pb1, value = run - 1)\n\t\n\t##Let's now create an object called colonies (we do not delete starting_colonies because it can still be used)\n\tcolonies <- starting_colonies\n\t\n\t##LOOP for each year of simulation\n\tfor (year in seq(start_time,end_time)){\n\t\t\n\t\ttkconfigure(l2, text = paste('Year',year))\n tkconfigure(pb2, value = 0)\n\t\ttcl('update')\n\t\t\n\t\tif (year == start_time) {\n\t\t\t\n\t\t\t##Estimate the approx. area covered by current colonies in Km^2\n\t\t\t##If writeRas=TRUE a raster file (.img or as defined in source file) is produced\n\t\t\tTot_area <- raster.save(colonies,year,writeRas=TRUE)\n\t\t\tarea.dataset[run,year-start_time+1] <- Tot_area\n\t\t\tcolnames(area.dataset)[year-start_time+1] <- year\n\t\t\t\n\t\t\t##Remove objects not needed from the memory\n\t\t\trm(Tot_area)\n\t\t\t\n\t\t\t##Update progress bar (move progress segment to the end of the bar)\n\t\t\ttkconfigure(pb2, value = 2)\n\t\t\ttcl('update')\n\t\t\t\n\t\t}else{\n\t\t\n\t\t\t##Increase Age and Timecount by 1\n\t\t\tcolonies <- age.increase()\n\t\t\t\n\t\t\t##Only keep current colonies (remove the past year)\n\t\t\tcolonies <- colonies[which(colonies$Timecount == year),]\n\t\t\t\n\t\t\t##Colonies older than MaxAge die (i.e. removed from dataset)\n\t\t\tif (length(which(colonies$Age > MaxAge)) > 0) colonies = colonies[-which(colonies$Age > MaxAge),]\n\t\t\t\n\t\t\t##Generate offspring for each existing colony\n\t\t\t##Change the scenario to 'pessimistic' if colonies generate more individuals at a younger age\n\t\t\t##(other scenarios can be defined within the script 'myfunctionsMC.R' and can be manually changed)\n\t\t\tif (any(colonies$Age >= ColAge_swarmers)) {\n\t\t\t\t\n\t\t\t\tout <- offspring.generate(survival_prob = 0.01, male_prob = 0.5, scenario = 'optimistic', dist.mean = 200) \n\t\t\t\tpop <- out$pop\n\t\t\t\tflag <- out$flag\n\t\t\t\t\n\t\t\t\t##flag = 1 if ONE or MORE individuals crossed the simulation boundaries\n\t\t\t\t##If flag is not NULL print a warning on screen, EXIT (break) the loop and move to the next MC simulation run \n\t\t\t\tif (!is.null(flag)) {\n\t\t\t\t\n\t\t\t\t\tcat('\\n')\n\t\t\t\t\tcat('WARNING: ONE OR MORE INDIVIDUALS LAY OUTSIDE THE SIMULATION EXTENT!!\\n')\n\t\t\t\t\tcat(paste('The Current & All Following Simulation Runs Will Be Terminated Before Year: ',year,'\\n',sep=''))\n\t\t\t\t\tcat('\\n')\n\t\t\t\t\tmaxyear <- year - 1\n\t\t\t\t\t\n\t\t\t\t\t##Overwrite end_time with a value corresponding to the current year - 1\n\t\t\t\t\t##so that in the next MC run the simulation will stop at the same year\n\t\t\t\t\t##This is done to be able to compare across MC runs for same years\n\t\t\t\t\tend_time <- maxyear\n\t\t\t\t\t\n\t\t\t\t\t##EXIT the inner loop and go to the next MC simulation run\n\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}else{ out <- NULL }\n\t\t\t\n\t\t\t##Configure the progress bar by updating its value \n\t\t\t##(the green bar will move 1 segment forward)\n\t\t\ttkconfigure(pb2, value = 1)\n\t\t\ttcl('update')\n\t\t\t\n\t\t\t##Only if there are AT LEAST two swarmers check for Male-Female within a 'radius' buffer\n\t\t\tif (!is.null(out)){\n\t\t\t\t\n\t\t\t\t##Check for Male-Female within a 'radius' buffer\n\t\t\t\tnew_colonies <- new.colonies.create()\n\t\t\t\t\t\t\n\t\t\t\t##Store new colonies in the main colony dataset\n\t\t\t\tif (nrow(new_colonies) > 0) {\n\t\t\t\n\t\t\t\t\tcolonies <- new.colonies.stack()\n\t\t\t\t\t\n\t\t\t\t\t##Check habitat suitability of current colonies\n\t\t\t\t\tcolonies <- habitat.survival(colonies)\n\t\t\t\t\t\n\t\t\t\t\t##Uncomment one of the following modules when having only ONE source of invasion\n\t\t\t\t\t##and you are interested in keeping ONLY colonies laying on the fringe:\t\t\n\t\t\t\t\t##colonies <- convex.hull(colonies) \n\t\t\t\t\t\n\t\t\t\t\t##If there are no colonies left exit the LOOP, set the new end_time to the current year\n\t\t\t\t\t##and EXIT the LOOP\n\t\t\t\t\tif (nrow(colonies) == 0) {\n\t\t\t\t\t\tprint(paste('No colonies survived at year', year))\n\t\t\t\t\t\tTot_area <- raster.save(colonies,year,writeRas=TRUE)\n\t\t\t\t\t\tarea.dataset[run,year-start_time+1] <- Tot_area\n\t\t\t\t\t\tcolnames(area.dataset)[year-start_time+1] <- year\n\t\t\t\t\t\tmaxyear <- year\n\t\t\t\t\t\tend_time <- maxyear\n\t\t\t\t\t\t##EXIT the inner loop and go to the next MC simulation run\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t\t##Remove objects not needed from the memory \n\t\t\t\trm(list=c('pop', 'new_colonies'))\n\t\t\t}\t\n\t\t\t\n\t\t\t##Configure the progress bar by updating its value \n\t\t\t##(the green bar will move 1 segment forward)\n\t\t\ttkconfigure(pb2, value = 2)\n\t\t\ttcl('update')\n\t\t\n\t\t\t##Estimate the approx. area covered by current colonies in Km^2\n\t\t\t##If writeRas=TRUE a raster file (.img or as defined in source file) is produced\n\t\t\tTot_area <- raster.save(colonies,year,writeRas=TRUE)\n\t\t\tarea.dataset[run,year-start_time+1] <- Tot_area\n\t\t\tcolnames(area.dataset)[year-start_time+1] <- year\n\t\t\t\n\t\t\t##If we are starting with ONE source of invasion, calculate the mean Eucl. dist. of all colonies \n\t\t\t##from the source\n\t\t\tif (nrow(starting_colonies) == 1) {\n\t\t\t\tavgdistSource[run,year-start_time+1] <- dist.source(colonies)\n\t\t\t\tcolnames(avgdistSource)[year-start_time+1] <- year\n\t\t\t}\n\t\t\t\n\t\t\t##Remove objects not needed from the memory\n\t\t\trm(Tot_area)\n\t\t\n\t\t}\n\t\t\n\t}\t\n\t\n\tsave.image()\n}\t\n\n#Final message of simulation is over\ntkmessageBox(title = \"Message\", message = 'The simulation is over!', icon = \"info\", type = \"ok\")\t\n\n##Suppress the progress bar\ntkdestroy(root)\n\n##Print on screen a summary of statistics across all MC runs \nsummary.stats()\n\n##Ask whether the user wants to compute and save an 'occupancy envelope' or not \nenvelope.raster()\n\t\n\n\n\n\n\n", "meta": {"hexsha": "b7d5811647e12b114e36e5264c6d7d5dee81bb88", "size": 10529, "ext": "r", "lang": "R", "max_stars_repo_path": "IBM/Mac OSX/MonteCarlo/IBM_MonteCarlo.r", "max_stars_repo_name": "f-tonini/Termite-Dispersal-Simulation", "max_stars_repo_head_hexsha": "ebf6ae776f18e4d6e6ee53028c280050d4df960b", "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": "IBM/Mac OSX/MonteCarlo/IBM_MonteCarlo.r", "max_issues_repo_name": "f-tonini/Termite-Dispersal-Simulation", "max_issues_repo_head_hexsha": "ebf6ae776f18e4d6e6ee53028c280050d4df960b", "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": "IBM/Mac OSX/MonteCarlo/IBM_MonteCarlo.r", "max_forks_repo_name": "f-tonini/Termite-Dispersal-Simulation", "max_forks_repo_head_hexsha": "ebf6ae776f18e4d6e6ee53028c280050d4df960b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-28T10:05:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T10:05:07.000Z", "avg_line_length": 35.5709459459, "max_line_length": 130, "alphanum_fraction": 0.6905689049, "num_tokens": 2776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.26482907213575}} {"text": "#use Rscript --vanilla /datacit/Development/RNAseq_YR/SMAP_fusion/fusionAnalysis_forpaper.r $STAR_FUSION_DIR $SAMPLE\n#exemple /datacit/Development/RNAseq_YR/SMAP_fusion/fusionAnalysis_forpaper.r /datacit/Development/RNAseq_YR/SMAP_fusion/ Sample_3\n\n#STAR_FUSION_DIR=commandArgs(trailingOnly=TRUE)[1]\n#SAMPLE=commandArgs(trailingOnly=TRUE)[2]\n\n.fuzprocess=function(f,sample){\n \n y=utils::read.delim(f,sep=\"\\t\",header=F,as.is=T,comment.char=\"\",skip=1)\n colnames(y)=gsub(\"^#\",\"\",unlist(strsplit(scan(f,sep='\\n',what=\"character\",nlines=1,quiet = T)[1],\"\\t\")))\n \n suppressWarnings({\n y[,2]=as.integer(\ty[,2])\n y[,3]=as.integer(\ty[,3])\n })\n \n y=y[which(!is.na(y[,2])&!is.na(y[,3])),]\n y[,1]=gsub(\"^#\",\"\" \t,y[,1])\n \n y=y[,which(colSums(is.na(y))0)\n nb0span = sum(frag_span>0)\n #print(nb0junc)\n #print(nb0span)\n \n if(nb0junc<4 & nb0span<4) .cstop(\"Too few reads support the interspecies-Fusion for H0 calculation\")\n \n if(nb0junc> 2 & nb0span<4){\n print(\"H0 on junction reads only\")\n nulld1=MASS::fitdistr(UnfiltFuz[which(UnfiltFuz[,rightgeneOrgCol] != UnfiltFuz[,leftgeneOrgCol]),valuecols[1]],\"negative binomial\")$estimate\n humanfuze[[paste(valuecols[1],\"_\",\"Pvalue\",sep=\"\")]] = 1-stats::pnbinom(humanfuze[[valuecols[1]]],size=nulld1[\"size\"],mu=nulld1[\"mu\"])\n humanfuze[[paste(valuecols[1],\"_\",\"adj.pvalue\",sep=\"\")]]=stats::p.adjust( humanfuze[[paste(valuecols[1],\"_\",\"Pvalue\",sep=\"\")]],method=\"fdr\")\n return(humanfuze)\n }\n if(nb0junc>2 & nb0span>2){\n print(\"H0 on junction reads and Spanning Fragments\")\n nulld1=MASS::fitdistr (UnfiltFuz[which(UnfiltFuz[,rightgeneOrgCol] != UnfiltFuz[,leftgeneOrgCol]),valuecols[1]],\"negative binomial\")$estimate\n nulld2=MASS::fitdistr (UnfiltFuz[which(UnfiltFuz[,rightgeneOrgCol] != UnfiltFuz[,leftgeneOrgCol]),valuecols[2]],\"negative binomial\")$estimate\n logx=unique(floor(2^(seq(0,10,by=0.1))))\n x=log2(logx+1)\n xd1 <- stats::dnbinom(logx, mu =nulld1[\"mu\"], size = nulld1[\"size\"])\n xd2 <- stats::dnbinom(logx, mu = nulld2[\"mu\"], size = nulld2[\"size\"])\n humanfuze[[paste(valuecols[1],\"_\",\"Pvalue\",sep=\"\")]] = 1-stats::pnbinom(humanfuze[[valuecols[1]]],size=nulld1[\"size\"],mu=nulld1[\"mu\"])\n humanfuze[[paste(valuecols[2],\"_\",\"Pvalue\",sep=\"\")]]=1-stats::pnbinom(humanfuze[[valuecols[2]]],size=nulld2[\"size\"],mu=nulld2[\"mu\"])\n humanfuze$Combined_pvalue=apply(humanfuze[,c(paste(valuecols[1],\"_\",\"Pvalue\",sep=\"\"),paste(valuecols[2],\"_\",\"Pvalue\",sep=\"\"))],1,.fishersMethod)\n humanfuze$Combined_adj.pvalue=stats::p.adjust(humanfuze$Combined_pvalue,method=\"fdr\")\n X=humanfuze\n X$decisionPvals=cut(X$Combined_adj.pvalue,breaks=c(0,0.001,0.01,0.05,0.1,1),include.lowest=T)\n FPvals=cbind(UnfiltFuz[which(UnfiltFuz[,rightgeneOrgCol] != UnfiltFuz[,leftgeneOrgCol]),valuecols[1]],\n UnfiltFuz[which(UnfiltFuz[,rightgeneOrgCol] != UnfiltFuz[,leftgeneOrgCol]),valuecols[2]])\n colnames(FPvals)=valuecols\n xmax=ceiling(log2(1+max(UnfiltFuz[,valuecols[1]])))\n logx=unique(floor(2^(seq(0,xmax,by=0.1))))\n xd1 <- stats::dnbinom(logx, mu =nulld1[\"mu\"], size = nulld1[\"size\"])\n xx=log2(logx+1)\n ymax=ceiling(log2(1+max(UnfiltFuz[,valuecols[2]])))\n logy=unique(floor(2^(seq(0,ymax,by=0.1))))\n xd2 <- stats::dnbinom(logy, mu = nulld2[\"mu\"], size = nulld2[\"size\"])\n xy=log2(logy+1)\n #pdf(paste(STAR_FUSION_DIR,\"/\", SAMPLE,\"/SMAPFusions_fusionsAnalysis_filternDecisionThreshPval.pdf\", sep=\"\"))\n \n par(fig=c(0,0.8,0,0.75),mar=c(5.1,4.1,1,1))\n smoothScatter(log2(FPvals+1),transformation = function(x) x^.2,xlim=c(0,ymax),ylim=c(0,xmax) )\n points(log2(X[,valuecols]+1),col=rev(c(\"black\",\"purple\",\"red\",\"orange\",\"green\"))[as.integer(X$decisionPvals)],pch=16)\n legend(\"topright\",paste(c(\">0.1\",\"<0.1\",\"<0.05\",\"<0.01\",\"<0.001\"),\"(fdr)\"),col=c(\"black\",\"purple\",\"red\",\"orange\",\"green\"),pch=16, cex=0.9)\n par(fig=c(0.8,1,0,0.75),new=T,mar=c(5.1,1,4.1,1))\n barplot(xd1,xx,type=\"l\",axes=T,bty=\"l\",horiz=T,xlab=\"Prob. distribution\")\n par(fig=c(0,0.8,0.75,1),new=T,mar=c(1,4.1,3,1))\n barplot(xd2,xy,type=\"l\",axes=T,bty=\"l\",main=\"Parametric p-values (negative binomial)\",ylab=\"Prob. distribution\")\n #dev.off()\n \n }\n \n \n \n # isfilt=unlist(lapply(1:nrow(humanfuze),function(i){\n # thisfuz=humanfuze[i,]\n # js=which(filtfuz$X.fusion_name == thisfuz$X.fusion_name &\n # filtfuz$sample == thisfuz$sample &filtfuz$LeftBreakpoint == thisfuz$LeftBreakpoint\n # &filtfuz$RightBreakpoint == thisfuz$RightBreakpoint&filtfuz$Splice_type == thisfuz$Splice_type )\n # length(js)\n #}))\n # humanfuze$PassStarFusion =isfilt>0\n return(humanfuze)\n \n}\n\n\n", "meta": {"hexsha": "51a10b6d8e96def8ab5594118a59bb40b51440bf", "size": 8643, "ext": "r", "lang": "R", "max_stars_repo_path": "R/SMAPfuz.r", "max_stars_repo_name": "RemyNicolle/SMAP", "max_stars_repo_head_hexsha": "8f4914632a718fc49e460971330e25e08aa09745", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-20T10:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T10:10:08.000Z", "max_issues_repo_path": "R/SMAPfuz.r", "max_issues_repo_name": "RemyNicolle/SMAP", "max_issues_repo_head_hexsha": "8f4914632a718fc49e460971330e25e08aa09745", "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/SMAPfuz.r", "max_forks_repo_name": "RemyNicolle/SMAP", "max_forks_repo_head_hexsha": "8f4914632a718fc49e460971330e25e08aa09745", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-29T10:10:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T10:10:10.000Z", "avg_line_length": 47.489010989, "max_line_length": 152, "alphanum_fraction": 0.6753442092, "num_tokens": 2841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.26348251969804043}} {"text": "#' Epigenome-wide association study\n#'\n#' Test association with each CpG site.\n#'\n#' @param beta Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param variable Independent variable vector.\n#' @param covariates Covariates data frame to include in regression model,\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param batch Batch vector to be included as a random effect (Default: NULL).\n#' @param weights Non-negative observation weights.\n#' Can be a numeric matrix of individual weights of same dimension as \\code{beta},\n#' or a numeric vector of weights with length \\code{ncol(beta)},\n#' or a numeric vector of weights with length \\code{nrow(beta)}. \n#' @param cell.counts Proportion of cell counts for one cell type in cases\n#' where the samples are mainly composed of two cell types (e.g. saliva) (Default: NULL).\n#' @param isva Apply Independent Surrogate Variable Analysis (ISVA) to the\n#' methylation levels and include the resulting variables as covariates in a\n#' regression model (Default: TRUE). \n#' @param sva Apply Surrogate Variable Analysis (SVA) to the\n#' methylation levels and covariates and include\n#' the resulting variables as covariates in a regression model (Default: TRUE).\n#' @param n.sv Number of surrogate variables to calculate (Default: NULL).\n#' @param winsorize.pct Apply all regression models to methylation levels\n#' winsorized to the given level. Set to NA to avoid winsorizing (Default: 0.05).\n#' @param robust Test associations with the 'robust' option when \\code{\\link{limma::eBayes}}\n#' is called (Default: TRUE).\n#' @param rlm Test assocaitions with the 'robust' option when \\code{\\link{limma:lmFit}}\n#' is called (Default: FALSE).\n#' @param outlier.iqr.factor For each CpG site, prior to fitting regression models,\n#' set methylation levels less than\n#' \\code{Q1 - outlier.iqr.factor * IQR} or more than\n#' \\code{Q3 + outlier.iqr.factor * IQR} to NA. Here IQR is the inter-quartile\n#' range of the methylation levels at the CpG site, i.e. Q3-Q1.\n#' Set to NA to skip this step (Default: NA).\n#' @param most.variable Apply (Independent) Surrogate Variable Analysis to the \n#' given most variable CpG sites (Default: 50000).\n#' @param featureset Name from \\code{\\link{meffil.list.featuresets}()} (Default: NA).\n#' @param verbose Set to TRUE if status updates to be printed (Default: FALSE).\n#'\n#' @export\nmeffil.ewas <- function(beta, variable,\n covariates=NULL, batch=NULL, weights=NULL,\n cell.counts=NULL,\n isva=T, sva=T, ## cate?\n n.sv=NULL,\n isva0=F,isva1=F, ## deprecated\n winsorize.pct=0.05,\n robust=TRUE,\n rlm=FALSE,\n outlier.iqr.factor=NA, ## typical value = 3\n most.variable=min(nrow(beta), 50000),\n featureset=NA,\n random.seed=20161123,\n verbose=F) {\n\n if (isva0 || isva1)\n stop(\"isva0 and isva1 are deprecated and superceded by isva and sva\")\n \n if (is.na(featureset))\n featureset <- guess.featureset(rownames(beta))\n features <- meffil.get.features(featureset)\n \n stopifnot(length(rownames(beta)) > 0 && all(rownames(beta) %in% features$name))\n stopifnot(ncol(beta) == length(variable))\n stopifnot(is.null(covariates) || is.data.frame(covariates) && nrow(covariates) == ncol(beta))\n stopifnot(is.null(batch) || length(batch) == ncol(beta))\n stopifnot(is.null(weights)\n || is.numeric(weights) && (is.matrix(weights) && nrow(weights) == nrow(beta) && ncol(weights) == ncol(beta)\n || is.vector(weights) && length(weights) == nrow(beta)\n || is.vector(weights) && length(weights) == ncol(beta)))\n stopifnot(most.variable > 1 && most.variable <= nrow(beta))\n stopifnot(!is.numeric(winsorize.pct) || winsorize.pct > 0 && winsorize.pct < 0.5)\n\n original.variable <- variable\n original.covariates <- covariates\n if (is.character(variable))\n variable <- as.factor(variable)\n \n stopifnot(!is.factor(variable) || is.ordered(variable) || length(levels(variable)) == 2)\n \n msg(\"Simplifying any categorical variables.\", verbose=verbose)\n variable <- simplify.variable(variable)\n if (!is.null(covariates))\n covariates <- do.call(cbind, lapply(covariates, simplify.variable))\n\n sample.idx <- which(!is.na(variable))\n if (!is.null(covariates))\n sample.idx <- intersect(sample.idx, which(apply(!is.na(covariates), 1, all)))\n \n msg(\"Removing\", ncol(beta) - length(sample.idx), \"missing case(s).\", verbose=verbose)\n\n if (is.matrix(weights))\n weights <- weights[,sample.idx]\n if (is.vector(weights) && length(weights) == ncol(beta))\n weights <- weights[sample.idx]\n \n beta <- beta[,sample.idx]\n variable <- variable[sample.idx]\n\n if (!is.null(covariates))\n covariates <- covariates[sample.idx,,drop=F]\n\n if (!is.null(batch))\n batch <- batch[sample.idx]\n\n if (!is.null(cell.counts))\n cell.counts <- cell.counts[sample.idx]\n\n if (!is.null(covariates)) {\n pos.var.idx <- which(apply(covariates, 2, var, na.rm=T) > 0)\n msg(\"Removing\", ncol(covariates) - length(pos.var.idx), \"covariates with no variance.\",\n verbose=verbose)\n covariates <- covariates[,pos.var.idx, drop=F]\n }\n\n covariate.sets <- list(none=NULL)\n if (!is.null(covariates))\n covariate.sets$all <- covariates\n\n if (is.numeric(winsorize.pct)) {\n msg(winsorize.pct, \"- winsorizing the beta matrix.\", verbose=verbose)\n beta <- winsorize(beta, pct=winsorize.pct)\n }\n\n too.hi <- too.lo <- NULL\n if (is.numeric(outlier.iqr.factor)) {\n q <- rowQuantiles(beta, probs = c(0.25, 0.75), na.rm = T)\n iqr <- q[,2] - q[,1]\n too.hi <- which(beta > q[,2] + outlier.iqr.factor * iqr, arr.ind=T)\n too.lo <- which(beta < q[,1] - outlier.iqr.factor * iqr, arr.ind=T)\n if (nrow(too.hi) > 0) beta[too.hi] <- NA\n if (nrow(too.lo) > 0) beta[too.lo] <- NA\n }\n\n if (isva || sva) {\n beta.sva <- beta\n \n autosomal.sites <- meffil.get.autosomal.sites(featureset)\n autosomal.sites <- intersect(autosomal.sites, rownames(beta.sva))\n if (length(autosomal.sites) < most.variable) {\n warning(\"Probes from the sex chromosomes will be used to calculate surrogate variables.\")\n } else {\n beta.sva <- beta.sva[autosomal.sites,]\n }\n var.idx <- order(rowVars(beta.sva, na.rm=T), decreasing=T)[1:most.variable]\n beta.sva <- impute.matrix(beta.sva[var.idx,,drop=F])\n \n if (!is.null(covariates)) {\n cov.frame <- model.frame(~., data.frame(covariates, stringsAsFactors=F), na.action=na.pass)\n mod0 <- model.matrix(~., cov.frame)\n }\n else\n mod0 <- matrix(1, ncol=1, nrow=length(variable))\n mod <- cbind(mod0, variable)\n\n if (isva) {\n msg(\"ISVA.\", verbose=verbose)\n set.seed(random.seed)\n isva.ret <- isva(beta.sva, mod, ncomp=n.sv, verbose=verbose)\n if (!is.null(covariates))\n covariate.sets$isva <- data.frame(covariates, isva.ret$isv, stringsAsFactors=F)\n else\n covariate.sets$isva <- as.data.frame(isva.ret$isv)\n cat(\"\\n\")\n }\n \n if (sva) {\n msg(\"SVA.\", verbose=verbose)\n set.seed(random.seed)\n sva.ret <- sva(beta.sva, mod=mod, mod0=mod0, n.sv=n.sv)\n if (!is.null(covariates))\n covariate.sets$sva <- data.frame(covariates, sva.ret$sv, stringsAsFactors=F)\n else\n covariate.sets$sva <- as.data.frame(sva.ret$sv)\n cat(\"\\n\")\n }\n }\n\n analyses <- sapply(names(covariate.sets), function(name) {\n msg(\"EWAS for covariate set\", name, verbose=verbose)\n covariates <- covariate.sets[[name]]\n ewas(variable,\n beta=beta,\n covariates=covariates,\n batch=batch,\n weights=weights,\n cell.counts=cell.counts,\n winsorize.pct=winsorize.pct, \n robust=robust, \n rlm=rlm)\n }, simplify=F)\n\n p.values <- sapply(analyses, function(analysis) analysis$table$p.value)\n coefficients <- sapply(analyses, function(analysis) analysis$table$coefficient)\n rownames(p.values) <- rownames(coefficients) <- rownames(analyses[[1]]$table)\n\n for (name in names(analyses)) {\n idx <- match(rownames(analyses[[name]]$table), features$name)\n analyses[[name]]$table$chromosome <- features$chromosome[idx]\n analyses[[name]]$table$position <- features$position[idx]\n }\n\n list(class=\"ewas\",\n version=packageVersion(\"meffil\"),\n samples=sample.idx,\n variable=original.variable[sample.idx],\n covariates=original.covariates[sample.idx,,drop=F],\n winsorize.pct=winsorize.pct,\n robust=robust,\n rlm=rlm,\n outlier.iqr.factor=outlier.iqr.factor,\n most.variable=most.variable,\n p.value=p.values,\n coefficient=coefficients,\n analyses=analyses,\n random.seed=random.seed,\n too.hi=too.hi,\n too.lo=too.lo)\n}\n\nis.ewas.object <- function(object)\n is.list(object) && \"class\" %in% names(object) && object$class == \"ewas\"\n\n# Test associations between \\code{variable} and each row of \\code{beta}\n# while adjusting for \\code{covariates} (fixed effects) and \\code{batch} (random effect).\n# If \\code{cell.counts} is not \\code{NULL}, then it is assumed that\n# the methylation data is derived from samples with two cell types.\n# \\code{cell.counts} should then be a vector of numbers\n# between 0 and 1 of length equal to \\code{variable} corresponding\n# to the proportions of cell of a selected cell type in each sample.\n# The regression model is then modified in order to identify\n# associations specifically in the selected cell type (PMID: 24000956).\newas <- function(variable, beta, covariates=NULL, batch=NULL, weights=NULL, cell.counts=NULL, winsorize.pct=0.05,\n robust=TRUE, rlm=FALSE, verbose=F) {\n stopifnot(all(!is.na(variable)))\n stopifnot(length(variable) == ncol(beta))\n stopifnot(is.null(covariates) || nrow(covariates) == ncol(beta))\n stopifnot(is.null(batch) || length(batch) == ncol(beta))\n stopifnot(is.null(cell.counts)\n || length(cell.counts) == ncol(beta)\n && all(cell.counts >= 0 & cell.counts <= 1))\n \n method <- \"ls\"\n if (rlm) method <- \"robust\"\n \n if (is.null(covariates))\n design <- data.frame(intercept=1, variable=variable)\n else\n design <- data.frame(intercept=1, variable=variable, covariates)\n rownames(design) <- colnames(beta)\n\n if (!is.null(cell.counts)) {\n ## Irizarray method: Measuring cell-type specific differential methylation\n ## in human brain tissue\n ## Mi is methylation level for sample i\n ## Xi is the value of the variable of interest for sample i\n ## pi is the proportion of the target cell type for sample i\n ## thus: Mi ~ target cell methylation * pi + other cell methylation * (1-pi)\n ## and target cell methylation = base target methylation + effect of Xi value\n ## and other cell methylation = base other methylation + effect of Xi value\n ## thus:\n ## Mi = (T + U Xi)pi + (O + P Xi)(1-pi) + e\n ## = C + A Xi pi + B Xi (1-pi) + e \n design <- design[,-which(colnames(design) == \"intercept\")]\n \n design <- cbind(design * cell.counts,\n typeB=design * (1-cell.counts))\n }\n\n msg(\"Linear regression with limma::lmFit\", verbose=verbose)\n fit <- NULL\n batch.cor <- NULL\n if (!is.null(batch)) {\n msg(\"Adjusting for batch effect\", verbose=verbose)\n corfit <- duplicateCorrelation(beta, design, block=batch, ndups=1)\n batch.cor <- corfit$consensus\n msg(\"Linear regression with batch as random effect\", verbose=verbose)\n tryCatch(fit <- lmFit(beta, design, method=method, block=batch, cor=batch.cor, weights=weights),\n error=function(e) {\n print(e)\n msg(\"lmFit failed with random effect batch variable, omitting\", verbose=verbose)\n })\n }\n if (is.null(fit)) {\n msg(\"Linear regression with only fixed effects\", verbose=verbose)\n batch <- NULL\n fit <- lmFit(beta, design, method=method, weights=weights)\n }\n \n msg(\"Empirical Bayes\", verbose=verbose)\n if (is.numeric(winsorize.pct) && robust) {\n fit.ebayes <- eBayes(fit, robust=T, winsor.tail.p=c(winsorize.pct, winsorize.pct))\n } else {\n fit.ebayes <- eBayes(fit, robust=robust)\n }\n\n alpha <- 0.975\n std.error <- (sqrt(fit.ebayes$s2.post) * fit.ebayes$stdev.unscaled[,\"variable\"])\n margin.error <- (std.error * qt(alpha, df=fit.ebayes$df.total))\n n <- rowSums(!is.na(beta))\n\n list(design=design,\n batch=batch,\n batch.cor=batch.cor,\n cell.counts=cell.counts,\n table=data.frame(p.value=fit.ebayes$p.value[,\"variable\"],\n fdr=p.adjust(fit.ebayes$p.value[,\"variable\"], \"fdr\"),\n p.holm=p.adjust(fit.ebayes$p.value[,\"variable\"], \"holm\"),\n t.statistic=fit.ebayes$t[,\"variable\"],\n coefficient=fit.ebayes$coefficient[,\"variable\"],\n coefficient.ci.high=fit.ebayes$coefficient[,\"variable\"] + margin.error,\n coefficient.ci.low=fit.ebayes$coefficient[,\"variable\"] - margin.error,\n coefficient.se=std.error,\n n=n)) \n}\n\n\n\n\n", "meta": {"hexsha": "bdfdf2922b6fd35e321a8a5c6e13e77e6ce7a11d", "size": 13931, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ewas.r", "max_stars_repo_name": "jlevy44/meffil", "max_stars_repo_head_hexsha": "09996e699cd2b833b0a8cb50eaaf52954315d26d", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-08T22:32:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-08T22:32:20.000Z", "max_issues_repo_path": "R/ewas.r", "max_issues_repo_name": "jlevy44/meffil", "max_issues_repo_head_hexsha": "09996e699cd2b833b0a8cb50eaaf52954315d26d", "max_issues_repo_licenses": ["Artistic-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/ewas.r", "max_forks_repo_name": "jlevy44/meffil", "max_forks_repo_head_hexsha": "09996e699cd2b833b0a8cb50eaaf52954315d26d", "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": 43.534375, "max_line_length": 121, "alphanum_fraction": 0.6115138899, "num_tokens": 3632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26067985162986895}} {"text": "#!/usr/bin/Rscript\n\n# attempt to load a library implementing the Bradley-Terry model for inferring rankings based on\n# comparisons; if it doesn't load, try to install it through R's in-language package management;\n# otherwise, abort and warn the user\n# https://www.jstatsoft.org/v48/i09/\n\n# Add the repo to the R search path\noptions(repos = list(CRAN=\"http://cran.rstudio.com/\"))\n\nloaded <- library(BradleyTerry2, quietly=TRUE, logical.return=TRUE)\nif (!loaded) { write(\"warning: R library 'BradleyTerry2' unavailable; attempting to install locally...\", stderr())\n install.packages(\"BradleyTerry2\")\n loadedAfterInstall <- library(BradleyTerry2, quietly=TRUE, logical.return=TRUE)\n if(!loadedAfterInstall) { write(\"error: 'BradleyTerry2' unavailable and cannot be installed. Aborting.\", stderr()); quit() }\n}\n# similarly, but for the library to parse command line arguments:\nloaded <- library(argparser, quietly=TRUE, logical.return=TRUE)\nif (!loaded) { write(\"warning: R library 'argparser' unavailable; attempting to install locally...\", stderr())\n install.packages(\"argparser\")\n loadedAfterInstall <- library(argparser, quietly=TRUE, logical.return=TRUE)\n if(!loadedAfterInstall) { write(\"error: 'argparser' unavailable and cannot be installed. Aborting.\", stderr()); quit() }\n}\np <- arg_parser(\"sort a list using comparative rankings under the Bradley-Terry statistical model; see https://www.gwern.net/Resorter\", name=\"resorter\")\np <- add_argument(p, \"--input\", short=\"-i\",\n \"input file: a CSV file of items to sort: one per line, with up to two columns. (eg both 'Akira\\\\n' and 'Akira, 10\\\\n' are valid).\", type=\"character\")\np <- add_argument(p, \"--output\", \"output file: a file to write the final results to. Default: printing to stdout.\")\np <- add_argument(p, \"--verbose\", \"whether to print out intermediate statistics\", flag=TRUE)\np <- add_argument(p, \"--queries\", short=\"-n\", default=NA,\n \"Maximum number of questions to ask the user; defaults to N*log(N) comparisons. If already rated, 𝒪(n) is a good max, but the more items and more levels in the scale and more accuracy desired, the more comparisons are needed.\")\np <- add_argument(p, \"--levels\", short=\"-l\", default=5, \"The highest level; rated items will be discretized into 1-l levels, so l=5 means items are bucketed into 5 levels: [1,2,3,4,5], etc\")\np <- add_argument(p, \"--quantiles\", short=\"-q\", \"What fraction to allocate to each level; space-separated; overrides `--levels`. This allows making one level of ratings narrower (and more precise) than the others, at their expense; for example, one could make 3-star ratings rarer with quantiles like `--quantiles '0 0.25 0.8 1'`. Default: uniform distribution (1--5 → '0.0 0.2 0.4 0.6 0.8 1.0').\")\np <- add_argument(p, \"--no-scale\", flag=TRUE, \"Do not discretize/bucket the final estimated latent ratings into 1-l levels/ratings; print out inferred latent scores.\")\np <- add_argument(p, \"--progress\", flag=TRUE, \"Print out mean standard error of items\")\nargv <- parse_args(p)\n\n# read in the data from either the specified file or stdin:\nif(!is.na(argv$input)) { ranking <- read.csv(file=argv$input, stringsAsFactors=TRUE, header=FALSE); } else {\n ranking <- read.csv(file=file('stdin'), stringsAsFactors=TRUE, header=FALSE); }\n\n# turns out noisy sorting is fairly doable in 𝒪(n * log(n)), so do that plus 1 to round up:\nif (is.na(argv$queries)) { n <- nrow(ranking)\n argv$queries <- round(n * log(n) + 1) }\n\n# if user did not specify a second column of initial ratings, then put in a default of '1':\nif(ncol(ranking)==1) { ranking$Rating <- 1; }\ncolnames(ranking) <- c(\"Media\", \"Rating\")\n# A set of ratings like 'foo,1\\nbar,2' is not comparisons, though. We *could* throw out everything except the 'Media' column\n# but we would like to accelerate the interactive querying process by exploiting the valuable data the user has given us.\n# So we 'seed' the comparison dataset based on input data: higher rating means +1, lower means −1, same rating == tie (0.5 to both)\ncomparisons <- NULL\nfor (i in 1:(nrow(ranking)-1)) {\n rating1 <- ranking[i,]$Rating\n media1 <- ranking[i,]$Media\n rating2 <- ranking[i+1,]$Rating\n media2 <- ranking[i+1,]$Media\n if (rating1 == rating2)\n {\n comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=0.5, \"win2\"=0.5))\n } else { if (rating1 > rating2)\n {\n comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=1, \"win2\"=0))\n } else {\n comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=0, \"win2\"=1))\n } } }\n# the use of '0.5' is recommended by the BT2 paper, despite causing quasi-spurious warnings:\n# > In several of the data examples (e.g., `?CEMS`, `?springall`, `?sound.fields`), ties are handled by the crude but\n# > simple device of adding half of a 'win' to the tally for each player involved; in each of the examples where this\n# > has been done it is found that the result is similar, after a simple re-scaling, to the more sophisticated\n# > analyses that have appeared in the literature. Note that this device when used with `BTm` typically gives rise to\n# > warnings produced by the back-end glm function, about non-integer 'binomial' counts; such warnings are of no\n# > consequence and can be safely ignored. It is likely that a future version of `BradleyTerry2` will have a more\n# > general method for handling ties.\nsuppressWarnings(priorRankings <- BTm(cbind(win1, win2), Media.1, Media.2, data = comparisons))\n\nif(argv$verbose) {\n print(\"higher=better:\")\n print(summary(priorRankings))\n print(sort(BTabilities(priorRankings)[,1]))\n}\n\nset.seed(2015-09-10)\ncat(\"Comparison commands: 1=yes, 2=tied, 3=second is better, p=print estimates, s=skip, q=quit\\n\")\nfor (i in 1:argv$queries) {\n\n # with the current data, calculate and extract the new estimates:\n suppressWarnings(updatedRankings <- BTm(cbind(win1, win2), Media.1, Media.2, br=TRUE, data = comparisons))\n coefficients <- BTabilities(updatedRankings)\n # sort by latent variable 'ability':\n coefficients <- coefficients[order(coefficients[,1]),]\n\n if(argv$verbose) { print(i); print(coefficients); }\n\n # select two media to compare: pick the media with the highest standard error and the media above or below it with the highest standard error:\n # which is a heuristic for the most informative pairwise comparison. BT2 appears to get caught in some sort of a fixed point with greedy selection,\n # so every few rounds pick a random starting point:\n media1N <- if (i %% 3 == 0) { which.max(coefficients[,2]) } else { sample.int(nrow(coefficients), 1) }\n media2N <- if (media1N == nrow(coefficients)) { nrow(coefficients)-1; } else { # if at the top & 1st place, must compare to 2nd place\n if (media1N == 1) { 2; } else { # if at the bottom/last place, must compare to 2nd-to-last\n # if neither at bottom nor top, then there are two choices, above & below, and we want the one with highest SE; if equal, arbitrarily choose the better:\n if ( (coefficients[,2][media1N+1]) > (coefficients[,2][media1N-1]) ) { media1N+1 } else { media1N-1 } } }\n\n targets <- row.names(coefficients)\n media1 <- targets[media1N]\n media2 <- targets[media2N]\n\n if (argv$`progress`) { cat(paste0(\"Mean stderr: \", round(mean(coefficients[,2]))), \" | \"); }\n cat(paste0(\"Is '\", as.character(media1), \"' greater than '\", as.character(media2), \"'? \"))\n rating <- scan(\"stdin\", character(), n=1, quiet=TRUE)\n\n switch(rating,\n \"1\" = { comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=1, \"win2\"=0)) },\n \"3\" = { comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=0, \"win2\"=1)) },\n \"2\" = { comparisons <- rbind(comparisons, data.frame(\"Media.1\"=media1, \"Media.2\"=media2, \"win1\"=0.5, \"win2\"=0.5))},\n \"p\" = { estimates <- data.frame(Media=row.names(coefficients), Estimate=coefficients[,1], SE=coefficients[,2]);\n print(comparisons)\n print(warnings())\n print(summary(updatedRankings))\n print(estimates[order(estimates$Estimate),], row.names=FALSE) },\n \"s\" = {},\n \"q\" = { break; }\n )\n}\n\n# results of all the questioning:\nif(argv$verbose) { print(comparisons); }\n\nsuppressWarnings(updatedRankings <- BTm(cbind(win1, win2), Media.1, Media.2, ~ Media, id = \"Media\", data = comparisons))\ncoefficients <- BTabilities(updatedRankings)\nif(argv$verbose) { print(rownames(coefficients)[which.max(coefficients[2,])]);\n print(summary(updatedRankings))\n print(sort(coefficients[,1])) }\n\nranking2 <- as.data.frame(BTabilities(updatedRankings))\nranking2$Media <- rownames(ranking2)\nrownames(ranking2) <- NULL\n\nif(!(argv$`no_scale`)) {\n\n # if the user specified a bunch of buckets using `--quantiles`, parse it and use it,\n # otherwise, take `--levels` and make a uniform distribution\n quantiles <- if (!is.na(argv$quantiles)) { (sapply(strsplit(argv$quantiles, \" \"), as.numeric))[,1]; } else {\n seq(0, 1, length.out=(argv$levels+1)); }\n ranking2$Quantile <- with(ranking2, cut(ability,\n breaks=quantile(ability, probs=quantiles),\n labels=1:(length(quantiles)-1),\n include.lowest=TRUE))\n df <- subset(ranking2[order(ranking2$Quantile, decreasing=TRUE),], select=c(\"Media\", \"Quantile\"));\n if (!is.na(argv$output)) { write.csv(df, file=argv$output, row.names=FALSE) } else { print(df); }\n} else { # return just the latent continuous scores:\n df <- data.frame(Media=rownames(coefficients), Estimate=coefficients[,1]);\n if (!is.na(argv$output)) { write.csv(df[order(df$Estimate, decreasing=TRUE),], file=argv$output, row.names=FALSE); } else {\n print(finalReport); }\n }\n\ncat(\"\\nResorting complete\")", "meta": {"hexsha": "357bd9ed1b22faf32526c2100a44f845a6472d33", "size": 10056, "ext": "r", "lang": "R", "max_stars_repo_path": "resorter.r", "max_stars_repo_name": "AndrewQuinn2020/resorter", "max_stars_repo_head_hexsha": "ec04c066f6ebbce929d01f06e15c279e8aebb44b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-28T19:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T19:45:56.000Z", "max_issues_repo_path": "resorter.r", "max_issues_repo_name": "AndrewQuinn2020/resorter", "max_issues_repo_head_hexsha": "ec04c066f6ebbce929d01f06e15c279e8aebb44b", "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": "resorter.r", "max_forks_repo_name": "AndrewQuinn2020/resorter", "max_forks_repo_head_hexsha": "ec04c066f6ebbce929d01f06e15c279e8aebb44b", "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": 64.4615384615, "max_line_length": 398, "alphanum_fraction": 0.6751193317, "num_tokens": 2727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2595221635520404}} {"text": "#setwd(\"D:/Dropbox/Data analyze/Rdocuments/datas\")\nlibrary(xlsx)\n library(RColorBrewer)\n \n #读取数据\n#k1<-read.xlsx(\"t_for.xls\", sheetName = \"0.2\", header = TRUE)\n#k2<-read.xlsx(\"t_for.xls\", sheetName = \"0.3\", header = TRUE)\n#k3<-read.xlsx(\"t_for.xls\", sheetName = \"0.4\", header = TRUE)\n#k4<-read.xlsx(\"t_for.xls\", sheetName = \"0.5\", header = TRUE)\nfv<-5:3500\n\nq<-c(2.5e-14, 4.5e-13, 9e-13, 3e-12) #不同的流量下\n\nk<-c(0.8,0.7,0.6,0.5) #不同占空比下无电场时间比例,即1-k_i\n\nv<-4.66e-13 #泰勒锥的体积总量\n\n#jpeg(file=\"figure2.jpg\")\n\npar(mfrow=c(2,2), mar=c(4,2,2,2), oma=c(2,4,2,2))\n\nmycolors<-c(\"red\", \"blue\", \"darkgreen\", \"yellow3\")\n\nc1<- 0.2 * 4.66e-13 #弯月面体积,用以标识体积增量占泰勒锥体积的大小\n#c2<- 0.1 * 4.66e-13\n#c3<- 0.05 * 4.66e-13\n#c4<-0.4 * 4.66e-13\n#c5<- 0.6 * 4.66e-13\nc<-4.66e-13 #泰勒锥体积\n\n\n\n#####占空比为0.2时######\nplot(fv, (k[1]*q[1]/fv+v), col=mycolors[1], log=\"x\", type=\"l\", xlab = expression(log(italic(f[\"v\"])) (Hz)), ylab = expression(italic(volume[\"increase\"](m^3))), main=\"k=0.2\", lwd=2.5, ylim=c(4e-13, 10e-13))#y轴的边界,在不同的占空比k下应该相差不大,最大应该是V_m的2倍,即10e-13左右\n\nfor (i in 1:3){\nlines(fv, (k[1]*q[i+1]/fv+v), lwd=2.5, col=mycolors[i+1] )\n}\ntitle(\"k=0.2\")\nlegend(\"topright\", c(\"1.5nl/min\",\"27nl/min\",\"54nl/min\",\"180nl/min\"), inset=0.02, col=mycolors, lwd=2.5, lty=1, cex=1.1, bty=\"n\")\n\nabline(h=c, col=\"red\", lty=2, lwd=2)\nabline(h=1.2*c, col=\"blue\", lty=2, lwd=2)\nabline(h=1.5*c, col=\"darkgreen\",lty=2, lwd=2)\n\n#text(50, 2.5e-14, \"5% V_M,red\", col=\"blue\", cex=1.2, font=2)\n#text(50, 4e-14, \"10% V_M,blue\", col=\"blue\", cex=1.2, font=2)\n\n#####占空比k=0.3######\nplot(fv, (k[2]*q[1]/fv+v), col=mycolors[1], log=\"x\", type=\"l\", xlab = expression(log(italic(f[\"v\"])) (Hz)), ylab = expression(italic(volume[\"increase\"](m^3))), main=\"k=0.3\", lwd=2.5, ylim=c(4e-13, 10e-13))\n\nfor (i in 1:3){\nlines(fv, (k[2]*q[i+1]/fv+v), lwd=2.5, col=mycolors[i+1] )\n}\ntitle(\"k=0.3\")\nlegend(\"topright\", c(\"1.5nl/min\",\"27nl/min\",\"54nl/min\",\"180nl/min\"), inset=0.02, col=mycolors, lwd=2.5, lty=1, cex=1.1, bty=\"n\")\n\nabline(h=c, col=\"red\", lty=2, lwd=2)\nabline(h=1.2*c, col=\"blue\", lty=2, lwd=2)\nabline(h=1.5*c, col=\"darkgreen\",lty=2, lwd=2)\n\n#text(50, 1.8e-13, \"20% V_M,green\", col=\"blue\", cex=1.2, font=2)\n#text(50, 1.2e-13, \"10% V_M,blue\", col=\"blue\", cex=1.2, font=2)\n#text(50, 0.75e-14, \"5% V_M,red\", col=\"blue\", cex=1.2, font=2)\n\n#####占空比k=0.4######\nplot(fv, (k[3]*q[1]/fv+v), col=mycolors[1], log=\"x\", type=\"l\", xlab = expression(log(italic(f[\"v\"])) (Hz)), ylab = expression(italic(volume[\"increase\"](m^3))), main=\"k=0.4\", lwd=2.5 , ylim=c(4e-13, 10e-13))\n\nfor (i in 1:3){\nlines(fv, (k[3]*q[i+1]/fv+v), lwd=2.5, col=mycolors[i+1] )\n}\ntitle(\"k=0.4\")\nlegend(\"topright\", c(\"1.5nl/min\",\"27nl/min\",\"54nl/min\",\"180nl/min\"), inset=0.02, col=mycolors, lwd=2.5, lty=1, cex=1.1, bty=\"n\")\n\nabline(h=c, col=\"red\", lty=2, lwd=2)\nabline(h=1.2*c, col=\"blue\", lty=2, lwd=2)\nabline(h=1.5*c, col=\"darkgreen\",lty=2, lwd=2)\n\n#text(50, 5e-13, \"20% V_M, green\", col=\"blue\", cex=1.2, font=2)\n#text(50, 4e-13, \"10% V_M, blue\", col=\"blue\", cex=1.2, font=2)\n#text(50, 3e-13, \"5% V_M, red\", col=\"blue\", cex=1.2, font=2)\n\n#####占空比k=0.5######\nplot(fv, (k[4]*q[1]/fv+v), col=mycolors[1], log=\"x\", type=\"l\", xlab = expression(log(italic(f[\"v\"])) (Hz)), ylab = expression(italic(volume[\"increase\"](m^3))), main=\"k=0.5\", lwd=2.5 , ylim=c(4e-13, 10e-13))\n\nfor (i in 1:3){\nlines(fv, (k[4]*q[i+1]/fv+v), lwd=2.5, col=mycolors[i+1] )\n}\ntitle(\"k=0.5\")\nlegend(\"topright\", c(\"1.5nl/min\",\"27nl/min\",\"54nl/min\",\"180nl/min\"), inset=0.02, col=mycolors, lwd=2.5, lty=1, cex=1.1, bty=\"n\")\n\nabline(h=c, col=\"red\", lty=2, lwd=2)\nabline(h=1.2*c, col=\"blue\", lty=2, lwd=2)\nabline(h=1.5*c, col=\"darkgreen\",lty=2, lwd=2)\n\n#text(50, 1.6e-12, \"60% V_M,yellow\", col=\"blue\", cex=1.2, font=2)\n#text(50, 1.2e-12, \"50% V_M,green\", col=\"blue\", cex=1.2, font=2)\n#text(50, 0.8e-12, \"20% V_M, blue\", col=\"blue\", cex=1.2, font=2)\n#text(50, 0.5e-12, \"5% V_M, red\", col=\"blue\", cex=1.2, font=2)\n\n#dev.off()", "meta": {"hexsha": "0fba6de1f500d5008a5301c1b4471fc694750457", "size": 3883, "ext": "r", "lang": "R", "max_stars_repo_path": "volume-chap3/volume_all.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": "volume-chap3/volume_all.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": "volume-chap3/volume_all.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": 38.4455445545, "max_line_length": 249, "alphanum_fraction": 0.5910378573, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.25919102195464}} {"text": "#-----------------------------------------------------------------------------------------------------------------------------------------------------------\n\n#------------------------------------------ Forest risk mapping models: Fig 1D-F code - 05/11/21 ----------------------------------------------\n\n#-----------------------------------------------------------------------------------------------------------------------------------------------------------\n# Author: William Anderegg (anderegg@utah.edu), University of Utah\n\nlibrary(rworldmap)\nlibrary(MASS)\nlibrary(SDMTools)\nlibrary(raster)\nlibrary(RNetCDF)\nlibrary(scales)\nlibrary(car)\nlibrary(RColorBrewer)\nlibrary(betareg)\nlibrary(pgirmess)\nlibrary(geosphere)\nlibrary(ape)\n\n\n#---------------------------------- Pull in FIA mort data -------------------------------------\ndir <- \"\"\nfianew <- read.csv(paste(dir, \"FIA-TerraClim-Wide-v17-04-14-2021.csv\", sep = \"\"), header = T)\nfialonga <- read.csv(paste(dir, \"FIA-TerraClim-Long-1990.1999-v17-04-14-2021.csv\", sep = \"\"), header = T)\nfialongb <- read.csv(paste(dir, \"FIA-TerraClim-Long-2000.2009-v17-04-14-2021.csv\", sep = \"\"), header = T)\nfialongc <- read.csv(paste(dir, \"FIA-TerraClim-Long-2010.2019-v17-04-14-2021.csv\", sep = \"\"), header = T)\nFTpred_ins <- read.csv(paste(dir, \"Insect_ForTypToPredict_04-21-2021.csv\", sep = \"\"), header = T)\nFTpred_drt <- read.csv(paste(dir, \"Drought_ForTypToPredict_04-21-2021.csv\", sep = \"\"), header = T)\n# FTs that meet the minimum 20 mortality threshold and cross-validated AUC>0.6\n\n# Processing projection and a useful logical function\nproj2 <- CRS(\"+proj=longlat +datum=WGS84 +ellps=WGS84\")\n\"%!in%\" <- function(x, y) !(\"%in%\"(x, y))\n\n\n\n# Get functional trait data from Trugman et al. (2020) PNAS\np50a <- open.nc(paste(dir, \"CWM_P50_025Deg.nc\", sep = \"\"))\np50m <- var.get.nc(p50a, \"CWM_P50\")\ndim(p50m)\np50r <- var.get.nc(p50a, \"mean_range_within_site\")\ndim(p50r)\nlat.tr <- var.get.nc(p50a, \"lat\")\ndim(lat.tr)\nlon.tr <- var.get.nc(p50a, \"lon\")\ndim(lon.tr)\n\n# Screen FIA data to remove fire, human disturbance, timber cutting, CONDPROP>0.3\nfianew1 <- fianew[which(fianew[, 8] >= 0.3 & fianew[, 59] != \"True\" & fianew[, 63] != \"True\" & fianew[, 71] != \"True\" & fianew[, 18] > 1), ]\n\n# Extract trait data for all FIA CONDs\ntraitdata <- array(dim = c(102453, 2))\nfor (i in 1:102453) {\n lati <- fianew1[i, 1]\n loni <- fianew1[i, 2]\n latcell <- which.min(abs(lati - lat.tr))\n loncell <- which.min(abs(loni - lon.tr))\n traitdata[i, 1] <- p50m[latcell, loncell]\n traitdata[i, 2] <- p50r[latcell, loncell]\n}\n\ntraitlong <- array(dim = c(498410, 2))\nfor (i in 1:498410) {\n lati <- fialonga[i, 1]\n loni <- fialonga[i, 2]\n latcell <- which.min(abs(lati - lat.tr))\n loncell <- which.min(abs(loni - lon.tr))\n traitlong[i, 1] <- p50m[latcell, loncell]\n traitlong[i, 2] <- p50r[latcell, loncell]\n}\n\n\n\n#------------------------------------------- Processing FIA data --------------------------------------------\n# For Obs, build a clean data-frame with dependent variable, predictor variables, FORTYP, lat/lon\nfianew1[is.na(fianew1[, 23]) == \"TRUE\", 23] <- 0 # Impute 0s where no mort was measured\nfianew1[is.na(fianew1[, 27]) == \"TRUE\", 27] <- 0 # Impute 0s where no mort was measured for insect mort\nfianew1[which(fianew1[, 151] < -16), 151] <- -16 # Set lower PDSI bounds\nfianew1[which(fianew1[, 151] > 16), 151] <- 16 # Set upper PDSI bounds\nfianew1[which(fianew1[, 152] < -16), 152] <- -16 # Set lower PDSI bounds\nfianew1[which(fianew1[, 152] > 16), 152] <- 16 # Set upper PDSI bounds\nfianew1[which(fianew1[, 153] < -16), 153] <- -16 # Set lower PDSI bounds\nfianew1[which(fianew1[, 153] > 16), 153] <- 16 # Set upper PDSI bounds\n\n# Combine all cond data and variables into a dataframe with columns: MortDrt, MortIns, 18 clim vars, 2 age vars, 8 traits, lat,lon, FORTYP\nfia.newm <- as.data.frame(cbind(\n (fianew1[, 23] / fianew1[, 18]) / (fianew1[, 15] - fianew1[, 14]), fianew1[, 27] * (fianew1[, 23] / fianew1[, 18]) / (fianew1[, 15] - fianew1[, 14]),\n scale(fianew1[, 127]), scale(fianew1[, 128]), scale(fianew1[, 129]), scale(fianew1[, 139]), scale(fianew1[, 140]), scale(fianew1[, 141]),\n scale(fianew1[, 151]), scale(fianew1[, 152]), scale(fianew1[, 153]), scale(fianew1[, 163]), scale(fianew1[, 164]), scale(fianew1[, 165]),\n scale(fianew1[, 175]), scale(fianew1[, 176]), scale(fianew1[, 177]), scale(fianew1[, 187]), scale(fianew1[, 188]), scale(fianew1[, 189]),\n scale(fianew1[, 3]^2), scale(fianew1[, 3]),\n scale(traitdata[, 1]), scale(traitdata[, 2]),\n (fianew1[, 19] - fianew1[, 18]), (fianew1[, 15] - fianew1[, 14]),\n fianew1[, 1], fianew1[, 2], fianew1[, 4], fianew1[, 18]\n))\n\n# Second, screen out NaN values that will mess up the model\nfia2 <- fia.newm[which(fia.newm[, 1] != \"NaN\" & fia.newm[, 5] != \"NaN\" & fia.newm[, 3] != \"NaN\" & fia.newm[, 9] != \"NaN\" & fia.newm[, 29] != \"NaN\" & fia.newm[, 21] != \"NaN\" & fia.newm[, 23] != \"NaN\" & fia.newm[, 1] < 1.01 & is.na(fia.newm[, 2]) == \"FALSE\"), ]\n\n# Third, scale up to 0.25x0.25 degree for model fitting\ndummy <- raster(ncols = 244, nrows = 100, xmn = -126, xmx = -65, ymn = 25, ymx = 50, crs = proj2) # 0.25 degree dummy raster\nfia.g1 <- array(dim = c(0, 30))\nfor (i in 1:112) {\n ftype <- unique(fia2[, 29])[i]\n d1 <- data.frame(fia2[which(fia2[, 29] == ftype), ])\n v1 <- rasterize(d1[, c(28, 27)], dummy, d1[, 1], fun = mean, background = NA, mask = FALSE, na.rm = T)\n v1i <- rasterize(d1[, c(28, 27)], dummy, d1[, 2], fun = mean, background = NA, mask = FALSE, na.rm = T)\n v1b <- rasterToPoints(v1)\n v1bi <- (as.matrix(as.vector(v1i)))[is.na(as.matrix(as.vector(v1i))) == \"FALSE\"]\n stack <- array(dim = c(length(v1bi), 0))\n for (j in 1:24) {\n varh <- rasterize(d1[, c(28, 27)], dummy, d1[, (j + 2)], fun = mean, background = NA, mask = FALSE, na.rm = T)\n var1 <- (as.matrix(as.vector(varh)))[is.na(as.matrix(as.vector(varh))) == \"FALSE\"]\n stack <- cbind(stack, var1)\n }\n ba <- rasterize(d1[, c(28, 27)], dummy, d1[, 30], fun = sum, background = NA, mask = FALSE, na.rm = T)\n ba0 <- (as.matrix(as.vector(ba)))[is.na(as.matrix(as.vector(ba))) == \"FALSE\"]\n fia.out <- cbind(v1b[, 3], v1bi, stack, v1b[, 1:2], rep(ftype, length(v1bi)), ba0)\n fia.g1 <- rbind(fia.g1, fia.out)\n}\n\n\n\n#------------------------------------------- Fit mortality functions --------------------------------------------------\n# GLM control parameters - bump up maxit to help with convergence\ngm.ctl <- glm.control(epsilon = 1e-8, maxit = 500, trace = FALSE)\n\nmod_insect_proj <- function(fitdata, minthres, ftypcol, preddata) {\n colnames(preddata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\", \"V11\", \"V12\", \"V13\")\n colnames(fitdata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\")\n mod1 <- array(dim = c(0, 7))\n for (i in 1:112) {\n ftype <- unique(fitdata[, ftypcol])[i]\n non_zero <- ifelse(fitdata[which(fitdata[, ftypcol] == ftype), 1] > 0, 1, 0)\n d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero) # Historical mortality data\n preddata1 <- data.frame(preddata[which(preddata[, 10] == ftype), ]) # Projection data\n # Set up the output matrix\n drt.out <- array(dim = c(dim(preddata1)[1], 7))\n drt.out[, 1] <- ftype # FORTYPCD\n drt.out[, 2] <- preddata1[, 12] # lat\n drt.out[, 3] <- preddata1[, 11] # lon\n drt.out[, 7] <- preddata1[, 13] # BAlive0 for the FORTYP\n\n # If FORTYP has non-meaningful historical model, set future projections == mean historical\n if (ftype %!in% FTpred_ins[, 1]) drt.out[, 6] <- mean(d1[, 1], na.rm = T) # Predicted mort = mean historical where Nmort 0) d1 <- d1[which(d1[, 1] < quantile(d1[, 1], 0.995)), ]\n if (dim(d1)[1] == 0) d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n # Construct historical mortality model\n m1 <- glm(non_zero ~ V2 + V3 + V4 + V5 + V6 + V7 + V8, data = d1, family = binomial(link = logit), control = gm.ctl)\n m2 <- betareg(V1 ~ V2 + V3 + V4 + V5 + V6 + V7 + V8, data = subset(d1, non_zero == 1))\n\n # Predict with future climate projections\n pred1 <- predict(m1, newdata = preddata1[, 2:8], se = TRUE, type = \"response\")\n pred2 <- predict(m2, newdata = preddata1[, 2:8], se = TRUE, type = \"response\")\n pred1a <- ifelse(pred1$fit >= 0.5, 1, 0)\n pred3 <- pred2 * pred1a\n pred4 <- pred2 * pred1$fit\n # \t\tStore model output\n drt.out[, 5] <- pred3\n drt.out[, 6] <- pred4 # Predicted (expected value) mort frac\n mod1 <- rbind(mod1, drt.out)\n }\n print(paste(\"FORTYPs projected: \", length(unique(mod1[which(mod1[, 5] != \"NA\"), 1])), sep = \"\"))\n print(paste(\"FORTYPs completed: \", i, sep = \"\"))\n return(mod1)\n}\n\ninsect_histmodel <- function(fitdata, minthres, ftypcol) {\n colnames(fitdata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\", \"V11\", \"V12\", \"V13\")\n mod1 <- array(dim = c(0, 7))\n for (i in 1:112) {\n ftype <- unique(fitdata[, ftypcol])[i]\n non_zero <- ifelse(fitdata[which(fitdata[, ftypcol] == ftype), 1] > 0, 1, 0)\n d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n drt.out <- array(dim = c(dim(d1)[1], 7))\n drt.out[, 1] <- d1[, ftypcol] # FORTYPCD\n drt.out[, 2] <- d1[, 12] # lat\n drt.out[, 3] <- d1[, 11] # lon\n drt.out[, 4] <- d1[, 1] # Obs mort frac\n drt.out[, 7] <- d1[, 13] # BAlive0 for the FORTYP\n\n # If FORTYP has non-meaningful historical model, set future projections == mean historical\n if (ftype %!in% FTpred_ins[, 1]) drt.out[, 6] <- mean(d1[, 1], na.rm = T) # Predicted mort = mean historical where Nmort 0) d1 <- d1[which(d1[, 1] < quantile(d1[, 1], 0.995)), ]\n if (dim(d1)[1] == 0) d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n m1 <- glm(non_zero ~ V2 + V3 + V4 + V5 + V6 + V7 + V8, data = d1, family = binomial(link = logit), control = gm.ctl)\n m2 <- betareg(V1 ~ V2 + V3 + V4 + V5 + V6 + V7 + V8, data = subset(d1, non_zero == 1))\n\n pred1 <- predict(m1, newdata = d1[, 2:8], se = TRUE, type = \"response\")\n pred2 <- predict(m2, newdata = d1[, 2:8], se = TRUE, type = \"response\")\n pred1a <- ifelse(pred1$fit >= 0.5, 1, 0)\n pred3 <- pred1$fit\n pred4 <- pred2 * pred1$fit\n\n if (dim(drt.out)[1] != dim(d1)[1]) drt.out <- array(dim = c(dim(d1)[1], 7))\n drt.out[, 1] <- d1[, ftypcol] # FORTYPCD\n drt.out[, 2] <- d1[, 12] # lat\n drt.out[, 3] <- d1[, 11] # lon\n drt.out[, 4] <- d1[, 1] # Obs mort frac\n drt.out[, 7] <- d1[, 13] # BAlive0 for the FORTYP\n\n drt.out[, 5] <- pred3\n drt.out[, 6] <- pred4 # Predicted (expected value) mort frac\n mod1 <- rbind(mod1, drt.out)\n }\n print(paste(\"FORTYPs modeled: \", length(unique(mod1[which(mod1[, 5] != \"NA\"), 1])), sep = \"\"))\n print(paste(\"FORTYPs completed: \", i, sep = \"\"))\n return(mod1)\n}\n\n\n\n\n\n\n#----------------- FIAlong climate data preprocessing function\nprepclim <- function(histclim, climdata, histcols, futcols) {\n climdata[which(climdata[, 6] < -16), 6] <- -16 # Set lower PDSI bounds\n climdata[which(climdata[, 6] > 16), 6] <- 16 # Set upper PDSI bounds\n climdata[which(climdata[, 13] < -16), 13] <- -16 # Set lower PDSI bounds\n climdata[which(climdata[, 13] > 16), 13] <- 16 # Set upper PDSI bounds\n histclim[which(histclim[, 25] < -16), 25] <- -16\n histclim[which(histclim[, 25] > 16), 25] <- 16\n histclim[which(histclim[, 26] < -16), 26] <- -16\n histclim[which(histclim[, 26] > 16), 26] <- 16\n print(histclim[1, histcols])\n print(climdata[1, futcols])\n # Get historical mean and SD for drought models\n hist1 <- array(dim = c(6, 2))\n for (i in 1:6) {\n hist1[i, 1] <- mean(histclim[, histcols[i]], na.rm = T)\n hist1[i, 2] <- sd(histclim[, histcols[i]], na.rm = T)\n }\n fia.futa <- as.data.frame(cbind(rep(1, 498410), (climdata[, futcols[1]] - hist1[1, 1]) / hist1[1, 2], (climdata[, futcols[2]] - hist1[2, 1]) / hist1[2, 2], (climdata[, futcols[3]] - hist1[3, 1]) / hist1[3, 2], (climdata[, futcols[4]] - hist1[4, 1]) / hist1[4, 2], (climdata[, futcols[5]] - hist1[5, 1]) / hist1[5, 2], (climdata[, futcols[6]] - hist1[6, 1]) / hist1[6, 2], scale(fialong[, 3]), scale(traitlong[, 2]), fialong[, 7], fialong[, 1], fialong[, 2], fialong[, 4]))\n finalclim <- fia.futa[which(fia.futa[, 1] != \"NaN\" & fia.futa[, 5] != \"NaN\" & fia.futa[, 3] != \"NaN\" & fia.futa[, 7] != \"NaN\" & fia.futa[, 10] != \"NaN\" & fia.futa[, 8] != \"NaN\" & is.na(fia.futa[, 2]) == \"FALSE\"), ]\n return(finalclim)\n}\n\n# Function when both inputs are FIAlong\nprepclim1 <- function(histclim, climdata, histcols, futcols) {\n climdata[which(climdata[, 25] < -16), 25] <- -16 # Set lower PDSI bounds\n climdata[which(climdata[, 25] > 16), 25] <- 16 # Set upper PDSI bounds\n climdata[which(climdata[, 26] < -16), 26] <- -16 # Set lower PDSI bounds\n climdata[which(climdata[, 26] > 16), 26] <- 16 # Set upper PDSI bounds\n histclim[which(histclim[, 25] < -16), 25] <- -16\n histclim[which(histclim[, 25] > 16), 25] <- 16\n histclim[which(histclim[, 26] < -16), 26] <- -16\n histclim[which(histclim[, 26] > 16), 26] <- 16\n print(histclim[1, histcols])\n print(climdata[1, futcols])\n # Get historical mean and SD for drought models\n hist1 <- array(dim = c(6, 2))\n for (i in 1:6) {\n hist1[i, 1] <- mean(histclim[, histcols[i]], na.rm = T)\n hist1[i, 2] <- sd(histclim[, histcols[i]], na.rm = T)\n }\n fia.futa <- as.data.frame(cbind(rep(1, 498410), (climdata[, futcols[1]] - hist1[1, 1]) / hist1[1, 2], (climdata[, futcols[2]] - hist1[2, 1]) / hist1[2, 2], (climdata[, futcols[3]] - hist1[3, 1]) / hist1[3, 2], (climdata[, futcols[4]] - hist1[4, 1]) / hist1[4, 2], (climdata[, futcols[5]] - hist1[5, 1]) / hist1[5, 2], (climdata[, futcols[6]] - hist1[6, 1]) / hist1[6, 2], scale(fialonga[, 3]), scale(traitlong[, 2]), fialonga[, 7], fialonga[, 1], fialonga[, 2], fialonga[, 4]))\n finalclim <- fia.futa[which(fia.futa[, 1] != \"NaN\" & fia.futa[, 5] != \"NaN\" & fia.futa[, 3] != \"NaN\" & fia.futa[, 7] != \"NaN\" & fia.futa[, 10] != \"NaN\" & fia.futa[, 8] != \"NaN\" & is.na(fia.futa[, 2]) == \"FALSE\"), ]\n return(finalclim)\n}\n\n\n\n\n#-------------------- Function to rasterize and weight model mortality projections by observed/current BA\nweight.proj1 <- function(raster1, grid, mortcol) {\n mort.bafi <- rasterize(raster1[which(raster1[, 1] == unique(raster1[, 1])[1]), c(2, 3)], grid, raster1[which(raster1[, 1] == unique(raster1[, 1])[1]), 7], fun = mean, background = NA, mask = FALSE, na.rm = TRUE)\n mort.predfi <- rasterize(raster1[which(raster1[, 1] == unique(raster1[, 1])[1]), c(2, 3)], grid, raster1[which(raster1[, 1] == unique(raster1[, 1])[1]), mortcol], fun = mean, background = NA, mask = FALSE, na.rm = TRUE)\n for (i in 2:length(unique(raster1[, 1]))) {\n mort.predfi <- addLayer(mort.predfi, rasterize(raster1[which(raster1[, 1] == unique(raster1[, 1])[i]), c(2, 3)], grid, raster1[which(raster1[, 1] == unique(raster1[, 1])[i]), mortcol], fun = mean, background = NA, mask = FALSE, na.rm = TRUE))\n mort.bafi <- addLayer(mort.bafi, rasterize(raster1[which(raster1[, 1] == unique(raster1[, 1])[i]), c(2, 3)], grid, raster1[which(raster1[, 1] == unique(raster1[, 1])[i]), 7], fun = mean, background = NA, mask = FALSE, na.rm = TRUE))\n }\n mort.predwi <- weighted.mean(mort.predfi, mort.bafi, na.rm = T)\n return(mort.predwi)\n}\n\n\n\n\n#-------------------------------- Run model and create figures\n# Fig 1E\ninsect.hist <- insect_histmodel(fia.g1[, c(2, 5, 6, 11, 13, 15, 20, 22, 24, 29, 28, 27, 30)], 20, 10)\n\n# Scale up by basal area\ninsect.obs <- weight.proj1(insect.hist, dummy, 4)\n\n# writeRaster(insect.obs, paste(dir, \"Fig1E_InsectModel_FIAwide-ObsMort_05-08-2021\", sep=\"\"), format='GTiff')\n\n# Fig 1F models\nhistcols6 <- c(19, 23, 25, 30, 32, 34)\ninsect.outa <- mod_insect_proj(fia.g1[, c(2, 5, 6, 11, 13, 15, 20, 22, 24, 29)], 20, 10, prepclim1(fialonga, fialonga, histcols6, histcols6))\ninsect.outb <- mod_insect_proj(fia.g1[, c(2, 5, 6, 11, 13, 15, 20, 22, 24, 29)], 20, 10, prepclim1(fialongb, fialongb, histcols6, histcols6))\ninsect.outc <- mod_insect_proj(fia.g1[, c(2, 5, 6, 11, 13, 15, 20, 22, 24, 29)], 20, 10, prepclim1(fialongc, fialongc, histcols6, histcols6))\n\n# Make Fig 1F\ninsect1 <- insect.outa\ninsect1[, 6] <- rowMeans(cbind(insect.outa[, 6], insect.outb[, 6], insect.outc[, 6])) # Average modeled mortality across 3 baselines\nmort.insects.modlong1 <- weight.proj1(insect1, dummy, 6)\n\n# writeRaster(mort.insects.modlong1, paste(dir, \"Fig1F_InsectModel_ModeledFIAlongEnsembleHistMort_05-08-2021\", sep=\"\"), format='GTiff')\n\n\n\n\n#-------------------------------------------- DROUGHT MODELS (Fig 1C/D)\nmod_drought_proj <- function(fitdata, minthres, ftypcol, preddata) {\n colnames(preddata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\", \"V11\", \"V12\", \"V13\")\n colnames(fitdata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\")\n mod1 <- array(dim = c(0, 7))\n for (i in 1:112) {\n ftype <- unique(fitdata[, ftypcol])[i]\n non_zero <- ifelse(fitdata[which(fitdata[, ftypcol] == ftype), 1] > 0, 1, 0)\n d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero) # Historical mortality data\n preddata1 <- data.frame(preddata[which(preddata[, 10] == ftype), ]) # Projection data\n\n # Set up the output matrix\n drt.out <- array(dim = c(dim(preddata1)[1], 7))\n drt.out[, 1] <- ftype # FORTYPCD\n drt.out[, 2] <- preddata1[, 12] # lat\n drt.out[, 3] <- preddata1[, 11] # lon\n drt.out[, 7] <- preddata1[, 13] # Biomass for the FORTYP\n\n # If FORTYP has non-meaningful historical model, set future projections == mean historical\n if (ftype %!in% FTpred_drt[, 1]) drt.out[, 6] <- mean(d1[, 1], na.rm = T) # Predicted mort = mean historical where Nmort 0) d1 <- d1[which(d1[, 1] < quantile(d1[, 1], 0.995)), ]\n if (dim(d1)[1] == 0) d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n # Construct historical mortality model\n m1 <- glm(non_zero ~ V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9, data = d1, family = binomial(link = logit), control = gm.ctl)\n m2 <- betareg(V1 ~ V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9, data = subset(d1, non_zero == 1))\n\n # Predict with future climate projections\n pred1 <- predict(m1, newdata = preddata1[, 2:9], se = TRUE, type = \"response\")\n pred2 <- predict(m2, newdata = preddata1[, 2:9], se = TRUE, type = \"response\")\n pred1a <- ifelse(pred1$fit >= 0.5, 1, 0)\n pred3 <- pred2 * pred1a\n pred4 <- pred2 * pred1$fit\n\n # \t\tStore model output\n drt.out[, 5] <- pred3\n drt.out[, 6] <- pred4 # Predicted (expected value) mort frac\n mod1 <- rbind(mod1, drt.out)\n }\n print(paste(\"FORTYPs projected: \", length(unique(mod1[which(mod1[, 5] != \"NA\"), 1])), sep = \"\"))\n print(paste(\"FORTYPs completed: \", i, sep = \"\"))\n return(mod1)\n}\n\n\ndrought_histmodel <- function(fitdata, minthres, ftypcol) {\n colnames(fitdata) <- c(\"V1\", \"V2\", \"V3\", \"V4\", \"V5\", \"V6\", \"V7\", \"V8\", \"V9\", \"V10\", \"V11\", \"V12\", \"V13\")\n mod1 <- array(dim = c(0, 7))\n for (i in 1:112) {\n ftype <- unique(fitdata[, ftypcol])[i]\n non_zero <- ifelse(fitdata[which(fitdata[, ftypcol] == ftype), 1] > 0, 1, 0)\n d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n drt.out <- array(dim = c(dim(d1)[1], 7))\n drt.out[, 1] <- d1[, ftypcol] # FORTYPCD\n drt.out[, 2] <- d1[, 12] # lat\n drt.out[, 3] <- d1[, 11] # lon\n drt.out[, 4] <- d1[, 1] # Obs mort frac\n drt.out[, 7] <- d1[, 13] # BAlive0 for the FORTYP\n\n # If FORTYP has non-meaningful historical model, set modeled values == mean historical\n if (ftype %!in% FTpred_drt[, 1]) drt.out[, 6] <- mean(d1[, 1], na.rm = T) # Predicted mort = mean historical where Nmort 0) d1 <- d1[which(d1[, 1] < quantile(d1[, 1], 0.995)), ]\n if (dim(d1)[1] == 0) d1 <- data.frame(fitdata[which(fitdata[, ftypcol] == ftype), ], non_zero)\n\n # Build models\n m1 <- glm(non_zero ~ V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9, data = d1, family = binomial(link = logit), control = gm.ctl)\n m2 <- betareg(V1 ~ V2 + V3 + V4 + V5 + V6 + V7 + V8 + V9, data = subset(d1, non_zero == 1))\n\n pred1 <- predict(m1, newdata = d1[, 2:9], se = TRUE, type = \"response\")\n pred2 <- predict(m2, newdata = d1[, 2:9], se = TRUE, type = \"response\")\n pred1a <- ifelse(pred1$fit >= 0.5, 1, 0)\n pred3 <- pred1$fit\n pred4 <- pred2 * pred1$fit\n\n if (dim(drt.out)[1] != dim(d1)[1]) drt.out <- array(dim = c(dim(d1)[1], 7))\n drt.out[, 1] <- d1[, ftypcol] # FORTYPCD\n drt.out[, 2] <- d1[, 12] # lat\n drt.out[, 3] <- d1[, 11] # lon\n drt.out[, 4] <- d1[, 1] # Obs mort frac\n drt.out[, 7] <- d1[, 13] # BAlive0 for the FORTYP\n\n drt.out[, 5] <- pred3\n drt.out[, 6] <- pred4 # Predicted (expected value) mort frac\n mod1 <- rbind(mod1, drt.out)\n }\n print(paste(\"FORTYPs modeled: \", length(unique(mod1[which(mod1[, 5] != \"NA\"), 1])), sep = \"\"))\n print(paste(\"FORTYPs completed: \", i, sep = \"\"))\n return(mod1)\n}\n\n\n\n#-------------------------------- Run model and create figures\n# Fig 1C\ndrought.hist <- drought_histmodel(fia.g1[, c(1, 5, 7, 11, 13, 17, 18, 22, 24, 29, 28, 27, 30)], 20, 10)\n\n# Scale up by basal area\ndrought.obs <- weight.proj1(drought.hist, dummy, 4)\n\n# writeRaster(drought.obs, paste(dir, \"Fig1C_DroughtModel_FIAwide-ObsMort_05-08-2021\", sep=\"\"), format='GTiff')\n\n# Fig 1D\nhistcols1a <- c(19, 24, 25, 30, 31, 35)\ndrought.outa <- mod_drought_proj(fia.g1[, c(1, 5, 7, 11, 13, 17, 18, 22, 24, 29)], 20, 10, prepclim1(fialonga, fialonga, histcols1a, histcols1a))\ndrought.outb <- mod_drought_proj(fia.g1[, c(1, 5, 7, 11, 13, 17, 18, 22, 24, 29)], 20, 10, prepclim1(fialongb, fialongb, histcols1a, histcols1a))\ndrought.outc <- mod_drought_proj(fia.g1[, c(1, 5, 7, 11, 13, 17, 18, 22, 24, 29)], 20, 10, prepclim1(fialongc, fialongc, histcols1a, histcols1a))\n\n# Make Fig 1D\ndrought1 <- drought.outa\ndrought1[, 6] <- rowMeans(cbind(drought.outa[, 6], drought.outb[, 6], drought.outc[, 6])) # Average modeled mortality across 3 baselines\nmort.drought.modlong1 <- weight.proj1(drought1, dummy, 6)\n\n# writeRaster(mort.drought.modlong1, paste(dir, \"Fig1D_DroughtModel_ModeledFIAlongEnsembleHistMort_05-08-2021\", sep=\"\"), format='GTiff')\n\n\n\n\n\n#-------------------------------------- First-order reversal estimates\n# Historical reversals for drought and insects in FIA data\ndrt.rev <- rep(0, 102453)\ndrt.rev[which(fianew1[, 27] < 0.01 & fianew1[, 19] < fianew1[, 18] & fianew1[, 31] < 0.01 & fianew1[, 35] < 0.01 & fianew1[, 39] < 0.01 & fianew1[, 47] < 0.01 & fianew1[, 55] == \"False\" & fianew1[, 59] == \"False\" & fianew1[, 63] == \"False\" & fianew1[, 71] == \"False\" & fianew1[, 75] == \"False\" & fianew1[, 79] == \"False\" & fianew1[, 83] == \"False\" & fianew1[, 151] < -2 & fianew1[, 67] == \"False\" & ((fianew1[, 19] - fianew1[, 18]) / -fianew1[, 18]) > 0.1)] <- 1\n\nins.rev <- rep(0, 102453)\nins.rev[which(fianew1[, 27] > 0.5 & fianew1[, 19] < fianew1[, 18] & ((fianew1[, 19] - fianew1[, 18]) / -fianew1[, 18]) > 0.1)] <- 1\n\n# Calculated annualized drought and insect p(rev)\nrevhist1 <- array(dim = c(102453, 2))\nfor (i in 1:102453) {\n ftrev <- fianew1[i, 4]\n revhist1[i, 1] <- drt.rev[i] / mean(fianew1[which(fianew1[, 4] == ftrev), 15] - fianew1[which(fianew1[, 4] == ftrev), 14], na.rm = T)\n revhist1[i, 2] <- ins.rev[i] / mean(fianew1[which(fianew1[, 4] == ftrev), 15] - fianew1[which(fianew1[, 4] == ftrev), 14], na.rm = T)\n}\n\n# Calculate 100-year integrated risk %s of constant historical reversal annual probabilities\n100 * dbinom(1, 100, mean(revhist1[, 1], na.rm = T)) # Drought\n100 * dbinom(1, 100, mean(revhist1[, 2], na.rm = T)) # Insects\n\n\n# Simulate 100-year integrated risk %s with Fig 2 multi-model mean CMIP6 projections\nout <- array(dim = c(1000, 0))\nperc1 <- c(1, 1.022, 1.063, 1.148, 1.151, 1.230, 1.380, 1.384, 1.799, 1.846) # Percent changes in BAmortfrac/yr from drought models compared to 1990-2010 baselines\nfor (i in 1:10) {\n dec1 <- rbinom(1000, 10, 0.002457 * perc1[i]) # Draw 1000 10-year draws with observed probability\n out <- cbind(out, dec1)\n sumout <- rowSums(out)\n sumout1 <- sum(ifelse(sumout > 0, 1, 0))\n}\n100 * sumout1 / 1000\n\n# Insects\nout <- array(dim = c(1000, 0))\nperc2 <- c(1, 1.049, 1.042, 1.193, 1.0231, 1.136, 1.289, 1.197, 1.622, 1.701) # Percent changes in BAmortfrac/yr from insect models compared to 1990-2010 baselines\nfor (i in 1:10) {\n dec1 <- rbinom(1000, 10, 0.00250982 * perc2[i]) # Draw 1000 10-year draws with observed probability\n out <- cbind(out, dec1)\n sumout <- rowSums(out)\n sumout1 <- sum(ifelse(sumout > 0, 1, 0))\n}\n100 * sumout1 / 1000\n\n# Fire\nout <- array(dim = c(1000, 0))\nhist1 <- read.csv(paste(dir, \"historical_fire.csv\", sep = \"\"), header = T)\nhistave <- mean(hist1[17:35, 2])\nfut1 <- read.csv(paste(dir, \"future_fire.csv\", sep = \"\"), header = T)\nperc3 <- c(rep(1, 19), (fut1[50:130, 3] - histave) / histave + 1)\nfor (i in 1:100) {\n dec1 <- rbinom(1000, 1, histave * perc3[i]) # Draw 1000 1-year draws with observed probability\n out <- cbind(out, dec1)\n sumout <- rowSums(out)\n sumout1 <- sum(ifelse(sumout > 0, 1, 0))\n}\n100 * sumout1 / 1000\n", "meta": {"hexsha": "1c648cdb893dfe7a821c1836184299940a724acd", "size": 28163, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Figure-1-Drought-Insect-Historical-Models.r", "max_stars_repo_name": "norlandrhagen/forest-risks", "max_stars_repo_head_hexsha": "2cbc87064ac05299dba952c9f0cb8022ffd8909a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20, "max_stars_repo_stars_event_min_datetime": "2021-05-01T18:08:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T10:24:53.000Z", "max_issues_repo_path": "R/Figure-1-Drought-Insect-Historical-Models.r", "max_issues_repo_name": "norlandrhagen/forest-risks", "max_issues_repo_head_hexsha": "2cbc87064ac05299dba952c9f0cb8022ffd8909a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2021-03-31T05:20:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T13:02:58.000Z", "max_forks_repo_path": "R/Figure-1-Drought-Insect-Historical-Models.r", "max_forks_repo_name": "norlandrhagen/forest-risks", "max_forks_repo_head_hexsha": "2cbc87064ac05299dba952c9f0cb8022ffd8909a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-10-26T20:52:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T07:42:52.000Z", "avg_line_length": 53.3390151515, "max_line_length": 479, "alphanum_fraction": 0.5961722828, "num_tokens": 10920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.25753538408679416}} {"text": "# ####\n# ####\n# #### AIM: Use PCT data to create scenario of change where commuting cycling levels increase and car journeys decrease which can be imported\n# #### into A/B Street city simulation software. This method should be fully reproducible for all other pct_regions.\n# ####\n# ####\n#\n# #### LIBRARYS ####\n# library(pct)\n# library(sf)\n# library(tidyverse)\n# library(abstr)\n#\n# # for plotting\n# # library(tmap)\n# # library (mapview)\n#\n# #### READ DATA ####\n# devon_zones = pct::get_pct_zones(region = \"devon\", geography = \"msoa\") # get zone data\n# exeter_zones = devon_zones %>% filter(lad_name == \"Exeter\") %>% select(geo_code) # filter for exeter\n#\n# exeter_commute_od = pct::get_pct_lines(region = \"devon\", geography = \"msoa\") %>% # get commute od data\n# filter(lad_name1 == \"Exeter\" &\n# lad_name2 == \"Exeter\") # filter for exeter\n#\n#\n# #### CLEAN DATA , CALCULATE EUCLIDEAN DISTANCE & GENERATE SCENARIOS OF CHANGE ####\n# exeter_commute_od = exeter_commute_od %>%\n# mutate(cycle_base = bicycle) %>%\n# mutate(walk_base = foot) %>%\n# mutate(transit_base = bus + train_tube) %>% # bunch of renaming -_-\n# mutate(drive_base = car_driver + car_passenger + motorbike + taxi_other) %>%\n# mutate(all_base = all) %>%\n# mutate(\n# # create new columns\n# pcycle_godutch_uptake = pct::uptake_pct_godutch_2020(distance = rf_dist_km, gradient = rf_avslope_perc),\n# cycle_godutch_additional = pcycle_godutch_uptake * drive_base,\n# cycle_godutch = cycle_base + cycle_godutch_additional,\n# pcycle_godutch = cycle_godutch / all_base,\n# drive__godutch = drive_base - cycle_godutch_additional,\n# across(c(drive__godutch, cycle_godutch), round, 0),\n# all_go_dutch = drive__godutch + cycle_godutch + transit_base + walk_base\n# ) %>%\n# select(\n# # select variables for new df\n# geo_code1,\n# geo_code2,\n# cycle_base,\n# drive_base,\n# walk_base,\n# transit_base,\n# all_base,\n# all_go_dutch,\n# drive__godutch,\n# cycle_godutch,\n# cycle_godutch_additional,\n# pcycle_godutch\n# )\n#\n# identical(exeter_commute_od$all_base, exeter_commute_od$all_go_dutch) # sanity check: make sure total remains the same (not a dynamic model where population change is factored in)\n#\n# #### DOWNLOAD OSM BUILDING DATA ####\n# osm_polygons = osmextract::oe_read(\n# \"https://download.geofabrik.de/europe/great-britain/england/devon-latest.osm.pbf\",\n# # download osm buildings for region using geofabrik\n# layer = \"multipolygons\"\n# )\n#\n# building_types = c(\n# \"yes\",\n# \"house\",\n# \"detached\",\n# \"residential\",\n# \"apartments\",\n# \"commercial\",\n# \"retail\",\n# \"school\",\n# \"industrial\",\n# \"semidetached_house\",\n# \"church\",\n# \"hangar\",\n# \"mobile_home\",\n# \"warehouse\",\n# \"office\",\n# \"college\",\n# \"university\",\n# \"public\",\n# \"garages\",\n# \"cabin\",\n# \"hospital\",\n# \"dormitory\",\n# \"hotel\",\n# \"service\",\n# \"parking\",\n# \"manufactured\",\n# \"civic\",\n# \"farm\",\n# \"manufacturing\",\n# \"floating_home\",\n# \"government\",\n# \"bungalow\",\n# \"transportation\",\n# \"motel\",\n# \"manufacture\",\n# \"kindergarten\",\n# \"house_boat\",\n# \"sports_centre\"\n# )\n# osm_buildings = osm_polygons %>%\n# dplyr::filter(building %in% building_types) %>%\n# dplyr::select(osm_way_id, name, building)\n#\n# osm_buildings_valid = osm_buildings[sf::st_is_valid(osm_buildings), ]\n#\n# exeter_osm_buildings_all = osm_buildings_valid[exeter_zones, ]\n#\n# #mapview(exeter_osm_buildings_all)\n#\n# # Filter down large objects for package -----------------------------------\n# exeter_osm_buildings_all_joined = exeter_osm_buildings_all %>%\n# sf::st_join(exeter_zones)\n#\n# set.seed(2021)\n# exeter_osm_buildings_sample = exeter_osm_buildings_all_joined %>%\n# dplyr::filter(!is.na(osm_way_id))\n#\n# exeter_osm_buildings_tbl = exeter_osm_buildings_all %>%\n# dplyr::filter(osm_way_id %in% exeter_osm_buildings_sample$osm_way_id)\n#\n#\n# #### LOGIC GATE ####\n# # Logic gate for go_dutch scenario of change, where cycling levels increase to a proportion reflecting the Netherlands.\n# #Switch to FALSE if you want census commuting OD\n# go_dutch = TRUE\n# if (go_dutch == TRUE) {\n# exeter_od = exeter_commute_od %>%\n# mutate(All = all_go_dutch) %>%\n# mutate(Bike = cycle_godutch) %>%\n# mutate(Transit = transit_base) %>%\n# mutate(Drive = drive_base) %>%\n# mutate(Walk = walk_base) %>%\n# select(geo_code1, geo_code2, All, Bike, Transit, Drive, Walk,geometry)\n# } else {\n# exeter_od = exeter_commute_od %>%\n# mutate(All = all_base) %>%\n# mutate(Bike = cycle_base) %>%\n# mutate(Drive = drive_base) %>%\n# mutate(Transit = transit_base) %>%\n# mutate(Walk = walk_base) %>%\n# select(geo_code1, geo_code2, All, Bike, Transit, Drive, Walk, geometry)\n# }\n#\n# #### GENERATE A/B STREET SCENARIO ####\n# output_sf = ab_scenario(\n# od = exeter_od,\n# zones = exeter_zones,\n# zones_d = NULL,\n# origin_buildings = exeter_osm_buildings_tbl,\n# destination_buildings = exeter_osm_buildings_tbl,\n# pop_var = 3,\n# time_fun = ab_time_normal,\n# output = \"sf\",\n# modes = c(\"Walk\", \"Bike\", \"Drive\", \"Transit\")\n# )\n#\n# # make map using tmap\n# # tm_shape(output_sf) + tmap::tm_lines(col = \"mode\", lwd = .8, lwd.legeld.col = \"black\") +\n# # tm_shape(exeter_zones) + tmap::tm_borders(lwd = 1.2, col = \"gray\") +\n# # tm_text(\"geo_code\", size = 0.6, col = \"black\") +\n# # tm_style(\"cobalt\")\n#\n# #### SAVE JSON FILE ####\n# output_json = ab_json(output_sf, time_fun = ab_time_normal, scenario_name = \"Exeter Example\")\n# ab_save(output_json, f = \"../../Desktop/exeter.json\")\n#\n# #### COMMANDS FOR AB STREET\n# # $ cargo run\n# # $ cargo run --bin import_traffic -- --map=PATH/TO/MAP --input=/PATH/TO/JSON.json\n", "meta": {"hexsha": "2aa224523a84e3abeb8089366ac60379d48f72c2", "size": 5738, "ext": "r", "lang": "R", "max_stars_repo_path": "data-raw/exeter.r", "max_stars_repo_name": "lucasccdias/abstr", "max_stars_repo_head_hexsha": "24baec9cb540374628db8bcfa9eda55395cdc09f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24, "max_stars_repo_stars_event_min_datetime": "2021-02-11T01:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T21:48:23.000Z", "max_issues_repo_path": "data-raw/exeter.r", "max_issues_repo_name": "lucasccdias/abstr", "max_issues_repo_head_hexsha": "24baec9cb540374628db8bcfa9eda55395cdc09f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 70, "max_issues_repo_issues_event_min_datetime": "2021-02-09T22:13:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T10:11:58.000Z", "max_forks_repo_path": "data-raw/exeter.r", "max_forks_repo_name": "lucasccdias/abstr", "max_forks_repo_head_hexsha": "24baec9cb540374628db8bcfa9eda55395cdc09f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-02-18T20:35:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-20T04:58:04.000Z", "avg_line_length": 32.0558659218, "max_line_length": 181, "alphanum_fraction": 0.6540606483, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.25740645474760376}} {"text": "# Module for graph based algorithms\n\n# Graph representation:\n# - An edges frame is a data frame with columns 'source.id', 'target.id' and 'weight',\n# where 'source' and 'target' each reference a vertex v_i in V (indexed from 1 to |V|),\n# and 'weight' gives the edge weight (often just 1 to measure degree).\n# - An edges representation is an object with a get_edges() method.\n# - A graph representation is an edges representation with the following methods:\n# * get_node_ids() - returns a vector of all vertex identifiers.\n# * get_out_edges(source.id) - returns an edges frame of all edges directed from the source vertex.\n# * get_in_edges(target.id) - returns an edges frame of all edges directed to the target vertex.\n\n# Description:\n# Wraps an edges frame into an edges representation.\n# Input:\n# edges - The edges frame.\n# Output:\n# edges.repr - The edges representation.\ngraph.get_edges_repr = function(edges) {\n edges.repr = list()\n edges.repr$get_edges = function() {\n return(edges)\n }\n return(edges.repr)\n}\n\n# Description:\n# Wraps an edges edges representation into a graph representation.\n# Input:\n# edges.repr - The edges representation.\n# Output:\n# graph.repr - The graph representation.\ngraph.from_edges_repr = function(edges.repr) {\n edges = edges.repr$get_edges()\n graph.repr = list()\n graph.repr$get_edges = function() {\n return(edges)\n }\n graph.repr$get_node_ids = function() {\n return(sort(unique(c(edges$source.id, edges$target.id))))\n }\n graph.repr$get_out_edges = function(source.id) {\n return(edges[edges$source.id == source.id,])\n }\n graph.repr$get_in_edges = function(target.id) {\n return(edges[edges$target.id == target.id,])\n }\n return(graph.repr)\n}\n\n# Description:\n# Internal function to encapsulate all clustering information into a single object.\n# Input:\n# num.nodes - The total number |V| of vertices in the graph, on the assumption that\n# every vertex id has been uniquely mapped to an integer from 1 to num.nodes.\n# trace - An optional flag indicating whether (TRUE) or not (FALSE) to\n# track incremental score changes; defaults to FALSE.\n# Output:\n# clusters - An object representing the internal cluster functions.\ngraph.init_clusters = function(num.nodes, trace=FALSE) {\n # Information about all nodes:\n # Sum of all edge weights (half of total vertex weight)\n total_edge_weights = 0\n # Map node index to cluster id\n node_cluster_map = 1:num.nodes\n # Count weight of internal edges in each cluster (both nodes in cluster)\n internal_cluster_edges_map = rep(0, num.nodes)\n # Count weight of external edges pointing into our out of each cluster (only one node in cluster)\n external_cluster_edges_map = rep(0, num.nodes)\n # Initial modularity score\n initial_score = 0\n # Cummulative change in modularity score\n change_score = 0\n if (trace) {\n change_scores = NULL\n }\n # Control initial score computation\n score_counter = 0\n \n # Information about about current (pivot) node:\n # Total edge weight of a node\n node_weight = 0\n # Weight of self edge to and from node\n self_weight = 0\n # Weights of edges from node to each cluster\n local_cluster_edges_map = rep(0, num.nodes)\n\n # Create object\n obj = list()\n # Add node v_i to new cluster if not already clustered\n obj$add_cluster_node = function(i) {\n # No action needed as nodes already indexed.\n }\n # Put node v_i into existing cluster c_i\n obj$set_cluster_node = function(i, c_i) {\n node_cluster_map[i] <<- c_i\n }\n # Add directed edge between node clusters\n obj$add_cluster_edge = function(i, j, w_ij) {\n if (i == j) w_ij = 0.5 * w_ij\n total_edge_weights <<- total_edge_weights + w_ij\n c_i = node_cluster_map[[i]]\n c_j = node_cluster_map[[j]]\n if (c_i == c_j) {\n internal_cluster_edges_map[c_i] <<- internal_cluster_edges_map[c_i] + w_ij\n } else {\n external_cluster_edges_map[c_i] <<- external_cluster_edges_map[c_i] + w_ij\n external_cluster_edges_map[c_j] <<- external_cluster_edges_map[c_j] + w_ij\n }\n }\n # Initialise local cluster edge counts for a single node\n obj$init_local_cluster_edges = function() {\n node_weight <<- 0\n self_weight <<- 0\n local_cluster_edges_map <<- rep(0, num.nodes)\n }\n # Add undirected edge between pivot node i and node j\n obj$add_local_cluster_edge = function(i, j, w_ij) {\n if (i == j) {\n self_weight <<- w_ij\n w_ij = 0.5 * w_ij\n }\n node_weight <<- node_weight + w_ij\n c_j = node_cluster_map[[j]]\n local_cluster_edges_map[c_j] <<- local_cluster_edges_map[c_j] + w_ij\n }\n # If possible, move pivot node to another cluster with highest positive change of score\n obj$move_to_best_cluster = function(i) {\n c_i = node_cluster_map[[i]]\n A_dd = 2 * total_edge_weights # A..\n A_id = node_weight # A_i.\n score_counter <<- score_counter + 1\n if (score_counter <= num.nodes) {\n # Continue computing initial score\n Q_i = (self_weight - A_id * A_id / A_dd) / A_dd\n initial_score <<- initial_score + Q_i\n }\n # Compute score change in removing node i from its cluster\n A_i_gpi = internal_cluster_edges_map[[c_i]] # A_i,g+i\n A_ig = A_i_gpi - self_weight # A_i,g\n sigma_gpi_tot = 2 * internal_cluster_edges_map[[c_i]] + external_cluster_edges_map[[c_i]] # Sigma_g+i^tot\n sigma_tot = sigma_gpi_tot - A_id # Sigma_g^tot\n delta_Q_gpimi = -2 * (A_ig - sigma_tot * A_id / A_dd) / A_dd # Delta Q_(g+i)-i\n max_delta_Q = -Inf\n max_cluster_id = 0\n local_cluster_edges_map[c_i] = 0 # Ignore current cluster\n for (c_j in which(local_cluster_edges_map > 0)) {\n sigma_tot = 2 * internal_cluster_edges_map[[c_j]] + external_cluster_edges_map[[c_j]] # Sigma_g'^tot\n A_igd = local_cluster_edges_map[[c_j]] # A_i,g'\n delta_Q_gdpi = 2 * (A_igd - sigma_tot * A_id / A_dd) / A_dd # Delta Q_g'+i\n delta_Q = delta_Q_gpimi + delta_Q_gdpi\n if (delta_Q > 1e-8 && delta_Q > max_delta_Q) {\n max_delta_Q = delta_Q\n max_cluster_id = c_j\n #print(paste0(\"DEBUG: Best delta-score=\", delta_Q, \". Suggest move node from cluster \", c_i, \" to cluster \", c_j))\n }\n }\n if (max_cluster_id > 0) {\n c_j = max_cluster_id\n change_score <<- change_score + max_delta_Q\n if (trace) {\n change_scores <<- c(change_scores, max_delta_Q)\n }\n # Remove node i from cluster c_i\n internal_cluster_edges_map[[c_i]] <<- internal_cluster_edges_map[[c_i]] - A_ig - 0.5 * self_weight\n external_cluster_edges_map[[c_i]] <<- external_cluster_edges_map[[c_i]] - A_id + 2 * A_ig + self_weight\n # Add node i to cluster c_j\n A_igd = local_cluster_edges_map[[c_j]] # A_i,g'\n internal_cluster_edges_map[[c_j]] <<- internal_cluster_edges_map[[c_j]] + A_igd + 0.5 * self_weight\n external_cluster_edges_map[[c_j]] <<- external_cluster_edges_map[[c_j]] + A_id - 2 * A_igd - self_weight\n node_cluster_map[i] <<- c_j\n return(TRUE)\n } else {\n return(FALSE)\n }\n }\n # Provide initial score for singleton clusters\n obj$get_inital_score = function() {\n return(initial_score)\n }\n # Provide final score for clustered graph\n obj$get_final_score = function() {\n return(initial_score + change_score)\n }\n # Provide incremental score changes\n obj$get_score_changes = function() {\n if (trace) return(change_scores)\n return(c())\n }\n # Remap the remaining clusters to indices in 1, 2, ..., K for smallest K\n obj$get_cluster_map = function() {\n cluster.nums = sort(unique(node_cluster_map))\n K = length(cluster.nums)\n new_cluster_map = rep(0, K)\n for (k in 1:K) {\n idx = which(node_cluster_map == cluster.nums[[k]])\n new_cluster_map[idx] = k\n }\n return(new_cluster_map)\n }\n # Expose object\n return(obj)\n}\n\n# Description:\n# An implementation of phase 1 of the Louvain modularity community detection (i.e. node clustering).\n# Input:\n# graph.repr - A graph representation.\n# trace - An optional flag indicating whether (TRUE) or not (FALSE) to\n# track incremental score changes; defaults to FALSE.\n# Output:\n# clusters - A |V| length vector giving the cluster index c_i for each vertex v_i.\ngraph.cluster = function(graph.repr, trace=FALSE) {\n node.ids = graph.repr$get_node_ids()\n num.nodes = length(node.ids)\n # Initialisation:\n clusters = graph.init_clusters(num.nodes, trace)\n for (i in 1:num.nodes) {\n v_i = node.ids[i]\n clusters$add_cluster_node(i)\n # To avoid double counting, only traverse edges in source -> target direction.\n out_edges = graph.repr$get_out_edges(v_i)\n num.out_edges = nrow(out_edges)\n if (num.out_edges > 0) {\n for (edge.idx in 1:num.out_edges) {\n edge = out_edges[edge.idx,]\n v_j = edge$target.id\n j = which(node.ids == v_j)\n clusters$add_cluster_node(j)\n w_ij = edge$weight\n clusters$add_cluster_edge(i, j, w_ij)\n }\n }\n }\n \n # Cluster reassignments:\n while (TRUE) {\n changed = FALSE\n for (i in 1:num.nodes) {\n v_i = node.ids[i]\n clusters$init_local_cluster_edges()\n out_edges = graph.repr$get_out_edges(v_i)\n num.out_edges = nrow(out_edges)\n if (num.out_edges > 0) {\n for (edge.idx in 1:num.out_edges) {\n edge = out_edges[edge.idx,]\n v_j = edge$target.id\n j = which(node.ids == v_j)\n w_ij = edge$weight\n clusters$add_local_cluster_edge(i, j, w_ij) # i -> j becomes i -- j.\n }\n }\n in_edges = graph.repr$get_in_edges(v_i)\n num.in_edges = nrow(in_edges)\n if (num.in_edges > 0) {\n for (edge.idx in 1:num.in_edges) {\n edge = in_edges[edge.idx,]\n v_j = edge$source.id\n j = which(node.ids == v_j)\n w_ji = edge$weight\n clusters$add_local_cluster_edge(i, j, w_ji) # Yes, i <- j becomes i -- j.\n }\n }\n moved = clusters$move_to_best_cluster(i)\n changed = changed || moved\n }\n if (!changed) break\n }\n # Map node id to cluster id\n cluster.ids = clusters$get_cluster_map()\n names(cluster.ids) = node.ids\n if (trace) {\n scores = cumsum(c(clusters$get_inital_score(), clusters$get_score_changes()))\n } else {\n scores = c(clusters$get_inital_score(), clusters$get_final_score())\n }\n return(list(\n cluster.ids = cluster.ids,\n initial.score = clusters$get_inital_score(),\n final.score = clusters$get_final_score(),\n incremental.scores = scores\n ))\n}\n\ngraph.matrix = function(graph.repr) {\n node.ids = graph.repr$get_node_ids()\n num.nodes = length(node.ids)\n D = matrix(data=0, nrow=num.nodes, ncol=num.nodes)\n for (i in 1:num.nodes) {\n v_i = node.ids[[i]]\n out.edges = graph.repr$get_out_edges(v_i)\n num.out.edges = nrow(out.edges)\n if (num.out.edges > 0) {\n for (edge.idx in 1:num.out.edges) {\n edge = out.edges[edge.idx,]\n v_j = edge$target.id\n j = which(node.ids == v_j)\n w_ij = edge$weight\n D[i, j] = D[i, j] + w_ij\n }\n }\n }\n rownames(D) = node.ids\n colnames(D) = node.ids\n return(D)\n}\n\ntest.graph.cluster = function() {\n edges = data.frame(source.id=c(\"X\", \"Y\", \"Z\"), target.id=c(\"Z\", \"X\", \"Y\"), weight=1, stringsAsFactors=FALSE)\n edges.repr = graph.get_edges_repr(edges)\n graph.repr = graph.from_edges_repr(edges.repr)\n D = graph.matrix(graph.repr)\n A = D + t(D)\n diag(A) = diag(D)\n A_id = rowSums(A)\n A_dd = sum(A_id)\n Q_mat = (A - A_id %*% t(A_id) / A_dd) / A_dd\n # Step 0 clusters: 1, 2, 3\n delta0 = matrix(0, nrow=3, ncol=3)\n diag(delta0) = 1\n step0.score = sum(Q_mat * delta0)\n # Step 1 clusters: 2, 2, 3\n delta1 = delta0\n delta1[1, 2] = 1; delta1[2, 1] = 1\n step1.score = sum(Q_mat * delta1)\n # Step 2 clusters: 2, 2, 2\n delta2 = delta1\n delta2[1, 3] = 1; delta2[2, 3] = 1; delta2[3, 1] = 1; delta2[3, 2] = 1\n step2.score = sum(Q_mat * delta2)\n scores = c(step0.score, step1.score, step2.score)\n # Step 3 clusters: 1, 1, 1 (remapped)\n res = graph.cluster(graph.repr, trace=TRUE)\n print(paste0(\"Expected incremental scores: \", paste(scores, collapse=\", \")))\n print(paste0(\"Observed incremental scores: \", paste(res$incremental.scores, collapse=\", \")))\n print(paste0(\"Expected clusters: \", paste(rep(1, 3), collapse=\", \")))\n print(paste0(\"Observed clusters: \", paste(res$cluster.ids, collapse=\", \")))\n}\n", "meta": {"hexsha": "a011e37a995b26b40dffce26ce2d67774235d1ac", "size": 13427, "ext": "r", "lang": "R", "max_stars_repo_path": "GraphAnalysis/R/graph.r", "max_stars_repo_name": "gaj67/gaj-data-science", "max_stars_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphAnalysis/R/graph.r", "max_issues_repo_name": "gaj67/gaj-data-science", "max_issues_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphAnalysis/R/graph.r", "max_forks_repo_name": "gaj67/gaj-data-science", "max_forks_repo_head_hexsha": "aadcf6ee2cd00606563f213167c2eeeb42430c59", "max_forks_repo_licenses": ["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.724852071, "max_line_length": 130, "alphanum_fraction": 0.6057942951, "num_tokens": 3480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.256554600637569}} {"text": "two_way_tanimoto_predict <- function(Kc, Kr, S0, S1, MW, similarity.consumer, similarity.resource, minimum_threshold) {\n # Two-way Tanimoto Algorithm\n # ===========================\n\n # Parameters:\n # Kc Integer, how many neighbors to select for consumers\n # Kr Integer, how many neighbors to select for resources\n # S0 A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']\n # S1 The subset of S0 where we want to predict new preys, string vector with taxa name\n # MW Mimimum weight to accept a candidate as a prey\n #\n\n # // TODO: I think MW should be a function of Kc & Kr and perhaps of the number of candidate resources. For example, a similar consumer could have multiple prey, which would artificially inflate the weight added to each prey in the candidate list. For exemple, Atlantic cod has over 600 prey species listed in the interaction catalogue... Hence, the longer the candidate list, the more likely a very small similarity will be turned into a predicted interaction\n # // REVIEW: Multiply similar.consumer[similarity] * similar.resource[similarity]? It's a similarity of a similarity in a sense...\n\n # // TODO: Different similarity measurement for resources and consumers\n\n # // REVIEW: Remove cannibalism from empirical data, or allow for it, or add parameter that allows or prevents cannibalism in the predictions. There are lots of predicted cannibalism interations in the catalogue and empirical webs. Accuracy would increase if it was allowed.\n\n\n # Output\n # A vector of sets (the preys for each species)\n\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # List of things to adjust - make it\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n # Process steps:\n # A prior process to this is to get the similarity matrix between all combinations of catalogue taxa and species in S1\n # For each species in S1:\n # 1. Identify resources already known in interaction catalogue (S0) for S1 species\n # 1.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions\n # 1.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity\n\n # 2. Identify Kc similar consumers to S1 in S0\n # 2.1 Extract set of candidate resources from each similar consumer, if any\n # 2.2 If candidate resource is in S1, add it to candidate list with weight 1\n # 2.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity\n\n # 3. Make predictions:\n # 3.1 Remove taxa with weight < to minimum weight (MW) from prediction list\n # 3.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed\n\n\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # !!! étendre predator et non predator pour resource... il faudrait aussi calculer la similarité des proies sur la base de leurs prédateurs partagés !!!\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n predictions <- matrix(nrow = length(S1), ncol = 3, data = \"\", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions\n predictions[, 'consumer'] <- S1\n\n # pb <- txtProgressBar(min = 0,max = length(S1), style = 3)\n for(i in 1:length(S1)) { # loop through each taxon in S1\n candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight\n resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], \" \\\\|\\\\ \")) # resources of S1[i]\n\n # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or\n # Find similar resources to resources for S1[i] in S1\n if(length(resources.S1) > 0) {\n empirical <- character()\n for(j in 1:length(resources.S1)) { #loop through empirical resources for S1\n if(resources.S1[j] %in% S1) {\n empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical\n } else { # selecting Kr most similar resources in S1\n # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.\n similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources\n similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE))\n similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE)\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {\n same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])\n similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]\n similar.resource <- similar.resource[1:Kr, ]\n } else {\n similar.resource <- similar.resource[1:Kr, ]\n }# if for random draw\n\n for(l in 1:Kr) { # extracting resource candidates\n if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed\n } else if(similar.resource[l, 'similarity'] < minimum_threshold) {\n NULL\n } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight\n candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])\n } else {\n candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight\n }#if3\n }#l\n }#if\n }#j\n predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')\n }#if1\n\n # Identify similar consumers to S1[i]\n similar.consumer <- matrix(nrow = nrow(similarity.consumer)-1, ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # emporting K nearest neighbors for consumers\n similar.consumer[, 'consumer'] <- names(sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE))\n similar.consumer[, 'similarity'] <- sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE)\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {\n same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])\n similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]\n similar.consumer <- similar.consumer[1:Kc, ]\n } else {\n similar.consumer <- similar.consumer[1:Kc, ]\n }# if for random draw\n\n\n # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?\n # If yes, we could add an argument call wt_predator.\n # if(wt_predator == FALSE) {\n # resources <- unique of all prey species of all similar predators\n # } else {}\n\n for(j in 1:Kc) { #loop through consumers\n\n if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n } else {\n\n # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource\n candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], \" \\\\|\\\\ \")) # list of resources for consumer j\n # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment\n\n for(k in 1:length(candidate.resource)) { # loop through resources of consumer j\n if(length(candidate.resource) == 0) { # if candidate resource list is empty, break\n break\n } else if(candidate.resource[1] == \"\") { # if candidate list is an empty vector \"\", break\n break\n } else if(candidate.resource[k] == S1[i]) {\n # #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not\n NULL\n } else if((candidate.resource[k] %in% S1) == TRUE) {\n if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight\n candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1\n } else {\n candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight\n }#if2\n\n } else {\n # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.\n similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources\n similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE))\n similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE)\n\n # If multiple taxa with same similarity, randomly select those that will be used as similar resources.\n if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {\n same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])\n similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]\n similar.resource <- similar.resource[1:Kr, ]\n } else {\n similar.resource <- similar.resource[1:Kr, ]\n }# if for random draw\n\n for(l in 1:Kr) { # extracting resource candidates\n if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break\n break\n } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided\n NULL\n # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed\n } else if(similar.resource[l, 'similarity'] < minimum_threshold) {\n NULL\n } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight\n candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])\n } else {\n candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity\n }#if3\n }#l\n } #if1\n }#k\n }#if\n }#j\n\n candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW\n if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order\n candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight\n predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')\n } else {\n predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')\n }#if\n # setTxtProgressBar(pb, i)\n }#i\n # close(pb)\n return(predictions)\n}#two_way_tanimoto_predict function\n", "meta": {"hexsha": "8c2ed6a147cf63f9a1c711dca0163d82bd85ccf7", "size": 14304, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/two_way_tanimoto_predict.r", "max_stars_repo_name": "david-beauchesne/predicting_interactions", "max_stars_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-08-12T11:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-09T18:16:12.000Z", "max_issues_repo_path": "Script/two_way_tanimoto_predict.r", "max_issues_repo_name": "david-beauchesne/predicting_interactions", "max_issues_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-08-12T14:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-12T15:25:21.000Z", "max_forks_repo_path": "Script/two_way_tanimoto_predict.r", "max_forks_repo_name": "david-beauchesne/predicting_interactions", "max_forks_repo_head_hexsha": "bcddde0b04325a7c8a64467d4adcf8f13d7208c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-08-12T10:46:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-12T10:46:53.000Z", "avg_line_length": 74.5, "max_line_length": 464, "alphanum_fraction": 0.5929110738, "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.25587326324589693}} {"text": "#############################################################################\n##\n## Indirection - phase 2: output gating \n## Role/filler recall task\n## 2017 Mike Jovanovich\n##\n## In this version OG sees WM after it has been update by IG within a timestep.\n## The action selection if this version simply checks if WM_out outputs only\n## the correct filler\n##\n#############################################################################\n\n## Usage\n# Rscript outputgate.r 1 100000 3 10 3 C C D F F SG\n\n#############################################################################\n## Parameter initialization\n#############################################################################\n\nsource('hrr.r')\nsource('sentenceSets.r')\nrequire(methods)\nrequire(Matrix)\n\n## Build args dictionary\nargnames <- list('seed','ntasks','nstripes','nfillers','nroles','state_cd','sid_cd','interstripe_cd',\n 'use_sids_input','use_sids_output','gen_test')\nargs <- commandArgs(trailingOnly = TRUE)\n\n## Set the seed for repeatability\nset.seed(as.integer(args[which(argnames=='seed')]))\n\n## Length of the HRRs\nn <- 1024\n## Number of possible fillers\nnfillers <- as.integer(args[which(argnames=='nfillers')])\n## Number of possible roles\nnroles <- as.integer(args[which(argnames=='nroles')])\n## Number of WM stripes\nnstripes <- as.integer(args[which(argnames=='nstripes')])\n\n## Define conj/disj scheme\nstate_cd <- args[which(argnames=='state_cd')]\nsid_cd <- args[which(argnames=='sid_cd')]\ninterstripe_cd <- args[which(argnames=='interstripe_cd')]\n\n## Identity vectors\nhrr_z <- rep(0,n)\nhrr_o <- rep(0,n)\nhrr_o[1] <- 1\n\n# Set this according to conj. disj. scheme;\nif( interstripe_cd == 'D' ) {\n hrr_i <- hrr_z \n} else {\n hrr_i <- hrr_o\n}\n\n## Filler vectors \n## Fillers don't have friendly names, only indexes\n## To index: [,filler]\nfillers <- replicate(nfillers,hrr(n,normalized=TRUE))\nwm_fillers <- replicate(nfillers,hrr(n,normalized=TRUE))\nf_fillers <- paste('f',1:nfillers,sep='') # Friendly names\n\n## Role vectors \n## Roles don't have friendly names, only indexes\n## To index: [,role]\nroles <- replicate(nroles,hrr(n,normalized=TRUE))\n\n## Stripe ID (SID) vectors \n## To index: [,sid]\nsids <- replicate(nstripes,hrr(n,normalized=TRUE))\nuse_sids_input <- args[which(argnames=='use_sids_input')] == 'T'\nuse_sids_output <- args[which(argnames=='use_sids_output')] == 'T'\n\n## Op code vectors\n## To index: [,1] for store, [,2] for retrieve\nops <- replicate(2,hrr(n,normalized=TRUE))\n\n## Op code vectors\n## To index: [,1] go, [,2] no go \ngono <- replicate(2,hrr(n,normalized=TRUE))\n\n## TD weight vectors\n## A suffix of '_m' indicates relation to the maintenance layer NN\n## To index: [,stripe]\nW_m <- replicate(nstripes,hrr(n,normalized=TRUE))\nW_o <- replicate(nstripes,hrr(n,normalized=TRUE))\n\n## Action weight vectors\n## There are 'nfillers' output units for this network\n## Each output unit should come to represent the desired filler\n## To index: [,output_unit]\nW_a <- replicate(nfillers,hrr(n,normalized=TRUE))\n\n## TD parameters\ndefault_reward <- 0.0\nsuccess_reward <- 1.0\nbias_m <- 1.0\nbias_o <- 1.0\nbias_a <- 1.0\ngamma_m <- 1.0\ngamma_o <- 1.0\ngamma_a <- 1.0\nlambda_m <- 0.9\nlambda_o <- 0.9\nlrate_m <- 0.1\nlrate_o <- 0.1\nlrate_a <- 0.1\nepsilon_m <- .025\nepsilon_o <- .025\n\n## Task parameters\nmax_tasks <- as.integer(args[which(argnames=='ntasks')])\ncur_task <- 1\ncur_block_task <- 1\nblock_tasks_correct <- 0\n\n## Get training and test sets\ntrain_set_size <- 200\ntest_set_size <- 100\n\n## Choose testing protocol\nif( args[which(argnames=='gen_test')] == 'SG' ) {\n sets <- standardGeneralization(nroles,nfillers,train_set_size,test_set_size)\n} else if( args[which(argnames=='gen_test')] == 'SA' ) {\n sets <- spuriousAnticorrelation(nroles,nfillers,train_set_size,test_set_size)\n} else if( args[which(argnames=='gen_test')] == 'FC' ) {\n sets <- fullCombinatorial(nroles,nfillers,train_set_size,test_set_size)\n} else if( args[which(argnames=='gen_test')] == 'NF' ) {\n sets <- novelFiller(nroles,nfillers,train_set_size,test_set_size)\n}\n\n#############################################################################\n## selectAction:\n##\n## This function handles action selection. To keep things simple, there must\n## be only one WM_out filler, otherwise a -1 action is returned.\n##\n#############################################################################\nselectAction <- function() {\n action <- -1\n for( i in 1:nstripes ) {\n if( f_stripes_o[i] != 'I' )\n ## if there are more than one fillers return -1\n if( action != -1 )\n return(-1)\n else\n action <- as.integer(substr(f_stripes_o[i],2,nchar(f_stripes_o[i])))\n }\n return (action)\n}\n\n#############################################################################\n## getState: Returns role/op combo\n#############################################################################\ngetState <- function(o,r) {\n ## Encode state (role,op)\n if( state_cd == 'C' ) {\n state <- convolve(ops[,o],roles[,r])\n } else {\n state <- cnorm(ops[,o] + roles[,r])\n }\n #state <- roles[,r]\n return (state)\n}\n\n#############################################################################\n## inputGate:\n##\n## This function handles input gating for a single timestep/operation in the task.\n## At each timestep a stripe can either retain its contents or update with the \n## provided filler. \n##\n## Multiple stripes update in a single timestep.\n##\n#############################################################################\ninputGate <- function(state,f=-1) {\n\n ## Get NN output unit values\n ## Note that state_wm is for the previous timestep\n ## We will return this to use in the eligibility trace\n #state_wm <- convolve(state,cur_wm_m)\n\n ## This is state_wm convolved with both the go and no go hrrs\n #state_wm_gono <- apply(gono,2,convolve,state_wm)\n state_gono <- apply(gono,2,convolve,state)\n\n ## Build to matrix of eligility trace vectors that will be returned\n ## for TD updates; default to no go\n #elig <- replicate(nstripes,state_wm_gono[,2])\n elig <- replicate(nstripes,state_gono[,2])\n vals <- rep(0.0,nstripes)\n open <- rep(FALSE,nstripes)\n\n ## Determine if open or close value is better\n for( i in 1:nstripes ) {\n #temp_vals <- (apply(state_wm_gono,2,nndot,W_m[,i]) + bias_m)\n temp_vals <- (apply(state_gono,2,nndot,W_m[,i]) + bias_m)\n vals[i] <- max(temp_vals)\n\n ## Epsilon soft policy\n r <- runif(1)\n if( r < epsilon_m ) {\n ## Pick a random open or close state\n r <- runif(1)\n if( r > .5 ) {\n #elig[,i] <- state_wm_gono[,1]\n elig[,i] <- state_gono[,1]\n open[i] <- TRUE\n vals[i] <- temp_vals[1]\n } else {\n vals[i] <- temp_vals[2]\n }\n } else if( temp_vals[1] > temp_vals[2] ) {\n #elig[,i] <- state_wm_gono[,1]\n elig[,i] <- state_gono[,1]\n open[i] <- TRUE\n }\n }\n\n\n ## Update WM_m contents \n ## We are convolving the fill with the appropriate SID\n for( i in 1:nstripes ) {\n if( open[i] ) {\n if( f == -1 ) {\n stripes_m[,i] <- hrr_i\n stripes_mo[,i] <- hrr_i\n f_stripes_m[i] <- 'I'\n } else {\n if( sid_cd == 'C' ) {\n if( use_sids_input )\n stripes_m[,i] <- convolve(fillers[,f],sids[,i])\n if( use_sids_output )\n stripes_mo[,i] <- convolve(fillers[,f],sids[,i])\n } else {\n if( use_sids_input )\n stripes_m[,i] <- cnorm(fillers[,f]+sids[,i])\n if( use_sids_output )\n stripes_mo[,i] <- cnorm(fillers[,f]+sids[,i])\n }\n if( !use_sids_input )\n stripes_m[,i] <- fillers[,f]\n if( !use_sids_output )\n stripes_mo[,i] <- fillers[,f]\n f_stripes_m[i] <- f_fillers[f]\n }\n }\n }\n\n ## Get updated wm representation\n if( interstripe_cd == 'D' ) {\n wm <- cnorm(apply(stripes_m,1,sum))\n if( is.nan(wm[1]) )\n wm <- hrr_o\n } else {\n wm <- mconvolve(stripes_m)\n }\n\n return(list(\n wm = wm,\n elig = elig,\n vals = vals,\n stripes_m = stripes_m,\n stripes_mo = stripes_mo,\n f_stripes_m = f_stripes_m\n ))\n}\n\n#############################################################################\n## outputGate:\n##\n## This function handles output gating for a single timestep/operation in the task.\n## Each PFC stripe can either output its contents or not.\n##\n#############################################################################\noutputGate <- function(state) {\n\n ## Start with a blank slate\n stripes_o <- replicate(nstripes,hrr_i)\n f_stripes_o <- replicate(nstripes,'I')\n\n ## Get NN output unit values\n ## Note that state_wm is for the previous timestep\n ## We will return this to use in the eligibility trace\n #state_wm <- convolve(state,cur_wm_m)\n\n ## This is state_wm convolved with both the go and no go hrrs\n #state_wm_gono <- apply(gono,2,convolve,state_wm)\n state_gono <- apply(gono,2,convolve,state)\n\n ## Build to matrix of eligility trace vectors that will be returned\n ## for TD updates; default to no go\n #elig <- replicate(nstripes,state_wm_gono[,2])\n elig <- replicate(nstripes,state_gono[,2])\n vals <- rep(0.0,nstripes)\n open <- rep(FALSE,nstripes)\n\n ## Determine if open or close value is better\n for( i in 1:nstripes ) {\n\n #temp_vals <- (apply(state_wm_gono,2,nndot,W_o[,i]) + bias_o)\n temp_vals <- (apply(state_gono,2,nndot,W_o[,i]) + bias_o)\n vals[i] <- max(temp_vals)\n\n ## Epsilon soft policy\n r <- runif(1)\n if( r < epsilon_o ) {\n ## Pick a random open or close state\n r <- runif(1)\n if( r > .5 ) {\n #elig[,i] <- state_wm_gono[,1]\n elig[,i] <- state_gono[,1]\n open[i] <- TRUE\n vals[i] <- temp_vals[1]\n } else {\n vals[i] <- temp_vals[2]\n }\n } else if( temp_vals[1] > temp_vals[2] ) {\n #elig[,i] <- state_wm_gono[,1]\n elig[,i] <- state_gono[,1]\n open[i] <- TRUE\n }\n }\n\n\n ## Update WM_o contents \n ## We are convolving the fill with the appropriate SID\n for( i in 1:nstripes ) {\n if( open[i] ) {\n stripes_o[,i] <- stripes_mo[,i]\n f_stripes_o[i] <- f_stripes_m[i]\n }\n }\n\n ## Get updated wm representation\n if( interstripe_cd == 'D' ) {\n wm <- cnorm(apply(stripes_o,1,sum))\n if( is.nan(wm[1]) )\n ## Change this depending on how we want 'nothing' to look for action selection\n #wm <- hrr_o\n wm <- hrr_z\n } else {\n wm <- mconvolve(stripes_o)\n }\n\n return(list(\n wm = wm,\n elig = elig,\n vals = vals,\n f_stripes_o = f_stripes_o\n ))\n}\n\n## Continue until we hit the max_tasks, or we have a block success rate of 95%\nwhile( cur_task <= max_tasks ) {\n\n ## Setup 200 task blocks\n if( cur_task %% 200 == 1 ) {\n if( block_tasks_correct/200 >= .95 )\n break\n cur_block_task <- 1\n block_tasks_correct <- 0\n }\n\n #############################################################################\n ## Initialization and task setup\n #############################################################################\n\n reward <- default_reward\n elig_m <- replicate(nstripes,rep(0,n)) # There is an elig. trace for each BG input gate\n elig_o <- replicate(nstripes,rep(0,n)) # There is an elig. trace for each BG output gate\n prev_val_m <- rep(0.0,nstripes) # prev. timestep values for maintenance NN output layer units\n prev_val_o <- rep(0.0,nstripes) # prev. timestep values for output NN output layer units\n cur_wm_m <- hrr_o\n cur_wm_o <- hrr_o\n\n ## Fill stripes with identity vector\n stripes_m <- replicate(nstripes,hrr_i) # Input layer stripes (hrrs)\n stripes_mo <- replicate(nstripes,hrr_i) # Output layer stripes (hrrs); these are same as above, but with no SID\n f_stripes_m <- replicate(nstripes,'I') # Friendly name for stripe contents of input WM layer\n f_stripes_o <- replicate(nstripes,'I') # Friendly name for stripe contents of output WM layer\n\n #############################################################################\n ## Store fillers\n #############################################################################\n\n ## Choose a sentence at random from the sample set\n s_f <- sets$train_set[sample(train_set_size,1),]\n\n ## Permute the sentence so that roles are not always presented in the same order\n p <- sample(nroles,nroles,replace=FALSE)\n\n for( t in 1:nroles ) {\n #cat(sprintf('t=%d\\n',t)) #debug\n\n state <- getState(1,p[t])\n\n #############################################################################\n ## Input gating\n #############################################################################\n\n ## Update WM input layer global variables\n ig <- inputGate(state,s_f[p[t]])\n cur_wm_m <- ig$wm\n stripes_m <- ig$stripes_m\n stripes_mo <- ig$stripes_mo\n f_stripes_m <- ig$f_stripes_m\n\n #############################################################################\n ## Output gating\n #############################################################################\n\n ## Update WM output layer global variables\n og <- outputGate(state)\n cur_wm_o <- og$wm\n f_stripes_o <- og$f_stripes_o\n\n #############################################################################\n ## Neural network and TD training for this trial\n #############################################################################\n\n ## INPUT GATE\n error <- (reward + gamma_m * ig$vals) - prev_val_m\n for( i in 1:nstripes ) {\n W_m[,i] <- W_m[,i] + lrate_m * error[i] * elig_m[,i]\n elig_m[,i] <- cnorm(lambda_m * elig_m[,i] + ig$elig[,i])\n }\n prev_val_m <- ig$vals \n\n ## OUTPUT GATE\n error <- (reward + gamma_o * og$vals) - prev_val_o\n for( i in 1:nstripes ) {\n W_o[,i] <- W_o[,i] + lrate_o * error[i] * elig_o[,i]\n elig_o[,i] <- cnorm(lambda_o * elig_o[,i] + og$elig[,i])\n }\n prev_val_o <- og$vals \n\n }\n #cat(sprintf('t=%d\\n',t+1)) #debug\n\n #############################################################################\n ## Query for roles\n #############################################################################\n\n ## Permute the sentence so that roles are not always queried in the same order\n nqueries <- 1\n p <- sample(nroles,nqueries,replace=FALSE)\n correct_trial <- rep(0,nqueries)\n\n for( t in 1:nqueries ) {\n state <- getState(2,p[t])\n\n #############################################################################\n ## Input gating\n #############################################################################\n\n ## Update WM input layer global variables\n ig <- inputGate(state)\n cur_wm_m <- ig$wm\n stripes_m <- ig$stripes_m\n stripes_mo <- ig$stripes_mo\n f_stripes_m <- ig$f_stripes_m\n\n #############################################################################\n ## Output gating\n #############################################################################\n\n ## Update WM output layer global variables\n og <- outputGate(state)\n cur_wm_o <- og$wm\n f_stripes_o <- og$f_stripes_o\n\n #############################################################################\n ## Action selection\n #############################################################################\n \n ac <- selectAction()\n\n #############################################################################\n ## Neural network and TD training for this trial\n #############################################################################\n\n ## INPUT GATE\n error <- (reward + gamma_m * ig$vals) - prev_val_m\n for( i in 1:nstripes ) {\n W_m[,i] <- W_m[,i] + lrate_m * error[i] * elig_m[,i]\n elig_m[,i] <- cnorm(lambda_m * elig_m[,i] + ig$elig[,i])\n }\n prev_val_m <- ig$vals \n\n ## OUTPUT GATE\n error <- (reward + gamma_o * og$vals) - prev_val_o\n for( i in 1:nstripes ) {\n W_o[,i] <- W_o[,i] + lrate_o * error[i] * elig_o[,i]\n elig_o[,i] <- cnorm(lambda_o * elig_o[,i] + og$elig[,i])\n }\n prev_val_o <- og$vals \n\n ## Determine correctness\n ## The trial is correct of the selected action matches the filler that\n ## was paired with the requested role.\n if( ac == s_f[p[t]] )\n correct_trial[t] <- 1\n\n #############################################################################\n ## Absorb reward\n #############################################################################\n if( t == nqueries ) {\n\n ## Reward if entire sequence is correct\n ## Update block correct tally\n if( sum(correct_trial) == nqueries ) {\n block_tasks_correct <- block_tasks_correct + 1\n reward <- success_reward\n } else {\n reward <- default_reward\n }\n\n ## Input NN\n error <- reward - ig$vals \n for( i in 1:nstripes ) {\n W_m[,i] <- W_m[,i] + lrate_m * error[i] * elig_m[,i]\n }\n\n ## Output NN\n error <- reward - og$vals \n for( i in 1:nstripes ) {\n W_o[,i] <- W_o[,i] + lrate_o * error[i] * elig_o[,i]\n }\n }\n }\n\n #############################################################################\n ## Output prints\n #############################################################################\n\n #if( FALSE ) {\n if( cur_task %% 200 == 0 ) {\n cat(sprintf('Tasks Complete: %d\\n',cur_task))\n cat(sprintf('Block Accuracy: %.2f\\n',(block_tasks_correct/200)*100))\n\n ## Only printing final request state here\n cat('Input WM Layer: \\t')\n cat(f_stripes_m)\n cat('\\n')\n cat('Output WM Layer: \\t')\n cat(f_stripes_o)\n cat('\\n')\n cat(sprintf('Requested Role: %d\\n',p[t]))\n cat(sprintf('Correct Action: %d\\n',s_f[p[t]]))\n cat('\\n')\n }\n\n #############################################################################\n ## Task wrapup\n #############################################################################\n\n ## Increment task tally\n cur_task <- cur_task + 1\n}\n\n## Print final results\n#cat(sprintf('%d\\n',cur_task))\ncat(sprintf('Final Block Accuracy: %.2f\\n',(block_tasks_correct/200)*100))\n\n#############################################################################\n## Generalization Test\n#############################################################################\nif(TRUE) {\n novel_tasks_correct <- 0\n for( i in 1:test_set_size ) {\n correct_trial <- rep(0,nqueries)\n\n #############################################################################\n ## Store fillers\n #############################################################################\n\n ## Retrieve novel sentence from the test set\n ## We aren't training here so no need to permute\n s_f <- sets$test_set[i,]\n\n ## Permute the sentence so that roles are not always presented in the same order\n p <- sample(nroles,nroles,replace=FALSE)\n\n ## Do a 'Store' for each filler\n ## Action selection can be skipped here\n ## Do not do any training\n for( t in 1:nroles ) {\n state <- getState(1,p[t])\n\n ig <- inputGate(state,s_f[p[t]])\n cur_wm_m <- ig$wm\n stripes_m <- ig$stripes_m\n stripes_mo <- ig$stripes_mo\n f_stripes_m <- ig$f_stripes_m\n\n og <- outputGate(state)\n cur_wm_o <- og$wm\n f_stripes_o <- og$f_stripes_o\n }\n\n ## Do a 'Retrieve' input gate, output gate, and select action\n p <- sample(nroles,nqueries,replace=FALSE)\n for( t in 1:nqueries ) {\n\n ## We can only query role 1 for the FC test\n ## consequently, nqueries must be set to 1\n state <- if(args[which(argnames=='gen_test')] == 'FC') getState(2,1) else getState(2,p[t])\n answer <- if(args[which(argnames=='gen_test')] == 'FC') s_f[1] else s_f[p[t]] \n\n ig <- inputGate(state)\n cur_wm_m <- ig$wm\n stripes_m <- ig$stripes_m\n stripes_mo <- ig$stripes_mo\n f_stripes_m <- ig$f_stripes_m\n\n og <- outputGate(state)\n cur_wm_o <- og$wm\n f_stripes_o <- og$f_stripes_o\n\n ac <- selectAction()\n if( ac == answer )\n correct_trial[t] <- 1\n }\n\n ## Determine if entire sequence is correct\n ## Not sure if we'll want to modify protocol above to train for this\n if( sum(correct_trial) == nqueries )\n novel_tasks_correct <- novel_tasks_correct + 1\n }\n\n ## Print final results\n cat(sprintf('Generalization Accuracy: %d\\n',novel_tasks_correct))\n #cat(sprintf('%d\\n',novel_tasks_correct))\n} ## End generalization test\n", "meta": {"hexsha": "4ff02188b2229e52964085ee749288469e4fa32b", "size": 21830, "ext": "r", "lang": "R", "max_stars_repo_path": "outputgate_no_ac_nn.r", "max_stars_repo_name": "ChaningBlake/novel_role_filler_generalization", "max_stars_repo_head_hexsha": "9bfc16b2de9103bed57ed1e8906c8cb3bd87a834", "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": "outputgate_no_ac_nn.r", "max_issues_repo_name": "ChaningBlake/novel_role_filler_generalization", "max_issues_repo_head_hexsha": "9bfc16b2de9103bed57ed1e8906c8cb3bd87a834", "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": "outputgate_no_ac_nn.r", "max_forks_repo_name": "ChaningBlake/novel_role_filler_generalization", "max_forks_repo_head_hexsha": "9bfc16b2de9103bed57ed1e8906c8cb3bd87a834", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1627543036, "max_line_length": 116, "alphanum_fraction": 0.485387082, "num_tokens": 5188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.25523477748527945}} {"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#' MVP, Memory-efficient, Visualization-enhanced, Parallel-accelerated\n#'\n#' Object 1: To perform GWAS using General Linear Model (GLM), Mixed Linear Model (MLM), and FarmCPU model\n#' Object 2: To calculate kinship among individuals using Varaden method\n#' Object 3: Estimate variance components using EMMA, FaST-LMM, and HE regression\n#' Object 4: Generate high-quality figures\n#' \n#' Build date: Aug 30, 2017\n#' Last update: Dec 14, 2018\n#' \n#' @author Lilin Yin, Haohao Zhang, and Xiaolei Liu\n#' \n#' @param phe phenotype, n * 2 matrix, n is sample size\n#' @param geno Genotype in bigmatrix format; m * n, m is marker size, n is sample size\n#' @param map SNP map information, SNP name, Chr, Pos\n#' @param K Kinship, Covariance matrix(n * n) for random effects, must be positive semi-definite\n#' @param nPC.GLM number of PCs added as fixed effects in GLM\n#' @param nPC.MLM number of PCs added as fixed effects in MLM\n#' @param nPC.FarmCPU number of PCs added as fixed effects in FarmCPU\n#' @param CV.GLM covariates added in GLM\n#' @param CV.MLM covariates added in MLM\n#' @param CV.FarmCPU covariates added in FarmCPU\n#' @param REML a list contains ve and vg\n#' @param priority speed or memory\n#' @param ncpus number of cpus used for parallel\n#' @param vc.method methods for estimating variance component(\"EMMA\" or \"HE\" or \"BRENT\")\n#' @param method the GWAS model, \"GLM\", \"MLM\", and \"FarmCPU\", models can be selected simutaneously, i.e. c(\"GLM\", \"MLM\", \"FarmCPU\")\n#' @param p.threshold if all p values generated in the first iteration are bigger than p.threshold, FarmCPU stops\n#' @param QTN.threshold in second and later iterations, only SNPs with lower p-values than QTN.threshold have chances to be selected as pseudo QTNs\n#' @param method.bin 'static' or 'FaST-LMM'\n#' @param bin.size window size in genome\n#' @param bin.selection a vector, how many windows selected\n#' @param maxLoop maximum number of iterations\n#' @param permutation.threshold if use a permutation cutoff or not (bonferroni cutoff)\n#' @param permutation.rep number of permutation replicates\n#' @param col for color of points in each chromosome on manhattan plot\n#' @param memo Character. A text marker on output files\n#' @param outpath Effective only when file.output = TRUE, determines the path of the output file\n#' @param file.output whether to output files or not\n#' @param file.type figure formats, \"jpg\", \"tiff\"\n#' @param dpi resolution for output figures\n#' @param threshold a cutoff line on manhattan plot, 0.05/marker size\n#' @param verbose whether to print detail.\n#' \n#' @export\n#' @return a m * 2 matrix, the first column is the SNP effect, the second column is the P values\n#' Output: MVP.return$map - SNP map information, SNP name, Chr, Pos\n#' Output: MVP.return$glm.results - p-values obtained by GLM method\n#' Output: MVP.return$mlm.results - p-values obtained by MLM method\n#' Output: MVP.return$farmcpu.results - p-values obtained by FarmCPU method\n#'\n#' @examples\n#' phePath <- system.file(\"extdata\", \"07_other\", \"mvp.phe\", package = \"rMVP\")\n#' phenotype <- read.table(phePath, header=TRUE)\n#' print(dim(phenotype))\n#' genoPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.desc\", package = \"rMVP\")\n#' genotype <- attach.big.matrix(genoPath)\n#' print(dim(genotype))\n#' mapPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.map\", package = \"rMVP\")\n#' map <- read.table(mapPath , head = TRUE)\n#' \n#' opts <- options(rMVP.OutputLog2File = FALSE)\n#' \n#' mvp <- MVP(phe=phenotype, geno=genotype, map=map, maxLoop=3,\n#' method=c(\"GLM\", \"MLM\", \"FarmCPU\"), file.output=FALSE, ncpus=1)\n#' str(mvp)\n#' \n#' options(opts)\nMVP <-\nfunction(phe, geno, map, K=NULL, nPC.GLM=NULL, nPC.MLM=NULL, nPC.FarmCPU=NULL,\n CV.GLM=NULL, CV.MLM=NULL, CV.FarmCPU=NULL, REML=NULL, priority=\"speed\", \n ncpus=detectCores(logical = FALSE), vc.method=c(\"BRENT\", \"EMMA\", \"HE\"), \n method=c(\"GLM\", \"MLM\", \"FarmCPU\"), p.threshold=NA, \n QTN.threshold=0.01, method.bin=\"static\", bin.size=c(5e5,5e6,5e7), \n bin.selection=seq(10,100,10), maxLoop=10, permutation.threshold=FALSE, \n permutation.rep=100, memo=NULL, outpath=getwd(),\n col=c(\"#4197d8\", \"#f8c120\", \"#413496\", \"#495226\", \"#d60b6f\", \"#e66519\", \n \"#d581b7\", \"#83d3ad\", \"#7c162c\", \"#26755d\"), file.output=TRUE, \n file.type=\"jpg\", dpi=300, threshold=0.05, verbose=TRUE\n) {\n\n # Compatible with old ways\n if (file.output == TRUE) {\n file.output <- c(\"pmap\", \"pmap.signal\", \"plot\", \"log\")\n } else if (file.output == FALSE) {\n file.output <- c()\n }\n\n for(mt in method){\n if(!mt %in% c(\"GLM\", \"MLM\", \"FarmCPU\"))\n stop(\"Unknow method: \", mt)\n }\n \n # Set output path of log file \n logging.outpath <- NULL\n if (\"log\" %in% file.output) {\n logging.outpath <- outpath\n }\n logging.initialize(\"MVP\", logging.outpath)\n\n MVP.Version(width = 60, verbose = verbose)\n logging.log(\"Start:\", as.character(Sys.time()), \"\\n\", verbose = verbose)\n if (\"log\" %in% file.output) {\n logging.log(\"The log has been output to the file:\", get(\"logging.file\", envir = package.env), \"\\n\", verbose = verbose)\n }\n vc.method <- match.arg(vc.method)\n if (nrow(phe) != ncol(geno)) stop(\"The number of individuals in phenotype and genotype doesn't match!\")\n if (nrow(geno) != nrow(map)) stop(\"The number of markers in genotype and map doesn't match!\")\n if (!is.big.matrix(geno)) stop(\"genotype should be in 'big.matrix' format.\")\n if(hasNA(geno@address)) stop(\"NA is not allowed in genotype, use 'MVP.Data.impute' to impute.\")\n \n #list -> matrix\n map <- as.data.frame(map)\n for(i in 1 : ncol(map)){\n if(is.factor(map[, i])) map[, i] <- as.character.factor(map[, i])\n }\n\n na.index <- NULL\n if (!is.null(CV.GLM)) {\n CV.GLM <- as.matrix(CV.GLM)\n if (nrow(CV.GLM) != ncol(geno)) stop(\"The number of individuals in covariates and genotype doesn't match!\")\n na.index <- c(na.index, which(is.na(CV.GLM), arr.ind = TRUE)[, 1])\n }\n if (!is.null(CV.MLM)) {\n CV.MLM <- as.matrix(CV.MLM)\n if (nrow(CV.MLM) != ncol(geno)) stop(\"The number of individuals in covariates and genotype doesn't match!\")\n na.index <- c(na.index, which(is.na(CV.MLM), arr.ind = TRUE)[, 1])\n }\n if (!is.null(CV.FarmCPU)) {\n CV.FarmCPU <- as.matrix(CV.FarmCPU)\n if (nrow(CV.FarmCPU) != ncol(geno)) stop(\"The number of individuals in covariates and genotype doesn't match!\")\n na.index <- c(na.index, which(is.na(CV.FarmCPU), arr.ind = TRUE)[, 1])\n }\n na.index <- unique(na.index)\n\n #Data information\n m <- nrow(geno)\n n <- ncol(geno)\n logging.log(paste(\"Input data has\", n, \"individuals,\", m, \"markers\"), \"\\n\", verbose = verbose)\n logging.log(\"Analyzed trait:\", colnames(phe)[2], \"\\n\", verbose = verbose)\n logging.log(\"Number of threads used:\", ncpus, \"\\n\", verbose = verbose)\n\n #remove samples with missing phenotype\n seqTaxa = which(!is.na(phe[,2]))\n if (length(na.index) != 0) seqTaxa <- intersect(seqTaxa, c(1:n)[-na.index])\n if (length(seqTaxa) != n) {\n logging.log(\"Total\", n - length(seqTaxa), \"individuals removed due to missings\", \"\\n\", verbose = verbose)\n geno = deepcopy(\n x = geno,\n cols = seqTaxa\n )\n phe = phe[seqTaxa,]\n if (!is.null(K)) { K = K[seqTaxa, seqTaxa] }\n if (!is.null(CV.GLM)) { CV.GLM = CV.GLM[seqTaxa,] }\n if (!is.null(CV.MLM)) { CV.MLM = CV.MLM[seqTaxa,] }\n if (!is.null(CV.FarmCPU)) { CV.FarmCPU = CV.FarmCPU[seqTaxa,] }\n }\n\n m <- nrow(geno)\n n <- ncol(geno)\n \n #initial results\n glm.results <- NULL\n mlm.results <- NULL\n farmcpu.results <- NULL\n \n #indicators for models\n glm.run <- \"GLM\" %in% method\n mlm.run <- \"MLM\" %in% method\n farmcpu.run <- \"FarmCPU\" %in% method\n \n\n nPC <- suppressWarnings(max(nPC.GLM, nPC.MLM, nPC.FarmCPU, na.rm = TRUE))\n if (nPC <= 0) {\n nPC <- NULL\n } else if (nPC < 3) {\n nPC <- 3\n }\n\n if (!is.null(K)) { K <- as.matrix(K) }\n if (!is.null(nPC) | \"MLM\" %in% method) {\n if (is.null(K)) {\n K <- MVP.K.VanRaden(\n M = geno, \n priority = priority, \n cpu = ncpus, \n verbose = verbose\n )\n }\n logging.log(\"Eigen Decomposition on GRM\", \"\\n\", verbose = verbose)\n eigenK <- eigen(K, symmetric = TRUE)\n if (!is.null(nPC)) {\n ipca <- eigenK$vectors[, 1:nPC]\n logging.log(\"Deriving PCs successfully\", \"\\n\", verbose = verbose)\n }\n if ((\"MLM\" %in% method) & vc.method == \"BRENT\") { K <- NULL; gc()}\n if (!\"MLM\" %in% method) { rm(eigenK); rm(K); gc() }\n }\n\n if (!is.null(nPC)) {\n #CV for GLM\n if (glm.run) {\n if (!is.null(CV.GLM)) {\n logging.log(\"Number of provided covariates of GLM:\", ncol(CV.GLM), \"\\n\", verbose = verbose)\n if (!is.null(nPC.GLM)) {\n logging.log(\"Number of PCs included:\", nPC.GLM, \"\\n\", verbose = verbose)\n CV.GLM <- cbind(ipca[,1:nPC.GLM], CV.GLM)\n }\n } else if (!is.null(nPC.GLM)) {\n logging.log(\"Number of PCs included in GLM:\", nPC.GLM, \"\\n\", verbose = verbose)\n CV.GLM <- ipca[,1:nPC.GLM]\n }\n }\n \n #CV for MLM\n if (mlm.run) {\n if (!is.null(CV.MLM)) {\n logging.log(\"Number of provided covariates of MLM:\", ncol(CV.MLM), \"\\n\", verbose = verbose)\n if (!is.null(nPC.MLM)) {\n logging.log(\"Number of PCs included:\", nPC.MLM, \"\\n\", verbose = verbose)\n CV.MLM <- cbind(ipca[,1:nPC.MLM], CV.MLM)\n }\n } else if (!is.null(nPC.MLM)) {\n logging.log(\"Number of PCs included in MLM:\", nPC.MLM, \"\\n\", verbose = verbose)\n CV.MLM <- ipca[,1:nPC.MLM]\n }\n }\n \n #CV for FarmCPU\n if (farmcpu.run) {\n if (!is.null(CV.FarmCPU)) {\n logging.log(\"Number of provided covariates of FarmCPU:\", ncol(CV.FarmCPU), \"\\n\", verbose = verbose)\n if (!is.null(nPC.FarmCPU)) {\n logging.log(\"Number of PCs included:\", nPC.FarmCPU, \"\\n\", verbose = verbose)\n CV.FarmCPU <- cbind(ipca[,1:nPC.FarmCPU], CV.FarmCPU)\n }\n }else if (!is.null(nPC.FarmCPU)) { \n logging.log(\"Number of PCs included in FarmCPU:\", nPC.FarmCPU, \"\\n\", verbose = verbose)\n CV.FarmCPU <- ipca[,1:nPC.FarmCPU]\n }\n } \n }else{\n if (glm.run) {\n if (!is.null(CV.GLM)) {\n logging.log(\"Number of provided covariates of GLM:\", ncol(CV.GLM), \"\\n\", verbose = verbose)\n }\n }\n if (mlm.run) {\n if (!is.null(CV.MLM)) {\n logging.log(\"Number of provided covariates of MLM:\", ncol(CV.MLM), \"\\n\", verbose = verbose)\n }\n }\n if (farmcpu.run) {\n if (!is.null(CV.FarmCPU)) {\n logging.log(\"Number of provided covariates of FarmCPU:\", ncol(CV.FarmCPU), \"\\n\", verbose = verbose)\n }\n }\n }\n\n #GWAS\n logging.log(\"-------------------------GWAS Start-------------------------\", \"\\n\", verbose = verbose)\n if (glm.run) {\n logging.log(\"General Linear Model (GLM) Start...\", \"\\n\", verbose = verbose)\n glm.results <- MVP.GLM(phe=phe, geno=geno, CV=CV.GLM, cpu=ncpus, verbose = verbose);gc()\n colnames(glm.results) <- c(\"Effect\", \"SE\", paste(colnames(phe)[2],\"GLM\",sep=\".\"))\n z = glm.results[, 1]/glm.results[, 2]\n lambda = median(z^2, na.rm=TRUE)/qchisq(1/2, df = 1,lower.tail=FALSE)\n logging.log(\"Genomic inflation factor (lambda):\", round(lambda, 4), \"\\n\", verbose = verbose)\n if (\"pmap\" %in% file.output) {\n logging.log(\"Writing results to local file\", \"\\n\", verbose = verbose)\n write.csv(x = cbind(map, glm.results), \n file = file.path(outpath, paste(colnames(phe)[2], \".GLM.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n\n if (mlm.run) {\n logging.log(\"Mixed Linear Model (MLM) Start...\", \"\\n\", verbose = verbose)\n mlm.results <- MVP.MLM(phe=phe, geno=geno, K=K, eigenK=eigenK, CV=CV.MLM, cpu=ncpus, vc.method=vc.method, verbose = verbose);gc()\n colnames(mlm.results) <- c(\"Effect\", \"SE\", paste(colnames(phe)[2],\"MLM\",sep=\".\"))\n z = mlm.results[, 1]/mlm.results[, 2]\n lambda = median(z^2, na.rm=TRUE)/qchisq(1/2, df = 1,lower.tail=FALSE)\n logging.log(\"Genomic inflation factor (lambda):\", round(lambda, 4), \"\\n\", verbose = verbose)\n if (\"pmap\" %in% file.output) {\n logging.log(\"Writing results to local file\", \"\\n\", verbose = verbose)\n write.csv(x = cbind(map, mlm.results), \n file = file.path(outpath, paste(colnames(phe)[2], \".MLM.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n \n if (farmcpu.run) {\n logging.log(\"FarmCPU Start...\", \"\\n\", verbose = verbose)\n farmcpu.results <- MVP.FarmCPU(phe=phe, geno=geno, map=map[,1:3], CV=CV.FarmCPU, ncpus=ncpus, memo=\"MVP.FarmCPU\", p.threshold=p.threshold, QTN.threshold=QTN.threshold, method.bin=method.bin, bin.size=bin.size, bin.selection=bin.selection, maxLoop=maxLoop, verbose = verbose)\n colnames(farmcpu.results) <- c(\"Effect\", \"SE\", paste(colnames(phe)[2],\"FarmCPU\",sep=\".\"))\n z = farmcpu.results[, 1]/farmcpu.results[, 2]\n lambda = median(z^2, na.rm=TRUE)/qchisq(1/2, df = 1,lower.tail=FALSE)\n logging.log(\"Genomic inflation factor (lambda):\", round(lambda, 4), \"\\n\", verbose = verbose)\n if (\"pmap\" %in% file.output) {\n logging.log(\"Writing results to local file\", \"\\n\", verbose = verbose)\n write.csv(x = cbind(map,farmcpu.results), \n file = file.path(outpath, paste(colnames(phe)[2], \".FarmCPU.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n \n MVP.return <- list(map=map, glm.results=glm.results, mlm.results=mlm.results, farmcpu.results=farmcpu.results)\n \n if(permutation.threshold){\n # set.seed(12345)\n i=1\n for(i in 1:permutation.rep){\n index = 1:nrow(phe)\n index.shuffle = sample(index,length(index),replace=FALSE)\n myY.shuffle = phe\n myY.shuffle[,2] = myY.shuffle[index.shuffle,2]\n #GWAS using t.test...\n myPermutation = MVP.GLM(phe=myY.shuffle[,c(1,2)], geno=geno, cpu=ncpus)\n pvalue = min(myPermutation[,2],na.rm=TRUE)\n if(i==1){\n pvalue.final=pvalue\n }else{\n pvalue.final=c(pvalue.final,pvalue)\n }\n }#end of permutation.rep\n permutation.cutoff = sort(pvalue.final)[ceiling(permutation.rep*0.05)]\n threshold = permutation.cutoff * m\n }\n logging.log(paste0(\"Significant level: \", formatC(threshold/m, format = \"e\", digits = 2)), \"\\n\", verbose = verbose)\n if (\"pmap.signal\" %in% file.output) {\n if (glm.run) {\n index <- which(glm.results[, ncol(glm.results)] < threshold/m)\n if (length(index) != 0) {\n write.csv(x = cbind.data.frame(map, glm.results)[index, ], \n file = file.path(outpath, paste(colnames(phe)[2], \".GLM_signals.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n if (mlm.run) {\n index <- which(mlm.results[, ncol(mlm.results)] < threshold/m)\n if (length(index) != 0) {\n write.csv(x = cbind.data.frame(map, mlm.results)[index, ], \n file = file.path(outpath, paste(colnames(phe)[2], \".MLM_signals.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n if (farmcpu.run) {\n index <- which(farmcpu.results[, ncol(farmcpu.results)] < threshold/m)\n if (length(index) != 0) {\n write.csv(x = cbind.data.frame(map, farmcpu.results)[index, ], \n file = file.path(outpath, paste(colnames(phe)[2], \".FarmCPU_signals.\", memo, ifelse(is.null(memo),\"csv\",\".csv\"), sep = \"\")),\n row.names = FALSE)\n }\n }\n }\n if (\"plot\" %in% file.output) {\n logging.log(\"---------------------Visualization Start--------------------\", \"\\n\", verbose = verbose)\n logging.log(\"Phenotype distribution Plotting\", \"\\n\", verbose = verbose)\n MVP.Hist(memo=memo, outpath=outpath, file.output=TRUE, phe=phe, file.type=file.type, col=col, dpi=dpi)\n #plot3D <- !is(try(library(\"rgl\"),silent=TRUE), \"try-error\")\n plot3D <- FALSE\n if(!is.null(nPC)){\n MVP.PCAplot(\n ipca[,1:3],\n col=col,\n plot3D=plot3D,\n file.output=TRUE,\n file.type=file.type,\n outpath=outpath, \n memo = ifelse(is.null(memo), colnames(phe)[2], paste(colnames(phe)[2], memo, sep=\".\")),\n dpi=dpi,\n )\n }\n \n MVP.Report(\n MVP.return,\n col=col,\n plot.type=c(\"c\",\"m\",\"q\",\"d\"),\n file.output=TRUE,\n file.type=file.type,\n outpath=outpath, \n memo = memo,\n chr.den.col=c(\"darkgreen\", \"yellow\", \"red\"),\n dpi=dpi,\n threshold=threshold/m,\n )\n\n if(sum(c(is.null(glm.results), is.null(mlm.results), is.null(farmcpu.results))) < 2) {\n MVP.Report(\n MVP.return,\n col=col,\n plot.type=c(\"m\",\"q\"),\n multracks=TRUE,\n file.output=TRUE,\n file.type=file.type,\n outpath=outpath, \n memo = memo,\n dpi=dpi,\n threshold=threshold/m\n )\n }\n }\n now <- Sys.time()\n if (length(file.output) > 0) {\n logging.log(\"Results are stored at Working Directory:\", outpath, \"\\n\", verbose = verbose)\n }\n logging.log(\"End:\", as.character(now), \"\\n\", verbose = verbose)\n print_accomplished(width = 60, verbose = verbose)\n \n return(invisible(MVP.return))\n}#end of MVP function\n", "meta": {"hexsha": "815b9c2b4c286920fda9d5fb53a844f22b7a4998", "size": 19148, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.r", "max_stars_repo_name": "hxxonly/rMVP", "max_stars_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-14T02:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T02:20:21.000Z", "max_issues_repo_path": "R/MVP.r", "max_issues_repo_name": "hxxonly/rMVP", "max_issues_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "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/MVP.r", "max_forks_repo_name": "hxxonly/rMVP", "max_forks_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "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": 45.0541176471, "max_line_length": 282, "alphanum_fraction": 0.5691456027, "num_tokens": 5330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.25515705659375565}} {"text": "\n##SNOPSIS\n\n#Qtl analysis based on rqtl.\n\n\n##AUTHOR\n## Isaak Y Tecle (iyt2@cornell.edu)\n\n\noptions(echo = FALSE)\n\nlibrary(qtl)\n\nallargs <- commandArgs()\n\ninfile <- grep(\"infile_list\", allargs, value=TRUE)\noutfile <- grep(\"outfile_list\", allargs, value=TRUE)\n\ninfile <- scan(infile, what=\"character\")\nstatfile <- grep(\"stat\", infile, value=TRUE)\n \n##### stat files\nstatfiles <- scan(statfile, what=\"character\")\n\n###### QTL mapping method ############\nqtlmethodfile <- grep(\"stat_qtl_method\", statfiles, value=TRUE)\nqtlmethod <- scan(qtlmethodfile, what=\"character\", sep=\"\\n\")\n\nif (qtlmethod == \"Maximum Likelihood\") {\n qtlmethod <- c(\"em\")\n} else if (qtlmethod == \"Haley-Knott Regression\") {\n qtlmethod <- c(\"hk\")\n} else if (qtlmethod == \"Multiple Imputation\") {\n qtlmethod <- c(\"imp\")\n} else if (qtlmethod == \"Marker Regression\") {\n qtlmethod <- c(\"mr\")\n}\n\n###### QTL model ############\nqtlmodelfile <- grep(\"stat_qtl_model\", statfiles, value=TRUE)\nqtlmodel <- scan(qtlmodelfile, what=\"character\", sep=\"\\n\")\n\nif (qtlmodel == \"Single-QTL Scan\") {\n qtlmodel <- c(\"scanone\")\n} else if (qtlmodel == \"Two-QTL Scan\") {\n qtlmodel<-c(\"scantwo\")\n}\n\n###### permutation############\nuserpermufile <- grep(\"stat_permu_test\", statfiles, value=TRUE)\nuserpermuvalue <- scan(userpermufile, what=\"numeric\", dec= \".\", sep=\"\\n\")\n\nif (userpermuvalue == \"None\") {\n userpermuvalue<-c(0)\n}\n\nuserpermuvalue <- as.numeric(userpermuvalue)\n\n#####for test only\n#userpermuvalue<-c(100)\n#####\n\n\n######genome step size############\nstepsizefile <- grep(\"stat_step_size\", statfiles, value=TRUE)\n\nstepsize <- scan(stepsizefile, what=\"numeric\", dec = \".\", sep=\"\\n\")\n\nif (qtlmethod == 'mr') {\n stepsize <- c(0)\n} else if (qtlmethod != 'mr' & stepsize == \"zero\") {\n stepsize <- c(0)\n }\n\nstepsize <- as.numeric(stepsize)\n\n######genotype calculation method############\ngenoprobmethodfile <- grep(\"stat_prob_method\", statfiles, value=TRUE)\n\ngenoprobmethod <- scan(genoprobmethodfile, what=\"character\", dec=\".\", sep=\"\\n\")\n\n\n########No. of draws for sim.geno method###########\ndrawsnofile <- c()\ndrawsno <- c()\nif (qtlmethod == 'imp') {\n if (is.null(grep(\"stat_no_draws\", statfiles))==FALSE) {\n drawsnofile <- grep(\"stat_no_draws\", statfiles, value=TRUE)\n }\n\n if (is.null(drawsnofile)==FALSE) {\n drawsno <- scan(drawsnofile, what=\"numeric\", dec = \".\", sep=\"\\n\")\n drawsno <- as.numeric(drawsno)\n }\n }\n########significance level for genotype\n#######probablity calculation\ngenoproblevelfile <- grep(\"stat_prob_level\", statfiles, value=TRUE)\ngenoproblevel <- scan(genoproblevelfile, what=\"numeric\", dec = \".\", sep=\"\\n\")\n\nif (qtlmethod == 'mr') {\n if (is.logical(genoproblevel) == FALSE) {\n genoproblevel <- c(0)\n }\n \n if (is.logical(genoprobmethod) ==FALSE) {\n genoprobmethod <- c('Calculate')\n }\n }\n\ngenoproblevel <- as.numeric(genoproblevel)\n\n########significance level for permutation test\npermuproblevelfile <- grep(\"stat_permu_level\", statfiles, value=TRUE)\n\npermuproblevel <- scan(permuproblevelfile, what=\"numeric\", dec = \".\", sep=\"\\n\")\n\npermuproblevel <- as.numeric(permuproblevel)\n\n#########\ncvtermfile <- grep(\"cvterm\", infile, value=TRUE)\n\npopidfile <- grep(\"popid\", infile, value=TRUE) \n\ngenodata <- grep(\"genodata\", infile, value=TRUE) \n\nphenodata <- grep(\"phenodata\", infile, value=TRUE) \n\npermufile <- grep(\"permu\", infile, value=TRUE) \n\ncrossfile <- grep(\"cross\", infile, value=TRUE)\n\npopid <- scan(popidfile, what=\"integer\", sep=\"\\n\")\n\ncross <- scan(crossfile,what=\"character\", sep=\"\\n\")\n\npopdata<-c()\n\nif (cross == \"f2\")\n{\n popdata <- read.cross(\"csvs\",\n genfile=genodata,\n phefile=phenodata,\n na.strings=c(\"NA\", \"-\"),\n genotypes=c(\"1\", \"2\", \"3\", \"4\", \"5\"),\n )\n\n popdata <-jittermap(popdata)\n} else if (cross == \"bc\" | cross == \"rilsib\" | cross == \"rilself\") {\n \n popdata <- read.cross(\"csvs\",\n genfile=genodata,\n phefile=phenodata,\n na.strings=c(\"NA\", \"-\"),\n genotypes=c(\"1\", \"2\"), \n )\n\n popdata<-jittermap(popdata)\n} \n\nif (cross == \"rilself\") {\n popdata<-convert2riself(popdata)\n} else if (cross == \"rilsib\") {\n popdata<-convert2risib(popdata) \n}\n\n#calculates the qtl genotype probablity at\n#the specififed step size and probability level\ngenotypetype <- c()\n\nif (genoprobmethod == \"Calculate\") {\n popdata <- calc.genoprob(popdata,\n step=stepsize,\n error.prob=genoproblevel\n )\n genotypetype<-c('prob')\n} else if (genoprobmethod == \"Simulate\") {\n popdata <- sim.geno(popdata,\n n.draws=drawsno,\n step=stepsize,\n error.prob=genoproblevel,\n stepwidth=\"fixed\"\n )\n \n genotypetype <- c('draws')\n}\n\ncvterm <- scan(cvtermfile, what=\"character\") #reads the cvterm\n\ncv <- find.pheno(popdata, cvterm)#returns the col no. of the cvterm\n\npermuvalues <- scan(permufile, what=\"character\")\n\npermuvalue1 <- permuvalues[1]\npermuvalue2 <- permuvalues[2]\npermu <- c()\n\nif (is.logical(permuvalue1) == FALSE) {\n if (qtlmodel == \"scanone\") {\n if (userpermuvalue == 0 ) {\n popdataperm <- scanone(popdata,\n pheno.col=cv,\n model=\"normal\",\n method=qtlmethod\n )\n \n } else if (userpermuvalue != 0) {\n popdataperm <- scanone(popdata,\n pheno.col=cv,\n model=\"normal\",\n n.perm = userpermuvalue,\n method=qtlmethod\n )\n \n permu <- summary(popdataperm, alpha=permuproblevel)\n }\n } else if (qtlmethod != \"mr\") {\n if (qtlmodel == \"scantwo\") {\n if (userpermuvalue == 0 ) {\n popdataperm <- scantwo(popdata,\n pheno.col=cv,\n model=\"normal\",\n method=qtlmethod\n )\n } else if (userpermuvalue != 0) {\n popdataperm <- scantwo(popdata,\n pheno.col=cv,\n model=\"normal\",\n n.perm=userpermuvalue,\n method=qtlmethod\n )\n \n permu <- summary(popdataperm, alpha=permuproblevel)\n \n }\n }\n }\n}\n\n##########set the LOD cut-off for singificant qtls ##############\nLodThreshold <- c()\n\nif(is.null(permu) == FALSE) {\n LodThreshold <- permu[1,1]\n}\n##########QTL EFFECTS ##############\n\nchrlist <- c(\"chr1\")\n\nfor (no in 2:12) {\n chr <- paste(\"chr\", no, sep=\"\")\n \n chrlist <- append(chrlist, chr)\n}\n\nchrdata <- paste(cvterm, popid, \"chr1\", sep=\"_\")\n\nchrtest <- c(\"chr1\")\n\nfor (ch in chrlist) {\n if (ch==\"chr1\") {\n chrdata <- paste(cvterm, popid, ch, sep=\"_\")\n } else {\n n <- paste(cvterm, popid, ch, sep=\"_\")\n chrdata <- append(chrdata, n) \n }\n} \n\nchrno <- 1\n\ndatasummary <- c()\nconfidenceints <- c()\nlodconfidenceints <- c()\nQtlChrs <- c()\nQtlPositions <- c()\nQtlLods <- c()\n\nfor (i in chrdata) { \n filedata <- paste(cvterm, popid, chrno, sep=\"_\")\n filedata <- paste(filedata,\"txt\",sep=\".\")\n \n i <- scanone(popdata,\n chr=chrno,\n pheno.col=cv,\n model = \"normal\",\n method= qtlmethod\n )\n \n position <- max(i,chr=chrno)\n \n p <- position[[\"pos\"]]\n LodScore <- position[[\"lod\"]]\n QtlChr <- levels(position[[\"chr\"]])\n\n if ( is.null(LodThreshold)==FALSE ) {\n if (LodScore >=LodThreshold ) {\n QtlChrs <- append(QtlChrs, QtlChr) \n QtlLods <- append(QtlLods, LodScore) \n QtlPositions <- append(QtlPositions, round(p, 0))\n }\n }\n \n peakmarker <- find.marker(popdata, chr=chrno, pos=p)\n \n lodpeakmarker <- i[peakmarker, ]\n \n lodconfidenceint <- bayesint(i, chr=chrno, prob=0.95, expandtomarkers=TRUE)\n\n if (is.na(lodconfidenceint[peakmarker, ])){\n lodconfidenceint <- rbind(lodconfidenceint, lodpeakmarker)\n }\n \n peakmarker <- c(chrno, peakmarker)\n \n if (chrno==1) { \n datasummary <- i\n peakmarkers <- peakmarker\n lodconfidenceints <- lodconfidenceint\n }\n \n if (chrno > 1 ) {\n datasummary <- rbind(datasummary, i)\n peakmarkers <- rbind(peakmarkers, peakmarker)\n lodconfidenceints <- rbind(lodconfidenceints, lodconfidenceint)\n }\n\nchrno <- chrno + 1;\n\n}\n\n##########QTL EFFECTS ##############\n ResultDrop <- c()\n ResultFull <- c()\n Effects <- c()\n\nif (is.null(LodThreshold) == FALSE) {\n if ( max(QtlLods) >= LodThreshold ) {\n QtlObj <- makeqtl(popdata,\n QtlChrs,\n QtlPositions,\n what=genotypetype\n )\n\n QtlsNo <- length(QtlPositions)\n Eq <- c(\"y~\")\n\n for (i in 1:QtlsNo) {\n q <- paste(\"Q\", i, sep=\"\")\n \n if (i==1) { \n Eq <- paste(Eq, q, sep=\"\") \n } else if (i>1) {\n Eq <- paste(Eq, q, sep=\"*\") \n }\n }\n \n QtlEffects <- try(fitqtl(popdata,\n pheno.col=cv,\n QtlObj,\n formula=Eq,\n method=\"hk\", \n get.ests=TRUE\n ) \n )\n \n if(class(QtlEffects) != 'try-error') {\n \n ResultModel <- attr(QtlEffects, \"formula\")\n Effects <- QtlEffects$ests$ests\n QtlLodAnova <- QtlEffects$lod\n ResultFull <- QtlEffects$result.full \n ResultDrop <- QtlEffects$result.drop\n \n if (is.numeric(Effects)) {\n Effects <- round(Effects, 2)\n }\n\n if (is.numeric(ResultFull)) {\n ResultFull <- round(ResultFull,2)\n }\n\n if (is.numeric(ResultDrop)) {\n ResultDrop<-round(ResultDrop, 2)\n }\n }\n }\n}\n\n##########creating vectors for the outfiles##############\n\noutfiles <- scan(file=outfile, what=\"character\")\n\nqtlfile <- grep(\"qtl_summary\", outfiles, value=TRUE)\npeakmarkersfile <- grep(\"peak_marker\", outfiles, value=TRUE)\nconfidencelodfile <- grep(\"confidence\", outfiles, value=TRUE)\nQtlEffectsFile <- grep(\"qtl_effects\", outfiles, value=TRUE)\nVariationFile <- grep(\"explained_variation\", outfiles, value=TRUE)\n\n##### writing outputs to their respective files\n\nwrite.table(datasummary,\n file=qtlfile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n\nwrite.table(peakmarkers,\n file=peakmarkersfile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n\nwrite.table(lodconfidenceints,\n file=confidencelodfile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n\nif (is.null(ResultDrop)==FALSE) {\n write.table(ResultDrop,\n file=VariationFile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n} else {\n if (is.null(ResultFull)==FALSE) {\n write.table(ResultFull,\n file=VariationFile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n }\n}\n\nwrite.table(Effects,\n file=QtlEffectsFile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n\nwrite.table(permu,\n file=permufile,\n sep=\"\\t\",\n col.names=NA,\n quote=FALSE,\n append=FALSE\n )\n\nq(runLast = FALSE)\n", "meta": {"hexsha": "dc199b9db6bae82db14bcb2a21799bce6b73cfee", "size": 12445, "ext": "r", "lang": "R", "max_stars_repo_path": "R/solGS/qtl_analysis.r", "max_stars_repo_name": "TriticeaeToolbox/sgn", "max_stars_repo_head_hexsha": "76602305fb60f326eed4bc4fcbd16680f6b9f606", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39, "max_stars_repo_stars_event_min_datetime": "2015-02-03T15:47:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T13:34:05.000Z", "max_issues_repo_path": "R/solGS/qtl_analysis.r", "max_issues_repo_name": "TriticeaeToolbox/sgn", "max_issues_repo_head_hexsha": "76602305fb60f326eed4bc4fcbd16680f6b9f606", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2491, "max_issues_repo_issues_event_min_datetime": "2015-01-07T05:49:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:31:05.000Z", "max_forks_repo_path": "R/solGS/qtl_analysis.r", "max_forks_repo_name": "TriticeaeToolbox/sgn", "max_forks_repo_head_hexsha": "76602305fb60f326eed4bc4fcbd16680f6b9f606", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20, "max_forks_repo_forks_event_min_datetime": "2015-06-30T19:10:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T13:34:09.000Z", "avg_line_length": 26.879049676, "max_line_length": 81, "alphanum_fraction": 0.506147047, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2538861933349491}} {"text": "# refine_spillover.r\n#\n# Copyright (c) 2020 VIB (Belgium) & Babraham Institute (United Kingdom)\n#\n# Software written by Carlos P. Roca, as research funded by the European Union.\n#\n# This software may be modified and distributed under the terms of the MIT\n# license. See the LICENSE file for details.\n\n\n#' Refine spillover coefficients\n#'\n#' Refines spillover coefficients iteratively.\n#'\n#' @param marker.spillover.unco.untr List of two matrices, with regressions\n#' intercepts and coefficients, resulting from the initial spillover\n#' calculation in untransformed scale.\n#' @param marker.spillover.unco.tran List of two matrices, with regressions\n#' intercepts and coefficients, resulting from the initial spillover\n#' calculation in transformed scale. Optional parameter used only in\n#' scatter plots, it can be \\code{NULL}.\n#' @param flow.gate List of vectors with ids of gated events per sample.\n#' @param flow.control List with data and metadata of a set of controls.\n#' @param asp List with AutoSpill parameters.\n#'\n#' @return List with four elements:\n#' \\itemize{\n#' \\item{Spillover matrix at final step.}\n#' \\item{Compensation matrix at final step.}\n#' \\item{Compensation error at final step, a list with four matrices:\n#' intercepts, coefficients, slopes, and skewness.}\n#' \\item{Dataframe with convergence data.}\n#' }\n#'\n#' @references Roca \\emph{et al}:\n#' AutoSpill: A method for calculating spillover coefficients to compensate\n#' or unmix high-parameter flow cytometry data.\n#' \\emph{bioRxiv} 2020.06.29.177196;\n#' \\href{https://doi.org/10.1101/2020.06.29.177196}{doi:10.1101/2020.06.29.177196}\n#' (2020).\n#'\n#' @seealso \\code{\\link{get.marker.spillover}}, \\code{\\link{gate.flow.data}},\n#' \\code{\\link{read.flow.control}}, and \\code{\\link{get.autospill.param}}.\n#'\n#' @export\n\nrefine.spillover <- function( marker.spillover.unco.untr,\n marker.spillover.unco.tran, flow.gate, flow.control, asp )\n{\n # set initial values for iteration variables\n\n rs.convergence <- FALSE\n rs.exit <- FALSE\n\n rs.iter <- 0\n rs.iter.last <- FALSE\n rs.iter.width <- floor( log10( asp$rs.iter.max ) ) + 1\n\n rs.lambda <- asp$rs.lambda.coarse\n\n rs.delta <- -1.0\n rs.delta.threshold <- asp$rs.delta.threshold.untr\n\n rs.delta.history <- rep( -1, asp$rs.delta.history.n )\n\n rs.scale.untransformed <- TRUE\n\n rs.convergence.log <- data.frame(\n iter = numeric(),\n scale = character(),\n lambda = numeric(),\n delta = numeric(),\n delta.max = numeric(),\n delta.change = numeric(),\n stringsAsFactors = FALSE\n )\n\n # set initial values for spillover calculation\n\n spillover.curr <- diag( flow.control$marker.n )\n spillover.update <- marker.spillover.unco.untr$coef -\n diag( flow.control$marker.n )\n\n while ( ! rs.exit )\n {\n # update spillover matrix and calculate compensation matrix\n\n spillover.curr <- spillover.curr + spillover.update\n spillover.curr <- sweep( spillover.curr, 1,\n diag( spillover.curr ), \"/\" )\n\n compensation.curr <- solve( spillover.curr )\n\n spillover.curr.original <- spillover.curr\n rownames( spillover.curr.original ) <- flow.control$marker.original\n colnames( spillover.curr.original ) <- flow.control$marker.original\n\n compensation.curr.original <- compensation.curr\n rownames( compensation.curr.original ) <- flow.control$marker.original\n colnames( compensation.curr.original ) <- flow.control$marker.original\n\n if ( ( rs.iter == 0 && asp$rs.save.table.initial ) ||\n ( asp$rs.save.table.every > 0 &&\n rs.iter %% asp$rs.save.table.every == 0 ) ||\n rs.iter.last )\n {\n # save spillover and compensation matrices\n\n if( ! is.null( asp$table.spillover.dir ) )\n {\n table.spillover.file.name <- ifelse( rs.iter.last,\n sprintf( \"%s.csv\", asp$spillover.file.name ),\n sprintf( \"%s_%0*d.csv\", asp$spillover.file.name,\n rs.iter.width, rs.iter ) )\n\n write.csv( spillover.curr.original,\n file = file.path( asp$table.spillover.dir,\n table.spillover.file.name ) )\n }\n\n if( ! is.null( asp$table.compensation.dir ) )\n {\n table.compensation.file.name <- ifelse( rs.iter.last,\n sprintf( \"%s.csv\", asp$compensation.file.name ),\n sprintf( \"%s_%0*d.csv\", asp$compensation.file.name,\n rs.iter.width, rs.iter ) )\n\n write.csv( compensation.curr.original,\n file = file.path( asp$table.compensation.dir,\n table.compensation.file.name ) )\n }\n\n # plot spillover and compensation matrices, by rows and columns\n # respectively\n\n if( ! is.null( asp$figure.spillover.dir ) )\n {\n figure.spillover.file.label <- ifelse( rs.iter.last, \"\",\n sprintf( \"_%0*d\", rs.iter.width, rs.iter ) )\n\n plot.matrix( spillover.curr, TRUE, asp$figure.spillover.dir,\n figure.spillover.file.label, flow.control, asp )\n }\n\n if( ! is.null( asp$figure.compensation.dir ) )\n {\n figure.compensation.file.label <- ifelse( rs.iter.last, \"\",\n sprintf( \"_%0*d\", rs.iter.width, rs.iter ) )\n\n plot.matrix( compensation.curr, FALSE,\n asp$figure.compensation.dir,\n figure.compensation.file.label, flow.control, asp )\n }\n }\n\n # set uncompensated expresion data and spillover\n\n if ( rs.scale.untransformed ) {\n expr.data.unco <- flow.control$expr.data.untr\n marker.spillover.unco <- marker.spillover.unco.untr\n }\n else {\n expr.data.unco <- flow.control$expr.data.tran\n marker.spillover.unco <- marker.spillover.unco.tran\n }\n\n # get compensated expression data\n\n flow.set.comp <- lapply( flow.control$flow.set, compensate,\n compensation( spillover.curr.original ) )\n\n if ( ! rs.scale.untransformed )\n flow.set.comp <- lapply( flow.set.comp, transform,\n transformList( names( flow.control$transform ),\n flow.control$transform ) )\n\n expr.data.comp <- get.flow.expression.data( flow.set.comp,\n flow.control )\n\n check.critical(\n identical( dimnames( expr.data.comp ),\n dimnames( expr.data.unco ) ),\n \"internal error: inconsistent event or dye names in compensated data\"\n )\n\n # get compensation error in compensated data\n\n if ( ( rs.iter == 0 && asp$rs.plot.figure.initial ) ||\n ( asp$rs.plot.figure.every > 0 &&\n rs.iter %% asp$rs.plot.figure.every == 0 ) ||\n rs.iter.last )\n {\n plot.scatter.figure <- TRUE\n figure.scatter.file.label <- ifelse( rs.iter.last, \"final\",\n sprintf( \"%0*d\", rs.iter.width, rs.iter ) )\n }\n else\n {\n plot.scatter.figure <- FALSE\n figure.scatter.file.label <- NULL\n }\n\n compensation.error <- get.compensation.error(\n expr.data.unco, expr.data.comp, marker.spillover.unco,\n rs.scale.untransformed, plot.scatter.figure,\n figure.scatter.file.label, flow.gate, flow.control, asp\n )\n\n # get slope error and update delta variables\n\n slope.error <- compensation.error$slop - diag( flow.control$marker.n )\n\n rs.delta.prev <- rs.delta\n rs.delta <- sd( slope.error )\n\n rs.delta.max <- max( abs( slope.error ) )\n\n if ( rs.delta.prev >= 0 )\n rs.delta.history[ rs.iter %% asp$rs.delta.history.n + 1 ] <-\n rs.delta - rs.delta.prev\n else\n rs.delta.history[ rs.iter %% asp$rs.delta.history.n + 1 ] <- -1\n\n rs.delta.change <- mean( rs.delta.history )\n\n rs.convergence.log[ rs.iter + 1, ] <- list( rs.iter,\n ifelse( rs.scale.untransformed, \"linear\", \"bi-exp\" ),\n rs.lambda, rs.delta, rs.delta.max, rs.delta.change )\n\n if ( asp$verbose )\n {\n cat( sprintf(\n \"iter %0*d, %s scale, lambda %.1f, delta %g, delta.max %g, delta.change %g\\n\",\n rs.iter.width, rs.iter,\n ifelse( rs.scale.untransformed, \"linear\", \"bi-exp\" ),\n rs.lambda, rs.delta, rs.delta.max, rs.delta.change ) )\n }\n\n if ( ( rs.iter == 0 && asp$rs.save.table.initial ) ||\n ( asp$rs.save.table.every > 0 &&\n rs.iter %% asp$rs.save.table.every == 0 ) ||\n rs.iter.last )\n {\n # save and plot slope error\n\n if( ! is.null( asp$table.slope.error.dir ) )\n {\n table.slope.error.file.name <- ifelse( rs.iter.last,\n sprintf( \"%s.csv\", asp$slope.error.file.name ),\n sprintf( \"%s_%0*d.csv\", asp$slope.error.file.name,\n rs.iter.width, rs.iter ) )\n\n write.csv( slope.error,\n file = file.path( asp$table.slope.error.dir,\n table.slope.error.file.name ) )\n }\n\n if( ! is.null( asp$figure.slope.error.dir ) )\n {\n figure.slope.error.file.name <- sprintf( \"%s%s.png\",\n asp$slope.error.file.name,\n ifelse( rs.iter.last, \"\",\n sprintf( \"_%0*d\", rs.iter.width, rs.iter ) ) )\n\n plot.density.log( slope.error, \"compensation error\",\n file.path( asp$figure.slope.error.dir,\n figure.slope.error.file.name ),\n asp )\n }\n\n # save and plot skewness\n\n if( ! is.null( asp$table.skewness.dir ) )\n {\n table.skewness.file.name <- ifelse( rs.iter.last,\n sprintf( \"%s.csv\", asp$skewness.file.name ),\n sprintf( \"%s_%0*d.csv\", asp$skewness.file.name,\n rs.iter.width, rs.iter ) )\n\n write.csv( compensation.error$skew,\n file = file.path( asp$table.skewness.dir,\n table.skewness.file.name ) )\n }\n\n if( ! is.null( asp$figure.skewness.dir ) )\n {\n if ( ! is.null( flow.control$autof.marker.idx ) )\n spillover.skewness <- compensation.error$skew[\n - flow.control$autof.marker.idx,\n - flow.control$autof.marker.idx ]\n else\n spillover.skewness <- compensation.error$skew\n\n figure.skewness.file.name <- sprintf( \"%s%s.png\",\n asp$skewness.file.name,\n ifelse( rs.iter.last, \"\",\n sprintf( \"_%0*d\", rs.iter.width, rs.iter ) ) )\n\n plot.density.log( spillover.skewness, \"spillover skewness\",\n file.path( asp$figure.skewness.dir,\n figure.skewness.file.name ),\n asp )\n }\n }\n\n # update iteration variables\n\n if( rs.scale.untransformed && rs.delta.max < rs.delta.threshold )\n {\n # switch to bi-exponential scale and reset lambda and delta history\n rs.scale.untransformed <- FALSE\n rs.delta.threshold <- asp$rs.delta.threshold.tran\n rs.lambda <- asp$rs.lambda.coarse\n rs.delta <- -1.0\n rs.delta.history <- rep( -1, asp$rs.delta.history.n )\n rs.delta.change <- -1\n }\n\n if ( rs.delta.change > - asp$rs.delta.threshold.change &&\n rs.lambda == asp$rs.lambda.coarse )\n {\n # reduce lambda and reset delta history\n rs.lambda <- asp$rs.lambda.fine\n rs.delta <- -1.0\n rs.delta.history <- rep( -1, asp$rs.delta.history.n )\n rs.delta.change <- -1\n }\n\n rs.convergence <- ! rs.scale.untransformed &&\n ( rs.delta.max < rs.delta.threshold ||\n rs.delta.change > - asp$rs.delta.threshold.change )\n\n rs.exit <- ( rs.convergence && rs.iter.last ) ||\n ( rs.delta.change > - asp$rs.delta.threshold.change &&\n rs.scale.untransformed ) ||\n ( ! rs.convergence && rs.iter == asp$rs.iter.max ) ||\n rs.iter > asp$rs.iter.max\n\n rs.iter.last <- rs.convergence\n\n rs.iter <- rs.iter + 1\n\n # update spillover matrix\n\n spillover.update <- rs.lambda * ( slope.error %*% spillover.curr )\n }\n\n # save and plot convergence\n\n if ( ! is.null( asp$table.convergence.dir ) )\n write.csv( rs.convergence.log,\n file = file.path( asp$table.convergence.dir,\n sprintf( \"%s.csv\", asp$convergence.file.name ) ),\n row.names = FALSE )\n\n if ( ! is.null( asp$figure.convergence.dir ) )\n plot_convergence( rs.convergence.log, NULL, asp )\n\n # check convergence\n\n check.critical( rs.convergence,\n \"no convergence in refinement of spillover matrix\" )\n\n list(\n spillover = spillover.curr,\n compensation = compensation.curr,\n error = compensation.error,\n convergence = rs.convergence.log\n )\n}\n\n", "meta": {"hexsha": "793b61c79d7a60185fa2558bb8c9a22fa6fa2c3a", "size": 13670, "ext": "r", "lang": "R", "max_stars_repo_path": "R/refine_spillover.r", "max_stars_repo_name": "hally166/autospill", "max_stars_repo_head_hexsha": "8e1f6f74fbafec5b91ed278260fbdb6678d482a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2020-08-07T21:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T03:00:59.000Z", "max_issues_repo_path": "R/refine_spillover.r", "max_issues_repo_name": "hally166/autospill", "max_issues_repo_head_hexsha": "8e1f6f74fbafec5b91ed278260fbdb6678d482a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-09-10T08:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-29T23:41:00.000Z", "max_forks_repo_path": "R/refine_spillover.r", "max_forks_repo_name": "hally166/autospill", "max_forks_repo_head_hexsha": "8e1f6f74fbafec5b91ed278260fbdb6678d482a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2020-09-05T14:15:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T14:36:42.000Z", "avg_line_length": 36.747311828, "max_line_length": 94, "alphanum_fraction": 0.5471836138, "num_tokens": 3146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2520769293816383}} {"text": "#' Arithmetic Operators\n#' \n#' Some binary arithmetic operations for shaqs. All operations are\n#' vector-shaq or shaq-vector, but not shaq-shaq. See details section for more\n#' information.\n#' \n#' @details\n#' For binary operations involving two shaqs, they must be distributed\n#' \\emph{identically}.\n#' \n#' @section Communication:\n#' Each operation is completely local.\n#' \n#' @param e1,e2\n#' A shaq or a numeric vector.\n#' \n#' @return \n#' A shaq.\n#' \n#' @examples\n#' \\dontrun{\n#' library(kazaam)\n#' x = ranshaq(runif, 10, 3)\n#' y = ranshaq(runif, 10, 3)\n#' \n#' x + y\n#' x / 2\n#' y + 1\n#' \n#' finalize()\n#' }\n#' \n#' @name arithmetic\n#' @rdname arithmetic\nNULL\n\n\n\nbounds.check = function(shaq, vec)\n{\n if (length(vec) != 1)\n comm.stop(\"invalid shaq-vector operation: vector must be length 1\")\n}\n\nshaqshaq.check = function(s1, s2)\n{\n if (nrow(s1) != nrow(s1) || ncol(s1) != ncol(s2))\n stop(\"non-conformable arrays\")\n \n if (nrow(Data(s1)) != nrow(Data(s2)) || ncol(Data(s1)) != ncol(Data(s2)))\n stop(\"shaqs not distributed identically\")\n}\n\n\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"+\", signature(e1=\"shaq\", e2=\"shaq\"), \n function(e1, e2)\n {\n shaqshaq.check(e1, e2)\n \n DATA(e1) = Data(e1) + Data(e2)\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"+\", signature(e1=\"shaq\", e2=\"numeric\"), \n function(e1, e2)\n {\n bounds.check(e1, e2)\n \n DATA(e1) = Data(e1) + e2\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"+\", signature(e1=\"numeric\", e2=\"shaq\"), \n function(e1, e2)\n {\n e2 + e1\n }\n)\n\n\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"-\", signature(e1=\"shaq\", e2=\"shaq\"), \n function(e1, e2)\n {\n shaqshaq.check(e1, e2)\n \n DATA(e1) = Data(e1) - Data(e2)\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"-\", signature(e1=\"shaq\", e2=\"numeric\"), \n function(e1, e2)\n {\n bounds.check(e1, e2)\n \n DATA(e1) = Data(e1) - e2\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"-\", signature(e1=\"numeric\", e2=\"shaq\"), \n function(e1, e2)\n {\n bounds.check(e2, e1)\n \n DATA(e2) = e1 - Data(e2)\n e2\n }\n)\n\n\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"*\", signature(e1=\"shaq\", e2=\"shaq\"), \n function(e1, e2)\n {\n shaqshaq.check(e1, e2)\n \n DATA(e1) = Data(e1) * Data(e2)\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"*\", signature(e1=\"shaq\", e2=\"numeric\"), \n function(e1, e2)\n {\n bounds.check(e1, e2)\n \n DATA(e1) = Data(e1) * e2\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"*\", signature(e1=\"numeric\", e2=\"shaq\"), \n function(e1, e2)\n {\n e2 * e1\n }\n)\n\n\n\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"/\", signature(e1=\"shaq\", e2=\"shaq\"), \n function(e1, e2)\n {\n shaqshaq.check(e1, e2)\n \n DATA(e1) = Data(e1) / Data(e2)\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"/\", signature(e1=\"shaq\", e2=\"numeric\"), \n function(e1, e2)\n {\n bounds.check(e1, e2)\n \n DATA(e1) = Data(e1) / e2\n e1\n }\n)\n\n#' @rdname arithmetic\n#' @export\nsetMethod(\"/\", signature(e1=\"numeric\", e2=\"shaq\"), \n function(e1, e2)\n {\n bounds.check(e2, e1)\n \n DATA(e2) = e1 / Data(e2)\n e2\n }\n)\n", "meta": {"hexsha": "aa11a1a1814999b17a1ab960c0e8f0c12f7233d2", "size": 3148, "ext": "r", "lang": "R", "max_stars_repo_path": "R/arithmetic.r", "max_stars_repo_name": "cran/kazaam", "max_stars_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/arithmetic.r", "max_issues_repo_name": "cran/kazaam", "max_issues_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/arithmetic.r", "max_forks_repo_name": "cran/kazaam", "max_forks_repo_head_hexsha": "4371c4c509f984d5cb97180ca9b93d37a4475901", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.74, "max_line_length": 79, "alphanum_fraction": 0.5711562897, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2512970110535084}} {"text": "## lines that SDSS tracks\n\nspeclines <- c(3727.092,3729.875,3869.857,3890.151,3971.123,4102.892,4341.684,4364.435,\n4686.991,4862.683,4960.295,5008.240,5413.024,5578.888,6302.046,6313.806,\n6365.535,6549.859,6564.614,6585.268,6718.294,6732.678,7137.757)\n\nnames(speclines) <- c(\"O_II_3725\",\"O_II_3727\",\"Ne_III_3868\",\"H_epsilon\",\n\"Ne_III_3970\",\"H_delta\",\"H_gamma\",\"O_III_4363\",\n\"He_II_4685\",\"H_beta\",\"O_III_4959\",\"O_III_5007\",\n\"He_II_5411\",\"O_I_5577\",\"O_I_6300\",\"S_III_6312\",\n\"O_I_6363\",\"N_II_6548\",\"H_alpha\",\"N_II_6583\",\n\"S_II_6716\",\"S_II_6730\",\"Ar_III_7135\")\n\n\n## major emission lines\n\nlambda_f <- c(3727.092,3729.875,3869.857,3971.123,4960.295,\n 5008.240,6302.046,6365.535,6549.859,6585.268,\n 6718.294,6732.678)\nnames(lambda_f) <- c(\"oii_3727\",\"oii_3729\",\"neiii_3869\",\n \"neiii_3970\",\"oiii_4959\",\"oiii_5007\",\n \"oi_6300\",\"oi_6363\",\"nii_6548\",\"nii_6584\",\n \"sii_6717\",\"sii_6730\")\n\nlambda_balmer <- c(3890.151,3970.072,4102.892,4341.684,4862.683,6564.614)\nnames(lambda_balmer) <- c(\"h_zeta\",\"h_epsilon\",\"h_delta\",\"h_gamma\",\"h_beta\",\"h_alpha\")\n\nlambda_em <- sort(c(lambda_f, lambda_balmer))\n\n## forbidden & recombination lines that are usually weak\n\nlambda_weak <- c(4364.435, 4686.991, 5413.024, 5578.888, 6313.806, 7137.757)\nnames(lambda_weak) <- c(\"oiii_4363\", \"heii_4685\", \"heii_5411\", \"oi_5577\", \"siii_6312\", \"ariii_7135\")\n\n## legacy support for reading an sdss spectrum in a csv file\n\nreadsdsspec <- function(fname, z, dname=\"spectra\") {\n gdat <- read.csv(file.path(dname,fname), header=TRUE)\n gdat$lambda <- gdat$lambda/(1+z)\n gdat$flux[gdat$ivar==0] <- NA\n gdat$flux[gdat$flux== -9999.] <- NA\n gdat$ivar[gdat$ivar==0] <- NA\n gdat$ivar[gdat$ivar== -9999.] <- NA\n gdat\n}\n\nregrid <- function(lambda.out, lib) {\n lambda.in <- lib$lambda\n nc <- ncol(lib)\n lib.out <- matrix(NA, length(lambda.out), nc)\n lib.out[,1] <- lambda.out\n for (i in 2:nc) {\n lib.out[,i] <- approx(lambda.in, lib[,i], xout=lambda.out)$y\n }\n colnames(lib.out) <- colnames(lib)\n data.frame(lib.out)\n}\n\n\nclosest <- function(x, vec) which.min(abs(x-vec))\n\n\nvactoair <- function(lambda) lambda/(1+2.735182e-4+131.4182/lambda^2+2.76249E8/lambda^4)\n\nairtovac <- function(lambda) {\n s2 <- (1e4/lambda)^2\n fac <- 1 + 5.792105e-2/(238.0185-s2)+1.67917e-3/(57.362-s2)\n lambda*fac\n}\n\n## Galactic extinction correction from Fitzpatrick (1998): http://arxiv.org/abs/astro-ph/9809387v1\n## This is spline fit portion valid from near-UV to near-IR and R=3.1\n\nelaw <- function(lambda, ebv) {\n il <- c(0,0.377,0.820,1.667,1.828,2.141,2.433,3.704,3.846)\n al <- c(0,0.265,0.829,2.688,3.055,3.806,4.315,6.265,6.591)\n fai <- splinefun(il,al)\n 10^(0.4*fai(10000/lambda)*ebv)\n}\n\nfitz <- function(lambda, tauv) {\n il <- c(0,0.377,0.820,1.667,1.828,2.141,2.433,3.704,3.846)\n al <- c(0,0.265,0.829,2.688,3.055,3.806,4.315,6.265,6.591)\n fai <- splinefun(il,al)\n exp(-fai(10000/lambda)*tauv)\n}\n\n## Calzetti et al. (2000-2001) extinction curve\n\ncalzetti.orig <- function(lambda, tauv) {\n lambda <- lambda/10000\n kl <- numeric(length(lambda))\n lb <- lambda < 0.63\n kl[lb] <- 1+(2.659/4.05)*(-2.151285+1.509/lambda[lb]-0.198/(lambda[lb]^2)+0.011/(lambda[lb]^3))\n kl[!lb] <- 1+(2.659/4.05)*(-1.8561715+1.04/lambda[!lb])\n exp(-kl*tauv)\n}\n\n## approximation to above using a single function\n\ncalzetti <- function(lambda, tauv) {\n ls <- lambda/10000\n k <- -0.2688+0.7958/ls-4.785e-2/(ls^2)-6.033e-3/(ls^3)+7.163e-04/(ls^4)\n exp(-k*tauv)\n}\n\n## modified calzetti relation from Salim et al. 2018\n\ncalzetti_mod <- function(lambda, tauv, delta=0) {\n ls <- 5500./lambda\n kl <- -0.101771 + 0.549882 * ls + 1.393039 * ls^2 - 1.098615 * ls^3 + 0.260618 * ls^4\n kl <- kl * ls^delta\n exp(-tauv * kl)\n}\n\n## galactic extinction law of Cardelli, Clayton, & Mathis 1989, ApJ 345, 245\n\nccm <- function(lambda, tauv, rv=3.1) {\n x <- 10000/lambda\n y <- x-1.82\n \n kl <- numeric(length(lambda))\n a <- numeric(length(lambda))\n b <- numeric(length(lambda))\n \n lb <- (x <= 1.1)\n \n a[lb] <- 0.574*x[lb]^1.61\n b[lb] <- -0.527*x[lb]^1.61\n \n a[!lb] <- 1 + 0.17699*y[!lb] - 0.50447*y[!lb]^2 - 0.02427*y[!lb]^3 + 0.72085*y[!lb]^4 +\n 0.01979*y[!lb]^5 - 0.7753*y[!lb]^6 + 0.32999*y[!lb]^7\n b[!lb] <- 1.41338*y[!lb] + 2.28305*y[!lb]^2 + 1.07233*y[!lb]^3 - 5.38434*y[!lb]^4 -\n 0.62251*y[!lb]^5 + 5.30260*y[!lb]^6 - 2.09002*y[!lb]^7\n kl <- a + b/rv\n exp(-tauv * kl)\n}\n\n\nsimplescreen <- function(lambda, tauv, delta = 0.) {\n exp(-tauv*(5500./lambda)^(0.7 + delta))\n}\n\n\n## make a fake emission line library\n\nmake_emlib <- function(lambda_em, vdisp_em, loglambda, isok, sthresh=5000) {\n vdisp_p <- vdisp_em/(299792.458*log(10))\n n_em <- length(lambda_em)\n nl <- length(loglambda)\n x_em <- matrix(0, nl, n_em)\n for (i in 1:n_em) {\n x_em[,i] <- dnorm(loglambda, mean=log10(lambda_em[i]), sd=vdisp_p)\n }\n in_em <- which(colSums(x_em[isok, ]) >= sthresh)\n x_em <- x_em[,in_em]/10000\n list(x_em=x_em, in_em=in_em)\n}\n\nblur.lib <- function(lib.ssp, vdisp, dlogl=1.e-4) {\n c <- 299792.458\n sigma.p <- vdisp/(dlogl*c*log(10))\n kw <- max(round(6*sigma.p), 3)\n if ((kw%%2)==0) kw <- kw+1\n k0 <- (kw %/% 2) + 1\n kernel <- dnorm((1:kw)-k0, sd=sigma.p)\n kernel <- kernel/sum(kernel)\n sp.st <- filter(lib.ssp[,-1], kernel, method=\"convolution\")\n as.matrix(sp.st)\n}\n\n\ndblineratios <- function(db, dthresh=3) {\n o3hbeta <- log10(db$oiii_flux) - log10(db$h_beta_flux)\n o3hbeta[(db$oiii_flux/db$oiii_flux_err < dthresh) | (db$h_beta_flux/db$h_beta_flux_err < dthresh)] <- NA\n n2halpha <- log10(db$nii_6584_flux) -log10(db$h_alpha_flux)\n n2halpha[(db$nii_6584_flux/db$nii_6584_flux_err < dthresh) | (db$h_alpha_flux/db$h_alpha_flux_err < dthresh)] <- NA\n db <- cbind(db, o3hbeta, n2halpha)\n return(db)\n}\n\n## galaxy class by emission line strengths, from Kewley et al. 2006 and Schawinski et al. 2007\n## only using n2halpha and o3hbeta for now. \n\nemclass <- function(db=NULL, snthresh=3, PLOT=TRUE) {\n \n \n if (!is.null(db)) {\n attach(db)\n class <- as.factor(rep(\"no em.\",length(n2halpha)))\n levels(class) <- c(\"no em.\", \"SF\", \"Comp.\", \"AGN\", \"LINER\", \"EL\")\n \n #starforming\n \n class[(o3hbeta <= 0.61/(n2halpha-0.05)+1.3) & (n2halpha <= 0.05)] <- \"SF\"\n \n # composite\n \n class[((o3hbeta > 0.61/(n2halpha-0.05)+1.3) | (n2halpha > 0.05)) & \n (o3hbeta <= .61/(n2halpha-0.47)+1.19)] <- \"Comp.\"\n \n # Seyfert == AGN\n \n class[(o3hbeta > .61/(n2halpha-0.47)+1.19) & (o3hbeta > 1.05*n2halpha+0.45)] <- \"AGN\"\n class[(n2halpha > 0.47) & (o3hbeta > 1.05*n2halpha+0.45)] <- \"AGN\"\n \n # Liners\n \n class[(o3hbeta > .61/(n2halpha-0.47)+1.19) & (o3hbeta <= 1.05*n2halpha+0.45)] <- \"LINER\"\n class[(n2halpha > 0.47) & (o3hbeta <= 1.05*n2halpha+0.45)] <- \"LINER\"\n \n # weak emission line \n \n class[((is.na(n2halpha) | is.na(o3hbeta)) & ((oii_flux/oii_flux_err > snthresh) |\n (oiii_flux/oiii_flux_err > snthresh) | \n (h_alpha_flux/h_alpha_flux_err > snthresh) |\n (nii_6584_flux/nii_6584_flux_err > snthresh)))] <- \"EL\"\n \n class <- as.factor(class)\n if (PLOT) {\n plot(n2halpha, o3hbeta, pch=20, col=unclass(class))\n }\n detach(db)\n }\n \n if (PLOT) {\n \n #kauffmann et al. curve\n \n curve(1.3+.61/(x-0.05),from= -1.5,to= -0.2,lty=2,add=TRUE)\n \n #kewley 2001 curve\n \n curve(.61/(x-0.47)+1.19, from= -1.5, to= 0.22, add=TRUE)\n \n #Shawinski et al. curve\n \n curve(0.45+1.05*x, from=-0.2, to= 1, add=TRUE)\n }\n \n \n if (!is.null(db)) return(class)\n}\n\n\n\n## flux ratio at the 4000 A discontinuity. Note 20130908 - weights have been dropped; improves\n## correlation with MPA-JHU pipeline estimates. Also corrected lambda weighting\n\n## d4000_n index\n\nd4000n <- function(lambda, flux, ivar, wl4000=c(3850,3950,4000,4100)) {\n wl4000 <- airtovac(wl4000)\n ni <- which(lambda>=wl4000[3] & lambda<=wl4000[4])\n di <- which(lambda>=wl4000[1] & lambda<=wl4000[2])\n dln <- diff(lambda)[ni]\n dld <- diff(lambda)[di]\n fn <- flux[ni]\n if (length(which(!is.na(fn))) < 2) {\n return(list(d4000_n=NA, d4000_n_err=NA))\n }\n if (any(is.na(fn))) {\n fn <- approx(lambda[ni], fn, xout=lambda[ni])$y\n }\n fd <- flux[di]\n if (length(which(!is.na(fd)))<2) {\n return(list(d4000_n=NA, d4000_n_err=NA))\n }\n if (any(is.na(fd))) {\n fd <- approx(lambda[di], fd, xout=lambda[di])$y\n }\n num <- sum(fn*dln*(lambda[ni]^2))\n vn <- sum((dln^2)*(lambda[ni]^4)/ivar[ni])\n den <- sum(fd*dld*(lambda[di]^2))\n vd <- sum((dld^2)*(lambda[di]^4)/ivar[di])\n d4000_n <- num/den\n d4000_n_err <- sqrt(num^2/den^2*(vn/den^2+vd/num^2))\n list(d4000_n=d4000_n, d4000_n_err=d4000_n_err)\n}\n\n## lick indices\n\nlickew <- function(lambda, flux, ivar, which.index=1) {\n \n wl <- t(matrix(airtovac(c(4083.5,4122.25,4041.6,4079.75,4128.5,4161,\n 4142.125,4177.125,4080.125,4117.625,4244.125,4284.125,\n 4142.125,4177.125,4083.875,4096.375,4244.125,4284.125,\n 4222.250,4234.750,4211.000,4219.750,4241.000,4251.000,\n 4281.375,4316.375,4266.375,4282.625,4318.875,4335.125,\n 4369.125,4420.375,4359.125,4370.375,4442.875,4455.375,\n 4452.125,4474.625,4445.875,4454.625,4477.125,4492.125,\n 4514.250,4559.250,4504.250,4514.250,4560.500,4579.250,\n 4634.000,4720.250,4611.500,4630.250,4742.750,4756.500,\n 4758.500,4800.000,4742.750,4756.500,4827.875,4847.875,\n 5069.125,5134.125,4895.125,4957.625,5301.125,5366.125,\n 5154.125,5196.625,4895.125,4957.625,5301.125,5366.125,\n 5160.125,5192.625,5142.625,5161.375,5191.375,5206.375,\n 5245.650,5285.650,5233.150,5248.150,5285.650,5318.150,\n 5312.125,5352.125,5304.625,5315.875,5353.375,5363.375,\n 5387.500,5415.000,5376.250,5387.500,5415.000,5425.000,\n 5445.000,5600.000,5420.000,5442.000,5630.000,5655.000,\n 5696.625,5720.375,5672.875,5696.625,5722.875,5736.625,\n 5776.625,5796.625,5765.375,5775.375,5797.875,5811.625,\n 5876.875,5909.375,5860.625,5875.625,5922.125,5948.125,\n 5936.625,5994.125,5816.625,5849.125,6038.625,6103.625,\n 6189.625,6272.125,6066.625,6141.625,6372.625,6415.125,\n 6357.500,6401.750,6342.125,6356.500,6408.500,6429.750,\n 6775.000,6900.000,6510.000,6539.250,7017.000,7064.000)),6,24))\n inames <- c(\"HdeltaA\",\"CN_1\",\"CN_2\",\"Ca4227\",\"G4300\",\n \"Fe4383\",\"Ca4455\",\"Fe4531\",\"Fe4668\",\"bTiO\",\n \"Mg_1\",\"Mg_2\",\"Mg_b\",\"Fe5270\",\"Fe5335\",\n \"Fe5406\",\"aTiO\",\"Fe5709\",\"Fe5782\",\"Na_D\",\n \"TiO_1\",\"TiO_2\",\"CaH1\", \"CaH2\")\n imag <- rep(FALSE, length(inames))\n imag[c(2,3,11,12,21,22)] <- TRUE\n imag <- imag[which.index]\n wl <- matrix(wl[which.index,], length(which.index), 6)\n ni <- nrow(wl)\n ew <- rep(NA,ni)\n ew_sd <- rep(NA,ni)\n df <- data.frame(lambda=lambda, flux=flux, ivar=ivar)\n for (j in 1:ni) {\n pb <- which(lambda>=wl[j,1] & lambda<=wl[j,2])\n bsb <- which(lambda>=wl[j,3] & lambda<=wl[j,4])\n rsb <- which(lambda>=wl[j,5] & lambda<=wl[j,6])\n if (all(is.na(flux[pb])) || all(is.na(flux[bsb])) || all(is.na(flux[rsb]))) next\n cfit <- lm(flux~lambda, data=df, subset=union(bsb,rsb))\n cont <- predict(cfit, newdata=df[pb,], interval=\"prediction\", level=0.7)\n sd.cont <- (cont[,3]-cont[,2])/2\n dl <- (diff(lambda))[pb]\n num <- flux[pb]\n den <- cont[,1]\n if (imag[j]) {\n ewd <- sum(num/den*dl)\n ew[j] <- -2.5*log10(ewd/(wl[j,2]-wl[j,1]))\n ew_sd[j] <- sqrt(sum(num^2/den^2*(1/(ivar[pb]*num^2)+sd.cont^2/den^2)*dl^2))/\n ewd*2.5/log(10)\n } else {\n ew[j] <- sum((1-num/den)*dl)\n ew_sd[j] <- sqrt(sum(num^2/den^2*(1/(ivar[pb]*num^2)+sd.cont^2/den^2)*dl^2))\n }\n }\n in_names <- inames[which.index]\n in_err_names <- paste(in_names, \"err\", sep=\"_\")\n retdat <- c(ew, ew_sd)\n names(retdat) <- c(in_names, in_err_names)\n retdat\n}\n\n", "meta": {"hexsha": "dc9316438469b2becdbd6911c234adf1f11b6a91", "size": 12610, "ext": "r", "lang": "R", "max_stars_repo_path": "spmutils/R/spmutils.r", "max_stars_repo_name": "mlpeck/spmutils", "max_stars_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spmutils/R/spmutils.r", "max_issues_repo_name": "mlpeck/spmutils", "max_issues_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spmutils/R/spmutils.r", "max_forks_repo_name": "mlpeck/spmutils", "max_forks_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0285714286, "max_line_length": 119, "alphanum_fraction": 0.5756542427, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2511698877171206}}