AutoMathText / data /code /r /0.15-0.20.jsonl
March07's picture
add batch 4/5 (200 files)
5697766 verified
Raw
History Blame Contribute Delete
84.5 kB
{"text": "#' Perform Decision Curve Analysis\n#'\n#' Diagnostic and prognostic models are typically evaluated with measures of\n#' accuracy that do not address clinical consequences.\n#' Decision-analytic techniques allow assessment of clinical outcomes but often\n#' require collection of additional information may be cumbersome to apply to\n#' models that yield a continuous result. Decision curve analysis is a method\n#' for evaluating and comparing prediction models that incorporates clinical\n#' consequences, requires only the data set on which the models are tested,\n#' and can be applied to models that have either continuous or dichotomous\n#' results.\n#' The dca function performs decision curve analysis for binary outcomes.\n#' Review the\n#' [DCA Vignette](http://www.danieldsjoberg.com/dcurves/articles/dca.html)\n#' for a detailed walk-through of various applications.\n#' Also, see [www.decisioncurveanalysis.org](https://www.mskcc.org/departments/epidemiology-biostatistics/biostatistics/decision-curve-analysis) for more information.\n#'\n#' @author Daniel D Sjoberg\n#'\n#' @param formula a formula with the outcome on the LHS and a sum of\n#' markers/covariates to test on the RHS\n#' @param data a data frame containing the variables in `formula=`.\n#' @param thresholds vector of threshold probabilities between 0 and 1.\n#' Default is `seq(0, 0.99, by = 0.01)`. Thresholds at zero are replaced\n#' with 10e-10.\n#' @param label named list of variable labels, e.g. `list(age = \"Age, years)`\n#' @param harm named list of harms associated with a test. Default is `NULL`\n#' @param as_probability character vector including names of variables\n#' that will be converted to a probability. Details below.\n#' @param time if outcome is survival, `time=` specifies the time the\n#' assessment is made\n#' @param prevalence When `NULL`, the prevalence is estimated from `data=`.\n#' If the data passed is a case-control set, the population prevalence\n#' may be set with this argument.\n#'\n#' @section as_probability argument:\n#' While the `as_probability=` argument can be used to convert a marker to the\n#' probability scale, use the argument only when the consequences are fully\n#' understood. For example, when the outcome is binary, logistic regression\n#' is used to convert the marker to a probability. The logistic regression\n#' model assumes linearity on the log-odds scale and can induce\n#' miscalibration when this assumption is not true. Miscalibration in a\n#' model will adversely affect performance on decision curve\n#' analysis. Similarly, when the outcome is time-to-event, Cox Proportional\n#' Hazards regression is used to convert the marker to a probability.\n#' The Cox model also has a linearity assumption and additionally assumes\n#' proportional hazards over the follow-up period. When these assumptions\n#' are violated, important miscalibration may occur.\n#'\n#' Instead of using the `as_probability=` argument, it is suggested to perform\n#' the regression modeling outside of the `dca()` function utilizing methods,\n#' such as non-linear modeling, as appropriate.\n#'\n#' @return List including net benefit of each variable\n#' @seealso [`net_intervention_avoided()`], [`standardized_net_benefit()`], [`plot.dca()`],\n#' [`as_tibble.dca()`]\n#' @export\n#'\n#' @examples\n#' # calculate DCA with binary endpoint\n#' dca(cancer ~ cancerpredmarker + marker,\n#' data = df_binary,\n#' as_probability = \"marker\",\n#' label = list(cancerpredmarker = \"Prediction Model\", marker = \"Biomarker\")) %>%\n#' # plot DCA curves with ggplot\n#' plot(smooth = TRUE) +\n#' # add ggplot formatting\n#' ggplot2::labs(x = \"Treatment Threshold Probability\")\n#'\n#' # calculate DCA with time to event endpoint\n#' dca(Surv(ttcancer, cancer) ~ cancerpredmarker, data = df_surv, time = 1)\ndca <- function(formula, data, thresholds = seq(0, 0.99, by = 0.01),\n label = NULL, harm = NULL, as_probability = character(),\n time = NULL, prevalence = NULL) {\n # checking inputs ------------------------------------------------------------\n if (!is.data.frame(data))\n stop(\"`data=` must be a data frame\", call. = FALSE)\n if (!inherits(formula, \"formula\"))\n stop(\"`formula=` must be a formula\", call. = FALSE)\n if (!is.null(label) && (!rlang::is_list(label) || !rlang::is_named(label)))\n stop(\"`label=` must be a named list or NULL.\", call. = FALSE)\n if (!is.null(harm) && (!rlang::is_list(harm) || !rlang::is_named(harm)))\n stop(\"`harm=` must be a named list or NULL.\", call. = FALSE)\n if (!is.character(as_probability))\n stop(\"`as_probability=` must be character.\", call. = FALSE)\n\n # prepping data --------------------------------------------------------------\n thresholds <- thresholds[thresholds >= 0 & thresholds < 1]\n thresholds[thresholds == 0] <- 10e-10\n\n label <-\n list(all = \"Treat All\", none = \"Treat None\") %>%\n purrr::list_modify(!!!label)\n model_frame <- stats::model.frame(formula, data)\n outcome_name <- names(model_frame)[1]\n if (any(c(\"all\", \"none\") %in% names(model_frame))) {\n stop(\"Variables cannot be named 'all' or 'none': they are reserved.\",\n call. = FALSE)\n }\n\n outcome_type <-\n dplyr::case_when(\n inherits(model_frame[[outcome_name]], \"Surv\") ~ \"survival\",\n length(unique(model_frame[[outcome_name]])) == 2L ~ \"binary\",\n length(unique(model_frame[[outcome_name]])) == 1L &&\n inherits(model_frame[[outcome_name]], \"factor\") &&\n length(attr(model_frame[[outcome_name]], \"level\")) == 2L ~ \"binary\",\n length(unique(model_frame[[outcome_name]])) == 1L &&\n inherits(model_frame[[outcome_name]], \"logical\") ~ \"binary\"\n )\n if (is.na(outcome_type)) {\n paste(\n \"Outcome type not supported. Expecting a binary endpoint\",\n \"or an object of class 'Surv'.\"\n ) %>%\n stop(call. = FALSE)\n }\n if (outcome_type == \"survival\" && is.null(time)) {\n stop(\"`time=` must be specified for survival endpoints.\")\n }\n\n # for binary outcomes, make the outcome a factor\n # so both levels always appear in `table()` results\n if (outcome_type == \"binary\") {\n model_frame[[outcome_name]] <-\n .convert_to_binary_fct(model_frame[[outcome_name]], quiet = FALSE)\n }\n\n # convert to probability if requested ----------------------------------------\n as_probability <-\n model_frame %>%\n dplyr::select(-dplyr::all_of(outcome_name)) %>%\n dplyr::select(dplyr::all_of(as_probability))\n for (v in names(as_probability)) {\n model_frame[[v]] <- .convert_to_risk(model_frame[[outcome_name]],\n model_frame[[v]],\n outcome_type = outcome_type,\n time = time\n )\n }\n for (v in names(model_frame) %>% setdiff(outcome_name)) {\n if (any(!dplyr::between(model_frame[[v]], 0L, 1L))) {\n glue::glue(\"Error in {v}. All covariates/risks must be between 0 and 1.\") %>%\n stop(call. = FALSE)\n }\n }\n\n # add treat all and treat none -----------------------------------------------\n model_frame <-\n model_frame %>%\n dplyr::mutate(\n all = 1L,\n none = 0L,\n .after = .data[[outcome_name]]\n )\n\n # calculate net benefit ------------------------------------------------------\n dca_result <-\n names(model_frame) %>%\n setdiff(outcome_name) %>%\n lapply(\n function(x) {\n .calculate_test_consequences(model_frame[[outcome_name]],\n model_frame[[x]],\n thresholds = thresholds,\n outcome_type = outcome_type,\n prevalence = prevalence,\n time = time\n ) %>%\n dplyr::mutate(\n variable = x,\n label = .env$label[[x]] %||% attr(model_frame[[x]], \"label\") %||% x,\n harm = .env$harm[[x]] %||% 0,\n .before = .data$threshold\n )\n }\n ) %>%\n dplyr::bind_rows() %>%\n dplyr::mutate(\n label = factor(.data$label, levels = unique(.data$label)),\n harm = dplyr::coalesce(harm, 0),\n net_benefit =\n .data$tp_rate - .data$threshold /\n (1 - .data$threshold) * .data$fp_rate - .data$harm\n ) %>%\n tibble::as_tibble()\n\n # return results -------------------------------------------------------------\n lst_result <-\n list(\n call = match.call(),\n y = outcome_name,\n n = dca_result$n[1],\n prevalence = dca_result$prevalence[1],\n time = time,\n dca = dca_result\n ) %>%\n purrr::compact()\n class(lst_result) <- \"dca\"\n lst_result\n}\n\n\n#' Calculate a test's consequences\n#'\n#' @param outcome outcome vector\n#' @param risk vector of risks\n#' @param thresholds threshold probs vector\n#' @param outcome_type type of outcome\n#' @param time time to calculate risk if Surv() outcome\n#' @param prevalence specifed prevleance (if cannot be estimated from data)\n#'\n#' @noRd\n#' @keywords internal\n.calculate_test_consequences <- function(outcome, risk, thresholds, outcome_type,\n prevalence, time) {\n df <-\n tibble::tibble(\n threshold = thresholds,\n n = length(outcome)\n )\n # case-control population prev\n if (!is.null(prevalence)) {\n df$prevalence <- prevalence\n } # survival endpoint prev\n else if (outcome_type == \"survival\") {\n outcome_prev <- .surv_to_risk(outcome ~ 1, time = time, quiet = TRUE) # TODO: print the multistate model note only once\n if (is.na(outcome_prev)) {\n paste(\n \"Cannot calculate outcome prevalence at specified time,\",\n \"likely due to no observed data beyond selected time.\"\n ) %>%\n stop(call. = FALSE)\n }\n df$prevalence <- outcome_prev\n }\n # typical binary prev\n else {\n df$prevalence <- table(outcome)[2] / length(outcome)\n }\n\n if (outcome_type == \"binary\") {\n df <-\n df %>%\n dplyr::rowwise() %>%\n dplyr::mutate(\n test_pos_rate =\n .convert_to_binary_fct(risk >= .data$threshold) %>%\n table() %>%\n purrr::pluck(2) %>% {\n . / .data$n\n },\n tp_rate =\n mean(risk[outcome == \"TRUE\"] >= .data$threshold) * .data$prevalence %>%\n unname(),\n fp_rate =\n mean(risk[outcome == \"FALSE\"] >= .data$threshold) * (1 - .data$prevalence) %>%\n unname(),\n )\n }\n else if (outcome_type == \"survival\") {\n df <-\n df %>%\n dplyr::rowwise() %>%\n dplyr::mutate(\n test_pos_rate =\n .convert_to_binary_fct(risk >= .data$threshold) %>%\n table() %>%\n purrr::pluck(2) %>%\n {. / .data$n},\n risk_rate_among_test_pos =\n tryCatch(\n .surv_to_risk(outcome[risk >= .data$threshold] ~ 1, time = time),\n error = function(e) {\n if (length(outcome[risk >= .data$threshold]) == 0L) {\n return(0)\n }\n NA_real_\n }\n ),\n tp_rate = .data$risk_rate_among_test_pos * .data$test_pos_rate %>%\n unname(),\n fp_rate = (1 - .data$risk_rate_among_test_pos) * .data$test_pos_rate %>%\n unname(),\n )\n }\n\n df %>%\n dplyr::ungroup() %>%\n dplyr::select(dplyr::any_of(c(\n \"threshold\", \"prevalence\",\n \"n\", \"tp_rate\", \"fp_rate\"\n )))\n}\n\n\n#' Convert binary outcome to factor\n#'\n#' @param x a vector\n#' @param quiet logical. default is TRUE\n#'\n#' @noRd\n#' @keywords internal\n.convert_to_binary_fct <- function(x, quiet = TRUE) {\n # if not logical, convert to lgl\n if (!inherits(x, \"logical\")) {\n outcome_levels_sorted <- unique(x) %>% sort()\n if (!quiet) {\n glue::glue(\n \"Assuming '{outcome_levels_sorted[2]}' is [Event] \",\n \"and '{outcome_levels_sorted[1]}' is [non-Event]\"\n ) %>%\n message()\n }\n x <-\n dplyr::case_when(\n x %in% outcome_levels_sorted[1] ~ FALSE,\n x %in% outcome_levels_sorted[2] ~ TRUE\n )\n }\n # convert lgl to fct\n factor(x, levels = c(FALSE, TRUE))\n}\n\n#' Calculate risks\n#'\n#' @param outcome outcome object\n#' @param variable variable\n#' @param outcome_type type of outcome\n#' @param time time to calculate risk if Surv() outcome\n#' @param prevalence specifed prevleance (if cannot be estimated from data)\n#'\n#' @noRd\n#' @keywords internal\n.convert_to_risk <- function(outcome, variable, outcome_type,\n time = NULL, prevalence = NULL) {\n if (outcome_type == \"binary\" && !is.null(prevalence)) {\n stop(\"Cannot convert to risks in case-control setting.\")\n }\n\n if (outcome_type == \"binary\") {\n risk <-\n stats::glm(outcome ~ variable, family = stats::binomial) %>%\n stats::predict(type = \"response\")\n } else if (outcome_type == \"survival\") {\n # construct data frame\n df <- data.frame(outcome = outcome, variable = variable)\n new_df <- data.frame(outcome = outcome, variable = variable)\n new_df$outcome[, 1] <- time\n # build model, and get predictions for time point of interest\n risk <-\n survival::coxph(outcome ~ variable, data = df) %>%\n stats::predict(newdata = new_df, type = \"expected\") %>%\n {\n exp(-.)\n }\n }\n\n risk\n}\n\n\n#' Convert a `Surv()` object to a n-time risk estimate\n#'\n#' @param outcome `Surv()` object\n#' @param time numeric time\n#' @param quiet logical, default is TRUE\n#'\n#' @noRd\n#' @keywords internal\n.surv_to_risk <- function(outcome, time, quiet = TRUE) {\n df_tidy <-\n survival::survfit(outcome) %>%\n broom::tidy()\n\n # if multistate (i.e. competing risks) delete states not of interest\n if (\"state\" %in% names(df_tidy)) {\n state <- unique(df_tidy$state) %>%\n setdiff(\"(s0)\") %>%\n purrr::pluck(1)\n df_tidy <- df_tidy %>% dplyr::filter(.data$state %in% .env$state)\n if (!isTRUE(quiet)) {\n glue::glue(\n \"Multi-state model detected. Showing probabilities into state '{state}'\") %>%\n message()\n }\n }\n # if regular survfit() model, convert survival to risk\n else {\n df_tidy <- dplyr::mutate(df_tidy, estimate = 1 - .data$estimate)\n }\n\n # if no observed times after specified time, return NA\n if (max(df_tidy$time) < time) {\n return(NA_real_)\n }\n\n df_tidy <-\n df_tidy %>%\n dplyr::filter(.data$time <= .env$time)\n\n # if no observed times after time point, return NA\n if (nrow(df_tidy) == 0L) {\n return(NA_real_)\n }\n\n df_tidy %>%\n dplyr::slice_tail() %>%\n dplyr::pull(.data$estimate)\n}\n", "meta": {"hexsha": "3009245d4c216cc2947b9889a5f152539b01ee3d", "size": 14239, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dca.r", "max_stars_repo_name": "ddsjoberg/dcurves", "max_stars_repo_head_hexsha": "759b5460416876645a853d3a812bd0a77a309760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2021-04-24T15:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T12:22:46.000Z", "max_issues_repo_path": "R/dca.r", "max_issues_repo_name": "weihancool/dcurves", "max_issues_repo_head_hexsha": "791c8c5ca54a78ca20df8758fd4302df955b836e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2021-04-20T18:47:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T14:08:11.000Z", "max_forks_repo_path": "R/dca.r", "max_forks_repo_name": "weihancool/dcurves", "max_forks_repo_head_hexsha": "791c8c5ca54a78ca20df8758fd4302df955b836e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2021-04-24T15:54:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T15:26:59.000Z", "avg_line_length": 34.6447688564, "max_line_length": 166, "alphanum_fraction": 0.615492661, "num_tokens": 3724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.19647808861436467}}
{"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#' Perform GWAS using FarmCPU method\n#'\n#' Date build: Febuary 24, 2013\n#' Last update: May 25, 2017\n#' Requirement: Y, GD, and CV should have same taxa order. GD and GM should have the same order on SNPs\n#' \n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param phe phenotype, n by t matrix, n is sample size, t is number of phenotypes\n#' @param geno genotype, m by n matrix, m is marker size, n is sample size. This is Pure Genotype Data Matrix(GD). THERE IS NO COLUMN FOR TAXA.\n#' @param map SNP map information, m by 3 matrix, m is marker size, the three columns are SNP_ID, Chr, and Pos\n#' @param CV covariates, n by c matrix, n is sample size, c is number of covariates\n#' @param P start p values for all SNPs\n#' @param method.sub method used in substitution process, five options: 'penalty', 'reward', 'mean', 'median', or 'onsite'\n#' @param method.sub.final method used in substitution process, five options: 'penalty', 'reward', 'mean', 'median', or 'onsite'\n#' @param method.bin method for selecting the most appropriate bins, three options: 'static', 'EMMA' or 'FaST-LMM'\n#' @param bin.size bin sizes for all iterations, a vector, the bin size is always from large to small\n#' @param bin.selection number of selected bins in each iteration, a vector\n#' @param memo a marker on output file name\n#' @param Prior prior information, four columns, which are SNP_ID, Chr, Pos, P-value\n#' @param ncpus number of threads used for parallele computation\n#' @param maxLoop maximum number of iterations\n#' @param threshold.output only the GWAS results with p-values lower than threshold.output will be output\n#' @param converge a number, 0 to 1, if selected pseudo QTNs in the last and the second last iterations have a certain probality (the probability is converge) of overlap, the loop will stop\n#' @param iteration.output whether to output results of all iterations\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 bound maximum number of SNPs selected as pseudo QTNs in each iteration\n#' @param verbose whether to print detail.\n#'\n#' @return a m by 4 results matrix, m is marker size, the four columns are SNP_ID, Chr, Pos, and p-value\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#' 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#' mapPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.map\", package = \"rMVP\")\n#' map <- read.table(mapPath , head = TRUE)\n#' \n#' farmcpu <- MVP.FarmCPU(phe=phenotype,geno=genotype,map=map,maxLoop=2,method.bin=\"static\")\n#' str(farmcpu)\n#' \n`MVP.FarmCPU` <- function(phe, geno, map, CV=NULL, P=NULL, method.sub=\"reward\", method.sub.final=\"reward\", \n method.bin=c(\"EMMA\", \"static\", \"FaST-LMM\"), bin.size=c(5e5,5e6,5e7), bin.selection=seq(10,100,10), \n memo=\"MVP.FarmCPU\", Prior=NULL, ncpus=2, maxLoop=10, \n threshold.output=.01, converge=1, iteration.output=FALSE, p.threshold=NA, \n QTN.threshold=0.01, bound=NULL, verbose=TRUE){\n #print(\"--------------------- Welcome to FarmCPU ----------------------------\")\n\n if(!is.big.matrix(geno)) stop(\"genotype should be in 'big.matrix' format.\")\n if(sum(is.na(phe[, 2])) != 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 echo=TRUE\n nm=nrow(map)\n if(!is.null(CV)){\n CV=as.matrix(CV)\n CV.index <- apply(CV, 2, function(x) length(table(x)) > 1)\n\t CV <- CV[, CV.index, drop=FALSE]\n npc=ncol(CV)\n }else{\n npc=0\n }\n method.bin=match.arg(method.bin)\n\n\tmap <- as.matrix(map)\n\tsuppressWarnings(max.chr <- max(as.numeric(map[, 2]), na.rm=TRUE))\n\tif(is.infinite(max.chr))\tmax.chr <- 0\n\tmap.xy.index <- which(!as.numeric(map[, 2]) %in% c(0 : max.chr))\n\tif(length(map.xy.index) != 0){\n\t\tchr.xy <- unique(map[map.xy.index, 2])\n\t\tfor(i in 1:length(chr.xy)){\n\t\t\tmap[map[, 2] == chr.xy[i], 2] <- max.chr + i\n\t\t}\n\t}\n map[, 1] = 1:nrow(map)\n\tsuppressWarnings(map <- matrix(as.numeric(map), nrow(map)))\n if(sum(is.na(map[,3]) != 0)) stop(\"Non-digital characters or NAs are not allowed in map for FarmCPU\")\n\t\n if(!is.na(p.threshold)) QTN.threshold = max(p.threshold, QTN.threshold)\n \n name.of.trait=colnames(phe)[2]\n if(!is.null(memo)) name.of.trait=paste(memo,\".\",name.of.trait,sep=\"\")\n theLoop=0\n theConverge=0\n seqQTN.save=c(0)\n seqQTN.pre=c(-1)\n isDone=FALSE\n name.of.trait2=name.of.trait\n\n while(!isDone) {\n theLoop=theLoop+1\n logging.log(paste(\"Current loop: \",theLoop,\" out of maximum of \", maxLoop, sep=\"\"), \"\\n\", verbose = verbose)\n \n spacer=\"0\"\n if(theLoop>9){\n spacer=\"\"\n }\n if(iteration.output){\n name.of.trait2=paste(\"Iteration_\",spacer,theLoop,\".\",name.of.trait,sep=\"\")\n }\n \n #Step 2a: Set prior\n myPrior=FarmCPU.Prior(GM=map,P=P,Prior=Prior)\n\n #Step 2b: Set bins\n if(theLoop<=2){\n myBin=FarmCPU.BIN(Y=phe[,c(1,2)],GDP=geno,GM=map,CV=CV,P=myPrior,method=method.bin,b=bin.size,s=bin.selection,theLoop=theLoop,bound=bound,ncpus=ncpus, verbose = verbose)\n }else{\n myBin=FarmCPU.BIN(Y=phe[,c(1,2)],GDP=geno,GM=map,CV=theCV,P=myPrior,method=method.bin,b=bin.size,s=bin.selection,theLoop=theLoop,ncpus=ncpus, verbose = verbose)\n }\n \n #Step 2c: Remove bin dependency\n #Remove QTNs in LD\n seqQTN=myBin$seqQTN\n\n if(theLoop==2){\n if(!is.na(p.threshold)){\n if(min(myPrior,na.rm=TRUE)>p.threshold){\n seqQTN=NULL\n logging.log(\"Top snps have little effect, set seqQTN to NULL!\", \"\\n\", verbose = verbose)\n }\n }else{\n if(min(myPrior,na.rm=TRUE)>0.01/nm){\n seqQTN=NULL\n logging.log(\"Top snps have little effect, set seqQTN to NULL!\", \"\\n\", verbose = verbose)\n }\n }\n }\n \n #when FarmCPU can not work, make a new QQ plot and manhatthan plot\n if(theLoop==2&&is.null(seqQTN)){\n #Report\n P=myGLM$P[,ncol(myGLM$P)]\n P[P==0] <- min(P[P!=0],na.rm=TRUE)*0.01\n results = cbind(myGLM$B, myGLM$S, P)\n colnames(results) = c(\"effect\", \"se\", \"p\")\n break\n }#force to exit for GLM model while seqQTN=NULL and h2=0\n\n if (!any(is.null(seqQTN.save)) && theLoop > 1) {\n if (!(0 %in% seqQTN.save || -1 %in% seqQTN.save) && !is.null(seqQTN)) {\n #Force previous QTNs in the model\n seqQTN <- union(seqQTN,seqQTN.save)\n }\n }\n if(theLoop!=1){\n seqQTN.p=myPrior[seqQTN]\n if(theLoop==2){\n index.p=seqQTN.p<QTN.threshold\n #if(!is.na(p.threshold)){\n #index.p=seqQTN.p<p.threshold\n #}\n seqQTN.p=seqQTN.p[index.p]\n seqQTN=seqQTN[index.p]\n seqQTN.p=seqQTN.p[!is.na(seqQTN)]\n seqQTN=seqQTN[!is.na(seqQTN)]\n }else{\n index.p=seqQTN.p<QTN.threshold\n #if(!is.na(p.threshold)){\n #index.p=seqQTN.p<p.threshold\n #}\n index.p[seqQTN%in%seqQTN.save]=TRUE\n seqQTN.p=seqQTN.p[index.p]\n seqQTN=seqQTN[index.p]\n seqQTN.p=seqQTN.p[!is.na(seqQTN)]\n seqQTN=seqQTN[!is.na(seqQTN)]\n }\n }\n\n myRemove=FarmCPU.Remove(GDP=geno,GM=map,seqQTN=seqQTN,seqQTN.p=seqQTN.p,threshold=.7)\n \n #Recoding QTNs history\n seqQTN=myRemove$seqQTN\n theConverge=length(intersect(seqQTN,seqQTN.save))/length(union(seqQTN,seqQTN.save))\n circle=(length(union(seqQTN,seqQTN.pre))==length(intersect(seqQTN,seqQTN.pre)))\n \n #handler of initial status\n if(is.null(seqQTN.pre)){circle=FALSE\n }else{\n if(seqQTN.pre[1]==0) circle=FALSE\n if(seqQTN.pre[1]==-1) circle=FALSE\n }\n\n logging.log(\"seqQTN:\", \"\\n\", verbose = verbose)\n if(is.null(seqQTN)){\n logging.log(\"NULL\", \"\\n\", verbose = verbose)\n }else{\n logging.log(seqQTN, \"\\n\", verbose = verbose)\n }\n \n if(theLoop==maxLoop){\n logging.log(paste(\"Total number of possible QTNs in the model is: \", length(seqQTN),sep=\"\"), \"\\n\", verbose = verbose)\n }\n \n isDone=((theLoop>=maxLoop) | (theConverge>=converge) | circle )\n \n seqQTN.pre=seqQTN.save\n seqQTN.save=seqQTN\n \n #Step 3: Screen with bins\n rm(myBin)\n gc()\n \n theCV=CV\n \n if(!is.null(myRemove$bin)){\n if(length(myRemove$seqQTN) == 1){\n #myRemove$bin = as.matrix(myRemove$bin)\n myRemove$bin = t(myRemove$bin)\n }\n theCV=cbind(CV,myRemove$bin)\n }\n\n myGLM=FarmCPU.LM(y=phe[,2],GDP=geno,w=theCV,ncpus=ncpus,npc=npc, verbose=verbose)\n if(!is.null(seqQTN)){\n if(ncol(myGLM$P) != (npc + length(seqQTN) + 1)) stop(\"wrong dimensions.\")\n }\n \n #Step 4: Background unit substitution\n if(!isDone){\n myGLM=FarmCPU.SUB(GM=map,GLM=myGLM,QTN=map[myRemove$seqQTN, , drop=FALSE],method=method.sub)\n }else{\n myGLM=FarmCPU.SUB(GM=map,GLM=myGLM,QTN=map[myRemove$seqQTN, , drop=FALSE],method=method.sub.final)\n }\n P=myGLM$P[,ncol(myGLM$P)]\n P[P==0] <- min(P[P!=0], na.rm=TRUE)*0.01\n results = cbind(myGLM$B, myGLM$S, P)\n colnames(results) = c(\"effect\", \"se\", \"p\")\n } #end of while loop\n #print(\"****************FarmCPU ACCOMPLISHED****************\")\n return(results)\n}#The MVP.FarmCPU function ends here\n\n\n#' FarmCPU.FaSTLMM.LL\n#' Evaluation of the maximum likelihood using FaST-LMM method\n#' \n#' Last update: January 11, 2017\n#' Requirement: pheno, snp.pool, and X0 must have same taxa order.\n#' Requirement: No missing data\n#' \n#' @author Xiaolei Liu (modified)\n#' \n#' @param pheno a two-column phenotype matrix\n#' @param snp.pool matrix for pseudo QTNs\n#' @param X0 covariates matrix\n#' @param ncpus number of threads used for parallel computation\n#'\n#' @return\n#' Output: beta - beta effect\n#' Output: delta - delta value\n#' Output: LL - log-likelihood\n#' Output: vg - genetic variance\n#' Output: ve - residual variance\n#'\n`FarmCPU.FaSTLMM.LL` <- function(pheno, snp.pool, X0=NULL, ncpus=2){\n y=pheno\n p=0\n deltaExpStart = -5\n deltaExpEnd = 5\n snp.pool=snp.pool[,]\n\n if(!is.null(snp.pool)&&var(snp.pool)==0){\n deltaExpStart = 100\n deltaExpEnd = deltaExpStart\n }\n if(is.null(X0)) {\n X0 = matrix(1, nrow(snp.pool), 1)\n }\n X=X0\n #########SVD of X\n K.X.svd <- svd(snp.pool)\n d=K.X.svd$d\n d=d[d>1e-08]\n d=d^2\n U1=K.X.svd$u\n U1=U1[,1:length(d)]\n #handler of single snp\n if(is.null(dim(U1))) U1=matrix(U1,ncol=1)\n n=nrow(U1)\n U1TX=crossprod(U1,X)\n U1TY=crossprod(U1,y)\n yU1TY <- y-U1%*%U1TY\n XU1TX<- X-U1%*%U1TX\n IU = -tcrossprod(U1)\n diag(IU) = rep(1,n) + diag(IU)\n IUX=crossprod(IU,X)\n IUY=crossprod(IU,y)\n #Iteration on the range of delta (-5 to 5 in glog scale)\n delta.range <- seq(deltaExpStart,deltaExpEnd,by=0.1)\n m <- length(delta.range)\n #for (m in seq(deltaExpStart,deltaExpEnd,by=0.1)){\n beta.optimize.parallel <- function(ii){\n #p=p+1\n delta <- exp(delta.range[ii])\n #----------------------------calculate beta-------------------------------------\n #######get beta1\n beta1=0\n for(i in 1:length(d)){\n one=matrix(U1TX[i,], nrow=1)\n beta=crossprod(one,(one/(d[i]+delta))) #This is not real beta, confusing\n beta1= beta1+beta\n }\n \n #######get beta2\n beta2=0\n for(i in 1:nrow(U1)){\n one=matrix(IUX[i,], nrow=1)\n beta = crossprod(one)\n beta2= beta2+beta\n }\n beta2<-beta2/delta\n \n #######get beta3\n beta3=0\n for(i in 1:length(d)){\n one1=matrix(U1TX[i,], nrow=1)\n one2=matrix(U1TY[i,], nrow=1)\n beta=crossprod(one1,(one2/(d[i]+delta)))\n beta3= beta3+beta\n }\n \n ###########get beta4\n beta4=0\n for(i in 1:nrow(U1)){\n one1=matrix(IUX[i,], nrow=1)\n one2=matrix(IUY[i,], nrow=1)\n beta=crossprod(one1,one2)\n beta4= beta4+beta\n }\n beta4<-beta4/delta\n \n #######get final beta\n zw1 <- ginv(beta1+beta2)\n #zw1 <- try(solve(beta1+beta2))\n #if(inherits(zw1, \"try-error\")){\n #zw1 <- ginv(beta1+beta2)\n #}\n \n zw2=(beta3+beta4)\n beta=crossprod(zw1,zw2)\n \n #----------------------------calculate LL---------------------------------------\n ####part 1\n part11<-n*log(2*3.14)\n part12<-0\n for(i in 1:length(d)){\n part12_pre=log(d[i]+delta)\n part12= part12+part12_pre\n }\n part13<- (nrow(U1)-length(d))*log(delta)\n part1<- -1/2*(part11+part12+part13)\n \n ###### part2\n part21<-nrow(U1)\n ######part221\n \n part221=0\n for(i in 1:length(d)){\n one1=U1TX[i,]\n one2=U1TY[i,]\n part221_pre=(one2-one1%*%beta)^2/(d[i]+delta)\n part221 = part221+part221_pre\n }\n \n part222=0\n for(i in 1:n){\n one1=XU1TX[i,]\n one2=yU1TY[i,]\n part222_pre=((one2-one1%*%beta)^2)/delta\n part222= part222+part222_pre\n }\n part22<-n*log((1/n)*(part221+part222))\n part2<- -1/2*(part21+part22)\n \n ################# likihood\n LL<-part1+part2\n part1<-0\n part2<-0\n \n return(list(beta=beta,delta=delta,LL=LL))\n }\n llresults <- lapply(1:m, beta.optimize.parallel)\n for(i in 1:m){\n if(i == 1){\n beta.save = llresults[[i]]$beta\n delta.save = llresults[[i]]$delta\n LL.save = llresults[[i]]$LL\n }else{\n if(llresults[[i]]$LL > LL.save){\n beta.save = llresults[[i]]$beta\n delta.save = llresults[[i]]$delta\n LL.save = llresults[[i]]$LL\n }\n }\n }\n #--------------------update with the optimum------------------------------------\n beta=beta.save\n delta=delta.save\n LL=LL.save\n \n #--------------------calculating Va and Vem-------------------------------------\n #sigma_a1\n sigma_a1=0\n for(i in 1:length(d)){\n one1=matrix(U1TX[i,], ncol=1)\n one2=matrix(U1TY[i,], nrow=1)\n #sigma_a1_pre=(one2-one1%*%beta)^2/(d[i]+delta)\n sigma_a1_pre=(one2-crossprod(one1,beta))^2/(d[i]+delta)\n sigma_a1= sigma_a1+sigma_a1_pre\n }\n \n ### sigma_a2\n sigma_a2=0\n \n for(i in 1:nrow(U1)){\n one1=matrix(IUX[i,], ncol=1)\n one2=matrix(IUY[i,], nrow=1)\n #sigma_a2_pre<-(one2-one1%*%beta)^2\n sigma_a2_pre<-(one2-crossprod(one1,beta))^2\n sigma_a2= sigma_a2+sigma_a2_pre\n }\n \n sigma_a2<-sigma_a2/delta\n sigma_a<- 1/n*(sigma_a1+sigma_a2)\n sigma_e<-delta*sigma_a\n \n return(list(beta=beta, delta=delta, LL=LL, vg=sigma_a, ve=sigma_e))\n}\n\n\n#' FarmCPU.BIN\n#'\n#' Last update: March 28, 2017\n#' Requirement: Y, GDP, and CV must have same taxa order. GDP and GM must have the same order on SNP\n#' Requirement: P and GM are in the same order\n#' Requirement: No missing data\n#' \n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param Y a n by 2 matrix, the fist column is taxa id and the second is trait\n#' @param GDP genotype, m by n matrix, m is marker size, n is sample size. This is Pure Genotype Data Matrix(GD). THERE IS NO COLUMN FOR TAXA\n#' @param GM SNP map information, m by 3 matrix, m is marker size, the three columns are SNP_ID, Chr, and Pos\n#' @param CV covariates, n by c matrix, n is sample size, c is number of covariates\n#' @param P start p values for all SNPs\n#' @param method two options, 'static' or 'FaST-LMM'\n#' @param b bin sizes for all iterations, a vector, the bin size is always from large to small\n#' @param s number of selected bins in each iteration, a vector\n#' @param theLoop iteration number\n#' @param bound maximum number of SNPs selected as pseudo QTNs in each iteration\n#' @param ncpus number of threads used for parallele computation\n#' @param verbose whether to print detail.\n#'\n#' @return\n#' Output: seqQTN - an s by 1 vecter for index of QTNs on GM file\n#'\n#' @keywords internal\nFarmCPU.BIN <-\n function(Y=NULL, GDP=NULL, GM=NULL, CV=NULL, P=NULL, method=\"EMMA\", b=c(5e5,5e6,5e7), s=seq(10,100,10), theLoop=NULL, bound=NULL, ncpus=2, verbose=TRUE){\n #print(\"FarmCPU.BIN Started\")\n \n if(is.null(P)) return(list(bin=NULL,binmap=NULL,seqQTN=NULL))\n \n #Set upper bound for bin selection to squareroot of sample size\n n=nrow(Y)\n #bound=round(sqrt(n)/log10(n))\n if(is.null(bound)){\n bound=round(sqrt(n)/sqrt(log10(n)))\n }\n \n s[s>bound]=bound\n s=unique(s[s<=bound]) #keep the within bound\n \n optimumable=(length(b)*length(s)>1)\n if(!optimumable & method!=\"optimum\"){\n method=\"static\"\n }\n \n if(optimumable){\n s[s>bound]=bound\n #print(\"optimizing possible QTNs...\")\n #GP=cbind(GM,P,NA,NA,NA)\n #mySpecify=FarmCPU.Specify(GI=GM, GP=GP, bin.size=b, inclosure.size=s)\n #seqQTN=which(mySpecify$index==TRUE)\n }\n \n #Method of static\n if(method==\"static\"&optimumable){\n #print(\"Via static\")\n if(theLoop==2){\n b=b[3]\n }else if(theLoop==3){\n b=b[2]\n }else{\n b=b[1]\n }\n s=bound\n s[s>bound]=bound\n logging.log(\"Optimizing Pseudo QTNs...\", \"\\n\", verbose = verbose)\n GP=cbind(GM,P,NA,NA,NA)\n mySpecify=FarmCPU.Specify(GI=GM,GP=GP,bin.size=b,inclosure.size=s)\n seqQTN.save=which(mySpecify$index==TRUE)\n }\n \n #Method of optimum: FaST-LMM\n #============================Optimize by FaST-LMM============================================\n if(method==\"FaST-LMM\"&optimumable){\n #print(\"c(bin.size, bin.selection, -2LL, VG, VE)\")\n logging.log(\"Optimizing Pseudo QTNs...\", \"\\n\", verbose = verbose)\n count=0\n for (bin in b){\n for (inc in s){\n count=count+1\n GP=cbind(GM,P,NA,NA,NA)\n mySpecify=FarmCPU.Specify(GI=GM,GP=GP,bin.size=bin,inclosure.size=inc)\n seqQTN=which(mySpecify$index==TRUE)\n GK=t(GDP[seqQTN,])\n myBurger=FarmCPU.Burger(Y=Y[,1:2], CV=CV, GK=GK, ncpus=ncpus, method=method)\n myREML=myBurger$REMLs\n myVG=myBurger$vg #it is unused\n myVE=myBurger$ve #it is unused\n logging.log(c(bin,inc,myREML,myVG,myVE), \"\\n\", verbose = verbose)\n #Recoding the optimum GK\n if(count==1){\n seqQTN.save=seqQTN\n LL.save=myREML\n bin.save=bin\n inc.save=inc\n vg.save=myVG # for genetic variance\n ve.save=myVE # for residual variance\n }else{\n if(myREML<LL.save){\n seqQTN.save=seqQTN\n LL.save=myREML\n bin.save=bin\n inc.save=inc\n vg.save=myVG # for genetic variance\n ve.save=myVE # for residual variance\n }\n } #end of if(count==1)\n }#loop on bin number\n }#loop on bin size\n #seqQTN=seqQTN.save\n }\n \n #Method of optimum: EMMA\n #============================Optimize by EMMA============================================\n if(method==\"EMMA\"&optimumable){\n #print(\"c(bin.size, bin.selection, -2LL, VG, VE)\")\n logging.log(\"Optimizing Pseudo QTNs...\", \"\\n\", verbose = verbose)\n m <- length(b)*length(s)\n inc.index = rep(c(1:length(s)), length(b))\n \n seqQTN.optimize.parallel <- function(ii){\n bin.index = floor((ii-0.1)/length(s)) + 1\n bin = b[bin.index]\n inc = s[inc.index[ii]]\n GP=cbind(GM,P,NA,NA,NA)\n mySpecify=FarmCPU.Specify(GI=GM,GP=GP,bin.size=bin,inclosure.size=inc)\n seqQTN=which(mySpecify$index==TRUE)\n GK=t(GDP[seqQTN,])\n myBurger=FarmCPU.Burger(Y=Y[,1:2], CV=CV, GK=GK, ncpus=ncpus, method=method)\n myREML=myBurger$REMLs\n myVG=myBurger$vg #it is unused\n myVE=myBurger$ve #it is unused\n logging.log(c(bin,inc,myREML,myVG,myVE), \"\\n\", verbose = verbose)\n return(list(seqQTN=seqQTN,myREML=myREML))\n }\n llresults <- lapply(1:m, seqQTN.optimize.parallel)\n\n for(i in 1:m){\n if(i == 1){\n seqQTN.save = llresults[[i]]$seqQTN\n myREML.save = llresults[[i]]$myREML\n }else{\n if(llresults[[i]]$myREML < myREML.save){\n seqQTN.save = llresults[[i]]$seqQTN\n myREML.save = llresults[[i]]$myREML\n }\n }\n }\n }\n \n #Method of optimum: GEMMA\n #can not be used to provide REML\n #============================Optimize by GEMMA============================================\n if(method==\"GEMMA\"&optimumable){\n #print(\"c(bin.size, bin.selection, -2LL, VG, VE)\")\n logging.log(\"Optimizing Pseudo QTNs...\\n\", verbose = verbose)\n m <- length(b)*length(s)\n \n seqQTN.optimize.parallel <- function(ii){\n bin = floor((ii-0.1)/length(s)) + 1\n inc = rep(c(1:length(s)), length(b))\n GP=cbind(GM,P,NA,NA,NA)\n mySpecify=FarmCPU.Specify(GI=GM,GP=GP,bin.size=bin[ii],inclosure.size=inc[ii])\n seqQTN=which(mySpecify$index==TRUE)\n GK=t(GDP[seqQTN,])\n myBurger=FarmCPU.Burger(Y=Y[,1:2], CV=CV, GK=GK, ncpus=ncpus, method=method)\n myREML=myBurger$REMLs\n myVG=myBurger$vg #it is unused\n myVE=myBurger$ve #it is unused\n logging.log(c(bin,inc,myREML,myVG,myVE), \"\\n\", verbose = verbose)\n return(list(seqQTN=seqQTN,myREML=myREML))\n }\n llresults <- lapply(1:m, seqQTN.optimize.parallel)\n\n for(i in 1:m){\n if(i == 1){\n seqQTN.save = llresults[[i]]$seqQTN\n myREML.save = llresults[[i]]$myREML\n }else{\n if(llresults[[i]]$myREML < myREML.save){\n seqQTN.save = llresults[[i]]$seqQTN\n myREML.save = llresults[[i]]$myREML\n }\n }\n }\n }\n \n return(list(seqQTN=seqQTN.save))\n }#The function FarmCPU.BIN ends here\n\n\n#' To get indicator (TURE or FALSE) for GI based on GP\n#' \n#' Last update: January 26, 2017\n#' Strategy\n#' 1.set bins for all snps in GP\n#' 2.keep the snp with smallest P value in each bin, record SNP ID\n#' 3.Search GI for SNP with SNP ID from above\n#' 4.return the position for SNP selected\n#' \n#' @author Zhiwu Zhang\n#' \n#' @param GI Data frame with three columns (SNP name, chr and base position)\n#' @param GP Data frame with seven columns (SNP name, chr and base position, P, MAF, N, effect)\n#' @param bin.size a value of @param b in 'FarmCPU.bin' function\n#' @param inclosure.size a value of @param s in 'FarmCPU.bin' function\n#' @param MaxBP maximum base pairs for each chromosome\n#'\n#' @return theIndex: a vector indicating if the SNPs in GI belong to QTN or not\nFarmCPU.Specify <-\n function(GI=NULL, GP=NULL, bin.size=10000000, inclosure.size=NULL, MaxBP=1e10){\n #print(\"Specification in process...\")\n if(is.null(GP))return (list(index=NULL,BP=NULL))\n \n #set inclosure bin in GP\n #Create SNP ID: position+CHR*MaxBP\n ID.GP=as.numeric(as.vector(GP[, 3]))+as.numeric(as.vector(GP[, 2]))*MaxBP\n \n #Creat bin ID\n bin.GP=floor(ID.GP/bin.size )\n \n #Create a table with bin ID, SNP ID and p value (set 2nd and 3rd NA temporately)\n binP=as.matrix(cbind(bin.GP,NA,NA,ID.GP,as.numeric(as.vector(GP[,4]))) )\n n=nrow(binP)\n \n #Sort the table by p value and then bin ID (e.g. sort p within bin ID)\n binP=binP[order(as.numeric(as.vector(binP[,5]))),] #sort on P alue\n binP=binP[order(as.numeric(as.vector(binP[,1]))),] #sort on bin\n \n #set indicator (use 2nd 3rd columns)\n binP[2:n,2]=binP[1:(n-1),1]\n binP[1,2]=0 #set the first\n binP[,3]= binP[, 1]-binP[, 2]\n \n #Se representives of bins\n ID.GP=binP[binP[, 3]>0,]\n \n #Choose the most influencial bins as estimated QTNs\n #Handler of single row\n if(is.null(dim(ID.GP))) ID.GP=matrix(ID.GP,1,length(ID.GP))\n ID.GP=ID.GP[order(as.numeric(as.vector(ID.GP[, 5]))),] #sort on P alue\n \n #Handler of single row (again after reshape)\n if(is.null(dim(ID.GP))) ID.GP=matrix(ID.GP,1,length(ID.GP))\n \n index=!is.na(ID.GP[, 4])\n ID.GP=ID.GP[index,4] #must have chr and bp information, keep SNP ID only\n \n if(!is.null(inclosure.size) ) {\n if(!any(is.na(inclosure.size))){\n avaiable=min(inclosure.size,length(ID.GP))\n if(avaiable==0){\n ID.GP=-1\n }else{\n ID.GP=ID.GP[1:avaiable] #keep the top ones selected\n }\n }\n }\n \n #create index in GI\n theIndex=NULL\n if(!is.null(GI)){\n ID.GI=as.numeric(as.vector(GI[, 3]))+as.numeric(as.vector(GI[, 2]))*MaxBP\n theIndex=ID.GI %in% ID.GP\n }\n \n myList=list(index=theIndex,CB=ID.GP)\n return (list(index=theIndex,CB=ID.GP))\n } #end of FarmCPU.Specify\n\n\n#' To quickly sovel LM with one variable substitute multiple times\n#'\n#' Start date: March 1, 2013\n#' Last update: March 6, 2013\n#' Strategy:\n#' 1. Separate constant covariates (w) and dynamic coveriates (x)\n#' 2. Build non-x related only once\n#' 3. Use apply to iterate x\n#' 4. Derive dominance indicate d from additive indicate (x) mathmaticaly\n#' 5. When d is not estimable, continue to test x\n#' \n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param y one column matrix, dependent variable\n#' @param w covariates, n by c matrix, n is sample size, c is number of covariates\n#' @param GDP genotype, m by n matrix, m is marker size, n is sample size. This is Pure Genotype Data Matrix(GD). THERE IS NO COLUMN FOR TAXA.\n#' @param ncpus number of threads used for parallele computation\n#' @param npc number of covariates without pseudo QTNs\n#' @param verbose whether to print detail.\n#'\n#' @return\n#' Output: P - p-value of each SNP\n#' Output: betapred - effects of pseudo QTNs\n#' Output: B - effect of each SNP\n#' \n#' @keywords internal\nFarmCPU.LM <-\n function(y, w=NULL, GDP, ncpus=2, npc=0, verbose=TRUE){\n #print(\"FarmCPU.LM started\")\n if(is.null(y)) return(NULL)\n if(is.null(GDP)) return(NULL)\n #Constant section (non individual marker specific)\n #---------------------------------------------------------\n #Configration\n nd=20 #number of markes for checking A and D dependency\n N=length(y) #Total number of taxa, including missing ones\n \n if(!is.null(w)){\n w=as.matrix(w,nrow = N)\n nf=ncol(w)\n w=cbind(rep(1,N),w)\n q0=ncol(w)\n }else{\n w=rep(1,N)\n nf=0\n q0=1\n }\n w = as.matrix(w)\n \n logging.log(\"number of covariates in current loop is:\", \"\\n\", verbose = verbose)\n logging.log(nf, \"\\n\", verbose = verbose)\n \n n=N\n if(nd>n)nd=n #handler of samples less than nd\n k=1 #number of genetic effect: 1 and 2 for A and AD respectively\n \n q1=(q0+1) # vecter index for the posistion of genetic effect (a)\n q2=(q0+1):(q0+2) # vecter index for the posistion of genetic effect (a and d)\n df=n-q0-k #residual df (this should be varied based on validating d)\n \n iXX=matrix(0,q0+k,q0+k) #Reserve the maximum size of inverse of LHS\n \n # ww=crossprodcpp(w)\n ww = crossprod(w)\n\n wy = crossprod(w,y)\n # yy=crossprodcpp(y)\n yy = crossprod(y)\n wwi = ginv(ww)\n \n #Statistics on the reduced model without marker\n rhs=wy\n beta <- crossprod(wwi,rhs)\n ve <- (yy - crossprod(beta, rhs)) / df\n se <- sqrt(diag(wwi) * ve[1])\n \n if(npc!=0){\n betapc = beta[2:(npc+1)]\n betapred = beta[-c(1:(npc+1))]\n sepred = se[-c(1:(npc+1))]\n }else{\n betapc = NULL\n betapred = beta[-1]\n sepred = se[-1]\n }\n\n #print(ncpus)\n logging.log(\"scanning...\", \"\\n\", verbose = verbose)\n\n # P <- NULL\n # B <- NULL\n # S <- NULL\n\n # setMKLthreads(10)\n # for(i in 1:nrow(GDP)){\n # xx <- summary(lm(y~cbind(w,GDP[i, ])))$coeff\n # P <- rbind(P, xx[-1,4,drop=TRUE])\n # B <- c(B, xx[nrow(xx), 1])\n # S <- c(S, xx[nrow(xx), 2])\n # }\n # if(ncol(w) == 50) write.csv(P, \"P.csv\")\n\n mkl_env({\n results <- glm_c(y=y, X=w, iXX = wwi, GDP@address, verbose=verbose, threads=ncpus)\n })\n return(list(P=results[ ,-c(1:3), drop=FALSE], betapred=betapred, sepred=sepred, B=results[ , 1, drop=FALSE], S=results[ , 2, drop=FALSE]))\n # return(list(P=P, betapred=betapred, B=as.matrix(B), S=S))\n } #end of FarmCPU.LM function\n\n\n#' FarmCPU.Burger\n#' \n#' Last update: Dec 21, 2016\n#' To calculate likelihood, variances and ratio, revised by Xiaolei based on GAPIT.Burger function from GAPIT package\n#'\n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param Y phenotype, n by t matrix, n is sample size, t is number of phenotypes\n#' @param CV covariates, n by c matrix, n is sample size, c is number of covariates\n#' @param GK Genotype data in numerical format, taxa goes to row and snp go to columns\n#' @param ncpus number of threads used for parallele computation\n#' @param method two options for estimating variance components, 'FaST-LMM' or 'EMMA'\n#'\n#' @return\n#' Output: REMLs - maximum log likelihood\n#' Output: vg - genetic variance\n#' Output: ve - residual variance\n#' Output: delta - exp(root)\n#' \n#' @keywords internal\nFarmCPU.Burger <-\n function(Y=NULL,CV=NULL,GK=NULL,ncpus=2, method=\"FaST-LMM\"){\n if(!is.null(CV)){\n CV=as.matrix(CV)#change CV to a matrix when it is a vector\n theCV=as.matrix(cbind(matrix(1,nrow(CV),1),CV))\n }else{\n theCV=matrix(1,nrow(Y),1)\n }\n \n #handler of single column GK\n n=nrow(GK)\n m=ncol(GK)\n\t\tif(!is.null(GK)){\n\t\t\tn=nrow(GK)\n\t\t\tm=ncol(GK)\n\t\t\tif(m > 2){\n\t\t\t\ttheGK = as.matrix(GK)#GK is pure genotype matrix\n\t\t\t}else if(m==0){\n\t\t\t\ttheGK = NULL\n\t\t\t}else{\n\t\t\t\ttheGK = matrix(GK,n,1)\n\t\t\t}\n\t\t}else{\n\t\t\ttheGK=GK\n\t\t}\n if(method==\"FaST-LMM\"){\n myFaSTREML=FarmCPU.FaSTLMM.LL(pheno=matrix(Y[,-1],nrow(Y),1), snp.pool=theGK, X0=theCV, ncpus=ncpus)\n REMLs=-2*myFaSTREML$LL\n delta=myFaSTREML$delta\n vg=myFaSTREML$vg\n ve=myFaSTREML$ve\n }\n \n if(method==\"EMMA\"){\n K <- MVP.K.VanRaden(M=as.big.matrix(t(theGK)), priority=\"speed\",verbose=FALSE)\n myEMMAREML <- MVP.EMMA.Vg.Ve(y=matrix(Y[,-1],nrow(Y),1), X=theCV, K=K)\n REMLs=-2*myEMMAREML$REML\n delta=myEMMAREML$delta\n vg=myEMMAREML$vg\n ve=myEMMAREML$ve\n }\n \n #print(\"FarmCPU.Burger succeed!\")\n return (list(REMLs=REMLs, vg=vg, ve=ve, delta=delta))\n } #end of FarmCPU.Burger\n\n\n#' FarmCPU.SUB\n#'\n#' Last update: Febuary 26, 2013\n#' Requirement: P has row name of SNP. s<=t. covariates of QTNs are next to SNP\n#'\n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param GM SNP map information, m by 3 matrix, m is marker size, the three columns are SNP_ID, Chr, and Pos\n#' @param GLM FarmCPU.GLM object\n#' @param QTN s by 3 matrix for SNP name, chromosome and BP\n#' @param method options are \"penalty\", \"reward\",\"mean\",\"median\",and \"onsite\"\n#'\n#' @return \n#' Output: GLM$P - Updated p-values by substitution process\n#' Output: GLM$B - Updated effects by substitution process\nFarmCPU.SUB <-\n function(GM=NULL,GLM=NULL,QTN=NULL,method=\"mean\"){\n if(is.null(GLM$P)) return(NULL) #P is required\n if(is.null(QTN)) return(NULL) #QTN is required\n #print(\"FarmCPU.SUB Started\")\n #print(length(QTN))\n #if(length(QTN)==3){\n #QTN=QTN[1]\n #}else{\n QTN=QTN[ , 1, drop=FALSE]\n #}\n position=match(QTN, GM[, 1, drop=FALSE], nomatch = 0)\n nqtn=length(position)\n if(is.numeric(GLM$P)){\n GLM$P = as.matrix(GLM$P)\n }\n GLM$B = as.matrix(GLM$B)\n index=(ncol(GLM$P)-nqtn):(ncol(GLM$P)-1)\n spot=ncol(GLM$P)\n \n if(ncol(GLM$P)!=1){\n if(length(index)>1){\n if(method==\"penalty\") P.QTN=apply(GLM$P[,index],2,max,na.rm=TRUE)\n if(method==\"reward\") P.QTN=apply(GLM$P[,index],2,min,na.rm=TRUE)\n if(method==\"mean\") P.QTN=apply(GLM$P[,index],2,mean,na.rm=TRUE)\n if(method==\"median\") P.QTN=apply(GLM$P[,index],2,median,na.rm=TRUE)\n if(method==\"onsite\") P.QTN=GLM$P0[(length(GLM$P0)-nqtn+1):length(GLM$P0)]\n }else{\n if(method==\"penalty\") P.QTN=max(GLM$P[,index, drop=FALSE],na.rm=TRUE)\n if(method==\"reward\") P.QTN=min(GLM$P[,index, drop=FALSE],na.rm=TRUE)\n if(method==\"mean\") P.QTN=mean(GLM$P[,index, drop=FALSE],na.rm=TRUE)\n if(method==\"median\") P.QTN=median(GLM$P[,index, drop=FALSE],median,na.rm=TRUE)\n if(method==\"onsite\") P.QTN=GLM$P0[(length(GLM$P0)-nqtn+1):length(GLM$P0)]\n }\n #replace SNP pvalues with QTN pvalue\n GLM$P[position, spot] = P.QTN\n GLM$B[position, ] = GLM$betapred\n GLM$S[position, ] = GLM$sepred\n }\n return(GLM)\n }#The function FarmCPU.SUB ends here\n\n\n#' Remove bins that are highly correlated\n#'\n#' Last update: March 4, 2013\n#' Requirement: GDP and GM have the same order on SNP\n#' \n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param GDP genotype, m by n matrix, m is marker size, n is sample size. This is Pure Genotype Data Matrix(GD). THERE IS NO COLUMN FOR TAXA\n#' @param GM SNP map information, m by 3 matrix, m is marker size, the three columns are SNP_ID, Chr, and Pos\n#' @param seqQTN s by 1 vecter for index of QTN on GM\n#' @param seqQTN.p p value of each @param seqQTN\n#' @param threshold pearson correlation threshold for remove correlated markers\n#'\n#' @return\n#' Output: bin - n by s0 matrix of genotype\n#' Output: binmap - s0 by 3 matrix for map of bin\n#' Output: seqQTN - s0 by 1 vecter for index of QTN on GM\n#' Relationship: bin=GDP[,c(seqQTN)], binmap=GM[seqQTN,], s0<=s\n#' @keywords internal\nFarmCPU.Remove <-\n function(GDP=NULL, GM=NULL, seqQTN=NULL, seqQTN.p=NULL, threshold=.99){\n if(is.null(seqQTN))return(list(bin=NULL,binmap=NULL,seqQTN=NULL))\n seqQTN=seqQTN[order(seqQTN.p)]\n \n hugeNum=10e10\n n=length(seqQTN)\n #fielter bins by physical location\n \n binmap=GM[seqQTN, , drop=FALSE]\n \n cb=as.numeric(binmap[, 2, drop=FALSE])*hugeNum+as.numeric(binmap[, 3, drop=FALSE])#create ID for chromosome and bp\n cb.unique=unique(cb)\n \n #print(\"debuge\")\n #print(cb)\n #print(cb.unique)\n \n index=match(cb.unique,cb,nomatch = 0)\n seqQTN=seqQTN[index]\n \n #print(\"Number of bins after chr and bp fillter\")\n n=length(seqQTN) #update n\n\n #Set sample\n ratio=.1\n maxNum=100000\n m=nrow(GDP) #sample size\n s=ncol(GDP) #number of markers\n \n sampled=s\n if(sampled>maxNum)sampled=maxNum\n \n \n #index=sample(s,sampled)\n index=1:sampled\n \n #This section has problem of turning big.matrix to R matrix\n #It is OK as x is small\n if(is.big.matrix(GDP)){\n x=t(as.matrix(deepcopy(GDP,rows=seqQTN,cols=index) ))\n }else{\n x=t(GDP[seqQTN,index] )\n }\n \n r=cor(as.matrix(x))\n index=abs(r)>threshold\n \n b=r*0\n b[index]=1\n c=1-b\n \n #The above are replaced by following\n c[lower.tri(c)]=1\n diag(c)=1\n bd <- apply(c,2,prod)\n \n position=(bd==1)\n seqQTN=seqQTN[position]\n #============================end of optimum============================================\n seqQTN=seqQTN[!is.na(seqQTN)]\n \n #This section has problem of turning big.matrix to R matrix\n if(is.big.matrix(GDP)){\n bin=t(as.matrix(deepcopy(GDP,rows=seqQTN,) ))\n }else{\n bin=t(GDP[seqQTN, , drop=FALSE] )\n }\n \n binmap=GM[seqQTN, , drop=FALSE]\n\n return(list(bin=bin, binmap=binmap, seqQTN=seqQTN))\n }#The function FarmCPU.Remove ends here\n\n\n#' Set prior on existing p value\n#'\n#' Last update: March 10, 2013\n#' Requirement: P and GM are in the same order, Prior is part of GM except P value\n#' \n#' @author Xiaolei Liu and Zhiwu Zhang\n#' \n#' @param GM an m by 3 matrix for SNP name, chromosome and BP\n#' @param P an m by 1 matrix containing probability\n#' @param Prior an s by 4 matrix for SNP name, chromosome, BP and p-value\n#'\n#' @return\n#' Output: P - updated P value by prior information\n#' \n#' @keywords internal\nFarmCPU.Prior <-\n function(GM, P=NULL, Prior=NULL){\n #print(\"FarmCPU.Prior Started\")\n \n if(is.null(Prior)& is.null(P))return(P)\n \n #get prior position\n if(!is.null(Prior)) index=match(Prior[, 1, drop=FALSE],GM[, 1, drop=FALSE],nomatch = 0)\n \n #if(is.null(P)) P=runif(nrow(GM)) #set random p value if not provided (This is not helpful)\n #print(\"debug set prior a\")\n \n #Get product with prior if provided\n if(!is.null(Prior) & !is.null(P) )P[index]=P[index]*Prior[, 4, drop=FALSE]\n \n return(P)\n }#The function FarmCPU.Prior ends here\n", "meta": {"hexsha": "e2854c85c1dbc9d57df1ba4a2589ae9b789dca04", "size": 41027, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.FarmCPU.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.FarmCPU.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.FarmCPU.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": 37.7433302668, "max_line_length": 189, "alphanum_fraction": 0.5468350111, "num_tokens": 11847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.1962436102635912}}
{"text": "## Step 3. Model ESM ###\n\n## Creates SDM following method by breinman for mdoels with small numbers of occurrence points\n\n\nsourceProtection\n\nsetwd(\"\")\ndir()\n\nlibrary(sf)\noptions(sf_max.plot=1)\nlibrary(raster)\nlibrary(dismo)\nlibrary(ecospat)\n\n# sirgas for BR (epgs 5880)\n# EPSG:5880\n# SIRGAS 2000 / Brazil Polyconic\n# proj4.defs(\"EPSG:5880\",\"+proj=poly +lat_0=0 +lon_0=-54 +x_0=5000000 +y_0=10000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs\");\n\nsirgas <- \"+proj=poly +lat_0=0 +lon_0=-54 +x_0=5000000 +y_0=10000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs\"\nwgs <- \"+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0\" # as in arcgis\n\nsource(\"https://raw.githubusercontent.com/Cdevenish/R-Material/master/Functions/w.xls.r\")\n\n# Modified from code example for calculating an \"Ensemble of Small Models\" (ESM) in R - Breiman.. supp. materials\n\n## get predictors\n\n# to load in...\nload(\"gis/r_sir/predNames.rdata\") # From s2\n# pred <- brick(\"gis/r_sir/predStack.tif\")\n# names(pred) <- pred.names\n# rm(pred.names)\n# pred\n\nwc.sir <- brick(\"gis/r_sir/wc.tif\")\nnames(wc.sir) <- wc.names\n\ndhi.sir <- brick(\"gis/r_sir/dhi.tif\")\nnames(dhi.sir) <- dhi.names\n\nterr.sir <- brick(\"gis/r_sir/terr.tif\")\nnames(terr.sir) <- terr.names\n\nrm(wc.names, dhi.names, terr.names, pred.names)\n\n## CHOOSE Predictors\n\nnames(terr.sir)\nraster::pairs(terr.sir, maxpixels = 1000)\n\n# BIO1 = Annual Mean Temperature - OUT (same as 5, 6,10,11)\n# BIO2 = Mean Diurnal Range (Mean of monthly (max temp - min temp))\n# BIO3 = Isothermality (BIO2/BIO7) (* 100) - OUT (similar to 4)\n# BIO4 = Temperature Seasonality (standard deviation *100)\n# BIO5 = Max Temperature of Warmest Month \n# BIO6 = Min Temperature of Coldest Month\n# BIO7 = Temperature Annual Range (BIO5-BIO6) - OUT (same as 2)\n# BIO8 = Mean Temperature of Wettest Quarter - OUT\n# BIO9 = Mean Temperature of Driest Quarter - OUT\n# BIO10 = Mean Temperature of Warmest Quarter - OUT (almost same as 11)\n# BIO11 = Mean Temperature of Coldest Quarter - OUT (same as 5,6)\n# BIO12 = Annual Precipitation\n# BIO13 = Precipitation of Wettest Month\n# BIO14 = Precipitation of Driest Month - OUT (same as 15,17)\n# BIO15 = Precipitation Seasonality (Coefficient of Variation)\n# BIO16 = Precipitation of Wettest Quarter - OUT (almost same as 13)\n# BIO17 = Precipitation of Driest Quarter - OUT (almost same as 14,15)\n# BIO18 = Precipitation of Warmest Quarter - OUT\n# BIO19 = Precipitation of Coldest Quarter - OUT\n\npairs(dropLayer(wc.sir, c(8,9,18,19)), maxpixels = 1000)\npairs(dropLayer(wc.sir, c(1,3,7,8,9,10,11,14,16,17,18,19)), maxpixels = 1000)# method= doesn;t work here.. \nraster::pairs\n\npairs(dhi.sir, maxpixels = 1000)\npairs(dropLayer(dhi.sir,c(1,4,7,10:12)), maxpixels = 1000)\ndhi.sir[[c(10,12)]]\n\nplot(dhi.sir[[c(10,12)]])\nplot(dhi.sir[[c(1,3)]])\n\nwriteRaster(dhi.sir[[c(10,12)]], filename = \"gis/r_sir/dhi.tif\", bylayer = T, suffix = 'names')\nwriteRaster(dhi.sir[[c(1,3)]], filename = \"gis/r_sir/dhi.tif\", bylayer = T, suffix = 'names')\n\n## CLIMATE AND LAND COVER MODEL\npred <- stack(dropLayer(wc.sir, c(1,3,7,8,9,10,11,14,16,17,18,19)), terr.sir[[c(\"dem\", \"slope\")]], dhi.sir[[c(1,3)]])\npred\nnames(pred)\n\n## CLIMATE ONLY MODEL\n# pred <- stack(dropLayer(wc.sir, c(1,3,7,8,9,10,11,14,16,17,18,19)), terr.sir[[c(\"dem\", \"slope\")]])\n# pred\n\n\n## All correlations below 70\n\n# check maxent\ndismo::maxent()\n\n## 2. Occurrence points ####\n\n## get aoi and occurrence points (from s1)\nload(\"gis/occ_aoi.rdata\")\nrm(bl.sirgas)\ncty0.sir\n\n## remove ercords for NA in presence records. Which ones are they?\ntmp1 <- extract(pred, pcl.sir)\ncc <- complete.cases(tmp1)\nsum(!cc)\npcl.sir[!cc,] # 7 cases\ntmp1[!cc,]\n\n# st_write(pcl.sir[!cc,], \"gis/s_sir/NA_occ_pts.shp\")\n\n## NA values correpond to some recods from urban ares, eg SAo paolo, curitiba, vitoria, rio de janeiro\npcl <- pcl.sir[cc,]\nrm(cc)\n\n## only for records >= 1990\nhead(pcl)\nsum(pcl$Year >= 1990)\npcl <- pcl[pcl$Year >= 1990,]\n\n## filter per 1 km grid cell\n# source(\"https://raw.githubusercontent.com/Cdevenish/R-Material/master/SDM_functions/filter_pts.r\")\n# pcl.f <- filter_pts(msk.aoi, pcl)\n\n# don't filter... so few points\npcl.f <- pcl\n\n# st_write(pcl, \"gis/s_sir/pcl.shp\")\n# st_write(pcl.f, \"gis/s_sir/pcl_f.shp\")\n\n## 3. background points ####\n\n\n## do background for all\n# same background data for all \nset.seed(99)\nbg <- randomPoints(pred, 10000)\n## check these points are within stck\ntmp <- extract(pred, bg)\nnrow(bg) - sum(complete.cases(tmp))\n\n# remove outside points (why are they outside??)\nbg <- bg[complete.cases(tmp),]\nrm(tmp)\n\n# save(pcl, pcl.f, bg, pred, file = \"LC_CLIM_modelData.rdata\")\n# save(pcl, pcl.f, bg, pred, file = \"CLIM_modelData.rdata\")\nrm(tmp1)\n\n## SAVE model data\n\nsave(pcl, pcl.f, pred, bg, file = \"final_mod_data.rdata\")\nload(\"final_mod_data.rdata\")\n\n### 4. Extract values ####\n\n## presences:\nenv.occ <- extract(pred, pcl.f)\n\n# bakcground env data\nenv.bg <- extract(pred, bg)\n\n# predictors\nenv <- as.data.frame(rbind(env.occ, env.bg))\nhead(env)\n\n# response coding\nresp <- c(rep(1,nrow(env.occ)),rep(0,nrow(env.bg)))\n\n### 5. Explore occ - preds ####\n\n# boxplots of all\npar(mfrow = c(3,4))\nsapply(1:ncol(env), function(x) boxplot(env[,x] ~ resp, main = colnames(env)[x], xlab = \"\", ylab = \"\"))\n\n\n## outliers\npar(mfrow = c(1,1))\nhead(env.occ)\nmDist <- mahalanobis(env.occ, colMeans(env.occ), cov(env.occ))\nplot(mDist)\nind <- which(mDist > 20)\n\n# eg compare with outliers on slope and bio6\n# par(mfrow = c(2,3))\n# colnames(env.occ)\n# plot(env.occ[,\"bio06\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n# plot(env.occ[,\"bio12\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n# plot(env.occ[,\"dem\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n# plot(env.occ[,\"slope\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n# plot(env.occ[,\"ndvi_cum\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n# plot(env.occ[,\"ndvi_sea\"], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1])\n\n\npar(mfrow = c(3,3))\n# par(mfrow = c(3,4))\nsapply(1:ncol(env.occ), function(x) plot(env.occ[,x], col = c(\"black\", \"red\")[(1:nrow(env.occ) %in% ind)+1], \n main = colnames(env.occ)[x], xlab = \"\", ylab = \"\"))\n\nrm(ind, mDist)\npar(mfrow = c(1,1))\nplot(pred)\n\n## check out mvoutlier package.. something similar.\n\nrm(pcl, pcl.sir)\n\n### 6. model starts here ####\n\n# =================================================================================\n# 10 runs using a random 50:50 split of data for training and testing ESM vs Maxent\n# =================================================================================\n\n# eval.test.st <- NULL # for evaluation results of Maxent standard\neval.test.esm <- NULL # for evaluation results of ESM\nw10List <- list()\n\nnr <- 20\n\n# i = 2\n\nset.seed(2066)\n\nfor (i in 1:nr) {\n \n print(paste(\"Run\",i))\n \n # split data for training and testing ()\n # mykfold <- kfold(resp, k=2, by=resp)\n # table(mykfold, resp)\n # \n # sel.train <- mykfold == 1\n # sel.test <- mykfold != 1\n # resp.train <- resp[sel.train]\n # resp.test <- resp[sel.test]\n # \n ## VERSION with all bg points, and only splitting presence for each run.. \n # split data for training and testing ()\n mykfold <- kfold(1:nrow(env.occ), k=4) # Split into 4, so roughly 3/4 for testing, and 11/12 for training\n \n sel.train <- c(mykfold != 1, rep(T, nrow(env.bg)))\n sel.test <- c(mykfold == 1, rep(T, nrow(env.bg)))\n \n resp.train <- resp[sel.train]\n resp.test <- resp[sel.test]\n \n table(resp.train)\n table(resp.test)\n \n # standard Maxent\n # st <- maxent(x=env[sel.train,], p=resp[sel.train], args=c(\"-P\",\"nohinge\", \"nothreshold\", \"noproduct\")) \n # pred.st <- predict(st, env) \n # auc.test <- evaluate(p=pred.st[sel.test ][resp.test ==1], a=pred.st[sel.test ][resp.test ==0])@auc\n # boyce.test <- ecospat.boyce(pred.st[sel.test], pred.st[sel.test][resp.test==1], PEplot=F)# $Pearson.cor\n # eval.test.st <- rbind(eval.test.st, cbind(auc=auc.test,boyce=boyce.test))\n # \n # # build ESM as weighted average of bivariate Maxent models\n weight.vec <- vector() # vector with weights of single bivariate models\n pred.biva.sum <- rep(0, length(resp)) # for ensemble prediction of bivariate models \n #pred.biva.sum.stck <- rep(0, ncell(stack))\n \n # m = 2; n = 3\n \n weight.vec.m <- matrix(NA, nrow = (dim(env)[2]-1), ncol = dim(env)[2]) # col is no of predictors\n \n for(m in 1:(dim(env)[2]-1)){ # build all bivariate predictor combinations\n for(n in (m+1):dim(env)[2]){\n \n # calibrate bivariate maxent model\n me.biva <- maxent(x=env[sel.train,c(m,n)], p=resp.train, args=c(\"-P\",\"nohinge\", \"nothreshold\", \"noproduct\")) \n \n # prediction\n pred.biva <- predict(me.biva, env)\n \n ## predict across whole raster\n #pred.biva.stck <- predict(me.biva, values(stack))\n \n # evaluate bivariate model and calculate its weight for ensemble prediction\n eval.train.biva <- evaluate(p=pred.biva[sel.train][resp.train==1], a=pred.biva[sel.train][resp.train==0])\n weight <- eval.train.biva@auc*2-1 # use Somers' D as weighting factor\n if(weight < 0) {weight <- 0}\n weight.vec <- c(weight.vec, weight)\n \n # collect all weights to do an average for final model weighting\n weight.vec.m[m,n] <- weight\n \n # build weighted sum of bivariate predictions\n pred.biva.sum <- pred.biva.sum + (pred.biva * weight)\n #pred.biva.sum.stck <- pred.biva.sum.stck + (pred.biva.stck * weight)\n \n }\n }\n \n w10List[[i]] <- weight.vec.m\n \n # calculate ESM prediction\n pred.esm <- pred.biva.sum/sum(weight.vec)\n # pred.esm.stck <- pred.biva.sum.stck/sum(weight.vec)\n \n # evaluate ESM\n auc.test <- evaluate(p=pred.esm[sel.test ][resp.test ==1], a=pred.esm[sel.test][resp.test == 0])@auc\n # ecospat.boyce(pred.esm[sel.test],pred.esm[sel.test][resp.test==1], PEplot=T)\n boyce.test <- ecospat.boyce(fit = pred.esm[sel.test],obs = pred.esm[sel.test][resp.test==1], PEplot=F)$Spearman.cor \n eval.test.esm <- rbind(eval.test.esm , cbind(auc=auc.test,boyce=boyce.test))\n #eval.test.esm <- rbind(eval.test.esm , cbind(auc=auc.test))\n #eval.test.esm <- c(eval.test.esm , auc.test)\n \n} # end of nr runs of ESM\n\neval.test.esm\napply(eval.test.esm, 2, mean)\n\n\n# save this below\n# eval.test.esm\n\n# weights for 10 runs of all bivariate combinations\n\n# save this below\n# w10List\n\n\n# get average weight for each bivariate combination\n#w.array <- do.call(abind, w10List)\nw.array <- array(as.numeric(unlist(w10List)), dim=c(dim(env)[2]-1, dim(env)[2], nr)) # r, c, h\nw.mn <- apply(w.array, c(1,2), mean)#*2-1 # convert mean AUC to somer's D\nw.mn\n\n# counter\nmn <- matrix(1:(nrow(w.mn)*ncol(w.mn)), nrow= nrow(w.mn), ncol = ncol(w.mn), byrow = T)\n\n### do full model\npred.biva.sum.full <- rep(0, ncell(pred))\n\n# m = 1; n = 2\n\nfor(m in 1:(dim(env)[2]-1)){ # build all bivariate predictor combinations\n for(n in (m+1):dim(env)[2]){\n \n # print counter\n print(paste(\"bivariate combination:\", mn[m,n]))\n \n # calibrate bivariate maxent model\n me.biva.full <- maxent(x=env[,c(m,n)], p=resp, args=c(\"-P\",\"nohinge\", \"nothreshold\", \"noproduct\"))\n \n # prediction\n pred.biva.full <- dismo::predict(me.biva.full, values(pred))\n # throwing error in if (class(x) == \"data.frame\") \n ## as it is \"matrix\" \"array\"... it takes false, so it's ok, ie not a raster \n #\n \n # build weighted sum of bivariate predictions\n pred.biva.sum.full <- pred.biva.sum.full + (pred.biva.full * w.mn[m,n])\n #pred.biva.sum.stck <- pred.biva.sum.stck + (pred.biva.stck * weight)\n \n }\n}\n\n# calculate ESM prediction\n# Weighting for full model is \npred.esm.full <- pred.biva.sum.full/sum(w.mn, na.rm = T)\n\nmodRes <- raster(pred)\nmodRes[] <- pred.esm.full\nplot(modRes)\n# dir.create(\"gis/r_sir/models\")\n\nwriteRaster(modRes, filename = \"gis/r_sir/models/modRes_habt.tif\", datatype = \"FLT4S\")\n# save this below\n# modRes - is species prediction\n\n# save(eval.test.esm, w10List, modRes, file = \"mod_res_habt.rdata\")\n\nload(\"mod_res_habt.rdata\")\n# habt only split for testing/training on presence data (all bg used to train), climate (+ dem) + veg indices\n# with k = 3,\n# and 10 runs. \n\n\n## Get threshold\npresVals <- raster::extract(modRes, pcl.f)\nsort(presVals)\n\nt.pres <- quantile(presVals, probs = 0.1, na.rm = T)\nbin.pres <- reclassify(modRes, rcl = c(0, t.pres, 0, t.pres, 1, 1))\n\n## do 3x3 filter\nbin.pres.mf <- focal(bin.pres, w = matrix(1, nrow=3, ncol=3), fun = modal)\nsave(bin.pres, bin.pres.mf, file= \"bin_mod.rdata\")\nwriteRaster(bin.pres, filename = \"gis/r_sir/models/modRes_habt_bin.tif\", datatype = \"INT1U\", overwrite = T)\nwriteRaster(bin.pres.mf, filename = \"gis/r_sir/models/modRes_habt_bin_mf.tif\", datatype = \"INT1U\", overwrite = T)\n\nbin.pres\n# area of presence is \nsum(values(bin.pres) == 1, na.rm = T) # 181546 km\nsum(values(bin.pres.mf) == 1, na.rm = T) # 174489 km\n\n\neval.test.esm\n\nse <- function(x) sd(x)/length(x)\napply(eval.test.esm, 2, mean)\napply(eval.test.esm, 2, se)\napply(eval.test.esm, 2, sd)\n\n## get absences within bin.pres (rom s1 occ)\nload(\"ebirdAbsences_in_aoi.rdata\")\n\nabsence.bin <- extract(bin.pres.mf, ebird.aoi)\ntable(absence.bin, useNA = \"always\")\n\n## how many cells do they overlap?\nabsence.count <- raster::extract(bin.pres, ebird.aoi, cellnumbers = TRUE)\nlength(unique(absence.count)) # 26232\n\n# as proportion of modelled range\n26232/174489 # ~ 15%\n\nebird.abs.bin <- ebird.aoi[absence.bin == 1 & !is.na(absence.bin),]\nst_write(ebird.abs.bin, \"gis/s_sir/ebird_abs_bin.shp\", delete_layer = T)\n\nbarplot(table(ebird.abs.bin$year), las = 2)\n\ntable(cut(ebird.abs.bin$year, breaks = c(0, 1990, 2000, 2010, 2020)), useNA = \"always\")\n# (0,1.99e+03] (1.99e+03,2e+03] (2e+03,2.01e+03] (2.01e+03,2.02e+03] <NA>\n# 96 337 1619 17972 0\n96 + 337 + 1619+17972\n\n337+1619+17972\nsum(ebird.abs.bin$year >1990) \n# 19928 \n\nsum(ebird.abs.bin$year >=1990) \n# 19961 including 1990\n\n# square bracket includes value, ie 109 up to and inlcuing 1990\n\n# cbind(1:10, cut(1:10, breaks = c(0,5,10)))\n\n", "meta": {"hexsha": "97cad0530d5ac1b152384d88e5d00dc28b7cdc82", "size": 14130, "ext": "r", "lang": "R", "max_stars_repo_path": "code/s3_model_ESM_v3.r", "max_stars_repo_name": "Cdevenish/Paraclaravis_project", "max_stars_repo_head_hexsha": "c9c869de39090864775f62feef801957f2ca6249", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/s3_model_ESM_v3.r", "max_issues_repo_name": "Cdevenish/Paraclaravis_project", "max_issues_repo_head_hexsha": "c9c869de39090864775f62feef801957f2ca6249", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/s3_model_ESM_v3.r", "max_forks_repo_name": "Cdevenish/Paraclaravis_project", "max_forks_repo_head_hexsha": "c9c869de39090864775f62feef801957f2ca6249", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.610738255, "max_line_length": 140, "alphanum_fraction": 0.6433121019, "num_tokens": 4751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.19395960471703508}}
{"text": "#' dmulti_ddirch_forecast.r\n#' NOTE: this assumes the predictor \"map\" is mean annual precipitation in mm, and natural log transforms.\n#'\n#' @param mod #model output from ddirch fitting function.\n#' @param cov_mu #dataframe of site-level covariates. Must include all covariates used in models.\n#' @param cov_sd #associated sd's if present.\n#' @param glob.covs #global level covariates and standard deviations to fill in missing data.\n#' @param n.samp #number of times to sample covariates/parameters for forecast. Default 1000.\n#' @param zero_parameter_uncertainty #turns off drawing from parameter distributions, keeps parameters fixed at means.\n#' @param zero_predictor_uncertainty #turns off drawing from covariate distributions, keeps covaraites fixed at means.\n#' @param zero_process_uncertainty #turns off process draw from rdirichlet. Basically just makes predictive interval = credible interval.\n#'\n#' @return #returns a list of forecasts (mean, 95% CI, 95% PI) same length as model list.\n#' @export\n#'\n#' @examples\nsource('NEFI_functions/precision_matrix_match.r')\ndmulti_ddirch_forecast <- function(mod, seq.depth = 1000, cov_mu, names, cov_sd = NA, n.samp = 1000,\n zero_parameter_uncertainty = F,\n zero_covariate_uncertainty = F,\n zero_process_uncertainty = F,\n make_it_work = F){\n #run some tests.----\n if(is.list(mod) == F){\n stop(\"Your model object isn't a list. It really needs to be.\")\n }\n \n #grab the model out of list\n j.mod <- mod$jags_model #separate out the jags model.\n \n #### organize your covariates and covariate standard deviations.----\n preds <- as.character(mod$species_parameter_output$other$predictor)\n #grab covariates that were predictors.\n covs <- cov_mu[,colnames(cov_mu) %in% preds]\n #add intercept.\n covs <- cbind(rep(1,nrow(covs)), covs)\n colnames(covs)[1] <- 'intercept'\n #grab uncertainties in sd, if present.\n if(is.data.frame(cov_sd)){\n cov.sd <- precision_matrix_match(covs, cov_sd)\n }\n \n #re-order to match predictor order. Conditional otherwise it breaks the intercept only case.\n if(ncol(covs) > 1){\n covs <- data.frame(covs[,preds])\n if(is.data.frame(cov_sd)){\n cov.sd <- data.frame(cov.sd[,preds]) \n }\n }\n \n #### Sample parameter and covariate space, make predictions.----\n pred.out <- list()\n cred.out <- list()\n for(j in 1:n.samp){\n #Sample parameters from mcmc output.----\n mcmc <- do.call(rbind,j.mod$mcmc)\n mcmc.sample <- mcmc[sample(nrow(mcmc),1),]\n #if we are fixing parameter uncertainty to zero, do something different.----\n if(zero_parameter_uncertainty == T){\n mcmc.sample <- colMeans(mcmc)\n }\n #grab x.m values, convert to matrix.\n x.m <- mcmc.sample[grep(\"^x\\\\.m\\\\[\", names(mcmc.sample))]\n x.m <- matrix(x.m, nrow = ncol(covs), ncol = length(x.m)/ncol(covs))\n \n #Sample from covariate distributions.----\n #fix covariate uncertainty? Do this by making sd zero.\n if(zero_covariate_uncertainty==T){\n cov_sd <- NA\n }\n \n #only sample if you supplied uncertainties.\n if(is.data.frame(cov_sd)){\n now.cov <- matrix(NA, ncol = ncol(covs), nrow = nrow(covs))\n for(k in 1:ncol(covs)){now.cov[,k] <- rnorm(nrow(covs),covs[,k], cov.sd[,k])}\n colnames(now.cov) <- preds\n now.cov <- data.frame(now.cov)\n #log transform map values if this is one of your covariates, put covariates back in matrix form.\n #anti-logit relEM, multiply by 100 if this is one of your covariates.\n if('relEM' %in% colnames(now.cov)){now.cov$relEM <- boot::inv.logit(now.cov$relEM) * 100}\n if('map' %in% colnames(now.cov)){now.cov$map <- log(now.cov$map)}\n now.cov <- as.matrix(now.cov)\n }\n \n #If you did not supply covariate uncertainties then now.cov is just covs.\n if(!is.data.frame(cov_sd)){\n now.cov <- as.matrix(covs)\n colnames(now.cov) <- preds\n now.cov <- data.frame(now.cov)\n #log transform map values if this is one of your covariates, put covariates back in matrix form.\n #anti-logit relEM, multiply by 100 if this is one of your covariates.\n if('relEM' %in% colnames(now.cov)){now.cov$relEM <- boot::inv.logit(now.cov$relEM) * 100}\n if('map' %in% colnames(now.cov)){now.cov$map <- log(now.cov$map)}\n now.cov <- as.matrix(now.cov)\n }\n \n #Combine covariates and parameters to make a prediction.----\n pred.x.m <- matrix(NA, ncol=ncol(x.m), nrow = nrow(covs))\n for(k in 1:ncol(x.m)){pred.x.m[,k] <- exp(now.cov %*% x.m[,k])}\n #Sometimes parameter draws generate infinities for groups that didnt fit well. Force it?\n if(make_it_work == T){\n pred.x.m[pred.x.m == Inf] <- max(pred.x.m < Inf)\n }\n #get mean prediction and then draw from multinomial-dirichlet distribution.\n cred.out[[j]] <- pred.x.m / rowSums(pred.x.m)\n #prediction interval passes through Dirichlet and multinomial processes.\n dirichlet_out <- DirichletReg::rdirichlet(nrow(pred.x.m), pred.x.m + 0.1)\n multinom_out <- list()\n for(i in 1:nrow(dirichlet_out)){\n multinom_out[[i]] <- t(stats::rmultinom(1,seq.depth,dirichlet_out[i,]))\n }\n multinom_out <- do.call(rbind, multinom_out)\n pred.out[[j]] <- multinom_out/rowSums(multinom_out)\n #Turn off process uncertainty? If so pred.out is just cred.out.\n if(zero_process_uncertainty == T){\n pred.out[[j]] <- cred.out[[j]]\n }\n }\n \n #Summarize prediction mean and confidence intervals.----\n pred.mean <- apply(simplify2array(cred.out), 1:2, mean)\n pred.ci.0.025 <- apply(simplify2array(cred.out), 1:2, quantile, probs = c(0.025))\n pred.ci.0.975 <- apply(simplify2array(cred.out), 1:2, quantile, probs = c(0.975))\n pred.pi.0.025 <- apply(simplify2array(pred.out), 1:2, quantile, probs = c(0.025))\n pred.pi.0.975 <- apply(simplify2array(pred.out), 1:2, quantile, probs = c(0.975))\n \n #batch into list, column names are group names, row names are siteIDs.\n output <- list(pred.mean, pred.ci.0.025, pred.ci.0.975, pred.pi.0.025, pred.pi.0.975)\n for(k in 1:length(output)){\n colnames(output[[k]]) <- names(mod$species_parameter_output)\n rownames(output[[k]]) <- names\n }\n names(output) <- c('mean','ci_0.025','ci_0.975','pi_0.025','pi_0.975')\n \n #return output.----\n return(output)\n} #end function.----\n", "meta": {"hexsha": "284e172aa1706d40aeb1b9360bd97ee0312b3c6a", "size": 6526, "ext": "r", "lang": "R", "max_stars_repo_path": "NEFI_functions/dmulti_ddirch_forecast.r", "max_stars_repo_name": "colinaverill/NEFI_microbe", "max_stars_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-13T17:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T17:13:54.000Z", "max_issues_repo_path": "NEFI_functions/dmulti_ddirch_forecast.r", "max_issues_repo_name": "colinaverill/NEFI_microbe", "max_issues_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NEFI_functions/dmulti_ddirch_forecast.r", "max_forks_repo_name": "colinaverill/NEFI_microbe", "max_forks_repo_head_hexsha": "e59ddef4aafcefdf0aff61765a8684859daad6e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-02-21T20:26:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T16:09:44.000Z", "avg_line_length": 47.2898550725, "max_line_length": 139, "alphanum_fraction": 0.6420471958, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.18297633540340252}}