{"text": "#\n# Script to implement MeTHODICAL for CCNX\n#\n#\n#ssh user@10.0.1.131\n# 10.0.1.123\n# 10.10.10.30\n\n# rngBen <- 2:2\n# rngCost <- 2:4\n# myRNGBEN <- 1:2\n# myRNGCOST <- 3:5\n# myWrngBEN <- 1:1\n# myWrngCost <- 2:4\n\n\n\naux_step03_Weight_of_Norm_matrix <-function(inMatrix, inWeight){\n \n outMat <- inMatrix\n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n #iMcalc2 <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=TRUE)\n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n \n nC <- dim(iMcalc)[2] # Convert weigths into a matrix in order to perform Mult \n aMmul <- matrix(rep(inWeight, times=nrows), ncol=nC, byrow=TRUE)\n \n auxCalc <- iMcalc * aMmul\n \n outMat[,2:ncols]<-auxCalc\n \n return(outMat)\n}\n\nFMC_WD <- function(mBen, mCost, wBen, wCost, namesList, name){\n\n mBen <- data.frame(matrix(unlist(mBen), ncol=2, byrow=F))\n colnames(mBen) <- c(\"id\", \"pop\")\n\n mCost <- data.frame(matrix(unlist(mCost), ncol=4, byrow=F))\n colnames(mCost) <- c(\"id\", \"ratio\", \"size\", \"pop\")\n\n namesList <- data.frame(matrix(unlist(namesList), ncol=2, byrow=F))\n colnames(namesList) <- c(\"id\", \"prefix\")\n\n save(mBen, mCost, wBen, wCost, namesList, file=name)\n}\n\nFMC_LD <- function(dataFile, algorithm){\n load(dataFile)\n out <- FMC_MADM(mBen, mCost, wBen, wCost, algorithm)\n\n dfNames <- data.frame(matrix(unlist(namesList), ncol=2, byrow=F))\n colnames(dfNames) <- c(\"id\", \"prefix\")\n\n dfOut <- data.frame(matrix(unlist(out), ncol=2, byrow=F))\n colnames(dfOut) <- c(\"id\", \"score\")\n\n output <- merge(dfNames, dfOut, by=\"id\")\n output <- output[2:3]\n output <- output[order(output$score),]\n return(output)\n}\n\nFMC_MADM <- function(mBen, mCost, wBen, wCost, algorithm=1){\n\n source(\"METH_related.r\")\n\n #save(file=\"./input_data_.data\", list=ls())\n\n auxBen_col <- dim(mBen)[2]\n auxCost_col <- dim(mCost)[2]\n\n if (dim(mBen)[1] < 1 || dim(mCost)[1] < 1){\n return(-2)\n }\n else if (dim(mBen)[1] < 2 || dim(mCost)[1] < 2){\n return(-1)\n }\n\n myRNGBEN <- seq(1, by=1, to=auxBen_col)\n rngBen <- seq(1, by=1, to=auxBen_col)\n\n #DANGER\n myRNGCOST <- seq(auxBen_col+1, by=1, to=auxBen_col + auxCost_col -1)\n rngCosts <- seq(2, by=1, to=auxCost_col)\n\n myWrngBEN <- seq(1, by=1, to=length(wBen))\n myWrngCost <- seq(length(wBen) +1, by=1, to=length(wBen) + length(wCost))\n\n if (is.list(mBen)){\n mBen <- matrix(unlist(mBen), ncol=auxBen_col, byrow=FALSE)\n }\n\n if (is.list(mCost)){\n mCost <- matrix(unlist(mCost), ncol=auxCost_col, byrow=FALSE)\n }\n\n if (algorithm == 1){\n \n iM <- mBen\n iM <- cbind(iM, mCost[,rngCosts])\n\n iVecWei <- wBen\n iVecWei <- append(iVecWei, wCost)\n\n aux_out <- METH_METHODICALv10(iM, iVecWei, rngBEN=myRNGBEN, rngCost=myRNGCOST, rngWBen=myWrngBEN, rngWCost=myWrngCost)\n }\n else if (algorithm == 2){\n aux_out <- METH_runTOPSIS(mBen, mCost, wBen, wCost)\n }\n else if (algorithm == 3){\n aux_out <- METH_runDiA(mBen, mCost, wBen, wCost)\n }\n else if (algorithm == 4){\n aux_out <- METH_runNMMD(mBen, mCost, wBen, wCost)\n }\n\n return(aux_out)\n}\n\n\n\nMETH_METHODICALv9 <-function(mBen, mCost, weiBen_prefMultihoming, weiCost_prefMultihoming){\n \n auxBen_col <- dim(mBen)[2] - 1\n auxCost_col <- dim(mCost)[2] - 1\n\n myRNGBEN <- seq(1, by=1, to=auxBen_col)\n rngBen <- seq(1, by=1, to=auxBen_col)\n # DANGER\n myRNGCOST <- seq(auxBen_col+1, by=1, to=auxBen_col + auxCost_col - 1 )\n rngCosts <- seq(2, by=1, to=auxCost_col)\n \n# print(\"BEN\")\n# print(auxBen_col)\n# print(myRNGBEN)\n# #print(rngBen)\n# \n# print(\"COST\")\n# print(auxCost_col)\n# print(myRNGCOST)\n# print(rngCosts)\n \n myWrngBEN <- seq(1, by=1, to=length(weiBen_prefMultihoming) )\n myWrngCost <- seq(length(weiBen_prefMultihoming) +1, by=1, to= length(weiBen_prefMultihoming) + length(weiCost_prefMultihoming) )\n \n# print(\"W BEN\")\n# print(myWrngBEN)\n# print(\"W COST\")\n# print(myWrngCost)\n \n iM <-mBen\n iM <- cbind(iM , mCost[,rngCosts])\n \n #str(iM)\n #print(\"#R\")\n #print(iM)\n \n iVecWei <- weiBen_prefMultihoming\n iVecWei <- append(iVecWei, weiCost_prefMultihoming)\n \n aux_res<-METH_METHODICALv10(iM, iVecWei, rngBEN=myRNGBEN, rngCost=myRNGCOST, rngWBen=myWrngBEN, rngWCost=myWrngCost )\n \n #str(aux_res)\n #print(\"#R\")\n #print(aux_res)\n \n return (aux_res)\n}\n\n\n\n#\n#\n# Code for Version 10 uses Variance instead of standard deviation\n# \nMETH_METHODICALv10 <- function(iM, iVecWei, rngBEN=1:5, rngCost=6, rngWBen=1:4, rngWCost=5, MeTHBeta=0.5, MeTHOmega=0.5, itry=1 ){\n \n \n MINSUM_TOPSIS <- 1e-99 # To avoid divisions by zero in normalization\n \n mBen_Criteria <- iM[,rngBEN]\n mCost_Criteria <- iM[,c(1,rngCost)] # Put also the id in the matrix of costs.\n \n vBen_weight <- iVecWei[rngWBen]\n vCost_weight <- iVecWei[rngWCost]\n \n applyWeight <- TRUE\n applyNorm <- TRUE\n \n #norm_method <- \"minmax\"\n norm_method <- \"vector\"\n #norm_method <- \"max\"\n #norm_method <- \"sum\"\n \n fAuxPos <- function(iN){\n \n if (iN < 0) {\n iN <- iN * (-1)\n }\n return(iN)\n }\n \n fAux_Positive_Dif <- function(i1, i2){\n adif <- (i1 - i2)\n #if (adif < 0) {\n # adif <- adif * (-1)\n #}\n adif<-fAuxPos(adif)\n return(adif)\n }\n \n # \n # Determine RScore\n #\n calcRscorev10 <- function(inM, alpha=0.5, omega=0.5){\n nrow <- dim(inM)[1]\n outMat <- inM\n outMat <- outMat[,-3]\n \n for (nR in 1:nrow){\n #outMat[nR,2] <- sqrt(alpha*(inM[nR,2]) + omega*(inM[nR,3]) ) # no square\n outMat[nR,2] <- sqrt((inM[nR,2]) + (inM[nR,3]) ) # no square\n outMat[nR,2] <- outMat[nR,2] #+ auxSD\n }\n \n return(outMat)\n }\n \n #\n # It can't be leads to zeros.\n #\n calcRscorev10b_asTOPSIS <- function(inM, alpha=0.5, omega=0.5){\n nrow <- dim(inM)[1]\n outMat <- inM\n outMat <- outMat[,-3]\n \n for (nR in 1:nrow){\n #outMat[nR,2] <- sqrt(alpha*(inM[nR,2]) + omega*(inM[nR,3]) ) # no square\n outMat[nR,2] <- inM[nR,3] / inM[nR,3] + inM[nR,2]\n outMat[nR,2] <- outMat[nR,2] #+ auxSD\n }\n \n return(outMat)\n }\n \n \n # I think this method produces a lot of zeros.\n aux_step02_MinMax_Normalization<- function(inMatrix, iTypeBen=TRUE, iRangeNorm=1){\n \n #internal function to help in normalization\n fAuxLinearBEN <- function(i, iMax, iMin){\n aa <- iMax - iMin\n if (aa != 0){\n aSu <- ( (i - iMin) / (iMax - iMin) ) \n }else{\n aSu <- 0\n }\n return(aSu)\n }\n \n fAuxLinearCOST <- function(i, iMax, iMin){\n aa <- iMax - iMin\n if (aa != 0){\n aSu <- ( (iMax - i) / (iMax - iMin) ) \n }else{\n aSu <- 0\n }\n return(aSu)\n }\n \n \n outMat <- inMatrix\n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n \n #Apply Sum by col\n MaxPer_Row <- apply(iMcalc, 2, max)\n MinPer_Row <- apply(iMcalc, 2, min)\n \n nC <- dim(iMcalc)[2]\n nR <- dim(iMcalc)[1]\n aMMax <- matrix(rep(MaxPer_Row, times=nR), ncol=nC, byrow=TRUE)\n aMMin <- matrix(rep(MinPer_Row, times=nR), ncol=nC, byrow=TRUE)\n \n if (iTypeBen==TRUE){\n auxCalc <- mapply(FUN=fAuxLinearBEN, iMcalc, aMMax, aMMin)\n }else{\n auxCalc <- mapply(FUN=fAuxLinearCOST, iMcalc, aMMax, aMMin)\n }\n \n auxCalc <- auxCalc * iRangeNorm\n \n auxCalc <- matrix(auxCalc, nrow=nR, ncol=nC, byrow=FALSE)\n #nC <- dim(iMcalc)[2]\n #aMSum <- matrix(rep(auxSum, times=nrows), ncol=nC, byrow=TRUE)\n #auxCalc <- iMcalc / sqrt(aMSum)\n \n outMat[,2:ncols]<-auxCalc\n return(outMat)\n \n }\n \n \n aux_step02_VEC_Normalization <- function(inMatrix){\n \n #internal function to help in normalization\n fSum <- function(i){\n sumrow <- MINSUM_TOPSIS\n aSu <- sum(i^2) + sumrow\n return(aSu)\n }\n \n outMat <- inMatrix\n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n #print(iMcalc)\n \n #Apply Sum by col\n auxSum <- apply(iMcalc, 2, FUN=fSum)\n #print(auxSum)\n \n nC <- dim(iMcalc)[2]\n aMSum <- matrix(rep(auxSum, times=nrows), ncol=nC, byrow=TRUE)\n auxCalc <- iMcalc / sqrt(aMSum)\n #print(auxCalc)\n \n outMat[,2:ncols]<-auxCalc\n return(outMat)\n \n }\n \n\n \n #\n # The opposite of minMax leads to a lot of one's if criterion is maximized.\n #\n aux_step02_Max_Normalization<- function(inMatrix, iTypeBen=TRUE, iRangeNorm=1){\n \n #internal function to help in normalization\n fAuxLinearBEN <- function(i, iMax){\n aa <- iMax \n if (aa != 0){\n aSu <- ( i / iMax ) \n }else{\n aSu <- 0\n }\n return(aSu)\n }\n \n fAuxLinearCOST <- function(i, iMax){\n aa <- iMax \n if (aa != 0){\n aSu <- 1 - ( i / iMax ) \n }else{\n aSu <- 0\n }\n return(aSu)\n }\n \n \n outMat <- inMatrix\n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n \n #Apply Sum by col\n MaxPer_Row <- apply(iMcalc, 2, max)\n #MinPer_Row <- apply(iMcalc, 2, min)\n \n nC <- dim(iMcalc)[2]\n nR <- dim(iMcalc)[1]\n aMMax <- matrix(rep(MaxPer_Row, times=nR), ncol=nC, byrow=TRUE)\n #aMMin <- matrix(rep(MinPer_Row, times=nR), ncol=nC, byrow=TRUE)\n if (iTypeBen==TRUE){\n auxCalc <- mapply(FUN=fAuxLinearBEN, iMcalc, aMMax)\n }else{\n auxCalc <- mapply(FUN=fAuxLinearCOST, iMcalc, aMMax)\n }\n \n auxCalc <- auxCalc * iRangeNorm\n \n auxCalc <- matrix(auxCalc, nrow=nR, ncol=nC, byrow=FALSE)\n #nC <- dim(iMcalc)[2]\n #aMSum <- matrix(rep(auxSum, times=nrows), ncol=nC, byrow=TRUE)\n #auxCalc <- iMcalc / sqrt(aMSum)\n \n outMat[,2:ncols]<-auxCalc\n return(outMat)\n \n }\n \n \n aux_step02_SUM_Normalization <- function(inMatrix){\n \n #internal function to help in normalization\n fSum <- function(i){\n sumrow <- MINSUM_TOPSIS\n aSu <- sum(i) + sumrow\n return(aSu)\n }\n \n outMat <- inMatrix\n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n #print(iMcalc)\n \n #Apply Sum by col\n auxSum <- apply(iMcalc, 2, FUN=fSum)\n #print(auxSum)\n \n nC <- dim(iMcalc)[2]\n aMSum <- matrix(rep(auxSum, times=nrows), ncol=nC, byrow=TRUE)\n auxCalc <- iMcalc / aMSum\n #print(auxCalc)\n \n outMat[,2:ncols]<-auxCalc\n return(outMat)\n \n }\n \n calcDist_METHODICALv10b<- function(inMatrix, inIdeal, inMin, inMax, BenCriteria=TRUE, ignFirstCol=TRUE){\n \n ncols<-dim(inMatrix)[2]\n nrows<-dim(inMatrix)[1]\n \n if (ignFirstCol){\n iMcalc <- matrix(inMatrix[,2:ncols], nrow=nrows, ncol=ncols-1, byrow=FALSE)\n \n }else{\n iMcalc <- inMatrix\n \n }\n \n fCalcAux <- function(iMcalc){\n auxMean <- mean(iMcalc) \n auxSD <- var(iMcalc) # MAIN difference in MeTH_v10\n #auxSD <- sd(iMcalc) # MAIN difference in MeTH_v10\n \n if (BENC){\n SDMean <- auxMean + auxSD \n }else{\n SDMean <- auxMean - auxSD\n }\n return(SDMean)\n }\n \n outMat <- matrix(ncol=2,nrow=nrows)\n outMat[,1] <- inMatrix[,1]\n \n nColMat <- dim(iMcalc)[2]\n ncolIdeal <- dim(inIdeal)[2]\n \n #}\n # Just to be sure\n stopifnot(nColMat == ncolIdeal)\n \n BENC <<- BenCriteria\n \n SDMean <- apply(iMcalc, 2, FUN=fCalcAux)\n \n mSDMean <- matrix(SDMean, byrow=TRUE, nrow=dim(iMcalc)[1], ncol=dim(iMcalc)[2])\n mIdeal <- matrix(inIdeal, byrow=TRUE, nrow=dim(iMcalc)[1], ncol=dim(iMcalc)[2])\n mMax <- matrix(inMax, byrow=TRUE, nrow=dim(iMcalc)[1], ncol=dim(iMcalc)[2])\n mMin <- matrix(inMin, byrow=TRUE, nrow=dim(iMcalc)[1], ncol=dim(iMcalc)[2])\n \n #Perform Operation\n #auxTETA <- -1 * (mSDMean - iMcalc)\n #Yaux <- (iMcalc - mIdeal)^2\n #auxDiffDeno <- (mMax - mMin)^2 #originally without sqrt\n #auxDeno <- (auxTETA + auxDiffDeno)\n \n \n #auxTETA <- -1 * (mSDMean - iMcalc)\n #Yaux <- (iMcalc - mIdeal)^2 + (mIdeal - mSDMean)^2\n #auxDiffDeno <- (mMax - mMin)^2 #originally without sqrt\n #auxDeno <- (auxDiffDeno - auxTETA)\n \n Yaux <- (iMcalc - mIdeal)^2 \n auxDeno <- abs(mIdeal - mSDMean) + 0.001\n \n \n auxCalcM <- (Yaux / auxDeno )\n auxCalcM[is.na(auxCalcM)]<-0\n \n auxCalc <- apply(auxCalcM, 1, sum)\n \n outMat[,2] <- auxCalc\n \n return(outMat) \n }\n \n \n \n ncolMB <- dim(mBen_Criteria)[2]\n MeTHTOPsisBenefits <- as.matrix(mBen_Criteria )\n \n ncolMC <- dim(mCost_Criteria)[2]\n MeTHTOPsisCosts <- as.matrix(mCost_Criteria )\n \n MeTHWeiBenTOP <- vBen_weight\n MeTHWeiCostTOP <- vCost_weight\n \n #\n # Step 01\n #\n \n # Needs libNormalization\n # apply Normalization\n if (applyNorm==TRUE){\n \n #ISSUE\n if (norm_method ==\"minmax\"){\n MeTHTOPsisBenefits <- aux_step02_MinMax_Normalization(MeTHTOPsisBenefits, iTypeBen=TRUE)\n MeTHTOPsisCosts <- aux_step02_MinMax_Normalization(MeTHTOPsisCosts, iTypeBen=FALSE)\n }\n \n if (norm_method ==\"vector\"){\n MeTHTOPsisBenefits <- aux_step02_VEC_Normalization(MeTHTOPsisBenefits)\n MeTHTOPsisCosts <- aux_step02_VEC_Normalization(MeTHTOPsisCosts)\n }\n \n if (norm_method ==\"sum\"){\n MeTHTOPsisBenefits <- aux_step02_SUM_Normalization(MeTHTOPsisBenefits)\n MeTHTOPsisCosts <- aux_step02_SUM_Normalization(MeTHTOPsisCosts)\n }\n \n if (norm_method ==\"max\"){\n MeTHTOPsisBenefits <- aux_step02_Max_Normalization(MeTHTOPsisBenefits, iTypeBen=TRUE)\n MeTHTOPsisCosts <- aux_step02_Max_Normalization(MeTHTOPsisCosts, iTypeBen=FALSE)\n }\n \n }\n \n \n \n #Apply Weighting\n if (applyWeight==TRUE){\n MeTHTOPsisBenefits <-aux_step03_Weight_of_Norm_matrix(MeTHTOPsisBenefits, MeTHWeiBenTOP) \n MeTHTOPsisCosts <-aux_step03_Weight_of_Norm_matrix(MeTHTOPsisCosts, MeTHWeiCostTOP) \n }\n \n \n #\n # Step 02\n #\n #Retrieve Maximum and Minimum\n rngBBen <- seq(from=2, by=1, to=dim(MeTHTOPsisBenefits)[2])\n rngCCost <- seq(from=2, by=1, to=dim(MeTHTOPsisCosts)[2])\n \n \n MeTHMaxIdeal<- as.numeric(apply(as.matrix(MeTHTOPsisBenefits[,rngBBen]), 2, max))\n MeTHBenMin <- as.numeric(apply(as.matrix(MeTHTOPsisBenefits[,rngBBen]), 2, min))\n MeTHBenMax <- MeTHMaxIdeal\n #\n MeTHMinIdeal<- as.numeric(apply(as.matrix(MeTHTOPsisCosts[,rngCCost]), 2, min))\n MeTHCostMax <- as.numeric(apply(as.matrix(MeTHTOPsisCosts[,rngCCost]), 2, max))\n MeTHCostMin <- MeTHMinIdeal\n \n \n\n MeTHBenDist<-calcDist_METHODICALv10b(MeTHTOPsisBenefits,MeTHMaxIdeal, MeTHBenMin, MeTHBenMax, BenCriteria=TRUE)\n MeTHCostDist<-calcDist_METHODICALv10b(MeTHTOPsisCosts,MeTHMinIdeal, MeTHCostMin, MeTHCostMax, BenCriteria=FALSE)\n \n \n \n #\n # Step 04\n #\n inMatForR <- MeTHBenDist\n inMatForR <- cbind(inMatForR, MeTHCostDist[,2])\n #inMatForR\n \n \n MeTHRScore<-calcRscorev10(inMatForR, MeTHBeta, MeTHOmega)\n #RScoreANT <<- MeTHRScore\n \n orderRet <- MeTHRScore[order(MeTHRScore[,2]),]\n \n return(orderRet)\n #return(MeTHRScore) \n}\n\n\n\n\n", "meta": {"hexsha": "4e2fdaed4f26159d7582d09f7a3b0446d6bd49e1", "size": 15035, "ext": "r", "lang": "R", "max_stars_repo_path": "METH_BSousa_v10.r", "max_stars_repo_name": "OneSourceConsult/FMC", "max_stars_repo_head_hexsha": "e3f86debeffe5b09d23f62d9cf997348949b5970", "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": "METH_BSousa_v10.r", "max_issues_repo_name": "OneSourceConsult/FMC", "max_issues_repo_head_hexsha": "e3f86debeffe5b09d23f62d9cf997348949b5970", "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": "METH_BSousa_v10.r", "max_forks_repo_name": "OneSourceConsult/FMC", "max_forks_repo_head_hexsha": "e3f86debeffe5b09d23f62d9cf997348949b5970", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1842546064, "max_line_length": 131, "alphanum_fraction": 0.6139008979, "num_tokens": 5400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24816273895567365}} {"text": "# The MIT License (MIT)\n# Copyright (c) 2017 Louise AC Millard, MRC Integrative Epidemiology Unit, University of Bristol\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without\n# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions\n# of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\n# Perform binary logistic regression\n#\n# Performs binary logistic regression on the phenotype stored in thisdata \n# and stores result in 'results-logistic-binary' results file.\nbinaryLogisticRegression <- function(varName, varType, thisdata, isExposure) {\n\n phenoFactor = factor(thisdata[,phenoStartIdx])\n\n facLevels = levels(phenoFactor)\n\n\t# assert variable has exactly two distinct values\n\tif (length(facLevels)!=2) {\n\t\t#stop(paste(\"Not 2 levels: \", length(facLevels), \" || \", sep=\"\"))\n\t\tcat(\"BINARY-NOT2LEVELS- (\", length(facLevels), \") || \",sep=\"\");\n incrementCounter(\"binary.nottwolevels\")\n\t}\n\n\tidxTrue = length(which(phenoFactor==facLevels[1]))\n\tidxFalse = length(which(phenoFactor==facLevels[2]))\n\tnumNotNA = length(which(!is.na(phenoFactor)))\n \n if (idxTrue|z|)']\n beta = sumx$coefficients[\"geno\",\"Estimate\"]\n\n\n\t\tif (opt$confidenceintervals == TRUE) {\n\t\t\tcis = confint(mylogit, \"geno\", level=0.95)\n\t lower = cis[\"2.5 %\"]\n\t upper = cis[\"97.5 %\"]\n\t\t}\n\t\telse {\n\t\t\tlower = NA\n\t\t\tupper = NA\n\t\t}\n\n numNotNA = length(na.omit(phenoFactor))\n\n ## save result to file\n write(paste(paste0(\"\\\"\", varName, \"\\\"\"),varType,paste(idxTrue,\"/\",idxFalse,\"(\",numNotNA,\")\",sep=\"\"), beta,lower,upper,pvalue, sep=\",\"), file=paste(opt$resDir,\"results-logistic-binary-\",opt$varTypeArg,\".txt\",sep=\"\"), append=\"TRUE\");\n cat(\"SUCCESS results-logistic-binary \");\n \n\t\tincrementCounter(\"success.binary\")\n\n\t\tif (isExposure==TRUE) {\n\t \tincrementCounter(\"success.exposure.binary\")\n\t }\t\n\n\t\t## END TRYCATCH\n }, error = function(e) {\n sink()\n sink(resLogFile, append=TRUE)\n cat(paste(\"ERROR:\", varName,gsub(\"[\\r\\n]\", \"\", e), sep=\" \"))\n incrementCounter(\"binary.error\")\n })\n\t\t}\t\n }\n}\n\n", "meta": {"hexsha": "e635d7f8292b0953d182737949aab1de2d90cd6b", "size": 4337, "ext": "r", "lang": "R", "max_stars_repo_path": "WAS/binaryLogisticRegression.r", "max_stars_repo_name": "MRCIEU/PHESANT", "max_stars_repo_head_hexsha": "becf44bb584fc9c5888b485e49e0a9a350adf0cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2017-02-27T00:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:42:01.000Z", "max_issues_repo_path": "WAS/binaryLogisticRegression.r", "max_issues_repo_name": "MRCIEU/PHESANT", "max_issues_repo_head_hexsha": "becf44bb584fc9c5888b485e49e0a9a350adf0cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-05-07T13:39:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:55.000Z", "max_forks_repo_path": "WAS/binaryLogisticRegression.r", "max_forks_repo_name": "MRCIEU/PHESANT", "max_forks_repo_head_hexsha": "becf44bb584fc9c5888b485e49e0a9a350adf0cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2017-02-27T12:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T22:03:16.000Z", "avg_line_length": 35.5491803279, "max_line_length": 247, "alphanum_fraction": 0.6253170394, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2467662459066459}} {"text": "# ADZES\n# - Main script to perform morphometric analysis on adzes (only)\n\n# LIBRARIES ====================================================================\nlibrary(Momocs)\nlibrary(tidyverse)\nlibrary(stringr)\nlibrary(gridExtra)\nlibrary(grid)\nlibrary(xtable)\n\n# INPUT ========================================================================\ninNProf <- list.files(\"Morpho/Adze/ProfileAll/\", full.names = TRUE)\ninNSide <- list.files(\"Morpho/Adze/SideView/\", full.names = TRUE)\ninNTop <- list.files(\"Morpho/Adze/TopView/\", full.names = TRUE)\n\ninProf <- import_jpg(\n jpg.path = inNProf,\n auto.notcentered = TRUE,\n threshold = 0.5,\n verbose = TRUE\n)\ninSide <- import_jpg(\n jpg.path = inNSide,\n auto.notcentered = TRUE,\n threshold = 0.5,\n verbose = TRUE\n)\ninTop <- import_jpg(\n jpg.path = inNTop,\n auto.notcentered = TRUE,\n threshold = 0.5,\n verbose = TRUE\n)\n\n# Clean mem\nrm(list = \"inNProf\", \"inNSide\", \"inNTop\")\nrm(list = \"inNPA\", \"inNSA\", \"inNTA\")\n\n# Save import data\nsave(inProf, file = \"./Archive/Adzes/Dt.inProf\")\nsave(inSide, file = \"./Archive/Adzes/Dt.inSide\")\nsave(inTop, file = \"./Archive/Adzes/Dt.inTop\")\n\n# Fac slot data\nprime <- read_csv(\"../Db.PRIME.csv\")\nsecon <- select(prime, -Lokalita, -Note, -Ident)\nsecon <- secon %>% filter(Morph == \"Ad\") %>% select(-Include)\n\n# Mutate Cult + Dat\nsecon <- secon %>%\n mutate(CultDat = paste(Cult, Dat, sep = \" \"))\n# String to edit CultDat\nsecon$CultDat <-\n str_replace(secon$CultDat, pattern = \"(.*) NA\", replacement = \"\\\\1\")\n\n# secon$Lok <- as.factor(secon$Lok)\n# secon$Orig <- as.factor(secon$Orig)\n# secon$Cult <- as.factor(secon$Cult)\n# secon$Dat <- as.factor(secon$Dat)\n# secon$RM <- as.factor(secon$RM)\n# secon$Morph <- as.factor(secon$Morph)\n# secon$OpSeq <- as.factor(secon$OpSeq)\n# secon$SalVar <- as.factor(secon$SalVar)\n# secon$SalProfVys <- as.factor(secon$SalProfVys)\n# secon$SalProfTvar <- as.factor(secon$SalProfTvar)\n# secon$SalTylBok <- as.factor(secon$SalTylBok)\n# secon$StUpev <- as.factor(secon$StUpev)\n# secon$StPrac <- as.factor(secon$StPrac)\n# secon$Pouzitelnost <- as.factor(secon$Pouzitelnost)\n# secon$Half <- as.factor(secon$Half)\n# secon$CultDat <- as.factor(secon$CultDat)\n\nfacProf <- filter(secon, Prof == TRUE) %>% select(-(Top:Prof))\nfacSide <- filter(secon, Side == TRUE) %>% select(-(Top:Prof))\nfacTop <- filter(secon, Top == TRUE) %>% select(-(Top:Prof))\n\nfacProf <- arrange(facProf, ID)\nfacSide <- arrange(facSide, ID)\nfacTop <- arrange(facTop, ID)\n\ncolsToFac <- c(\"Lok\", \"Orig\", \"Cult\", \"Dat\", \"CultDat\", \"RM\", \"Morph\", \"OpSeq\", \n \"SalVar\", \"SalProfVys\", \"SalProfTvar\", \"SalTylBok\", \n \"StUpev\", \"StPrac\", \"Pouzitelnost\", \"Half\")\n\nfacProf %<>%\n mutate_at(funs(factor(.)), .vars = colsToFac)\n\nfacSide %<>%\n mutate_at(funs(factor(.)), .vars = colsToFac)\n\nfacTop %<>%\n mutate_at(funs(factor(.)), .vars = colsToFac)\n\ndetach(\"package:tidyverse\", unload = TRUE)\ndetach(\"package:stringr\", unload = TRUE)\n\n# t-test korelace stop\nStPrac <- secon$StPrac\nStUpev <- secon$StUpev\nSt <- data.frame(StPrac, StUpev)\nStPracN <- as.numeric(St$StPrac)\nStUpevN <- as.numeric(St$StUpev)\nStN <- data.frame(StPracN, StUpevN)\nt.test(StN)\nrcorr(as.matrix(StN))\n\n# korelace cultDat a profVys\n# CultDat <- as.numeric(factor(secon$CultDat))\n# ProfVys <- as.numeric(factor(secon$SalProfVys))\n# cor.test(CultDat, ProfVys)\n\n# MORPHOMETRICS ================================================================\n# Outlines ---------------------------------------------------------------------\noutProf <- Out(inProf, fac = facProf)\noutSide <- Out(inSide, fac = facSide)\noutTop <- Out(inTop, fac = facTop)\n\n# Check whether outlines fit with fac!\npanel(outProf, fac = \"Orig\", names = TRUE)\npanel(outSide, fac = \"Orig\", names = TRUE)\npanel(outTop, fac = \"Orig\", names = TRUE)\n\n# Clean mem.\nrm(list = \"prime\", \"secon\")\nrm(list = \"facProf\", \"facSide\", \"facTop\")\nrm(list = \"inProf\", \"inSide\", \"inTop\")\n\n# Save\nsave(outProf, file = \"./Archive/Adzes/Dt.outProf\")\nsave(outSide, file = \"./Archive/Adzes/Dt.outSide\")\nsave(outTop, file = \"./Archive/Adzes/Dt.outTop\")\n\nload(file = \"./Archive/Adzes/Dt.outProf\")\nload(file = \"./Archive/Adzes/Dt.outSide\")\nload(file = \"./Archive/Adzes/Dt.outTop\")\n\n# Manipulate -------------------------------------------------------------------\nmanProf <- outProf %>%\n coo_slidedirection(\"N\") %>%\n coo_center() %>%\n coo_smooth(50) %>%\n coo_sample(200)\n\nmanSide <- outSide %>%\n coo_alignxax() %>%\n coo_slidedirection(\"W\") %>%\n coo_center() %>%\n coo_smooth(200) %>%\n coo_sample(400)\n\nmanTop <- outTop %>%\n coo_alignxax() %>%\n coo_slidedirection(\"W\") %>%\n coo_center() %>%\n coo_smooth(200) %>%\n coo_sample(400)\n\n# # Calibrating harmonics ------------------------------------------------------\n# # Profile\n# # devProf <- calibrate_deviations(manProf, method = \"efourier\")\n# harmProf <- calibrate_harmonicpower(manProf, method = \"efourier\",\n# nb.h = 12, plot = TRUE)\n# pdf(\"./Adzes/panelHarmProf.pdf\")\n# calibrate_reconstructions(manProf, \"efourier\", id = 30, range = 1:12)\n# dev.off()\n# \n# # Side\n# # devSide <- calibrate_deviations(manSide, method = \"efourier\")\n# harmSide <- calibrate_harmonicpower(manSide, method = \"efourier\",\n# nb.h = 16, plot = TRUE)\n# pdf(\"./Adzes/panelHarmSide.pdf\", width = 7, height = 3)\n# calibrate_reconstructions(manSide, \"efourier\", id = 23, range = 1:16)\n# dev.off()\n# \n# # Top\n# # devTop <- calibrate_deviations(manTop, method = \"efourier\")\n# harmTop <- calibrate_harmonicpower(manTop, method = \"efourier\",\n# nb.h = 12, plot = TRUE)\n# pdf(\"./Adzes/panelHarmTop.pdf\", width = 7, height = 2.5)\n# calibrate_reconstructions(manTop, \"efourier\", id = 17, range = 1:12)\n# dev.off()\n# \n# # rm(list = \"devProf\", \"devSide\", \"devTop\")\n# \n# # Exporting table with harmonic power to Latex\n# harmonicPower <- rbind(harmProf$minh, harmSide$minh, harmTop$minh)\n# row.names(harmonicPower) <- c(\"Profile\", \"Side\", \"Top\")\n# harmonicPower <- xtable(harmonicPower,\n# caption = \"Příspěvek harmonických proměnných k popisu tvaru\")\n# print(harmonicPower, file = \"./Adzes/Tab.HarmPow.tex\",\n# booktabs = T, caption.placement = \"top\")\n# #\n# # rm(list = \"harmonicPower\", \"harmProf\", \"harmSide\", \"harmTop\")\n\n# Elliptical Fourier Transform -------------------------------------------------\nefProf <- efourier(\n manProf,\n nb.h = 10,\n norm = FALSE,\n smooth.it = 0,\n start = FALSE,\n verbose = TRUE\n)\nefSide <- efourier(\n manSide,\n nb.h = 12,\n norm = F,\n smooth.it = 0,\n start = FALSE,\n verbose = TRUE\n)\nefTop <- efourier(\n manTop,\n nb.h = 10,\n norm = F,\n smooth.it = 0,\n start = FALSE,\n verbose = TRUE\n)\n\n# Save and clean memory\nsave(efProf, file = \"./Archive/Adzes/Dt.efProf\")\nsave(efSide, file = \"./Archive/Adzes/Dt.efSide\")\nsave(efTop, file = \"./Archive/Adzes/Dt.efTop\")\n\nload(\"./Archive/Adzes/Dt.efProf\")\nload(\"./Archive/Adzes/Dt.efSide\")\nload(\"./Archive/Adzes/Dt.efTop\")\n\n# ANALYSIS =====================================================================\n# Symmetry ---------------------------------------------------------------------\n# - rm_sym/rm_asym works only for Prof, why? or does it?\n# hokuspokus <- rm_sym(efProf)\n# panel(hokuspokus)\n# panel(efProf)\n\nsymProf <- symmetry(efProf)\nsymSide <- symmetry(efSide)\nsymTop <- symmetry(efTop)\n\n# hSymProf <- qplot(symProf[, \"sym\"],\n# xlab = \"(a) sym (Prof)\", ylab = \"frequency\") +\n# stat_bin(bins = 10, fill = \"white\", color = \"black\") + theme_bw()\n\n# hSymSide <- qplot(symSide[, \"sym\"],\n# xlab = \"(b) sym (Side)\", ylab = \"frequency\") +\n# stat_bin(bins = 10, fill = \"white\", color = \"black\") + theme_bw()\n\n# hSymTop <- qplot(symTop[, \"sym\"],\n# xlab = \"(c) sym (Top)\", ylab = \"frequency\") +\n# stat_bin(bins = 10, fill = \"white\", color = \"black\") + theme_bw()\n\npdf(file = \"./Adzes/Symmetry.pdf\",\n height = 2,\n width = 7)\nlayout(matrix(c(1, 2, 3), 1, 3, byrow = TRUE))\nhist(\n symProf[, \"sym\"],\n xlab = \"(a) sym (Prof)\",\n ylab = \"density\",\n main = NA,\n freq = FALSE\n)\nhist(\n symSide[, \"sym\"],\n xlab = \"(b) sym (Side)\",\n ylab = \"density\",\n main = NA,\n freq = FALSE\n)\nhist(\n symTop[, \"sym\"],\n xlab = \"(c) sym (Top)\",\n ylab = \"density\",\n main = NA,\n freq = FALSE\n)\n# grid.arrange(hSymProf, hSymSide, hSymTop, nrow = 1)\ndev.off()\n\n# PCA ==========================================================================\npcProf <- PCA(efProf)\npcSide <- PCA(efSide)\npcTop <- PCA(efTop)\n\nsave(pcProf, file = \"./Archive/Adzes/Dt.pcProf\")\nsave(pcSide, file = \"./Archive/Adzes/Dt.pcSide\")\nsave(pcTop, file = \"./Archive/Adzes/Dt.pcTop\")\n\nload(\"./Archive/Adzes/Dt.pcProf\")\nload(\"./Archive/Adzes/Dt.pcSide\")\nload(\"./Archive/Adzes/Dt.pcTop\")\n\n# # Scree plots\n# scree(pcProf, 1:5)\n# scree_min(pcProf, 0.98)\n# sp <- scree_plot(pcProf, 1:4)\n# pdf(file = \"./Adzes/pcContribProf.pdf\", height = 5)\n# PCcontrib(pcProf,\n# nax = 1:3,\n# sd.r = c(-1.5,-1,-0.5, 0, 0.5, 1, 1.5))\n# dev.off()\n# \n# scree(pcSide, 1:5)\n# scree_min(pcSide, 0.98)\n# ss <- scree_plot(pcSide, 1:5)\n# pdf(file = \"./Adzes/pcContribSide.pdf\",\n# height = 2.5,\n# width = 10)\n# PCcontrib(pcSide,\n# nax = 1:3,\n# sd.r = c(-1.5,-1,-0.5, 0, 0.5, 1, 1.5))\n# dev.off()\n# \n# scree(pcTop, 1:5)\n# scree_min(pcTop, 0.98)\n# st <- scree_plot(pcTop, 1:4)\n# pdf(file = \"./Adzes/pcContribTop.pdf\",\n# height = 2.5,\n# width = 10)\n# PCcontrib(pcTop, nax = 1:3, sd.r = c(-1,-0.5, 0, 0.5, 1))\n# dev.off()\n# \n# tp <- textGrob(\"(a) Prof (profil)\")\n# ts <- textGrob(\"(b) Side (bokorys)\")\n# tt <- textGrob(\"(c) Top (nárys)\")\n# lay <- rbind(c(1, 3, 5),\n# c(1, 3, 5),\n# c(1, 3, 5),\n# c(1, 3, 5),\n# c(1, 3, 5),\n# c(2, 4, 6))\n# \n# pdf(file = \"./Adzes/screePlots.pdf\",\n# width = 10,\n# height = 4)\n# grid.arrange(sp, tp, ss, ts, st, tt, layout_matrix = lay)\n# dev.off()\n# \n# rm(list = \"sp\", \"ss\", \"st\", \"tp\", \"ts\", \"tt\", \"lay\")\n\n# Basic PCA plots --------------------------------------------------------------\npdf(\n file = \"./Adzes/pcProf.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcProf,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 0.5,\n amp.shp = 0.9,\n pch = 4,\n center.origin = FALSE,\n zoom = 1.2,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\npdf(\n file = \"./Adzes/pc2Prof.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcProf,\n xax = 2,\n yax = 3,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 0.5,\n amp.shp = 0.9,\n pch = 4,\n center.origin = FALSE,\n zoom = 1.2,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\npdf(\n file = \"./Adzes/pcSide.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcSide,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 1,\n amp.shp = 0.9,\n flipx.shp = F,\n flipy.shp = T,\n pch = 4,\n center.origin = F,\n zoom = 1.6,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\npdf(\n file = \"./Adzes/pc2Side.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcSide,\n xax = 2,\n yax = 3,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 1,\n amp.shp = 0.9,\n flipx.shp = F,\n flipy.shp = T,\n pch = 4,\n center.origin = T,\n zoom = 1.4,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\npdf(\n file = \"./Adzes/pcTop.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcTop,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 0.8,\n amp.shp = 0.6,\n pch = 4,\n center.origin = F,\n zoom = 1.4,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\npdf(\n file = \"./Adzes/pc2Top.pdf\",\n paper = \"a4r\",\n width = 12,\n height = 8\n)\nplot(\n pcTop,\n xax = 2,\n yax = 3,\n points = TRUE,\n morphospace = TRUE,\n pos.shp = \"xy\",\n size.shp = 1,\n amp.shp = 0.8,\n pch = 4,\n center.origin = TRUE,\n zoom = 1,\n density = T,\n contour = F,\n axisvar = T,\n box = TRUE,\n cex.labelsgroups = 2\n)\ndev.off()\n\n# PCA 3 plots ------------------------------------------------------------------\n# color palettes (see color brewer)\npal2 <- c(\"#e41a1c\", \"#33a02c\")\npal3 <- c(\"#377eb8\", \"#33a02c\", \"#e41a1c\")\npalN <- c(\"#e41a1c\", \"gray50\", \"#33a02c\")\npalN3 <- c(\"gray50\", \"#33a02c\", \"#e41a1c\") ##377eb8\npalN2 <- c(\"#33a02c\", \"#e41a1c\", \"gray50\")\npal4 <- c(\"#377eb8\", \"#33a02c\", \"#e41a1c\", \"gray50\")\n\n# pca3Plot <- function(pcaSlot, facSlot) {\n# plot3(pcaSlot, fac = facSlot,\n# size.shp = 0.5, amp.shp = 0.8, pch = c(15, 4, 19),\n# morphospace = T, pos.shp = \"range_axes\",\n# chull = T, chull.filled = T, chull.lty = 0,\n# ellipses = F,\n# labelsgroups = TRUE, abbreviate.labelsgroups = TRUE)\n# }\n\n# Stopy\npdf(file = \"./Obr/pc3-Top_StUpev.pdf\")\nplot3(\n pcTop,\n fac = \"StUpev\",\n size.shp = 1,\n amp.shp = 1,\n col = palN3,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n zoom = 1.2,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Adzes/pc3-Top_StPrac.pdf\")\nplot3(\n pcTop,\n fac = \"StPrac\",\n size.shp = 1,\n amp.shp = 1,\n col = palN,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n zoom = 1.2,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Obr/pc3-Side_StUpev.pdf\")\nplot3(\n pcSide,\n fac = \"StUpev\",\n size.shp = 1,\n amp.shp = 1,\n col = palN3,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE,\n flipx.shp = T,\n zoom = 1.2\n)\ndev.off()\n\npdf(file = \"./Adzes/pc3-Side_StPrac.pdf\")\nplot3(\n pcSide,\n fac = \"StPrac\",\n size.shp = 1,\n amp.shp = 1,\n col = palN,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE,\n flipx.shp = T,\n zoom = 1.2\n)\ndev.off()\n\n# plot3(pcProf, fac = \"Half\",\n# size.shp = 0.5, amp.shp = 0.8, col = pal2, pch = c(4, 19),\n# morphospace = T, pos.shp = \"range_axes\",\n# chull = T, chull.filled = T, chull.lty = 0,\n# ellipses = F,\n# labelsgroups = TRUE, abbreviate.labelsgroups = TRUE)\n\n# SalVar\npdf(file = \"./Adzes/pc3-Prof_SalProfVys.pdf\")\nplot3(\n pcProf,\n fac = \"SalProfVys\",\n size.shp = 1,\n amp.shp = 1,\n col = pal3,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n zoom = 1,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Obr/pc3-Prof_SalProfTvar.pdf\")\nplot3(\n pcProf,\n fac = \"SalProfTvar\",\n size.shp = 1,\n amp.shp = 1,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n zoom = 1,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Obr/pc3-Side_SalTylBok.pdf\")\nplot3(\n pcSide,\n fac = \"SalTylBok\",\n size.shp = 1,\n amp.shp = 1,\n pch = c(15, 4, 19),\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n zoom = 1.3,\n flipx.shp = T,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\n# Orig\npdf(file = \"./Adzes/pc3-Prof_Orig.pdf\")\nplot3(\n pcProf,\n fac = \"Orig\",\n size.shp = 0.5,\n amp.shp = 0.8,\n col = pal3,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Adzes/pc3-Side_Orig.pdf\")\nplot3(\n pcSide,\n fac = \"Orig\",\n size.shp = 0.5,\n amp.shp = 0.8,\n col = pal3,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\npdf(file = \"./Adzes/pc3-Top_Orig.pdf\")\nplot3(\n pcTop,\n fac = \"Orig\",\n size.shp = 0.5,\n amp.shp = 0.8,\n col = pal3,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = TRUE\n)\ndev.off()\n\n\nplot(\n pcProf,\n fac = \"CultDat\",\n size.shp = 0.5,\n amp.shp = 0.8,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n abbreviate.labelsgroups = F\n)\n\n\nplot(\n pcSide,\n fac = \"CultDat\",\n size.shp = 0.5,\n amp.shp = 0.8,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n)\n\n\n\nplot(\n pcTop,\n fac = \"CultDat\",\n size.shp = 0.5,\n amp.shp = 0.8,\n pch = 4,\n morphospace = T,\n pos.shp = \"range_axes\",\n chull = T,\n chull.filled = T,\n chull.lty = 0,\n ellipses = F,\n labelsgroups = TRUE,\n)\n\n\n# Clustering ===================================================================\n# Count number of clusters K and perform kmeans clustering\n# - elbow method (wss - within-clusters sum of squares)\n# - stolen and modified from rbloggers (DataScience+, by Sunny Anand)\nk.max <- 8\n\n# Prof\nwssProf <- sapply(1:k.max,\n function(k) {\n kmeans(pcProf$x, k, nstart = 50,\n iter.max = 15)$tot.withinss\n })\n\nplot(\n 1:k.max,\n wssProf,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Prof)\",\n ylab = \"Total within-clusters sum of squares\"\n)\n\n# Side\nwssSide <- sapply(1:k.max,\n function(k) {\n kmeans(pcSide$x, k, nstart = 50,\n iter.max = 15)$tot.withinss\n })\n\nplot(\n 1:k.max,\n wssSide,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Side)\",\n ylab = \"Total within-clusters sum of squares\"\n)\n\n# Top\nwssTop <- sapply(1:k.max,\n function(k) {\n kmeans(pcTop$x, k, nstart = 50,\n iter.max = 15)$tot.withinss\n })\n\nplot(\n 1:k.max,\n wssTop,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Top)\",\n ylab = \"Total within-clusters sum of squares\"\n)\n\n# grid arrange\npdf(file = \"./Adzes/elbow.pdf\",\n width = 10,\n height = 4)\nlayout(matrix(c(1, 2, 3), 1, 3, byrow = TRUE))\nplot(\n 1:k.max,\n wssProf,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Prof)\",\n ylab = \"Total within-clusters sum of squares\"\n)\nplot(\n 1:k.max,\n wssSide,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Side)\",\n ylab = NA\n)\nplot(\n 1:k.max,\n wssTop,\n type = \"b\",\n pch = 19,\n frame = FALSE,\n xlab = \"Number of clusters K (Top)\",\n ylab = NA\n)\ndev.off()\n\n# K means clustering -----------------------------------------------------------\npdf(file = \"./Adzes/kmeansProf.pdf\")\nKMEANS(pcProf, 3)\ndev.off()\n\npdf(file = \"./Obr/kmeansSide.pdf\")\nKMEANS(pcSide, 2)\ndev.off()\n\npdf(file = \"./Obr/kmeansTop.pdf\")\nKMEANS(pcTop, 2)\ndev.off()\n\n# VedTop <- filter(pcTop, pcTop$fac$Lok == \"Ved\")\n# KMEANS(VedTop, 2)\n\n# Hierarchical clustering ------------------------------------------------------\n# CLUST(\n# pcTop,\n# fac = \"StPrac\",\n# type = \"phylogram\",\n# hclust_method = \"ward.D2\",\n# tip_labels = \"StPrac\"\n# )\n# CLUST(\n# pcSide,\n# fac = \"SalTylBok\",\n# type = \"phylogram\",\n# hclust_method = \"ward.D2\",\n# tip_labels = \"SalTylBok\"\n# )\n# CLUST(\n# pcTop,\n# fac = \"RM\",\n# type = \"phylogram\",\n# hclust_method = \"ward.D2\",\n# tip_labels = \"RM\"\n# )\n\n# Linear dicriminant analysis ==================================================\nload(\"./Archive/Adzes/Dt.efProf\")\nload(\"./Archive/Adzes/Dt.efSide\")\nload(\"./Archive/Adzes/Dt.efTop\")\n\nfunLDA <- function(efSLot, facSlot, view) {\n plot(LDA(efSLot, fac = facSlot), \n chull.filled = TRUE,\n ellipsesax = FALSE,\n title = sprintf(\"Linear discriminant analysis (%s: %s)\", view, facSlot))\n}\n\npdf(file = \"./Adzes/ldaProf_Vys.pdf\")\nfunLDA(efProf, \"SalProfVys\", \"Prof\")\ndev.off()\n\npdf(file = \"./Adzes/ldaProf_Tvar.pdf\")\n#funLDA(efProf, \"SalProfTvar\", \"Prof\")\nplot(LDA(efProf, fac = \"SalProfTvar\"), zoom = 2.4, \n chull.filled = TRUE,\n ellipsesax = FALSE,\n title = (\"Linear discriminant analysis (Prof: Tvar)\"))\ndev.off()\n\npdf(file = \"./Adzes/ldaSide_Bok.pdf\")\n#funLDA(efSide, \"SalTylBok\", \"Side\")\nplot(LDA(efSide, fac = \"SalTylBok\"), zoom = 4.5, \n chull.filled = TRUE,\n ellipsesax = FALSE,\n title = (\"Linear discriminant analysis (Side: Tyl)\"))\ndev.off()\n\npdf(file = \"./Adzes/ldaTop_StUpev.pdf\")\nfunLDA(efTop, \"StUpev\", \"Top\")\ndev.off()\npdf(file = \"./Adzes/ldaTop_StPrac.pdf\")\nfunLDA(efTop, \"StPrac\", \"Top\")\ndev.off()\npdf(file = \"./Adzes/ldaSide_StUpev.pdf\")\nfunLDA(efSide, \"StUpev\", \"Side\")\ndev.off()\npdf(file = \"./Adzes/ldaSide_StPrac.pdf\")\nfunLDA(efSide, \"StPrac\", \"Side\")\ndev.off()\n\npdf(file = \"./Adzes/ldaProf_Orig.pdf\")\nfunLDA(efProf, \"Orig\", \"Prof\")\ndev.off()\npdf(file = \"./Adzes/ldaSide_Orig.pdf\")\nfunLDA(efSide, \"Orig\", \"Side\")\ndev.off()\npdf(file = \"./Adzes/ldaTop_Orig.pdf\")\nfunLDA(efTop, \"Orig\", \"Top\")\ndev.off()\n\n# Other\n# - it is possible to distinguish Lbk I vs II in Top view thanks to LDA\nplot3(PCA(efTop), fac = \"CultDat\")\nfunLDA(efTop, \"CultDat\", \"Top\")\n\n# - same for OpSeq in Side and Top views\nfunLDA(efProf, \"OpSeq\", \"Prof\")\n\npdf(file = \"./Adzes/ldaSide_OpSeq.pdf\")\nfunLDA(efSide, \"OpSeq\", \"Side\")\ndev.off()\n\npdf(file = \"./Adzes/ldaTop_OpSeq.pdf\")\nfunLDA(efTop, \"OpSeq\", \"Top\")\ndev.off()\n\n# MANOVA =======================================================================\nload(\"./Archive/Adzes/Dt.pcProf\")\nload(\"./Archive/Adzes/Dt.pcSide\")\nload(\"./Archive/Adzes/Dt.pcTop\")\n\n# Normality tests --------------------------------------------------------------\ntopStUpevT <- filter(pcTop, StUpev == \"T\")\ntopStUpevF <- filter(pcTop, StUpev == \"F\")\n\ntopStPracT <- filter(pcTop, StPrac == \"T\")\ntopStPracF <- filter(pcTop, StPrac == \"F\")\n\nsideStUpevT <- filter(pcSide, StUpev == \"T\")\nsideStUpevF <- filter(pcSide, StUpev == \"F\")\n\nsideStPracT <- filter(pcSide, StPrac == \"T\")\nsideStPracF <- filter(pcSide, StPrac == \"F\")\n\n# Q-Q plot\n# qqnorm(topStUpevT$x[, 1])\nlibrary(ggpubr)\nlibrary(mvnormtest)\n# ggqqplot(pcTop$x[, 1])\n# ggqqplot(pcSide$x[, 1])\n# ggqqplot(pcTop$x[, 1])\n# \n# ggqqplot(pcTop$x[, 2])\n# ggqqplot(pcSide$x[, 2])\n# ggqqplot(pcTop$x[, 2])\n\nggqqplot(topStUpevT$x[, 1])\nggqqplot(topStUpevF$x[, 1])\n\nggqqplot(topStPracT$x[, 1])\nggqqplot(topStPracF$x[, 1])\n\nggqqplot(sideStUpevT$x[, 1])\nggqqplot(sideStUpevF$x[, 1])\n\nggqqplot(sideStPracT$x[, 1])\nggqqplot(sideStPracF$x[, 1])\n\n# Shapiro--Wilk normality test\n# shapiro.test(pcTop$x[, 1])\n# shapiro.test(pcSide$x[, 1])\n# \n# shapiro.test(pcTop$x[, 2])\n# shapiro.test(pcSide$x[, 2])\n\nshapiro.test(topStUpevT$x)\nshapiro.test(topStUpevF$x)\n\nshapiro.test(topStPracT$x)\nshapiro.test(topStPracF$x)\n\nshapiro.test(sideStUpevT$x)\nshapiro.test(sideStUpevF$x)\n\nshapiro.test(topStPracT$x)\nshapiro.test(topStPracF$x)\n\n# Tests of homogeneity of variances\n# - Bartlett for Top ~StUpev, ~StPrac; pc1:pc2 \nbartlett.test(pcTop$x[, 1], pcTop$fac$StUpev) # rejected\nbartlett.test(pcTop$x[, 2], pcTop$fac$StUpev) # not\n\nbartlett.test(pcTop$x[, 1], pcTop$fac$StPrac) # not\nbartlett.test(pcTop$x[, 2], pcTop$fac$StPrac) # not\n\n# - Fligner-Killeen for Top ~StUpev, ~StPrac; pc1:pc2 \nfligner.test(pcTop$x[, 1], pcTop$fac$StUpev) # not\nfligner.test(pcTop$x[, 2], pcTop$fac$StUpev) # not\n\nfligner.test(pcTop$x[, 1], pcTop$fac$StPrac) # not\nfligner.test(pcTop$x[, 2], pcTop$fac$StPrac) # not\n\n# - Bartlett for Side ~StUpev, ~StPrac; pc1:pc2 \nbartlett.test(pcSide$x[, 1], pcSide$fac$StPrac) # not\nbartlett.test(pcSide$x[, 2], pcSide$fac$StPrac) # not\n\nbartlett.test(pcSide$x[, 1], pcSide$fac$StUpev) # rejected\nbartlett.test(pcSide$x[, 2], pcSide$fac$StUpev) # not\n\n# - Fligner-Killeen for Side ~StUpev, ~StPrac; pc1:pc2\nfligner.test(pcSide$x[, 1], pcSide$fac$StUpev) # not\nfligner.test(pcSide$x[, 2], pcSide$fac$StUpev) # not\n\nfligner.test(pcSide$x[, 1], pcSide$fac$StPrac) # not\nfligner.test(pcSide$x[, 2], pcSide$fac$StPrac) # not\n\nbartlett.test(efTop$coe[, 1], efTop$fac$StUpev) # rejected\n\n# vlastní MANOVA\nMANOVA(pcProf, fac = \"SalProfVys\", retain = 0.99)\nMANOVA(pcProf, fac = \"SalProfTvar\", retain = 0.99)\nMANOVA(pcSide, fac = \"SalTylBok\", retain = 0.99)\n\nMANOVA(pcSide, fac = \"StPrac\", retain = 0.99)\nMANOVA(pcSide, fac = \"StUpev\", retain = 0.99)\n\nMANOVA(pcTop, fac = \"StPrac\", retain = 0.99)\nMANOVA(pcTop, fac = \"StUpev\", retain = 0.99)\n\nMANOVA(pcTop, fac = \"Orig\", retain = 0.99)\nMANOVA(pcTop, fac = \"CultDat\", retain = 0.99)\nMANOVA(pcSide, fac = \"Orig\", retain = 0.99)\nMANOVA(pcSide, fac = \"CultDat\", retain = 0.99)\nMANOVA(pcProf, fac = \"Orig\", retain = 0.99)\nMANOVA(pcProf, fac = \"CultDat\", retain = 0.99)\n\nMANOVA(pcTop, fac = \"OpSeq\")\nMANOVA(pcSide, fac = \"OpSeq\")\nMANOVA(pcProf, fac = \"OpSeq\")\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$StPrac) # * pcTop$fac$StUpev\nsummary(m)\nsummary.aov(m)\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$StUpev)\nsummary(m)\nsummary.aov(m)\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$CultDat)\nsummary(m)\nsummary.aov(m)\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$Orig)\nsummary(m)\nsummary.aov(m)\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$Orig)\nsummary(m)\nsummary.aov(m)\n\nm <- manova(cbind(pcTop$x[, 1], pcSide$x[, 1]) ~ pcTop$fac$OpSeq)\nsummary(m)\nsummary.aov(m)\n\n# m <- manova(cbind(pcProf$x[, 1:2], pcProf$x[, 1:2]) ~ pcProf$fac$SalProfVys) # * pcTop$fac$StUpev\n# summary(m)\n# summary.aov(m)\n# \n# m <- manova(pcSide$x[, 1:2] ~ pcSide$fac$SalTylBok) # * pcTop$fac$StUpev\n# summary(m)\n# summary.aov(m)\n\n# Kruskal--Wallis test\n# boxplot(sideStPracT$x[, 1], sideStPracF$x[, 1])\nkruskal.test(pcTop$x[, 1], pcTop$fac$StPrac)\nkruskal.test(pcSide$x[, 1], pcSide$fac$StPrac)\n# kruskal.test(pcTop$x[, 2], pcTop$fac$StPrac)\n# kruskal.test(pcSide$x[, 2], pcSide$fac$StPrac)\n\nkruskal.test(pcTop$x[, 1], pcTop$fac$StUpev)\nkruskal.test(pcSide$x[, 1], pcSide$fac$StUpev)\n# kruskal.test(pcTop$x[, 2], pcTop$fac$StUpev)\n# kruskal.test(pcSide$x[, 2], pcSide$fac$StUpev)\n\nkruskal.test(pcSide$x[, 1], pcSide$fac$SalTylBok)\nkruskal.test(pcProf$x[, 1], pcProf$fac$SalProfTvar)\nkruskal.test(pcProf$x[, 1], pcProf$fac$SalProfVys)\nkruskal.test(pcProf$x[, 2], pcProf$fac$SalProfTvar)\nkruskal.test(pcProf$x[, 2], pcProf$fac$SalProfVys)\n\nkruskal.test(pcSide$x[,1], pcSide$fac$CultDat)\nkruskal.test(pcTop$x[,1], pcTop$fac$CultDat)\nkruskal.test(pcProf$x[,1], pcProf$fac$CultDat)\nkruskal.test(pcProf$x[,2], pcProf$fac$CultDat)\n\nkruskal.test(pcSide$x[,1], pcSide$fac$Orig)\nkruskal.test(pcTop$x[,1], pcTop$fac$Orig)\nkruskal.test(pcProf$x[,1], pcProf$fac$Orig)\nkruskal.test(pcProf$x[,2], pcProf$fac$Orig)\n\n# END ==========================================================================\ngraphics.off()\nrm(list = ls())\ngc()\n.rs.restartR()\nq(\"no\")\n", "meta": {"hexsha": "21dd2cff3d6ff7b9afae16bbb6fae7c2ff1e4d46", "size": 27135, "ext": "r", "lang": "R", "max_stars_repo_path": "Scripts/Adzes.r", "max_stars_repo_name": "PetPaj/DiplomaThesis", "max_stars_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-08T10:02:36.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T10:02:36.000Z", "max_issues_repo_path": "Scripts/Adzes.r", "max_issues_repo_name": "petrpajdla/DiplomaThesis", "max_issues_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scripts/Adzes.r", "max_forks_repo_name": "petrpajdla/DiplomaThesis", "max_forks_repo_head_hexsha": "5d1bc646223dca743d090610f656e15d82a701d3", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.473183391, "max_line_length": 99, "alphanum_fraction": 0.5862170628, "num_tokens": 9922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24489643445328263}} {"text": "suppressMessages({\n library(CHNOSZ)\n library(dplyr)\n})\noptions(stringsAsFactors=F)\n\n\nvprint <- function(string, verbose=2){\n # print messages depending on desired level of 'verbose'-ness.\n if(verbose == 2){\n print(string)\n } else if(verbose == 1){\n if(grepl(\"warning\", tolower(string)) | grepl(\"error\", tolower(string))){\n print(string)\n }\n }\n}\n\n\nheader_unit <- function(header, keepcase=FALSE){\n # get units from a header\n # (unit should always be at end of header after an underscore)\n split_header <- strsplit(header, \"_\")[[1]] # split header by underscore\n if(!keepcase){\n tolower(split_header[length(split_header)]) # get last string in split\n } else {\n split_header[length(split_header)] # get last string in split\n }\n}\n\nuc_molal <- function(value=1, chemical=\"H+\", unit=\"ppm\"){\n # convert unit name to lowercase\n unit <- tolower(unit)\n\n # convert ppb to ppm\n if(unit == \"ppb\"){\n value <- value/1000\n }\n\n # convert ppm or mg/L to molality\n if(unit == \"ppb\" | unit == \"ppm\" | unit == \"mg/l\"){\n value <- value*0.001/mass(info(info(\"water\"))$formula)\n return(value)\n } else if(unit == \"molality\" | unit == \"molal\"){\n return(value)\n } else {\n stop(\"Error in uc_molal(): unit must be either ppb, ppm, or mg/L\")\n }\n}\n\n\nheader_species <- function(header){\n # get chemical species from header\n # (should always be at start of header before an underscore)\n split_header <- strsplit(header, \"_\")[[1]][1] # split header by underscore\n}\n\n\nEQ3_jflags <- c(\"Suppressed\", \"Molality\", \"Molarity\", \"mg/L\",\n \"mg/kg.sol\", \"Alk., eq/kg.H2O\", \"Alk., eq/L\",\n \"Alk., eq/kg.sol\", \"Alk., mg/L CaCO3\", \"Alk., mg/L HCO3-\",\n \"Log activity\", \"Log act combo\", \"Log mean act\", \"pX\",\n \"pH\", \"pHCl\", \"pmH\", \"pmX\", \"Hetero. equil.\",\n \"Homo. equil.\", \"Make non-basis\", \"logfO2\")\n\n# function to convert ppb, ppm, or mg/L to molality\nacceptable_units <- c(\"ppb\", \"ppm\", \"mg/l\", \"molality\", \"molal\")\n\npreprocess <- function(input_filename,\n exclude,\n grid_temps,\n grid_press,\n strict_minimum_pressure,\n dynamic_db,\n poly_coeffs_1,\n poly_coeffs_2,\n water_model,\n verbose=2){\n\n \n vprint(\"Reading input file...\", verbose=verbose)\n \n # Read input\n r <- read.csv(input_filename,\n header=T,\n check.names=F,\n stringsAsFactors=F,\n colClasses=\"character\")\n \n df <- as.data.frame(r)\n \n df_numeric <- df[!(names(df) %in% exclude)]\n \n df_numeric <- df_numeric[, df_numeric[1, ] != \"Hetero. equil.\"]\n num_cols <- names(df_numeric)\n num_cols <- match(num_cols, colnames(df))\n num_cols <- num_cols[num_cols != 1]\n \n vprint(\"Handling headers...\", verbose=verbose)\n\n # specify headers and subheaders\n header1 <- names(df)\n header2 <- df[1, ]\n\n # create concatenated header_subheader column names\n for(i in 1:length(header1)){\n if(is.na(header2[i])){\n header2[i] <- \"\"\n }\n if(header2[i] != \"\"){\n colnames(df)[i] <- paste(header1[i], header2[i], sep=\"_\")\n }else{\n colnames(df)[i] <- header1[i]\n }\n \n }\n #colnames(df) <- paste(header1, header2, sep=\"_\")\n df = df[-1, ] # remove subheader row\n colnames(df)[1] <- \"Sample\" # rename \"_\" as sample name header\n\n # Convert data to numeric ------------------------------------------------------\n vprint(\"Ensuring data is numeric...\", verbose=verbose)\n\n # convert columns to numeric\n df[, num_cols] <- mutate_all(df[, num_cols], function(x) as.numeric(as.character(x)))\n\n # convert these special columns to numeric even if excluded from aqueous block\n special_numeric <- c(\"rho_\", \"Pressure_\", \"redox_\", \"Temperature_\", \"pe_\", \"Eh_\", \"logfO2_\") \n\n for(col in special_numeric){\n if(TRUE %in% grepl(col, colnames(df))){\n this_match <- grep(col, colnames(df))\n df[, this_match] <- as.numeric(as.character(df[, this_match]))\n }\n } \n\n # add columns to exclusion list\n exclude <- c(exclude, \"\", \"Sample\", \"rho\", \"Pressure\", \"redox\", \"Temperature\", \"pe\", \"Eh\", \"logfO2\")\n\n # find temperature (in degK)\n if(\"Temperature_degC\" %in% names(df)){\n temp_degC <- df[, \"Temperature_degC\"]\n temp_degK <- temp_degC + 273.15\n } else if(\"Temperature_degK\" %in% names(df)){\n temp_degK <- df[, \"Temperature_degK\"]\n temp_degC <- temp_degK - 273.15\n } else {\n stop(\"Error: need a column for 'Temperature' with units in 'degC' or 'degK'\")\n }\n \n # handle TP-dependent preprocessing\n if(!dynamic_db){\n \n grid_temps <- as.numeric(as.character(grid_temps))\n grid_press <- as.numeric(as.character(grid_press))\n minimum_pressure <- min(grid_press)\n \n ### interpolate pressure\n \n f1 <- function(T) {\n return(poly_coeffs_1[1] + poly_coeffs_1[2]*T + poly_coeffs_1[3]*T^2 + poly_coeffs_1[4]*T^3)\n }\n \n f2 <- function(T) {\n return(poly_coeffs_2[1] + poly_coeffs_2[2]*T + poly_coeffs_2[3]*T^2 + poly_coeffs_2[4]*T^3 + poly_coeffs_2[5]*T^4)\n }\n \n if(grid_temps[1] <= temp_degC && temp_degC <= grid_temps[4]){\n pressure_bar <- f1(temp_degC)\n }else if (grid_temps[4] <= temp_degC && temp_degC <= grid_temps[8]){\n pressure_bar <- f2(temp_degC)\n }else{\n stop(paste0(\"Error: one or more temperatures in this sample set is outside of the temperature range of this thermodynamic dataset (\", grid_temps[1], \" to \", grid_temps[8], \" C).\"))\n }\n \n if(strict_minimum_pressure){\n if(pressure_bar < minimum_pressure){\n pressure_bar <- rep(minimum_pressure, length(temp_degC))\n }\n }\n }else{\n if(\"Pressure_bar\" %in% colnames(df)){\n \n if(any(is.na(df[, \"Pressure_bar\"]))){\n vprint(paste(\"Warning: a pressure value is missing for one or more\",\n \"samples in the sample input file. Defaulting to liquid vapor\",\n \"saturation pressure for these missing pressures...\"),\n verbose=verbose)\n \n water(water_model)\n psat_pressures <- water(\"Psat\", T=temp_degC+273.15)[[1]]\n \n df[, \"Pressure_bar\"][is.na(df[, \"Pressure_bar\"])] <- psat_pressures[is.na(df[, \"Pressure_bar\"])]\n }\n \n pressure_bar <- df[, \"Pressure_bar\"]\n \n }else{\n # assume PSAT if no pressure column in sample input file\n\n vprint(paste(\"Warning: a column for Pressure was not found in the\",\n \"sample input file. Defaulting to liquid vapor saturation pressure...\"),\n verbose=verbose)\n water(water_model)\n pressure_bar <- water(\"Psat\", T=temp_degC+273.15)[[1]]\n }\n \n minimum_pressure <- 0\n }\n\n # create unique df row names that will become .3i filenames\n row_order <- make.names(df$Sample, unique=T)\n rownames(df) <- row_order\n \n input_processed_list = list(\"df\"=df,\n \"temp_degC\"=temp_degC,\n \"pressure_bar\"=pressure_bar,\n \"minimum_pressure\"=minimum_pressure,\n \"exclude\"=exclude)\n\n vprint(\"Preprocessing done!\", verbose=verbose)\n\n return(input_processed_list)\n}\n\n \n \n \n \n \n \nwrite_3i_file <- function(df,\n temp_degC,\n pressure_bar,\n minimum_pressure,\n strict_minimum_pressure,\n pressure_override,\n suppress_missing,\n exclude,\n allowed_aq_block_species,\n charge_balance_on,\n suppress,\n alter_options,\n get_solid_solutions,\n input_dir,\n redox_flag,\n redox_aux,\n default_logfO2,\n water_model,\n warned_about_redox_column,\n verbose){\n \n \n # Set water model -------------------------------------------------------------- \n suppressMessages(water(water_model))\n \n row <- 1\n\n # calculate rho and append\n df[1, \"rho\"] <- water(\"rho\", T=temp_degC+273.15, P=pressure_bar)[[1]]\n df[1, \"rho\"] <- df[1, \"rho\"]/1000 #convert rho to g/cm3\n \n \n # Handle redox block ---------------------------------------------------------\n df$redox_flag <- redox_flag\n df$redox_value <- NA\n df$redox_unit <- NA\n\n this_redox_flag <- redox_flag\n assigned <- FALSE\n\n # use gaseous O2 in aqueous species block\n if(redox_flag == -3){\n redox_col_index <- grep(\"O2(g)\", names(df), fixed = T, value = T)\n tryCatch({\n redox_col_index <- redox_col_index[substring(redox_col_index, 1, nchar(\"O2(g)\")) == \"O2(g)\"]\n unit <- strsplit(redox_col_index, \"_\")[[1]][2]\n }, error=function(e){\n redox_col_index = 0\n })\n if(length(redox_col_index) > 0){\n if(!is.na(df[row, redox_col_index])){\n if(unit == \"Hetero. equil.\"){\n this_redox_value <- unit\n }else{\n this_redox_value <- sprintf(\"%.4E\", df[row, redox_col_index])\n }\n this_redox_unit <- \"using O2(g) in aqueous species block\"\n } else {\n vprint(paste0(\"Warning: non-numeric 'O2(g)' value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste(\"Warning: no 'O2(g)' column found. Resorting to using\",\n \"Log fO2 (log bars) with a value of\", default_logfO2),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n }\n\n # specify pe in pe units\n if(redox_flag == -2){\n redox_col_index <- grep(\"^pe_\", names(df))\n if(!(identical(redox_col_index, integer(0)) | identical(redox_col_index, character(0)))){\n if(!is.na(df[row, redox_col_index])){\n this_redox_value <- sprintf(\"%.4E\", df[row, redox_col_index])\n this_redox_unit <- \"pe, pe units\"\n } else {\n vprint(paste0(\"Warning: non-numeric pe value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste0(\"Warning: no 'pe' column found. Resorting to using\",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n }\n\n # specify Eh in volts\n if(redox_flag == -1){\n redox_col_index <- grep(\"Eh_volts\", names(df))\n if(!(identical(redox_col_index, integer(0)) | identical(redox_col_index, character(0)))){\n if(!is.na(df[row, redox_col_index])){\n this_redox_value <- sprintf(\"%.4E\", df[row, redox_col_index])\n this_redox_unit <- \"Eh, volts\"\n } else {\n vprint(paste0(\"Warning: non-numeric Eh value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste0(\"Warning: no 'Eh' column found with 'volts' units. \",\n \"Resorting to using Log fO2 (log bars) with a value of \",\n default_logfO2),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n }\n\n if(redox_flag == 0 && assigned == FALSE){\n redox_col_index <- grep(\"logfO2\", names(df))\n if(!(identical(redox_col_index, integer(0)) | identical(redox_col_index, character(0)))){\n if(!is.na(df[row, redox_col_index])){\n this_redox_value <- sprintf(\"%.4E\", df[row, redox_col_index])\n this_redox_unit <- \"Log fO2 (log bars) [from logfO2 column]\"\n } else {\n vprint(paste0(\"Warning: non-numeric logfO2 value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"a logfO2 value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste(\"Warning: no 'logfO2' column found. Attempting to find a\",\n \"column for aqueous O2 to estimate logfO2 at sample temperature and\",\n \"pressure...\"),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n redox_col_index <- grep(\"(^O2,AQ)|(^O2_)\", names(df)) # TODO: make more flexible (June 25, 2020)\n if(length(redox_col_index) > 0){\n if(!is.na(df[row, redox_col_index])){\n header_name <- names(df)[redox_col_index]\n this_header_unit <- header_unit(header_name)\n if(this_header_unit %in% c(acceptable_units, EQ3_jflags)){\n O2_molal <- uc_molal(value=df[row, redox_col_index],\n chemical=\"O2\", unit=this_header_unit)\n if(is.na(temp_degC[row]) | is.na(pressure_bar[row])){\n vprint(paste0(\"Warning: non-numeric temperature or pressure value \",\n \"in sample \", df[row, \"Sample\"], \". Resorting to \",\n \"using Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n } else {\n suppressMessages({\n logfO2 <- log10(O2_molal*10^subcrt(c(\"O2\", \"O2\"),\n c(-1, 1),\n c(\"aq\", \"g\"),\n T=temp_degC[row],\n P=pressure_bar[row],\n exceed.rhomin=TRUE,\n exceed.Ttr=TRUE)$out$logK)\n })\n this_redox_value <- sprintf(\"%.4E\", logfO2)\n this_redox_unit <- paste(\"Log fO2 (log bars) [calculated from O2(aq) = O2(g) at\",\n \"temperature and pressure of sample]\")\n assigned <- TRUE\n }\n } else {\n vprint(paste(\"Warning: column found for aqueous O2, but units are not recognized. Resorting to using Log fO2\",\n \"(log bars) with a value of\", default_logfO2, \"for all samples.\"),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n vprint(paste0(\"Warning: non-numeric aqueous O2 value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste(\"Warning: a column for aqueous O2 was not found. Resorting to\",\n \"using Log fO2 (log bars) with a value of \",\n default_logfO2),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n }\n }\n\n # specify aux species redox couple\n if(redox_flag == 1){\n redox_col_index <- grep(redox_aux, names(df), fixed = T, value = T)\n redox_col_index <- redox_col_index[substring(redox_col_index, 1, nchar(redox_aux)) == redox_aux]\n if(length(redox_col_index) > 0){\n if(!is.na(df[row, redox_col_index])){\n this_redox_value <- sprintf(\"%.4E\", df[row, redox_col_index])\n this_redox_unit <- paste(redox_aux, \"aux. sp.\")\n } else {\n vprint(paste0(\"Warning: non-numeric \", redox_aux, \" value in sample \",\n df[row, \"Sample\"], \". Resorting to using \",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n } else {\n if(!warned_about_redox_column){\n vprint(paste(\"Warning: no\", redox_aux, \"column found. Resorting to using\",\n \"Log fO2 (log bars) with a value of \", default_logfO2),\n verbose=verbose)\n warned_about_redox_column <- TRUE\n }\n this_redox_flag <- 0\n this_redox_value <- sprintf(\"%.4E\", default_logfO2)\n this_redox_unit <- paste0(\"Log fO2 (log bars) [default = \", default_logfO2, \"]\")\n assigned <- TRUE\n }\n }\n\n # append redox values\n df[row, \"redox_flag\"] <- this_redox_flag\n df[row, \"redox_value\"] <- this_redox_value\n df[row, \"redox_unit\"] <- this_redox_unit\n \n \n \n if(charge_balance_on == \"none\"){\n eq3.cb_block <- paste(\"\\n|Electrical balancing option (iebal3): |\",\n \"| [x] ( 0) No balancing is done |\",\n \"| [ ] ( 1) Balance on species |None | (uebal) |\", sep=\"\\n\")\n\n } else {\n eq3.cb_block <- paste(\n \"\\n|Electrical balancing option (iebal3): |\",\n \"| [ ] ( 0) No balancing is done |\",\n paste0(\"| [x] ( 1) Balance on species |\", format(charge_balance_on, width=24), \"| (uebal) |\"), sep=\"\\n\")\n }\n \n eq3.filename <- paste0(c(rownames(df)[row], \".3i\"), collapse = \"\") #create the name of the file\n\n eq3.header1 <- paste(\"|------------------------------------------------------------------------------|\",\n \"| Title | (utitl(n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"| |\",\n \"|\", sep=\"\\n\")\n\n eq3.samplename <- paste(c(\"Sample:\", format(df[row, \"Sample\"], width=70)), collapse = \" \")\n\n eq3.header2 <- paste(\"|\",\n \"| |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Special Basis Switches (for model definition only) | (nsbswt) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Replace |None | (usbsw(1,n)) |\",\n \"| with |None | (usbsw(2,n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Temperature (C) | \", sep=\"\\n\")\n\n eq3.temperature <- sprintf(\"%.5E\", temp_degC[row])\n \n if (pressure_override){\n eq3.header3 <- paste(\"| (tempc) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Pressure option (jpres3): |\",\n \"| [ ] ( 0) Data file reference curve value |\",\n \"| [ ] ( 1) 1.013-bar/steam-saturation curve value |\",\n paste0(\"| [x] ( 2) Value (bars) |\", format(sprintf(\"%.5E\", pressure_bar[row]), width=12, justify=\"right\"),\n \"| (press) |\"),\n \"|------------------------------------------------------------------------------|\",\n \"|Density (g/cm3) | \", sep=\"\\n\")\n }else if(strict_minimum_pressure == FALSE | pressure_bar[row] > minimum_pressure){\n eq3.header3 <- paste(\"| (tempc) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Pressure option (jpres3): |\",\n \"| [x] ( 0) Data file reference curve value |\",\n \"| [ ] ( 1) 1.013-bar/steam-saturation curve value |\",\n \"| [ ] ( 2) Value (bars) | 1.00000E+00| (press) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Density (g/cm3) | \", sep=\"\\n\")\n }else{\n eq3.header3 <- paste(\"| (tempc) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Pressure option (jpres3): |\",\n \"| [ ] ( 0) Data file reference curve value |\",\n \"| [ ] ( 1) 1.013-bar/steam-saturation curve value |\",\n paste0(\"| [x] ( 2) Value (bars) |\", format(sprintf(\"%.5E\", minimum_pressure), width=12, justify=\"right\"),\n \"| (press) |\"),\n \"|------------------------------------------------------------------------------|\",\n \"|Density (g/cm3) | \", sep=\"\\n\")\n }\n \n \n eq3.density <- sprintf(\"%.5E\", df[row, \"rho\"])\n\n eq3.header4 <- paste(\"| (rho) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Total dissolved solutes option (itdsf3): |\",\n \"| [x] ( 0) Value (mg/kg.sol) | 0.00000E+00| (tdspkg) |\",\n \"| [ ] ( 1) Value (mg/L) | 0.00000E+00| (tdspl) |\",\n \"|------------------------------------------------------------------------------|\",\n sep=\"\\n\")\n\n # cb_block will be pasted here (one for all samples)\n\n eq3.header5 <- paste(\"\\n|------------------------------------------------------------------------------|\",\n \"|Default redox constraint (irdxc3): |\", sep=\"\\n\")\n\n default_redox_minus3 <- \"\\n| [ ] (-3) Use O2(g) line in the aqueous basis species block |\"\n default_redox_minus2 <- \"| [ ] (-2) pe (pe units) | 0.00000E+00| (pei) |\"\n default_redox_minus1 <- \"| [ ] (-1) Eh (volts) | 0.00000E+00| (ehi) |\"\n default_redox_0 <- \"| [ ] ( 0) Log fO2 (log bars) | 0.00000E+00| (fo2lgi) |\"\n default_redox_1 <- \"| [ ] ( 1) Couple (aux. sp.) |None | (uredox) |\"\n\n\n if(df[row, \"redox_flag\"] == -3){\n default_redox_minus3 <- \"\\n| [x] (-3) Use O2(g) line in the aqueous basis species block |\"\n } else if(df[row, \"redox_flag\"] == -2){\n default_redox_minus2 <- paste0(\"| [x] (-2) pe (pe units) |\",\n format(df[row, \"redox_value\"], width=12, justify=\"right\"),\n \"| (pei) |\")\n } else if(df[row, \"redox_flag\"] == -1){\n default_redox_minus1 <- paste0(\"| [x] (-1) Eh (volts) |\",\n format(df[row, \"redox_value\"], width=12, justify=\"right\"),\n \"| (ehi) |\")\n } else if(df[row, \"redox_flag\"] == 0){\n default_redox_0 <- paste0(\"| [x] ( 0) Log fO2 (log bars) |\",\n format(df[row, \"redox_value\"], width=12, justify=\"right\"),\n \"| (fo2lgi) |\")\n } else if(df[row, \"redox_flag\"] == 1){\n default_redox_1 <- paste0(\"| [x] ( 1) Couple (aux. sp.) | \",\n format(redox_aux, width=23, justify=\"left\"),\n \"| (uredox) |\")\n } else {\n stop(paste0(\"Error when writing .3i file for sample \", df[row, \"Sample\"],\n \". Redox flag was not recognized! Choose -3, -2, -1, 0, or 1.\"))\n }\n redox_block <- paste(default_redox_minus3, default_redox_minus2,\n default_redox_minus1, default_redox_0,\n default_redox_1, sep = \"\\n\")\n\n eq3.header6 <- paste(\"\\n|------------------------------------------------------------------------------|\",\n \"|Aqueous Basis Species/Constraint Species |Conc., etc. |Units/Constraint|\",\n \"| (uspeci(n)/ucospi(n)) | (covali(n))|(ujf3(jflgi(n)))|\",\n \"|------------------------------------------------------------------------------|\",\n sep = \"\\n\")\n \n if(allowed_aq_block_species[1] == \"all\"){\n allowed_aq_block_species <- unlist(lapply(names(df), FUN=header_species))\n }\n \n # handle aqueous block\n aqueous_lines <- c()\n for(column in names(df)){\n if(suppress_missing & is.na(df[row, column])){\n df[row, column] <- 0\n }\n if(!is.na(df[row, column])){\n species_name <- header_species(column)\n if(!(species_name %in% exclude) && (species_name %in% allowed_aq_block_species)){\n species_value <- df[row, column]\n # EQ3 won't balance on a species if its concentration is 0 so\n # change it to a very small non-zero value\n if(charge_balance_on == species_name && as.numeric(species_value)==0){\n species_value <- 1e-99\n }\n species_unit <- header_unit(column, keepcase=T)\n if(!(species_unit %in% EQ3_jflags)){\n if(tolower(species_unit) == \"ppb\"){\n species_value <- species_value/1000\n species_unit <- \"mg/L\"\n } else if(tolower(species_unit) == \"ppm\"){\n species_unit <- \"mg/L\"\n } else {\n print(paste(\"Error creating .3i file:\", species_unit,\n \"is not a recognized aqueous block jflag. Try checking\",\n \"capitalization and spelling to match one of the following:\",\n paste(EQ3_jflags, collapse=\" \")))\n }\n }\n if(species_unit == \"Hetero. equil.\"){\n species_value_split <- strsplit(species_value, \" \")[[1]]\n if(length(species_value_split) == 2){\n # for gases\n species_value <- species_value_split[1]\n hetero_equil_species <- species_value_split[2]\n }else{\n # for minerals\n hetero_equil_species <- species_value\n species_value <- 0\n }\n \n }\n species_value <- format(sprintf(\"%.5E\", as.numeric(species_value)), width=12, justify=\"right\")\n this_aq_line <- paste0(\"\\n|\",\n format(species_name, width=48), \"|\",\n species_value, \"|\",\n format(species_unit, width=16), \"|\")\n # handle additional line for 'Hetero. equil.' jflag\n if(species_unit == \"Hetero. equil.\"){\n this_aq_line <- paste0(this_aq_line, \"\\n\", \"|->|\", format(hetero_equil_species, width=45), \"| \", format(\"(ucospi(n))\", width=28), \"|\")\n }\n aqueous_lines <- c(aqueous_lines, this_aq_line)\n }\n }\n }\n\n # suppressing species\n for(species in suppress){\n this_aq_line <- paste0(\"\\n|\",\n format(species, width=48), \"| \",\n sprintf(\"%.5E\", 0), \"|\",\n format(\"Suppressed\", width=16), \"|\")\n aqueous_lines <- c(aqueous_lines, this_aq_line)\n }\n\n aqueous_block <- paste(aqueous_lines, collapse=\"\")\n\n eq3.ender1 <- paste(\"\\n|------------------------------------------------------------------------------|\",\n \"* Valid jflag strings (ujf3(jflgi(n))) are: *\",\n \"* Suppressed Molality Molarity *\",\n \"* mg/L mg/kg.sol Alk., eq/kg.H2O *\",\n \"* Alk., eq/L Alk., eq/kg.sol Alk., mg/L CaCO3 *\",\n \"* Alk., mg/L HCO3- Log activity Log act combo *\",\n \"* Log mean act pX pH *\",\n \"* pHCl pmH pmX *\",\n \"* Hetero. equil. Homo. equil. Make non-basis *\",\n \"*------------------------------------------------------------------------------*\",\n \"|Create Ion Exchangers | (net) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Advisory: no exchanger creation blocks follow on this file. |\",\n \"|Option: on further processing (writing a PICKUP file or running XCON3 on the |\",\n \"|present file), force the inclusion of at least one such block (qgexsh): |\",\n \"| [ ] (.true.) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Ion Exchanger Compositions | (neti) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Exchanger phase |None | (ugexpi(n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|->|Moles/kg.H2O | 0.0000 | (cgexpi(n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|->|Exchange site |None | (ugexji(j,n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|--->|Exchange species |Eq. frac. | (this is a table header) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|--->|None | 0.00000E+00| (ugexsi(i,j,n), egexsi(i,j,n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Solid Solution Compositions | (nxti) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Solid Solution |None | (usoli(n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|->|Component |Mole frac. | (this is a table header) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|->|None | 0.00000E+00| (umemi(i,n), xbari(i,n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Alter/Suppress Options | (nxmod) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Species |Option |Alter value |\",\n \"| (uxmod(n)) |(ukxm(kxmod(n)))| (xlkmod(n))|\",\n \"|------------------------------------------------------------------------------|\", sep=\"\\n\")\n \n alter_block <- c()\n if(length(alter_options) > 0){\n for(i in 1:length(alter_options)){\n species <- names(alter_options)[i]\n option <- alter_options[[i]]\n if(length(option == 3)){\n alter_line <- paste0(\"\\n|\",\n format(species, width=48), \"| \",\n format(option[1], width=15), \"|\",\n format(sprintf(\"%.5E\", as.numeric(option[2])), width=12, justify=\"right\"), \"|\")\n }\n alter_block <- c(alter_block, alter_line)\n }\n alter_block <- paste(alter_block, collapse=\"\")\n }else{\n alter_block <- \"\\n|None |None | 0.00000E+00|\"\n }\n\n if(get_solid_solutions){\n ss_checkbox_ignore <- \" \"\n ss_checkbox_permit <- \"x\"\n }else{\n ss_checkbox_ignore <- \"x\"\n ss_checkbox_permit <- \" \"\n }\n \n eq3.ender2 <- paste(\"\\n|------------------------------------------------------------------------------|\",\n \"* Valid alter/suppress strings (ukxm(kxmod(n))) are: *\",\n \"* Suppress Replace AugmentLogK *\",\n \"* AugmentG *\",\n \"*------------------------------------------------------------------------------*\",\n \"|Iopt Model Option Switches (\\\"( 0)\\\" marks default choices) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopt(4) - Solid Solutions: |\",\n paste0(\"| [\", ss_checkbox_ignore, \"] ( 0) Ignore |\"),\n paste0(\"| [\", ss_checkbox_permit, \"] ( 1) Permit |\"),\n \"|------------------------------------------------------------------------------|\",\n \"|iopt(11) - Auto Basis Switching in pre-N-R Optimization: |\",\n \"| [x] ( 0) Turn off |\",\n \"| [ ] ( 1) Turn on |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopt(17) - PICKUP File Options: |\",\n \"| [ ] (-1) Don't write a PICKUP file |\",\n \"| [x] ( 0) Write a PICKUP file |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopt(19) - Advanced EQ3NR PICKUP File Options: |\",\n \"| [x] ( 0) Write a normal EQ3NR PICKUP file |\",\n \"| [ ] ( 1) Write an EQ6 INPUT file with Quartz dissolving, relative rate law |\",\n \"| [ ] ( 2) Write an EQ6 INPUT file with Albite dissolving, TST rate law |\",\n \"| [ ] ( 3) Write an EQ6 INPUT file with Fluid 1 set up for fluid mixing |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Iopg Activity Coefficient Option Switches (\\\"( 0)\\\" marks default choices) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopg(1) - Aqueous Species Activity Coefficient Model: |\",\n \"| [ ] (-1) The Davies equation |\",\n \"| [x] ( 0) The B-dot equation |\",\n \"| [ ] ( 1) Pitzer's equations |\",\n \"| [ ] ( 2) HC + DH equations |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopg(2) - Choice of pH Scale (Rescales Activity Coefficients): |\",\n \"| [ ] (-1) \\\"Internal\\\" pH scale (no rescaling) |\",\n \"| [x] ( 0) NBS pH scale (uses the Bates-Guggenheim equation) |\",\n \"| [ ] ( 1) Mesmer pH scale (numerically, pH = -log m(H+)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Iopr Print Option Switches (\\\"( 0)\\\" marks default choices) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(1) - Print All Species Read from the Data File: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(2) - Print All Reactions: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print the reactions |\",\n \"| [ ] ( 2) Print the reactions and log K values |\",\n \"| [ ] ( 3) Print the reactions, log K values, and associated data |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(3) - Print the Aqueous Species Hard Core Diameters: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(4) - Print a Table of Aqueous Species Concentrations, Activities, etc.: |\",\n \"| [ ] (-3) Omit species with molalities < 1.e-8 |\",\n \"| [ ] (-2) Omit species with molalities < 1.e-12 |\",\n \"| [ ] (-1) Omit species with molalities < 1.e-20 |\",\n \"| [x] ( 0) Omit species with molalities < 1.e-100 |\",\n \"| [ ] ( 1) Include all species |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(5) - Print a Table of Aqueous Species/H+ Activity Ratios: |\",\n \"| [ ] ( 0) Don't print |\",\n \"| [ ] ( 1) Print cation/H+ activity ratios only |\",\n \"| [x] ( 2) Print cation/H+ and anion/H+ activity ratios |\",\n \"| [ ] ( 3) Print ion/H+ activity ratios and neutral species activities |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(6) - Print a Table of Aqueous Mass Balance Percentages: |\",\n \"| [ ] (-1) Don't print |\",\n \"| [x] ( 0) Print those species comprising at least 99% of each mass balance |\",\n \"| [ ] ( 1) Print all contributing species |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(7) - Print Tables of Saturation Indices and Affinities: |\",\n \"| [ ] (-1) Don't print |\",\n \"| [x] ( 0) Print, omitting those phases undersaturated by more than 10 kcal |\",\n \"| [ ] ( 1) Print for all phases |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(8) - Print a Table of Fugacities: |\",\n \"| [ ] (-1) Don't print |\",\n \"| [x] ( 0) Print |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(9) - Print a Table of Mean Molal Activity Coefficients: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(10) - Print a Tabulation of the Pitzer Interaction Coefficients: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print a summary tabulation |\",\n \"| [ ] ( 2) Print a more detailed tabulation |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iopr(17) - PICKUP file format (\\\"W\\\" or \\\"D\\\"): |\",\n \"| [x] ( 0) Use the format of the INPUT file |\",\n \"| [ ] ( 1) Use \\\"W\\\" format |\",\n \"| [ ] ( 2) Use \\\"D\\\" format |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Iodb Debugging Print Option Switches (\\\"( 0)\\\" marks default choices) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iodb(1) - Print General Diagnostic Messages: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print Level 1 diagnostic messages |\",\n \"| [ ] ( 2) Print Level 1 and Level 2 diagnostic messages |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iodb(3) - Print Pre-Newton-Raphson Optimization Information: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print summary information |\",\n \"| [ ] ( 2) Print detailed information (including the beta and del vectors) |\",\n \"| [ ] ( 3) Print more detailed information (including matrix equations) |\",\n \"| [ ] ( 4) Print most detailed information (including activity coefficients) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iodb(4) - Print Newton-Raphson Iteration Information: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print summary information |\",\n \"| [ ] ( 2) Print detailed information (including the beta and del vectors) |\",\n \"| [ ] ( 3) Print more detailed information (including the Jacobian) |\",\n \"| [ ] ( 4) Print most detailed information (including activity coefficients) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|iodb(6) - Print Details of Hypothetical Affinity Calculations: |\",\n \"| [x] ( 0) Don't print |\",\n \"| [ ] ( 1) Print summary information |\",\n \"| [ ] ( 2) Print detailed information |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Numerical Parameters |\",\n \"|------------------------------------------------------------------------------|\",\n \"| Beta convergence tolerance | 0.00000E+00| (tolbt) |\",\n \"| Del convergence tolerance | 0.00000E+00| (toldl) |\",\n \"| Max. Number of N-R Iterations | 0 | (itermx) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Ordinary Basis Switches (for numerical purposes only) | (nobswt) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Replace |None | (uobsw(1,n)) |\",\n \"| with |None | (uobsw(2,n)) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Sat. flag tolerance | 0.00000E+00| (tolspf) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|Aq. Phase Scale Factor | 1.00000E+00| (scamas) |\",\n \"|------------------------------------------------------------------------------|\",\n \"|End of problem |\",\n \"|------------------------------------------------------------------------------|\", sep=\"\\n\")\n\n\n this_file <- paste0(eq3.header1, eq3.samplename, eq3.header2,\n eq3.temperature, eq3.header3, eq3.density,\n eq3.header4, eq3.cb_block, eq3.header5,\n redox_block, eq3.header6, aqueous_block,\n eq3.ender1, alter_block, eq3.ender2,\n collapse = \"\")\n\n\n write(this_file, paste0(input_dir, \"/\", eq3.filename), append=FALSE)\n\n return(warned_about_redox_column)\n \n}", "meta": {"hexsha": "9f9ead8833d4da2724cb813481a49b315481e87b", "size": 47110, "ext": "r", "lang": "R", "max_stars_repo_path": "AqEquil/preprocess_for_EQ3.r", "max_stars_repo_name": "worm-portal/AqEquil", "max_stars_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-04T00:44:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T18:57:43.000Z", "max_issues_repo_path": "AqEquil/preprocess_for_EQ3.r", "max_issues_repo_name": "worm-portal/AqEquil", "max_issues_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqEquil/preprocess_for_EQ3.r", "max_forks_repo_name": "worm-portal/AqEquil", "max_forks_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.3180827887, "max_line_length": 186, "alphanum_fraction": 0.4071746975, "num_tokens": 10573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767283, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2439927804038579}} {"text": "# The MIT License (MIT)\n# Copyright (c) 2017 Louise AC Millard, MRC Integrative Epidemiology Unit, University of Bristol\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without\n# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions\n# of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n\nmakeQQPlot <- function(resDir, resultsAll) {\n\n\t## remove the fields excluded as stated in variable information file\n idx = which(is.na(resultsAll[,\"isTraitOfInterest\"]) | resultsAll[,\"isTraitOfInterest\"]==\"\")\n\n\tprint(paste(\"Number not exposure variable:\", length(idx)))\n\n\tresultsIncluded = resultsAll[idx,];\n\tpvalues = sort(resultsIncluded[,\"pvalue\"]);\n\n\tnumRes = length(pvalues)\n\tpSort = sort(pvalues)\n\trank = rank(pSort, ties.method=\"first\")\n\trankProportion = rank/numRes\n\trankProportionLog10 = -log10(rankProportion)\n\tpLog10 = -log10(pSort)\n\n\t## do bonferroni correction and output this.\n\tbonf= 0.05/numRes\n\tprint(paste('Bonferroni threshold:', bonf))\n\tthreshold = -log10(bonf)\n\tbelowBonf = length(which(pSort0) {\n print(paste(\"There are \", length(idxZero),\" results with pvalues too small to be stored exactly, colored red on QQ plot.\", sep=\"\"))\n }\n\n\t# set indicator for pvalue ~zero (we don't have a precise p value for these results), these are coloured red on QQ plot\n\tzeroVal = rep(0, length(rankProportionLog10))\n\tzeroVal[idxZero] = 1\n\tzeroVal = as.factor(zeroVal)\n\tpLog10[idxZero] = -log10(5e-324)\n\n\t## plot qqplot\n\tpdf(paste(resDir,\"qqplot.pdf\",sep=\"\"))\n\n\t# qq\n\tpar(pch='.')\n\tplot(rankProportionLog10, pLog10,col=c(\"#990099\", \"red\")[zeroVal], xlab='expected -log10(p)', ylab='actual -log10(p)',cex=0.8, pch=c(16, 8)[zeroVal])\n\n\t# ascending diagonal, dotted blue\n\tminVal = min(max(rankProportionLog10), max(pLog10))\n\tsegments(0, 0, minVal, minVal, col='#0066cc',lty=3)\t\n\n\t# horizontal threshold line, dashed green\n\tsegments(0, threshold, max(rankProportionLog10), threshold, col='#008000',lty=2)\n\n\tjunk<- dev.off()\n\n\tprint(\"Finished QQ plot\")\n\n}\n", "meta": {"hexsha": "094ca003fb74ef8559c378b2653ea42feea49d53", "size": 3035, "ext": "r", "lang": "R", "max_stars_repo_path": "resultsProcessing/makeQQPlot.r", "max_stars_repo_name": "carbocation/PHESANT", "max_stars_repo_head_hexsha": "9f7609e905ceecc0aa0e8173b425e0e81fd0c0c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2017-02-27T00:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:42:01.000Z", "max_issues_repo_path": "resultsProcessing/makeQQPlot.r", "max_issues_repo_name": "carbocation/PHESANT", "max_issues_repo_head_hexsha": "9f7609e905ceecc0aa0e8173b425e0e81fd0c0c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-05-07T13:39:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:55.000Z", "max_forks_repo_path": "resultsProcessing/makeQQPlot.r", "max_forks_repo_name": "carbocation/PHESANT", "max_forks_repo_head_hexsha": "9f7609e905ceecc0aa0e8173b425e0e81fd0c0c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2017-02-27T12:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T22:03:16.000Z", "avg_line_length": 40.4666666667, "max_line_length": 150, "alphanum_fraction": 0.7301482702, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2433898135257869}} {"text": "#functions used to calculate differentiation between two populations or diversity statistics within populations\n# make sure the output file is already written in format (header):\n# population1\tpopulation2\tstatistic\tchromosome\tstart\tend\tnumber_sites\tnumber_variable_sites\tcalculated_stat\n# e.g., write(c(\"pop1\", \"pop2\", \"stat\", \"chr\", \"start\", \"end\", \"number_sites\", \"number_variable_sites\", \"calculated_stat\"), ncolumns=9, file=outname, sep=\"\\t\")\n\n# input is simplified vcf (entire vcf) and 3-column popmap (ordered the same as the vcf) and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\nheterozygosity <- function(xxx, popmap, outname, filename) {\n\toptions(scipen=999)\n\txxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n\tfor(a in 1:nrow(popmap)) {\n\t\toutput_rep <- c(popmap[a,1], \"none\", \"heterozygosity\", strsplit(filename, \":\")[[1]][1], \n\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]))\n\t\t# select this individual\n\t\ta_rep <- xxx[,a+3]\n\t\t# remove missing genotypes\n\t\ta_rep <- a_rep[a_rep != \"./.\"]\n\t\t# count number of sites\n\t\ta_total <- length(a_rep)\n\t\t# remove phasing information\n\t\ta_rep <- gsub(\"\\\\|\", \"/\", a_rep)\n\t\t# find number of heterozygous sites\n\t\ta_het <- length(a_rep[a_rep == \"0/1\"])\n\t\t# add to output\n\t\toutput_rep <- c(output_rep, a_total, a_het, a_het/a_total)\n\t\twrite(output_rep, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t}\n}\n\n\n# function to determine if a site is polymorphic (to be applied across rows)\n# used in pi_tajima_theta function\npolymorphic_function <- function(xxx) {\n\treturn(length(unique(xxx)))\n}\n# function to determine frequency of allele 1 (to be applied across rows)\n# used in pi_tajima_theta function\np_function <- function(xxx) {\n\txxxx <- c(sapply(strsplit(xxx, \"/\"), \"[[\", 1), sapply(strsplit(xxx, \"/\"), \"[[\", 2))\n\txxxx <- length(xxxx[xxxx == 0])\n\treturn(xxxx)\n}\n# function to determine frequency of allele 2 (to be applied across rows)\n# used in pi_tajima_theta function\nq_function <- function(xxx) {\n\txxxx <- c(sapply(strsplit(xxx, \"/\"), \"[[\", 1), sapply(strsplit(xxx, \"/\"), \"[[\", 2))\n\txxxx <- length(xxxx[xxxx == 1])\n\treturn(xxxx)\n}\n\n# input is simplified vcf (subsampled to single population (plus initial three columns)), \n# the name of the populations, and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\n# no missing data allowed\n# estimate watterson's theta, nucleotide diversity, and tajima's d with the formulae from \n# Carlson et al. 2005: 10.1101/gr.4326505 (equations 1, 2, and 4)\n\n# e.g., xxx <- test[,c(1,2,3,5,6,7)]\npi_tajima_theta <- function(xxx, popname, outname, filename) {\n\toptions(scipen=999)\n\t# remove sites that are not either invariant or bi-allelic SNPs\n\txxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n\t# remove phasing information\n\tfor(a in 4:ncol(xxx)) {\n\t\txxx[,a] <- gsub(\"\\\\|\", \"/\", xxx[,a])\n\t}\n\t# remove sites with missing data\n\tfor(a in 4:ncol(xxx)) {\n\t\txxx <- xxx[xxx[,a] != \"./.\",]\n\t}\n\t\n\t# define number of chromosomes sampled\n\tn_chromosomes <- (ncol(xxx) - 3) * 2\n\t# define number of sites genotyped for this population without missing data\n\tn_sites <- nrow(xxx)\n\t\n\t# continue if there are sites genotyped\n\tif(n_sites > 0) {\n\t\t# subset to only polymorphic sites\n\t\txxx <- xxx[apply(xxx[,4:ncol(xxx)], 1, polymorphic_function) > 1, ]\n\t\t\n\t\t# count polymorphic sites\n\t\tn_polymorphic <- nrow(xxx)\n\t\t\n\t\t# determine denominator of theta calculation\n\t\ttheta_denominator <- sum(1 / seq(from=1, to=(n_chromosomes - 1)))\n\t\t\n\t\t# continue if there are polymorphic sites\n\t\tif(n_polymorphic > 0) {\n\t\t\t# calculate per site theta\n\t\t\ttheta <- (n_polymorphic / theta_denominator) / n_sites\n\t\t\t\t\t\t\t\n\t\t\t# calculate frequencies of alleles 1 and 2 for each polymorphic site\n\t\t\tp_freq <- as.vector(apply(xxx[,4:ncol(xxx)], 1, p_function)) / n_chromosomes\n\t\t\tq_freq <- as.vector(apply(xxx[,4:ncol(xxx)], 1, q_function)) / n_chromosomes\n\t\t\t\n\t\t\t# calculate per site nucleotide diversity (pi)\n\t\t\tpi <- sum(2 * p_freq * q_freq) * (n_chromosomes / (n_chromosomes - 1)) / n_sites\n\t\t\t\n\t\t\t# calculate D using the variance of d (and all necessary subcomponents)\n\t\t\ta1 <- sum(1 / seq(from=1, to=(n_chromosomes - 1)))\n\t\t\ta2 <- sum(1 / (seq(from=1, to=(n_chromosomes - 1))^2))\n\t\t\tb1 <- (n_chromosomes + 1) / (3 * (n_chromosomes - 1))\n\t\t\tb2 <- (2 * (n_chromosomes^2 + n_chromosomes + 3)) / (9 * n_chromosomes * (n_chromosomes - 1))\n\t\t\tc1 <- b1 - (1 / a1)\n\t\t\tc2 <- b2 - ((n_chromosomes + 2) / (a1 * n_chromosomes)) + (a2 / (a1^2))\n\t\t\te1 <- c1 / a1\n\t\t\te2 <- c2 / ((a1^2) + a2)\n\t\t\tVar_d <- (e1 * n_polymorphic) + (e2 * n_polymorphic * (n_polymorphic - 1))\n\t\t\tTajima_D <- ((pi * n_sites - theta * n_sites)) / sqrt(Var_d)\n\t\t\t\n\t\t\t# write output\n\t\t\toutput_rep1 <- c(popname, \"none\", \"theta\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, theta)\n\t\t\toutput_rep2 <- c(popname, \"none\", \"pi\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, pi)\n\t\t\toutput_rep3 <- c(popname, \"none\", \"Tajima_D\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, Tajima_D)\n\t\t\twrite(output_rep1, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t\twrite(output_rep2, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t\twrite(output_rep3, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t} else { # if no polymorphic sites retained\n\t\t\toutput_rep1 <- output_rep1 <- c(popname, \"none\", \"theta\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, \"NA\")\n\t\t\toutput_rep2 <- output_rep1 <- c(popname, \"none\", \"pi\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, \"NA\")\n\t\t\toutput_rep3 <- output_rep1 <- c(popname, \"none\", \"Tajima_D\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_polymorphic, \"NA\")\n\t\t\twrite(output_rep1, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t\twrite(output_rep2, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t\twrite(output_rep3, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\t}\n\t} else { # if no sites retained\n\t\toutput_rep1 <- output_rep1 <- c(popname, \"none\", \"theta\", strsplit(filename, \":\")[[1]][1], \n\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\tn_sites, \"NA\", \"NA\")\n\t\toutput_rep2 <- output_rep1 <- c(popname, \"none\", \"pi\", strsplit(filename, \":\")[[1]][1], \n\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\tn_sites, \"NA\", \"NA\")\n\t\toutput_rep3 <- output_rep1 <- c(popname, \"none\", \"Tajima_D\", strsplit(filename, \":\")[[1]][1], \n\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\tn_sites, \"NA\", \"NA\")\n\t\twrite(output_rep1, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\twrite(output_rep2, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\twrite(output_rep3, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t}\n\t\n}\n\n\n\n# function to determine if a site is only missing data for a population (used across rows of vcf)\n# used in differentiation function\ntotal_missing <- function(xxx) {\n\treturn(length(xxx[xxx != \"./.\"]) > 0)\n}\t\t\t\n# function to determine if a site is polymorphic (to be applied across rows) after removing missing\n# used in differentiation function\npolymorphic_function2 <- function(xxx) {\n\txxx <- xxx[xxx != \"./.\"]\n\treturn(length(unique(xxx)))\n}\t\t\t\n\n# input is two simplified vcfs (subsampled to single population), already filtered for invariant/biallelic SNPs, \n# the names of the populations, and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\n# fst is calculation of Reich et al. 2009\n# fst is the reich et al. 2009 estimator for small sample sizes\n# equation presented nicer in Willing et al. 2012 page 9\n\n\ndifferentiation <- function(xxx1, xxx2, popname1, popname2, outname, filename) {\n\t# remove phasing information\n\tfor(a in 1:ncol(xxx1)) {\n\t\txxx1[,a] <- gsub(\"\\\\|\", \"/\", xxx1[,a])\n\t}\n\tfor(a in 1:ncol(xxx2)) {\n\t\txxx2[,a] <- gsub(\"\\\\|\", \"/\", xxx2[,a])\n\t}\n\t\n\t# remove sites that are completely missing from either population\n\tkeep1 <- apply(xxx1, 1, total_missing)\n\tkeep2 <- apply(xxx2, 1, total_missing)\n\txxx1 <- xxx1[keep1 == TRUE & keep2 == TRUE, ]\n\txxx2 <- xxx2[keep1 == TRUE & keep2 == TRUE, ]\n\t\n\t# count the total number of included genotyped sites at this point\n\tn_sites <- nrow(xxx1)\n\t\n\t# combine the two matrices to find sites that are variant w/in and between the two pops\n\txxx_combined <- cbind(xxx1, xxx2)\n\tvariant_sites <- apply(xxx_combined, 1, polymorphic_function2)\n\t\n\t# keep only variant sites\n\txxx1_variant <- xxx1[variant_sites > 1, ]\n\txxx2_variant <- xxx2[variant_sites > 1, ]\n\t\n\t# count the number of variant sites\n\tn_variant_sites <- nrow(xxx1_variant)\n\t\n\t# loop for each polymorphic site to calculate dxy\n\tdxy_all <- list()\n\tfor(a in 1:nrow(xxx1_variant)) {\n\t\ta_rep1 <- as.character(xxx1_variant[a,])\n\t\ta_rep2 <- as.character(xxx2_variant[a,])\n\t\t\n\t\t# remove missing\n\t\ta_rep1 <- a_rep1[a_rep1 != \"./.\"]\n\t\ta_rep2 <- a_rep2[a_rep2 != \"./.\"]\n\t\t\n\t\t# measure proportion of reference allele \n\t\ta_ref1 <- (length(a_rep1[a_rep1 == \"0/0\"]) * 2 + length(a_rep1[a_rep1 == \"0/1\"]) * 1) / (length(a_rep1) * 2)\n\t\ta_ref2 <- (length(a_rep2[a_rep2 == \"0/0\"]) * 2 + length(a_rep2[a_rep2 == \"0/1\"]) * 1) / (length(a_rep2) * 2)\n\t\t\n\t\t# calc dxy\n\t\tdxy_all[[a]] <- a_ref1 * (1 - a_ref2) + a_ref2 * (1 - a_ref1)\n\t}\n\tdxy_all <- sum(unlist(dxy_all)) / n_sites\n\t\n\t\n\t# loop for each polymorphic site to calculate fst\n\tnumerator_all <- list()\n\tdenominator_all <- list()\n\tfor(a in 1:nrow(xxx1_variant)) {\n\t\ta_rep1 <- as.character(xxx1_variant[a,])\n\t\ta_rep2 <- as.character(xxx2_variant[a,])\n\t\t\n\t\t# remove missing\n\t\ta_rep1 <- a_rep1[a_rep1 != \"./.\"]\n\t\ta_rep2 <- a_rep2[a_rep2 != \"./.\"]\n\n\t\t# number of individuals per population\n\t\tpop1_ind_count <- length(a_rep1) \n\t\tpop2_ind_count <- length(a_rep2)\n\t\t\n\t\t# non-reference allele counts\n\t\talt_allele_count1 <- (2 * length(a_rep1[a_rep1 == \"1/1\"]) + 1 * length(a_rep1[a_rep1 == \"0/1\"]))\n\t\talt_allele_count2 <- (2 * length(a_rep2[a_rep2 == \"1/1\"]) + 1 * length(a_rep2[a_rep2 == \"0/1\"]))\n\n\t\t# total allele counts\n\t\tall_allele_count1 <- 2 * length(a_rep1)\n\t\tall_allele_count2 <- 2 * length(a_rep2)\n\n\t\t# expected heterozygosity for each population\n\t\texpected_het1 <- (alt_allele_count1 * (all_allele_count1 - alt_allele_count1)) / \n\t\t\t(all_allele_count1 * (all_allele_count1 - 1))\n\t\texpected_het2 <- (alt_allele_count2 * (all_allele_count2 - alt_allele_count2)) / \n\t\t\t(all_allele_count2 * (all_allele_count2 - 1))\n\n\t\t# find the fst numerator and denominator values for this snp (they all get summed and divided for \n\t\t# the final estimate)\n\t\tnumerator_all[[a]] <- (alt_allele_count1 / (2 * pop1_ind_count) - \n\t\t\talt_allele_count2 / (2 * pop2_ind_count))^2 - (expected_het1 / (2 * pop1_ind_count)) - \n\t\t\t(expected_het2 / (2 * pop2_ind_count))\n\t\tdenominator_all[[a]] <- numerator_all[[a]] + expected_het1 + expected_het2\t\t\n\t}\n\t# calculate total fst for this window\n\tfst_all <- sum(unlist(numerator_all)) / sum(unlist(denominator_all))\n\t\n\t# write to output for dxy and fst\n\toutput_rep1 <- c(popname1, popname2, \"Dxy\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_variant_sites, dxy_all)\n\toutput_rep2 <- c(popname1, popname2, \"Fst\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_variant_sites, fst_all)\n\twrite(output_rep1, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\twrite(output_rep2, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\n}\n\n\n\n\n# input is one simplified vcfs, \n# the popmap, and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only for invariant sites and biallelic snps\n# lastly, input number of sites needed to write file\n\ncreate_fasta_from_vcf <- function(xxx, popmap, outname, filename, num_sites_needed) {\n\toptions(scipen=999)\n\t# remove sites that are not either invariant or bi-allelic SNPs\n\txxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n\t\n\t# keep going only if enough sites\n\tif(num_sites_needed <= nrow(xxx)) {\n\t\t# remove phasing information\n\t\tfor(a in 4:ncol(xxx)) {\n\t\t\txxx[,a] <- gsub(\"\\\\|\", \"/\", xxx[,a])\n\t\t}\n\t\t\n\t\t# define names of individuals in output fasta\n\t\toutput_names_fasta <- paste(\">\", popmap[,1], sep=\"\")\n\t\t\n\t\t# subset the genotypes from the allele info\n\t\tallele_info <- xxx[,2:3]\n\t\tgenotypes <- xxx[,4:ncol(xxx)]\n\t\t\n\t\t# convert all numbers in genotypes to actual bases and ambiguities\n\t\tfor(a in 1:nrow(genotypes)) {\n\t\t\tif(allele_info[a,2] == \".\") { # if non-polymorphic\n\t\t\t\tgenotypes[a,] <- gsub(\"0/0\", allele_info[a,1], genotypes[a,])\n\t\t\t\tgenotypes[a,] <- gsub(\"\\\\./\\\\.\", \"?\", genotypes[a,])\n\t\t\t} else { # if polymorphic\n\t\t\t\tboth_genotypes <- sort(as.character(allele_info[a,]))\n\t\t\t\tif(both_genotypes[1] == \"A\" & both_genotypes[2] == \"C\") { het = \"M\" }\n\t\t\t\tif(both_genotypes[1] == \"A\" & both_genotypes[2] == \"G\") { het = \"R\" }\n\t\t\t\tif(both_genotypes[1] == \"A\" & both_genotypes[2] == \"T\") { het = \"W\" }\n\t\t\t\tif(both_genotypes[1] == \"C\" & both_genotypes[2] == \"G\") { het = \"S\" }\n\t\t\t\tif(both_genotypes[1] == \"C\" & both_genotypes[2] == \"T\") { het = \"Y\" }\n\t\t\t\tif(both_genotypes[1] == \"G\" & both_genotypes[2] == \"T\") { het = \"K\" }\n\t\t\t\tgenotypes[a,] <- gsub(\"0/0\", allele_info[a,1], genotypes[a,])\n\t\t\t\tgenotypes[a,] <- gsub(\"\\\\./\\\\.\", \"?\", genotypes[a,])\n\t\t\t\tgenotypes[a,] <- gsub(\"1/1\", allele_info[a,2], genotypes[a,])\n\t\t\t\tgenotypes[a,] <- gsub(\"0/1\", het, genotypes[a,])\n\t\t\t}\n\t\t}\n\t\t\n\t\t# write output\n\t\tfor(a in 1:ncol(genotypes)) {\n\t\t\tif(a == 1) {\n\t\t\t\twrite(output_names_fasta[a], file=outname, ncolumns=1)\n\t\t\t\twrite(paste(genotypes[,a], collapse=\"\"), file=outname, ncolumns=1, append=T)\n\t\t\t} else {\n\t\t\t\twrite(output_names_fasta[a], file=outname, ncolumns=1, append=T)\n\t\t\t\twrite(paste(genotypes[,a], collapse=\"\"), file=outname, ncolumns=1, append=T)\n\t\t\t}\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "18cb7be2c72977f8b64175f671e15a002ccbbbc0", "size": 15277, "ext": "r", "lang": "R", "max_stars_repo_path": "16_revisions/window_stat_calculations.r", "max_stars_repo_name": "jdmanthey/certhia_genomes1", "max_stars_repo_head_hexsha": "95cce3cf7375203fe8b9970e2b0b19f70bb18559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "16_revisions/window_stat_calculations.r", "max_issues_repo_name": "jdmanthey/certhia_genomes1", "max_issues_repo_head_hexsha": "95cce3cf7375203fe8b9970e2b0b19f70bb18559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "16_revisions/window_stat_calculations.r", "max_forks_repo_name": "jdmanthey/certhia_genomes1", "max_forks_repo_head_hexsha": "95cce3cf7375203fe8b9970e2b0b19f70bb18559", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-23T23:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T06:42:20.000Z", "avg_line_length": 43.1553672316, "max_line_length": 159, "alphanum_fraction": 0.6482293644, "num_tokens": 4996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24276019912445274}} {"text": "#' Trains an ARTMAP network on the given input data.\n#' \n#' This function trains an ARTMAP network on the given input data. Each sample\n#' of the data is presented to the network, which categorizes each sample\n#' and compares that category's entry in the map field to the supervisor signal.\n#' If the map field value and the supervisor signal do not match, match-tracking\n#' is induced until a category is found to code the input correctly. This\n#' category then learns the input vector.\n#' \n#' The function returns a new ARTMAP network which has learned the input data\n#' according to the supervisor signal. If the maximum number of categories \n#' is reached and an appropriate categorization of the input cannot be made,\n#' no learning occurs. The program prints out a warning message that the \n#' maximum category limit has been reached and begins to process the next\n#' input vector.\n#' @title ARTMAP_Learn\n#' @param artmap_network ARTMAP network to be trained It should be created with ARTMAP_Create_Network().\n#' @param data Training data to be presented to the network. It is a matrix of size NumFeatures-by-NumSamples.\n#' @param supervisor the correct classification for each input vector. It is a matrix of size 1-by-NumSamples.\n#' @return New ARTMAP network which has learned the input data.\n#' @export\nARTMAP_Learn=function(artmap_network, data, supervisor)\n{\n # Make sure the user specifies the input parameters.\n if(nargs() != 3)\n {\n stop('You must specify all 3 input parameters.');\n }\n \n # Make sure that the data is appropriate for the given network.\n numFeatures = ncol(data);\n numSamples = nrow(data);\n if(numFeatures != artmap_network$numFeatures)\n {\n stop('The data does not contain the same number of features as the network.');\n }\n \n # Make sure the vigilance is within the (0, 1] range.\n if((artmap_network$vigilance <= 0) | (artmap_network$vigilance > 1))\n {\n stop('The vigilance must be within the range (0, 1].');\n }\n \n # Make sure that the number of epochs is a positive integer.\n if(artmap_network$numEpochs < 1)\n {\n stop('The number of epochs must be a positive integer.');\n }\n \n # Go through the data once for every epoch.\n for (epochNumber in 1:artmap_network$numEpochs)\n {\n # This variable will allow us to keep up with the total\n # network change due to learning.\n # Initialize the number of changes to 0.\n numChanges = 0;\n \n # Classify and learn on each sample.\n for (sampleNumber in 1:numSamples)\n { \n # Get the current data sample.\n currentData = data[sampleNumber,];\n \n # Get the current supervisory signal.\n currentSupervisor = supervisor[sampleNumber,1];\n \n # Create a new category if this supervisory signal\n # has never been seen before.\n if((length(artmap_network$mapField)==0) | (length(which(artmap_network$mapField == currentSupervisor)))==0)\n {\n auxList = ARTMAP_Add_New_Category(artmap_network$weight, artmap_network$mapField);\n resizedWeight=auxList[[1]];\n resizedMapField=auxList[[2]];\n auxList = ART_Update_Weights(currentData, resizedWeight, length(resizedMapField), artmap_network$learningRate);\n resizedWeight = auxList[[1]];\n weightChange = auxList[[2]];\n artmap_network$weight = resizedWeight;\n artmap_network$numCategories = artmap_network$numCategories + 1;\n resizedMapField[length(resizedMapField),1] = currentSupervisor;\n artmap_network$mapField = resizedMapField;\n numChanges = numChanges + 1;\n next; \n }\n else\n { \n # Activate the categories for this sample.\n bias = artmap_network$bias;\n categoryActivation = ART_Activate_Categories(currentData, artmap_network$weight, bias);\n \n # Rank the activations in order from highest to lowest.\n # This will allow us easier access to step through the categories.\n auxList = sort(-categoryActivation,index.return=TRUE);\n sortedActivations = auxList[[1]];\n sortedCategories = auxList[[2]];\n \n # Go through the process of locating the highest activated category\n # with the correct value in the map field for the supervisory signal.\n matchTracking = 1;\n vigilance = artmap_network$vigilance;\n \n # Go through each category in the sorted list looking for the best match.\n resonance = 0;\n match = 0;\n numSortedCategories = length(sortedCategories);\n currentSortedIndex = 1;\n while(!resonance)\n { \n # Get the current category based on the sorted index.\n currentCategory = sortedCategories[currentSortedIndex];\n \n # Get the current weight vector from the sorted category list.\n currentWeightVector = artmap_network$weight[currentCategory,];\n \n # Calculate the match given the current data sample and weight vector.\n match = ART_Calculate_Match(currentData, currentWeightVector);\n \n # Check to see if the match is less than the vigilance.\n if(match < vigilance)\n {\n # If so, choose the next category in the sorted category list.\n # If the current category is the last in the list, make sure that\n # the maximum number of categories have not been reached. If the \n # maximum has not been reached, create a new category for the input, \n # update the weights, and induce resonance.\n if(currentSortedIndex == numSortedCategories)\n {\n if(currentSortedIndex == artmap_network$maxNumCategories)\n {\n print('WARNING: The maximum number of categories has been reached.\\n');\n resonance = 1;\n }\n else\n {\n auxList = ARTMAP_Add_New_Category(artmap_network$weight, artmap_network$mapField);\n resizedWeight = auxList[[1]];\n resizedMapField = auxList[[2]];\n auxList = ART_Update_Weights(currentData, resizedWeight, currentSortedIndex + 1, artmap_network$learningRate);\n resizedWeight = auxList[[1]];\n weightChange = auxList[[2]];\n artmap_network$weight = resizedWeight;\n artmap_network$numCategories = artmap_network$numCategories + 1;\n resizedMapField[currentSortedIndex + 1,1] = currentSupervisor;\n artmap_network$mapField = resizedMapField;\n \n # Increment the number of changes since we added a new category.\n numChanges = numChanges + 1; \n resonance = 1;\n }\n }\n else\n {\n currentSortedIndex = currentSortedIndex + 1;\n } \n }\n else \n {\n # Otherwise, check the category's value in the map field.\n if(artmap_network$mapField[currentCategory,1] == currentSupervisor)\n {\n # If they're equal, the category should code the input.\n # Therefore, we should update the weights and induce resonance.\n auxList = ART_Update_Weights(currentData, artmap_network$weight, currentCategory, artmap_network$learningRate);\n artmap_network$weight = auxList[[1]];\n weightChange = auxList[[2]];\n if(weightChange == 1)\n {\n numChanges = numChanges + 1;\n } \n resonance = 1;\n }\n else\n {\n # If they're not equal, we must find another category by\n # inducing match-tracking. This means that we should increase\n # the vigilance by the current match plus epsilon and then \n # continue through the category list until another match is\n # found.\n vigilance = match + 0.000001;\n if(currentSortedIndex == numSortedCategories)\n {\n if(currentSortedIndex == artmap_network$maxNumCategories)\n { \n print('WARNING: The maximum number of categories has been reached.\\n');\n resonance = 1;\n } \n else\n {\n auxList = ARTMAP_Add_New_Category(artmap_network$weight, artmap_network$mapField);\n resizedWeight = auxList[[1]];\n resizedMapField = auxList[[2]];\n auxList = ART_Update_Weights(currentData, resizedWeight, currentSortedIndex + 1, artmap_network$learningRate);\n resizedWeight = auxList[[1]];\n weightChange = auxList[[2]];\n artmap_network$weight = resizedWeight;\n artmap_network$numCategories = artmap_network$numCategories + 1;\n resizedMapField[currentSortedIndex + 1,1] = currentSupervisor;\n artmap_network$mapField = resizedMapField;\n \n # Increment the number of changes since we added a new category.\n numChanges = numChanges + 1;\n \n resonance = 1;\n }\n }\n else\n {\n currentSortedIndex = currentSortedIndex + 1;\n resonance = 0;\n }\n }\n }\n }\n }\n }\n \n # If the network didn't change at all during the last epoch,\n # then we've reached equilibrium. Thus, we can stop training.\n if(numChanges == 0)\n {\n break;\n }\n }\n artmap_network$neededEpochs=epochNumber\n print(sprintf('The number of epochs needed was %d\\n', epochNumber));\n \n # Fill the new network with the appropriate values.\n new_artmap_network = artmap_network;\n \n return (new_artmap_network);\n}", "meta": {"hexsha": "ffa54de0b2ccf480cf2aacde3952565374962977", "size": 9907, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ARTMAP_Learn.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ARTMAP_Learn.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ARTMAP_Learn.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0739130435, "max_line_length": 128, "alphanum_fraction": 0.6159281316, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}} {"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 results.\n#' The dca function performs decision curve analysis for binary outcomes.\n#' See http://www.decisioncurveanalysis.org for more information.\n#'\n#' @author Daniel D Sjoberg\n#'\n#' @param formula formula\n#' @param data a data frame containing the outcome of the outcome predictions.\n#' @param thresholds vector of threshold probabilities between 0 and 1.\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.\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#' @return List including net benefit of each variable\n#' @seealso [`autoplot.dca()`], [`as_tibble.dca()`]\n#'\n#' @examples\n#' dca(cancer ~ cancerpredmarker, data = df_binary)\n#'\n#' dca(Surv(ttcancer, cancer) ~ cancerpredmarker, data = df_surv, time = 1)\n#'\n#' @export\n\ndca <- function(formula, data, thresholds = seq(0.01, 0.99, length.out = 99),\n label = NULL, harm = NULL, as_probability = character(),\n time = NULL, prevalence = NULL) {\n # checking inputs ------------------------------------------------------------\n if (!is.data.frame(data)) stop(\"`data=` must be a data frame\")\n if (!inherits(formula, \"formula\")) stop(\"`formula=` must be a formula\")\n\n # prepping data --------------------------------------------------------------\n thresholds <- thresholds[thresholds > 0 & thresholds < 1]\n label <- list(all = \"Treat All\", none = \"Treat None\") %>% 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.\", 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(\"Outcome type not supported. Expecting a binary endpoint\",\n \"or an object of class 'Surv'.\") %>%\n stop(call. = FALSE)\n if (outcome_type == \"survival\" && is.null(time))\n stop(\"`time=` must be specified for survival endpoints.\")\n\n # for binary outcomes, make the outcome a factor to 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 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 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 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 / (1 - .data$threshold) * .data$fp_rate - .data$harm\n ) %>%\n dplyr::left_join(\n dplyr::filter(., .data$variable %in% \"all\") %>%\n dplyr::select(.data$threshold, net_benefit_all = .data$net_benefit),\n by = \"threshold\"\n ) %>%\n dplyr::mutate(\n net_intervention_avoided =\n (.data$net_benefit - .data$net_benefit_all) / (.data$threshold / (1 - .data$threshold))\n ) %>%\n dplyr::select(-.data$net_benefit_all) %>%\n tibble::as_tibble()\n\n # return results -------------------------------------------------------------\n lst_result <-\n list(\n call = match.call(),\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) <- c(\"dca\", class(lst_result))\n lst_result\n}\n\n.calculate_test_consequences <- function(outcome, risk, thresholds, outcome_type,\n prevalence, time) {\n df <-\n tibble::tibble(threshold = thresholds,\n n = length(outcome))\n # case-control population prev\n if (!is.null(prevalence)) df$prevalence <- prevalence\n # survival endpoitn prev\n else if (outcome_type == \"survival\")\n df$prevalence <-\n tryCatch(\n survival::survfit(outcome ~ 1) %>%\n summary(time = time) %>%\n purrr::pluck(\"surv\") %>%\n {1 - .},\n error = function(e) NA_real_\n )\n # typical binary prev\n else df$prevalence <- table(outcome)[2] / length(outcome)\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 tp_rate =\n mean(risk[outcome == \"TRUE\"] >= .data$threshold) * .data$prevalence,\n fp_rate =\n mean(risk[outcome == \"FALSE\"] >= .data$threshold) * (1 - .data$prevalence),\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 surv_rate_among_test_pos =\n tryCatch(\n survival::survfit(outcome[risk >= .data$threshold] ~ 1) %>%\n summary(time = time) %>%\n purrr::pluck(\"surv\"),\n error = function(e) {\n if (length(outcome[risk >= .data$threshold]) == 0L) return(0)\n NA_real_\n }\n ),\n tp_rate = (1 - .data$surv_rate_among_test_pos) * .data$test_pos_rate,\n fp_rate = .data$surv_rate_among_test_pos * .data$test_pos_rate,\n )\n }\n\n df %>%\n dplyr::ungroup() %>%\n dplyr::select(any_of(c(\"threshold\", \"prevalence\", \"n\", \"tp_rate\", \"fp_rate\")))\n}\n\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(\"Assuming '{outcome_levels_sorted[2]}' is [Event] \",\n \"and '{outcome_levels_sorted[1]}' is [non-Event]\") %>%\n message()\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.convert_to_risk <- function(outcome, variable, outcome_type, time = NULL, prevalence = NULL) {\n if (outcome_type == \"binary\" && !is.null(prevalence))\n stop(\"Cannot convert to risks in case-control setting.\")\n\n if (outcome_type == \"binary\")\n risk <-\n stats::glm(outcome ~ variable, family = stats::binomial) %>%\n stats::predict()\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 {exp(-.)}\n }\n\n risk\n}\n\n\n", "meta": {"hexsha": "c24e6d838777d61e9f87f529232c1fc56b2de9d0", "size": 9962, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dca.r", "max_stars_repo_name": "shaankhurshid/dcurves", "max_stars_repo_head_hexsha": "1bc29be443e12211b3ed9ebc976bbbf31cc35ddc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-01-21T12:42:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T12:42:12.000Z", "max_issues_repo_path": "R/dca.r", "max_issues_repo_name": "shaankhurshid/dcurves", "max_issues_repo_head_hexsha": "1bc29be443e12211b3ed9ebc976bbbf31cc35ddc", "max_issues_repo_licenses": ["MIT"], "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/dca.r", "max_forks_repo_name": "shaankhurshid/dcurves", "max_forks_repo_head_hexsha": "1bc29be443e12211b3ed9ebc976bbbf31cc35ddc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4511278195, "max_line_length": 100, "alphanum_fraction": 0.5780967677, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23901246187607114}} {"text": "#' @title calcLLAF\n#'\n#' @description Creates a data table of low load adjustment factors (unitless)\n#' for the given parameters.\n#'\n#'@param engineType Engine type (vector of strings) (see\n#'\\code{\\link{calcEngineType}}). Valid values are: \\itemize{\n#'\\item \"SSD\"\n#'\\item \"MSD\"\n#'\\item \"MSD-ED\"\n#'\\item \"GT\"\n#'\\item \"GT-ED\"\n#'\\item \"ST\"\n#'\\item \"LNG\"\n#'\\item \"HSD\" (auxiliary only)\n#'\\item \"Boiler\" (boiler only)\n#'}\n#'@param location Location of vessel (vector of strings). Valid values are:\n#'\\itemize{\n#' \\item \"ECA\"\n#' \\item \"OutsideECA\"\n#' \\item \"GreatLakes\"\n#' }\n#'@param loadFactor Fractional percentage (between 0 and 1) of main engine\n#' required to propel vessel at given speed (vector of numericals) (see\n#' ShipPowerModel library)\n#'@param ECAfuelSulfurPercentage Fuel sulfur cap (percentage by weight) for the\n#'Emissions Control Area (ECA). Default = 0.1\\% (in effect Jan. 1, 2015)\n#'@param GlobalfuelSulfurPercentage Fuel sulfur cap (percentage by weight) for\n#'outside the Emissions Control Area (ECA). Default = 0.5\\% (in effect Jan. 1,\n#'2020)\n#'@param pollutants Select pollutants (default = \"ALL\"). Options: \\itemize{\n#'\\item \"co\"\n#'\\item \"hc\"\n#'\\item \"co2\"\n#'\\item \"so2\"\n#'\\item \"pm10\"\n#'\\item \"pm2.5\"\n#'\\item \"nox\"\n#'}\n#' @param inputTableLocation File path (optional). Used to specify a\n#' user-supplied set of adjustment factors. See details for formatting\n#' requirements\n#'\n#'@details\n#'Location is important for determining the fuel being used, as type of fuel\n#'typically used varies by location. This impacts the calculation of LLAF\n#'for SO2.\n#'\n#'For more information about the default low load adjustment factors, see\n#'Section 3.7 of the Port Emissions Inventory Guidance.\n#'\n#'If user-supplied adjustment factors are used, the file should be\n#'in .csv format with a header row. The headers should be \"load\" and one or more\n#'pollutants listed in the \\code{pollutants} argument. The load column should\n#'contain numerical values in percentage space (i.e., it can range between 0 and\n#'100). The pollutant columns should contain the specific adjustment factors for\n#'that pollutant, corresponding to the load values. Note: This function will\n#'linearly interpolate between the nearest values for any given load factor, and\n#'will return an adjustment factor of 1 for load factors outside the range of\n#'the table (i.e., it will not extrapolate).\n#'\n#'@return\n#' a data.table of low load adjusted emission factors the given parameters. Each\n#' pollutant selected in the \\code{pollutants} argument will be a column in the\n#' table.\n#'\n#' @references\n#' \\href{https://nepis.epa.gov/Exe/ZyPDF.cgi?Dockey=P10102U0.pdf}{EPA. 2020.\n#' \"Ports Emissions Inventory Guidance: Methodologies for Estimating\n#' Port-Related and Goods Movement Mobile Source Emissions.\" Ann Arbor, MI:\n#' Office of Transportation and Air Quality. US Environmental Protection Agency.}\n#'\n#'@examples\n#'calcLLAF(engineType=c(\"SSD\",\"MSD\",\"MSD-ED\",\"GT\"),\n#' location = \"ECA\",\n#' loadFactor=c(0.8,0.5,0.14,0.03),\n#' pollutants=\"co2\")\n#'calcLLAF(engineType=c(\"SSD\",\"MSD\",\"MSD-ED\",\"GT\"),\n#' location = c(\"ECA\",\"GreatLakes\",\"ECA\",\"OutsideECA\"),\n#' loadFactor=c(0.8,0.5,0.14,0.03))\n#'calcLLAF(engineType=c(\"HSD\",\"MSD\",\"LNG\"),\n#' location = c(\"ECA\",\"GreatLakes\",\"ECA\",\"OutsideECA\"),\n#' loadFactor=c(0.8,0.5,0.14),\n#' ECAfuelSulfurPercentage=0.1,\n#' GlobalfuelSulfurPercentage=2.7,\n#' pollutants=\"ALL\")\n#'\n#'@import data.table\n#'@importFrom stats spline\n#'@export\n\ncalcLLAF <- function(engineType, location, loadFactor,\n ECAfuelSulfurPercentage=0.1,GlobalfuelSulfurPercentage=0.5,\n pollutants=\"ALL\",\n inputTableLocation=NULL)\n{\n\n #bind variables to make devtools::check() happy\n so2<-.<-NULL\n\n if(is.element(\"ALL\",pollutants)){\n pollutants<-c(\"hc\",\n \"co2\",\n \"co\",\n \"nox\",\n \"pm2.5\",\n \"so2\",\n \"pm10\")\n }\n\n #get low-load adjustments if an input table is given\n if(is.null(inputTableLocation) == FALSE)\n {\n tbl<-fread(inputTableLocation)\n\n # convert load from percent space to fractional space to make it consistent with loadFactor\n tbl[,load:=load/100]\n\n # only include the selected pollutants\n tbl<-subset(tbl, select=c(\"load\", pollutants) )\n\n # linear interpolate the table for each given load factor\n LLAF<-tbl[, lapply(.SD, function(y) spline(load, y, xout = loadFactor)[['y']])]\n\n # Excluding electric drive oil engines (MSD-ED & GT-ED) who can switch off engines instead of operating at low loads.\n LLAF[engineType %in% c(\"MSD-ED\",\"GT-ED\")]<-LLAF[, lapply(.SD, function(y) 1)]\n\n # Excluding load factors that fall outside the range of this table\n LLAF[is.na(load)]<-LLAF[, lapply(.SD, function(y) 1)]\n\n # drop load column so we are just returning the results\n LLAF[, load:=NULL]\n return(LLAF)\n }\n\n #calculate low-load adjustments\n LLAFCoeff<-ShipEF::LLAFCoeff\n #initialize PollutantsLLAF====================================\n LLAF<- lapply(pollutants, function(x) data.table::data.table(matrix(nrow=length(engineType))))\n\n names(LLAF)<-pollutants\n\n #assign FuelSulfurFraction according to ECA constraints=======\n\n for(pol in pollutants){\n\n #Equation 3-26 C3RIA pg.3-27\n #Normalized to 20% load\n if(pol==\"so2\") {\n # create data table of location and load factor so that we can calculate SO2 LLAF from loadFactor differently depending on location\n dt <- data.table::data.table(location, loadFactor)\n\n dt[location %in% c(\"ECA\", \"GreatLakes\"),\n so2 := (LLAFCoeff$a[LLAFCoeff$pollutant==\"so2\"]*((14.1205*(1/loadFactor)+205.7169) * ECAfuelSulfurPercentage)\n +LLAFCoeff$b[LLAFCoeff$pollutant==\"so2\"])/(LLAFCoeff$a[LLAFCoeff$pollutant==\"so2\"]*((14.1205*(1/0.2)+205.7169)\n * ECAfuelSulfurPercentage)+LLAFCoeff$b[LLAFCoeff$pollutant==\"so2\"])]\n\n dt[!(location %in% c(\"ECA\", \"GreatLakes\")),\n so2 := (LLAFCoeff$a[LLAFCoeff$pollutant==\"so2\"]*((14.1205*(1/loadFactor)+205.7169) * GlobalfuelSulfurPercentage)\n +LLAFCoeff$b[LLAFCoeff$pollutant==\"so2\"])/(LLAFCoeff$a[LLAFCoeff$pollutant==\"so2\"]*((14.1205*(1/0.2)+205.7169)\n * GlobalfuelSulfurPercentage)+LLAFCoeff$b[LLAFCoeff$pollutant==\"so2\"])]\n # LLAF is a list containing data.table columns\n LLAF[paste(pol)] <- dt[, .(so2)]\n rm(dt)\n\n } else { # All other pollutants\n\n LLAF[paste(pol)]<-data.table::as.data.table(\n (LLAFCoeff$a[LLAFCoeff$pollutant==pol]*(loadFactor^-LLAFCoeff$x[LLAFCoeff$pollutant==pol])+LLAFCoeff$b[LLAFCoeff$pollutant==pol])/(\n LLAFCoeff$a[LLAFCoeff$pollutant==pol]*(0.2^-LLAFCoeff$x[LLAFCoeff$pollutant==pol])+LLAFCoeff$b[LLAFCoeff$pollutant==pol])\n )\n\n } #end SO2 vs other pollutants if/else\n }\n\n #Excluding electric drive oil engines (MSD-ED & GT-ED) who can switch off engines instead of operating at low loads.\n #Excluding Auxiliary Engines\n #Excluding Non-Low Load Operations (>20% or 0% (Hotelling))\n LLAF<-lapply(LLAF, function(x){\n x[which(loadFactor>0.2|loadFactor==0)]<-1\n x\n })\n\n LLAF<-lapply(LLAF, function(x){\n x[which(engineType%in%c(\"MSD-ED\",\"GT-ED\"))]<-1\n x\n })\n\n LLAF<-data.table::as.data.table(do.call(cbind,LLAF))\n\n return(LLAF)\n}\n", "meta": {"hexsha": "f6ecdea8ed0a6c71b07d992004c152b217550dde", "size": 7609, "ext": "r", "lang": "R", "max_stars_repo_path": "ShipEF/R/calcLLAF.r", "max_stars_repo_name": "USEPA/Marine_Emissions_Tools", "max_stars_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-05-13T17:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:47:39.000Z", "max_issues_repo_path": "ShipEF/R/calcLLAF.r", "max_issues_repo_name": "USEPA/Marine_Emissions_Tools", "max_issues_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShipEF/R/calcLLAF.r", "max_forks_repo_name": "USEPA/Marine_Emissions_Tools", "max_forks_repo_head_hexsha": "28e12dc51acb5baafc460b1a9de35d355f3cc64f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-08T15:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T15:55:06.000Z", "avg_line_length": 39.2216494845, "max_line_length": 181, "alphanum_fraction": 0.6459455907, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23801850911057468}} {"text": "#' @title U2F\n#' @description exploitation rate to fishing mortality\n#' @family abysmally documented\n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\nU2F <- function(U){\n\treturn(-log(1-U))\n}", "meta": {"hexsha": "e6a9729be92863c60211bd465d2dd2f2ae5e7f3a", "size": 206, "ext": "r", "lang": "R", "max_stars_repo_path": "R/U2F.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/U2F.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/U2F.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.75, "max_line_length": 54, "alphanum_fraction": 0.6893203883, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.2377066236355286}} {"text": "# Calculate Ne from frequency change at many loci\n# start from ANGSD output\n# set up to run on Saga\n\n####################\n# load functions\n####################\nrequire(data.table)\nrequire(boot) # for bootstrap CIs\n\n################################\n# read in data \n################################\n# MAFS\ndat07 <- fread('data_2020.01.31/Lof_07_freq.mafs.gz', header=TRUE) # 1907 Lof\ndat11 <- fread('data_2020.01.31/Lof_11_freq.mafs.gz', header=TRUE) # 2011 Lof\ndat14 <- fread('data_2020.01.31/Lof_14_freq.mafs.gz', header=TRUE) # 2014 Lof\ndatCan40 <- fread('data_2020.01.31/Can_40_freq.mafs.gz', header=TRUE) # 1940 Can\ndatCan14 <- fread('data_2020.01.31/Can_14_freq.mafs.gz', header=TRUE) # 2014 Can\n\n# high quality loci\n#gatk <- fread('data_2020.01.31/GATK_filtered_SNP_set.tab')\ngatk <- fread('data_2020.05.07/GATK_filtered_SNP_no_dam2.tab')\nsetnames(gatk, c('chromo', 'position', 'ref', 'alt'))\n\n# unlinked loci\nunlnkCan <- fread('analysis/ld.unlinked.Can.gatk.nodam.csv.gz')\nunlnkLof <- fread('analysis/ld.unlinked.Lof.gatk.nodam.csv.gz')\nsetnames(unlnkCan, c('chromo', 'position', 'cluster', 'nloci'))\nsetnames(unlnkLof, c('chromo', 'position', 'cluster', 'nloci'))\n\n##############\n# Trim loci\n##############\n\n# trim to loci that meet GATK and unlinked filter\nsetkey(dat07, chromo, position)\nsetkey(dat11, chromo, position)\nsetkey(dat14, chromo, position)\nsetkey(datCan40, chromo, position)\nsetkey(datCan14, chromo, position)\nsetkey(gatk, chromo, position)\nsetkey(unlnkCan, chromo, position)\nsetkey(unlnkLof, chromo, position)\n\nnrow(dat07)\nnrow(dat11)\nnrow(dat14)\nnrow(datCan40)\nnrow(datCan14)\n\ndat07 <- dat07[gatk, nomatch=0] # nomatch=0 so that non-matching rows are dropped\ndat11 <- dat11[gatk, nomatch=0]\ndat14 <- dat14[gatk, nomatch=0]\ndatCan40 <- datCan40[gatk, nomatch=0]\ndatCan14 <- datCan14[gatk, nomatch=0]\n\nnrow(dat07)\nnrow(dat11)\nnrow(dat14)\nnrow(datCan40)\nnrow(datCan14)\n\ndat07 <- dat07[unlnkLof, nomatch=0] # nomatch=0 so that non-matching rows are dropped\ndat11 <- dat11[unlnkLof, nomatch=0]\ndat14 <- dat14[unlnkLof, nomatch=0]\ndatCan40 <- datCan40[unlnkCan, nomatch=0]\ndatCan14 <- datCan14[unlnkCan, nomatch=0]\n\nnrow(dat07)\nnrow(dat11)\nnrow(dat14)\nnrow(datCan40)\nnrow(datCan14)\n\n# trim out Unplaced\ndat07 <- dat07[!(chromo == 'Unplaced'),]\ndat11 <- dat11[!(chromo == 'Unplaced'),]\ndat14 <- dat14[!(chromo == 'Unplaced'),]\ndatCan40 <- datCan40[!(chromo == 'Unplaced'),]\ndatCan14 <- datCan14[!(chromo == 'Unplaced'),]\n\nnrow(dat07)\nnrow(dat11)\nnrow(dat14)\nnrow(datCan40)\nnrow(datCan14)\n\n\n################################\n# Merge population comparisons\n# also trim to loci genotyped in both populations and >0.1\n################################\nsetnames(dat07, c(\"knownEM\", 'nInd'), c(\"freq1\", 'nInd1'))\nsetnames(dat11, c(\"knownEM\", 'nInd'), c(\"freq2\", 'nInd2'))\nsetnames(dat14, c(\"knownEM\", 'nInd'), c(\"freq2\", 'nInd2'))\nsetnames(datCan40, c(\"knownEM\", 'nInd'), c(\"freq1\", 'nInd1'))\nsetnames(datCan14, c(\"knownEM\", 'nInd'), c(\"freq2\", 'nInd2'))\n\ndat0711 <- dat07[dat11, .(chromo, position, freq1, freq2, nInd1, nInd2)][!is.na(freq1) & !is.na(freq2) & freq1 > 0.1 & freq2 > 0.1, ]\ndat0714 <- dat07[dat14, .(chromo, position, freq1, freq2, nInd1, nInd2)][!is.na(freq1) & !is.na(freq2) & freq1 > 0.1 & freq2 > 0.1, ]\ndatCan <- datCan40[datCan14, .(chromo, position, freq1, freq2, nInd1, nInd2)][!is.na(freq1) & !is.na(freq2) & freq1 > 0.1 & freq2 > 0.1, ]\n\nnrow(dat0711) # 94976 (w/out unplaced), 95426 (w/ unplaced)\nnrow(dat0714) # 92730, 93154\nnrow(datCan) # 93728, 94263\n\n######################\n# Run calculations\n######################\n\n### Jorde & Ryman/NeEstimator approach\n# Jorde & Ryman 2007\n\n# Ne in # diploid individuals\n# based on NeEstimator manual v2.1 \njrNe2 <- function(maf1, maf2, n1, n2, gen){\n\tFsnum <- (maf1-maf2)^2 + (1-maf1 - (1-maf2))^2 # the numerator, summing across the two alleles\n\n\tz <- (maf1+maf2)/2 # for the first allele\n\tz2 <- ((1-maf1)+(1-maf2))/2 # z for the 2nd allele\n\tFsdenom <- z*(1-z) + z2*(1-z2) # the denominator of Fs, summing across the 2 alleles\n\tFs <- sum(Fsnum)/sum(Fsdenom) # from NeEstimator calculations manual\n\n\tsl <- 2/(1/n1 + 1/n2) # harmonic mean sample size for each locus, in # individuals\n\n\tS <- length(maf1)*2/sum(2/sl) # harmonic mean sample size in # individuals, across loci and across both times. 2 alleles. Eq. 4.10 in NeEstimator v2.1 manual\n\tS2 <- length(maf2)*2/sum(2/n2) # harmonic mean sample size of 2nd sample in # individuals, across loci. all 2 alleles. See NeEstimator v2.1 below Eq. 4.13\n\tFsprime <- (Fs*(1 - 1/(4*S)) - 1/S)/((1 + Fs/4)*(1 - 1/(2*S2))) # Eq. 4.13 in NeEstimator v2.1\n\treturn(gen/(2*Fsprime)) # calculation of Ne in # diploid individuals\n}\n\ndat0711[, jrNe2(freq1, freq2, nInd1, nInd2, 11)]\ndat0714[, jrNe2(freq1, freq2, nInd1, nInd2, 11)]\ndatCan[, jrNe2(freq1, freq2, nInd1, nInd2, 8)]\n\n\n\n####################################\n# bootstrap over loci to get CIs\n####################################\n# Jorde & Ryman Ne estimator, for boot() to use\njrNe2boot <- function(data, gen, indices){\n\tmaf1 <- data$freq1[indices]\n\tmaf2 <- data$freq2[indices]\n\tn1 <- data$nInd1[indices]\n\tn2 <- data$nInd2[indices]\n\n\tFsnum <- (maf1-maf2)^2 + (1-maf1 - (1-maf2))^2 # the numerator, summing across the two alleles\n\n\tz <- (maf1+maf2)/2 # for the first allele\n\tz2 <- ((1-maf1)+(1-maf2))/2 # z for the 2nd allele\n\tFsdenom <- z*(1-z) + z2*(1-z2) # the denominator of Fs, summing across the 2 alleles\n\tFs <- sum(Fsnum)/sum(Fsdenom) # from NeEstimator calculations manual\n\n\tsl <- 2/(1/n1 + 1/n2) # harmonic mean sample size for each locus, in # individuals\n\n\tS <- length(maf1)*2/sum(2/sl) # harmonic mean sample size in # individuals, across loci and across both times. 2 alleles. Eq. 4.10 in NeEstimator v2.1 manual\n\tS2 <- length(maf2)*2/sum(2/n2) # harmonic mean sample size of 2nd sample in # individuals, across loci. all 2 alleles. See NeEstimator v2.1 below Eq. 4.13\n\tFsprime <- (Fs*(1 - 1/(4*S)) - 1/S)/((1 + Fs/4)*(1 - 1/(2*S2))) # Eq. 4.13 in NeEstimator v2.1\n\tNe <- gen/(2*Fsprime)\n\tif(Ne < 0) Ne <- Inf\n\treturn(Ne) # calculation of Ne in # diploid individuals\n}\n\n# for block bootstrapping across LGs\n# frin https://stackoverflow.com/questions/11919808/block-bootstrap-from-subject-list\njrNe2block <- function(lgs, gen, alldata, indices){\n\tmydata <- do.call(\"rbind\", lapply(indices, function(n) subset(alldata, chromo==lgs[n])))\n\treturn(jrNe2boot(mydata, gen, indices = 1:nrow(mydata)))\n}\n\n# regular bootstrap calculations\n# not enough memory to do BCa CIs\n# boot0711 <- boot(data = dat0711, statistic = jrNe2boot, R = 1000, gen = 11)\n# boot.ci(boot0711, type = 'perc')\n# \n# boot0714 <- boot(data = dat0714, statistic = jrNe2boot, R = 1000, gen = 11)\n# boot.ci(boot0714, type = 'perc')\n# \n# bootCan <- boot(data = datCan, statistic = jrNe2boot, R = 1000, gen = 8)\n# boot.ci(bootCan, type = 'perc')\n\n\n# block bootstrapping across LGs\nlgs <- dat0711[, sort(unique(chromo))]\n\nboot0711lg <- boot(lgs, jrNe2block, 4000, gen = 11, alldata = dat0711)\nprint(boot0711lg)\nmedian(boot0711lg$t[is.finite(boot0711lg$t)]) # median bootstrap\nboot.ci(boot0711lg, type = c('perc'))\n\nboot0714lg <- boot(lgs, jrNe2block, 10000, gen = 11, alldata = dat0714)\nprint(boot0714lg)\nmedian(boot0714lg$t[is.finite(boot0714lg$t)]) # median bootstrap\nboot.ci(boot0714lg, type = c('perc'))\n\nbootCanlg <- boot(lgs, jrNe2block, 4000, gen = 8, alldata = datCan)\nprint(bootCanlg)\nmedian(bootCanlg$t[is.finite(bootCanlg$t)]) # median bootstrap\nboot.ci(bootCanlg, type = c('perc'))\n", "meta": {"hexsha": "4a1cf96ac5a6142fb920adbe4ebe18d67017f804", "size": 7435, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/calcNe_ANGSD.r", "max_stars_repo_name": "pinskylab/codEvol", "max_stars_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/calcNe_ANGSD.r", "max_issues_repo_name": "pinskylab/codEvol", "max_issues_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-04-11T11:14:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T19:57:31.000Z", "max_forks_repo_path": "scripts/calcNe_ANGSD.r", "max_forks_repo_name": "pinskylab/codEvol", "max_forks_repo_head_hexsha": "2710c4e4d9223ce02873938fd7aa7fc80f7dd8ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8069306931, "max_line_length": 158, "alphanum_fraction": 0.6638870208, "num_tokens": 2669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23699021132464065}} {"text": "model_registerzadok <- function (cumulTT = 354.582294511779,\n phase = 2.0,\n leafNumber = 4.8854219661087575,\n calendarMoments = c('Sowing'),\n calendarDates = c('2007/3/21'),\n calendarCumuls = c(0.0),\n cumulTTFromZC_65 = 0.0,\n currentdate = '2007/4/9',\n der = 300.0,\n slopeTSFLN = 0.9,\n intTSFLN = 0.9,\n finalLeafNumber = 8.797582013199484,\n currentZadokStage = 'MainShootPlus1Tiller',\n hasZadokStageChanged_t1 = 0,\n sowingDate = '2007/3/21'){\n #'- Name: RegisterZadok -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: RegisterZadok Model\n #' * Author: Pierre MARTRE\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA/LEPSE Montpellier\n #' * Abstract: Record the zadok stage in the calendar\n #' \t\n #'- inputs:\n #' * name: cumulTT\n #' ** description : \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 354.582294511779\n #' ** unit : °C d\n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: phase\n #' ** description : instance of the phase class . You can get the name of the phase using phase.getPhaseAsString(PhaseValue) \n #' ** variablecategory : state\n #' ** inputtype : variable\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** default : 2\n #' ** unit : \n #' ** uri : some url\n #' * name: leafNumber\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 4.8854219661087575\n #' ** unit : leaf\n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: calendarMoments\n #' ** description : List containing apparition of each stage\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** default : ['Sowing']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarDates\n #' ** description : List containing the dates of the wheat developmental phases\n #' ** variablecategory : state\n #' ** datatype : DATELIST\n #' ** default : ['2007/3/21']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarCumuls\n #' ** description : list containing for each stage occured its cumulated thermal times\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** default : [0.0]\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: cumulTTFromZC_65\n #' ** description : cumul of the thermal time (DeltaTT) since the moment ZC_65\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 0\n #' ** unit : °C d\n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: currentdate\n #' ** description : current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DATE\n #' ** min : \n #' ** max : \n #' ** default : 2007/4/9\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: der\n #' ** description : Duration of the endosperm endoreduplication phase\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 300.0\n #' ** unit : °C d\n #' ** uri : some url\n #' ** inputtype : parameter\n #' * name: slopeTSFLN\n #' ** description : used to calculate Terminal spikelet\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0.9\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : parameter\n #' * name: intTSFLN\n #' ** description : used to calculate Terminal spikelet\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0.9\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : parameter\n #' * name: finalLeafNumber\n #' ** description : final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 8.797582013199484\n #' ** unit : leaf\n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: currentZadokStage\n #' ** description : current zadok stage\n #' ** variablecategory : state\n #' ** datatype : STRING\n #' ** min : \n #' ** max : \n #' ** default : MainShootPlus1Tiller\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: hasZadokStageChanged_t1\n #' ** description : true if the zadok stage has changed this time step\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : variable\n #' * name: sowingDate\n #' ** description : Date of Sowing\n #' ** parametercategory : constant\n #' ** datatype : DATE\n #' ** min : \n #' ** max : \n #' ** default : 2007/3/21\n #' ** unit : \n #' ** inputtype : parameter\n #'- outputs:\n #' * name: hasZadokStageChanged\n #' ** description : true if the zadok stage has changed this time step\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** uri : some url\n #' * name: currentZadokStage\n #' ** description : current zadok stage\n #' ** variablecategory : state\n #' ** datatype : STRING\n #' ** unit : \n #' ** uri : some url\n #' * name: calendarMoments\n #' ** description : List containing apparition of each stage\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** unit : \n #' * name: calendarDates\n #' ** description : List containing the dates of the wheat developmental phases\n #' ** variablecategory : state\n #' ** datatype : DATELIST\n #' ** unit : \n #' * name: calendarCumuls\n #' ** description : list containing for each stage occured its cumulated thermal times\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** unit : °C d\n roundedFinalLeafNumber <- as.integer(finalLeafNumber + 0.5)\n if (leafNumber >= 4.0 && !('MainShootPlus1Tiller' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'MainShootPlus1Tiller')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'MainShootPlus1Tiller'\n }\n else if ( leafNumber >= 5.0 && !('MainShootPlus2Tiller' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'MainShootPlus2Tiller')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'MainShootPlus2Tiller'\n }\n else if ( leafNumber >= 6.0 && !('MainShootPlus3Tiller' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'MainShootPlus3Tiller')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'MainShootPlus3Tiller'\n }\n else if ( finalLeafNumber > 0.0 && (leafNumber >= slopeTSFLN * finalLeafNumber - intTSFLN && !('TerminalSpikelet' %in% calendarMoments)))\n {\n calendarMoments <- c(calendarMoments, 'TerminalSpikelet')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'TerminalSpikelet'\n }\n else if ( leafNumber >= roundedFinalLeafNumber - 4.0 && roundedFinalLeafNumber - 4 > 0 && !('PseudoStemErection' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'PseudoStemErection')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'PseudoStemErection'\n }\n else if ( leafNumber >= roundedFinalLeafNumber - 3.0 && roundedFinalLeafNumber - 3 > 0 && !('1stNodeDetectable' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, '1stNodeDetectable')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- '1stNodeDetectable'\n }\n else if ( leafNumber >= roundedFinalLeafNumber - 2.0 && roundedFinalLeafNumber - 2 > 0 && !('2ndNodeDetectable' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, '2ndNodeDetectable')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- '2ndNodeDetectable'\n }\n else if ( leafNumber >= roundedFinalLeafNumber - 1.0 && roundedFinalLeafNumber - 1 > 0 && !('FlagLeafJustVisible' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'FlagLeafJustVisible')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'FlagLeafJustVisible'\n }\n else if ( !('MidGrainFilling' %in% calendarMoments) && (phase == 4.5 && cumulTTFromZC_65 >= der))\n {\n calendarMoments <- c(calendarMoments, 'MidGrainFilling')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n hasZadokStageChanged <- 1\n currentZadokStage <- 'MidGrainFilling'\n }\n else\n {\n hasZadokStageChanged <- 0\n }\n return (list (\"hasZadokStageChanged\" = hasZadokStageChanged,\"currentZadokStage\" = currentZadokStage,\"calendarMoments\" = calendarMoments,\"calendarDates\" = calendarDates,\"calendarCumuls\" = calendarCumuls))\n}", "meta": {"hexsha": "199c50fc63cd5792189fc5f2ee7e367936666be6", "size": 14201, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Registerzadok.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Registerzadok.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Registerzadok.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 51.64, "max_line_length": 207, "alphanum_fraction": 0.4232096331, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23589120855962284}} {"text": "#' Expected Value of Information\n#'\n#' Calculate the expected value of information for box ironbark and woodland \n#' management\n#'\n#' @param data Input and output data as a single data.frame.\n#' @param ncores Interger. Number of cpu cores.\n#' @param max_eco Numeric. Maximum proportion of the landscape allocatable to \n#' thinning.\n#' @param type Character. Type of evoi analysis.\n#' @param parameter_list list. When \\code{type = \"evpxi_list\"} a list of\n#' parameter sets must be supplied where the list elements are named\n#' vectors of parameter where the names correspond to the action the\n#' parameter of interest associated with.\n#'\n#' @importFrom dplyr arrange distinct select_\n#' @importFrom parallel mclapply\n#' @importFrom tidyr spread_\n#' @importFrom stats predict\n#' @importFrom earth earth\n\n#' @export\n\nevoi <-\n function(\n data, ncores = 1, max_eco = .2, \n type = c(\"evpi\", \"evwoi\", \"evpxi_list\", \"evpxi\"),\n parameter_list = NULL\n ) {\n\n type <- match.arg(type)\n \n with(\n data,\n {\n actions <- unique(action)\n\n data <-\n lapply(\n actions,\n function(x) {\n data <-\n spread_(\n data[data[, \"action\"] == x, ],\n \"parameter\",\n \"parameter_value\"\n )\n data <- arrange(data, sample, run)\n data[, setdiff(colnames(data), c(\"action\", \"run\", \"sample\"))]\n }\n )\n\n models <- lapply(data, fit_earth, \"outcome\")\n parameters <- lapply(data, select_, paste0(\"-\", \"outcome\"))\n parameters <- lapply(parameters, distinct)\n outcomes <- mapply(predict, models, parameters)\n n_samples <- length(unique(sample))\n colnames(outcomes) <- names(models) <- names(parameters) <- actions\n\n out <-\n lapply(\n max_eco,\n evoi_,\n outcomes,\n parameters,\n models,\n n_samples,\n actions,\n ncores,\n type,\n parameter_list\n )\n\n do.call(rbind, out)\n }\n )\n }\n\no2v <- function(outcomes, max_eco) {\n with(\n as.data.frame(outcomes),\n data.frame(\n NM = NM,\n HF = HF,\n EN = ET * max_eco + NM * (1 - max_eco),\n EH = ET * max_eco + HF * (1 - max_eco)\n )\n )\n}\n\ncalc_vwpxi <-\n function(sample, theta, action, parameters, models, max_eco) {\n for (i in seq_along(action)) {\n parameter_action <- getElement(parameters, action[i])\n parameter_action[, theta[i]] <- parameter_action[sample, theta[i]]\n parameters <- within(parameters, assign(action[i], parameter_action))\n }\n outcomes <- mapply(predict, models, parameters)\n colnames(outcomes) <- names(models)\n value <- o2v(outcomes, max_eco)\n mean_value <- colMeans(value)\n ans <- max(mean_value)\n attr(ans, \"which.max\") <- which.max(mean_value)\n ans\n }\n\ncalc_evwpxi <-\n function(theta, action, n_samples, parameters, models, max_eco) {\n\n results <-\n sapply(\n seq_len(n_samples),\n calc_vwpxi,\n theta,\n action,\n parameters,\n models,\n max_eco\n )\n\n list(evwpxi = mean(results), vwpxi = results)\n\n }\n\ncalc_evwpxi_ <-\n function(action, n_theta, n_samples, parameters, models, max_eco, ncores) {\n mclapply(\n seq_len(n_theta[[action]]),\n calc_evwpxi,\n action,\n n_samples,\n parameters,\n models,\n max_eco,\n mc.cores = ncores\n )\n }\n\nevoi_ <-\n function(\n max_eco, outcomes, parameters, models, n_samples, actions,\n ncores, type, parameter_list\n ) {\n\n value <- o2v(outcomes, max_eco)\n\n evwoi <- max(colMeans(value))\n\n switch(\n type,\n\n evpi =\n {\n evwpi <- mean(apply(value, 1, max))\n\n attr(evwpi, \"vwpi\") <- apply(value, 1, which.max)\n\n data.frame(\n parameters = \"EVPI\",\n max_eco = max_eco,\n evi = evwpi - evwoi,\n stringsAsFactors = FALSE\n )\n },\n\n evwoi = \n data.frame(\n parameters = \"EVWOI\",\n max_eco = max_eco,\n evi = evwoi,\n stringsAsFactors = FALSE\n ),\n\n evpxi_list =\n {\n evwpxi <-\n mapply(\n calc_evwpxi,\n parameter_list,\n lapply(parameter_list, names),\n MoreArgs =\n list(\n n_samples = n_samples,\n parameters = parameters,\n models = models,\n max_eco = max_eco\n ),\n SIMPLIFY = FALSE\n )\n\n ans <-\n data.frame(\n parameters = names(parameter_list),\n max_eco = max_eco,\n evi =\n unlist(lapply(evwpxi, getElement, name = \"evwpxi\")) - evwoi,\n stringsAsFactors = FALSE\n )\n\n attr(ans, \"vwpxi\") <- lapply(evwpxi, getElement, name = \"vwpxi\")\n\n ans\n },\n\n evpxi = \n {\n evwpxi <-\n lapply(\n actions,\n calc_evwpxi_,\n lapply(parameters, ncol),\n n_samples,\n parameters,\n models,\n max_eco,\n ncores\n )\n\n ans <-\n data.frame(\n parameters = unlist(lapply(parameters, names)),\n max_eco = max_eco,\n evi = \n unlist(\n lapply(\n evwpxi, \n function(x) lapply(x, getElement, name = \"evwpxi\")\n )\n ) - evwoi,\n stringsAsFactors = FALSE\n )\n\n attr(ans, \"vwpxi\") <-\n lapply(\n evwpxi,\n function(x) lapply(x, getElement, name = \"vwpxi\")\n )\n\n ans\n\n }\n )\n }\n\nfit_earth <-\n function(x, outcome, ...) {\n earth(\n x = x[, setdiff(colnames(x), outcome)],\n y = x[, outcome],\n degree = 5,\n ...\n )\n }\n", "meta": {"hexsha": "0da5e13dbd9796ed8ad6e502069130b70e247274", "size": 6180, "ext": "r", "lang": "R", "max_stars_repo_path": "R/evoi.r", "max_stars_repo_name": "wkmor1/voiWoodland", "max_stars_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_stars_repo_licenses": ["MIT"], "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/evoi.r", "max_issues_repo_name": "wkmor1/voiWoodland", "max_issues_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_issues_repo_licenses": ["MIT"], "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/evoi.r", "max_forks_repo_name": "wkmor1/voiWoodland", "max_forks_repo_head_hexsha": "8780f764c5bee8f2d31e35e8c6ef28841b736dfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3307086614, "max_line_length": 78, "alphanum_fraction": 0.4951456311, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.3629691917376782, "lm_q1q2_score": 0.23513079557918584}} {"text": "#Title: Draw fitting curve\r\n#Auther: Naoto Imamachi\r\n#ver: 1.0.0\r\n#Date: 2015-10-08\r\n\r\nBridgeRDraw <- function(InputFile=\"BridgeR_5C_HalfLife_calculation_R2_selection.txt\",\r\n group,\r\n hour,\r\n ComparisonFile,\r\n CutoffRelExp = 0,\r\n CutoffDataPoint = 4,\r\n InforColumn = 4,\r\n GeneInfor = 2,\r\n OutputDir = \"BridgeRDraw_fig\",\r\n ModelMode = \"R2_selection\",\r\n DrawMode = \"Simple\",\r\n Color = c(\"black\",\"red\")){\r\n ###Check_ModelMode & DrawMode###\r\n if(ModelMode == \"Raw_model\" || ModelMode == \"Three_model\" || ModelMode == \"R2_selection\"){\r\n if(DrawMode == \"Simple\" || DrawMode == \"Ribbon\"){\r\n ###Make_stored_directory###\r\n ComparisonFile_name <- paste(ComparisonFile, collapse = \"_\")\r\n output_dir_name <- paste(OutputDir, ComparisonFile_name, sep=\"_\")\r\n dir.create(output_dir_name)\r\n \r\n ###Prepare_file_infor###\r\n time_points <- length(hour)\r\n group_number <- length(group)\r\n input_file <- fread(InputFile, header = T)\r\n comp_file_number <- NULL\r\n for(a in 1:length(ComparisonFile)){\r\n comp_file_number <- append(comp_file_number, which(group == ComparisonFile[a])) #1,2,3 => 1,2 || 1,3\r\n }\r\n \r\n ###Draw_fitting_curve###\r\n gene_number <- length(input_file[[1]])\r\n for(x in 1:gene_number){\r\n data <- as.vector(as.matrix(input_file[x,]))\r\n \r\n #Save_fig\r\n gene_name <- as.character(data[GeneInfor])\r\n file_name <- sprintf(\"%1$s.png\",gene_name)\r\n file_name <- paste(output_dir_name, \"/\", file_name, sep=\"\")\r\n png(filename = file_name, width=640, height=640)\r\n \r\n #Prepare_ggplot2\r\n p <- ggplot()\r\n \r\n flg <- 0\r\n fig_color <- NULL\r\n for(a in comp_file_number){\r\n #Select_color\r\n if(flg == 0){\r\n fig_color <- Color[1]\r\n }else if(flg == 1){\r\n fig_color <- Color[2]\r\n }\r\n \r\n infor_st <- NULL\r\n infor_ed <- NULL\r\n model_name <- NULL\r\n if(ModelMode == \"Raw_model\" || ModelMode == \"R2_selection\"){\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn + 3)\r\n infor_ed <- (InforColumn)*a + (a - 1)*(time_points + 3)\r\n model_index <- infor_ed + time_points + 1\r\n model_name <- data[model_index]\r\n }else if(ModelMode == \"Three_model\"){\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn + 23)\r\n infor_ed <- (InforColumn)*a + (a - 1)*(time_points + 23)\r\n model_index <- infor_ed + time_points + 21\r\n model_name <- data[model_index]\r\n }\r\n exp_st <- infor_ed + 1\r\n exp_ed <- infor_ed + time_points\r\n \r\n exp_data <- as.numeric(data[exp_st:exp_ed])\r\n time_point_exp_original <- data.frame(hour=hour, exp=exp_data)\r\n \r\n if(ModelMode == \"R2_selection\"){\r\n if(model_name == \"Raw\" || model_name == \"Notest\"){\r\n }else{\r\n select_name <- gsub(\"Delete_\", \"\", model_name)\r\n select_name <- gsub(\"hr\", \"\", select_name)\r\n select_name <- as.numeric(as.vector(strsplit(select_name, \"_\")[[1]])) #Delete_1hr_2hr\r\n for(test in select_name){\r\n time_point_exp_original <- time_point_exp_original[time_point_exp_original$hour != test,]\r\n }\r\n }\r\n }\r\n \r\n #Draw_time_points\r\n p <- p + geom_point(data = time_point_exp_original,\r\n mapping = aes(x = hour, y = exp),\r\n size = 4,\r\n shape = 19,\r\n colour = fig_color)\r\n \r\n #Remove_exp0_data\r\n time_point_exp <- time_point_exp_original[time_point_exp_original$exp > CutoffRelExp,]\r\n data_point <- length(time_point_exp$exp)\r\n \r\n #Draw_fitting_curve\r\n if(!is.null(time_point_exp)){\r\n if(data_point >= CutoffDataPoint){\r\n if(ModelMode == \"Raw_model\" || ModelMode == \"R2_selection\"){\r\n model <- lm(log(time_point_exp$exp) ~ time_point_exp$hour - 1)\r\n fig_data <- data.frame(hour=time_point_exp$hour)\r\n predicted <- as.numeric(as.vector(as.matrix(predict(model, fig_data))))\r\n fig_data$exp <- exp(as.vector(as.matrix(predicted)))\r\n \r\n p <- p + geom_line(data=fig_data,\r\n mapping=(aes(x=hour, y=exp)),\r\n size=1.2,\r\n colour=fig_color)\r\n \r\n }else if(ModelMode == \"Three_model\"){\r\n if(!is.na(model_name) || model_name != \"no_good_model\" || \r\n model_name != \"few_data\" || model_name != \"low_expresion\"){\r\n #Parameter_setting\r\n a_1_index <- exp_ed + 4\r\n a_2_index <- exp_ed + 10\r\n b_2_index <- exp_ed + 11\r\n a_3_index <- exp_ed + 16\r\n b_3_index <- exp_ed + 17\r\n c_3_index <- exp_ed + 18\r\n model_index <- exp_ed + 21\r\n model <- data[model_index]\r\n \r\n #model_curve\r\n if(flg == 0){\r\n model_curve_1 <- NULL\r\n a_1_1 <- as.numeric(data[a_1_index])\r\n a_2_1 <- as.numeric(data[a_2_index])\r\n b_2_1 <- as.numeric(data[b_2_index])\r\n a_3_1 <- as.numeric(data[a_3_index])\r\n b_3_1 <- as.numeric(data[b_3_index])\r\n c_3_1 <- as.numeric(data[c_3_index]) \r\n if(model == \"model1\"){\r\n model_curve_1 <- function(t){exp(-a_1_1 * t)}\r\n }else if(model == \"model2\"){\r\n model_curve_1 <- function(t){(1.0 - b_2_1) * exp(-a_2_1 * t) + b_2_1}\r\n }else if(model == \"model3\"){\r\n model_curve_1 <- function(t){(c_3_1) * exp(-a_3_1 * t) + (1.0 - c_3_1) * exp(-b_3_1 * t)}\r\n }\r\n p <- p + geom_path(stat=\"function\",\r\n fun=model_curve_1,\r\n mapping=aes(color=\"model_curve_1\"),\r\n size=1.2)\r\n }else if(flg == 1){\r\n model_curve_2 <- NULL\r\n a_1_2 <- as.numeric(data[a_1_index])\r\n a_2_2 <- as.numeric(data[a_2_index])\r\n b_2_2 <- as.numeric(data[b_2_index])\r\n a_3_2 <- as.numeric(data[a_3_index])\r\n b_3_2 <- as.numeric(data[b_3_index])\r\n c_3_2 <- as.numeric(data[c_3_index])\r\n if(model == \"model1\"){\r\n model_curve_2 <- function(t){exp(-a_1_2 * t)}\r\n }else if(model == \"model2\"){\r\n model_curve_2 <- function(t){(1.0 - b_2_2) * exp(-a_2_2 * t) + b_2_2}\r\n }else if(model == \"model3\"){\r\n model_curve_2 <- function(t){(c_3_2) * exp(-a_3_2 * t) + (1.0 - c_3_2) * exp(-b_3_2 * t)}\r\n }\r\n p <- p + geom_path(stat=\"function\",\r\n fun=model_curve_2,\r\n mapping=aes(color=\"model_curve_2\"),\r\n size=1.2)\r\n }\r\n }else{ #!is.na(model_name) || model_name != \"no_good_model\" || model_name != \"few_data\" || model_name != \"low_expresion\"\r\n }\r\n } #ModelMode: Raw_model, R2_selection, Three_model\r\n }else{ #data_point >= CutoffDataPoint\r\n }\r\n }else{ #!is.null(time_point_exp)\r\n }\r\n flg <- 1\r\n } #a in comp_file_number\r\n \r\n if(ModelMode == \"Three_model\"){\r\n p <- p + scale_colour_manual(name=\"Sample\",\r\n values=c(\"model_curve_1\"=\"black\",\"model_curve_2\"=\"red\"),\r\n labels=ComparisonFile)\r\n }\r\n \r\n p <- p + ggtitle(gene_name)\r\n p <- p + xlab(\"Time\")\r\n p <- p + ylab(\"Relative RPKM (Time0 = 1)\")\r\n p <- p + xlim(0,12)\r\n ybreaks <- seq(0,10,0.1)[2:101]\r\n p <- p + scale_y_log10(breaks=ybreaks,labels=ybreaks)\r\n plot(p)\r\n \r\n dev.off() #close_fig\r\n plot.new()\r\n }\r\n }else{\r\n return(print(\"ERROR: Defined wrong DrawMode. Choose the following DrawMode: Simple, Ribbon. You cannot choose Ribbon mode\r\n if you use Three_model ModelMode.\"))\r\n }\r\n }else{\r\n return(print(\"ERROR: Defined wrong ModelMode. Choose the following ModelMode: Raw_model, Three_model, R2_selection\"))\r\n }\r\n}\r\n\r\n\r\n\r\n#####################################################\r\nBridgeRDrawFittingCurve <- function(filename=\"BridgeR_4_Normalized_expression_dataset.txt\", group, hour, ComparisonFile, CutoffRelExp = 0.1, CutoffDataPoint = 3, InforColumn = 4, OutputDir = \"BridgeR_fig\", OutputFile = \"BridgeR_4_HalfLife_Pvalue.txt\"){\r\n ###Import_library###\r\n #library(data.table)\r\n #library(ggplot2)\r\n \r\n ###Make_stored_directory###\r\n ComparisonFile_name = paste(ComparisonFile,collapse=\"_\")\r\n output_dir_name <- paste(OutputDir,ComparisonFile_name,sep=\"_\")\r\n dir.create(output_dir_name)\r\n \r\n ###Prepare_file_infor###\r\n time_points <- length(hour)\r\n group_number <- length(group)\r\n input_file <- fread(filename, header=T)\r\n comp_file_number <- NULL\r\n for(a in 1:length(ComparisonFile)){\r\n comp_file_number <- append(comp_file_number, which(group == ComparisonFile[a]))\r\n }\r\n output_file <- OutputFile\r\n \r\n #setwd(output_dir_name)\r\n \r\n ###print_header###\r\n cat(\"\",file=output_file)\r\n hour_label <- NULL\r\n for(a in comp_file_number){\r\n if(!is.null(hour_label)){\r\n cat(\"\\t\", file=output_file, append=T)\r\n }\r\n hour_label <- NULL\r\n for(x in hour){\r\n hour_label <- append(hour_label, paste(\"T\", x, \"_\", a, sep=\"\"))\r\n }\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn)\r\n infor_ed <- (InforColumn)*a + (a - 1)*time_points\r\n infor <- colnames(input_file)[infor_st:infor_ed]\r\n cat(infor,hour_label, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n cat(\"Model\",\"Decay_rate_coef\",\"coef_error\",\"coef_p-value\",\"R2\",\"Adjusted_R2\",\"Residual_standard_error\",\"half_life\",\"SD_ori\",\"half_exp_minus\",\"half_exp_plus\",\"half_life_SD\", sep=\"\\t\", file=output_file, append=T)\r\n }\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n cat(\"p_value(Welch Modified Two-Sample t-Test)\",\"\\n\", sep=\"\\t\", file=output_file, append=T)\r\n \r\n ###Draw_fitting_curve###\r\n gene_number <- length(input_file[[1]])\r\n for(x in 1:gene_number){\r\n data <- as.vector(as.matrix(input_file[x,]))\r\n \r\n #Save_fig\r\n gene_name <- as.character(data[2])\r\n file_name <- sprintf(\"%1$s.png\",gene_name)\r\n file_name <- paste(output_dir_name,\"/\",file_name,sep=\"\")\r\n png(filename=file_name,width = 640, height = 640)\r\n \r\n #Prepare_ggplot2\r\n p.fitting <- ggplot()\r\n\r\n flg <- 0\r\n fig_color <- NULL\r\n N_for_p <- NULL\r\n SD_for_p <- NULL\r\n X_for_p <- NULL\r\n flg_for_p <- 0\r\n for(a in comp_file_number){\r\n if(flg == 0){\r\n fig_color <- \"black\"\r\n }else{\r\n fig_color <- \"red\"\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn)\r\n infor_ed <- (InforColumn)*a + (a - 1)*time_points\r\n exp_st <- infor_ed + 1\r\n exp_ed <- infor_ed + time_points\r\n \r\n gene_infor <- data[infor_st:infor_ed]\r\n cat(gene_infor, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", file=output_file, append=T)\r\n exp <- as.numeric(data[exp_st:exp_ed])\r\n cat(exp, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", file=output_file, append=T)\r\n #hour <- c(0,1,2,4,8,12) ###TEST###\r\n #exp <- c(1,0.8350178,0.7806458,0.6386572,0.3946119,0.2603135) #\r\n ##exp <- c(1,0.9637603,1.131551,1.025119,1.246695,1.437431) #\r\n #gene_name <- \"test\" #\r\n #fig_color <- \"black\" #\r\n #CutoffRelExp <- 0.1 #\r\n #CutoffDataPoint <- 3 #\r\n time_point_exp_original <- data.frame(hour,exp)\r\n \r\n #p.fitting <- ggplot() #\r\n p.fitting <- p.fitting + geom_point(data=time_point_exp_original, \r\n mapping=aes(x=hour, y=exp), \r\n size=4,\r\n shape=19,\r\n colour=fig_color)\r\n\r\n time_point_exp <- time_point_exp_original[time_point_exp_original$exp >= CutoffRelExp, ] #>=0.1\r\n data_point <- length(time_point_exp$exp)\r\n \r\n if(!is.null(time_point_exp)){\r\n if(data_point >= CutoffDataPoint){ #>=3\r\n model <- lm(log(time_point_exp$exp) ~ time_point_exp$hour - 1)\r\n model_summary <- summary(model)\r\n coef <- -model_summary$coefficients[1]\r\n coef_error <- model_summary$coefficients[2]\r\n coef_p <- model_summary$coefficients[4]\r\n r_squared <- model_summary$r.squared\r\n adj_r_squared <- model_summary$adj.r.squared\r\n residual_standard_err <- model_summary$sigma\r\n half_life <- log(2)/coef\r\n #if(coef < 0 || half_life >= 24){\r\n # half_life <- 24\r\n #}\r\n if(coef < 0){\r\n half_life <- Inf\r\n }\r\n cat(\"Exponential_Decay_Model\",coef,coef_error,coef_p,r_squared,adj_r_squared,residual_standard_err,half_life, sep=\"\\t\", file=output_file, append=T)\r\n\r\n half_life_exp_lm <- exp(log(0.5))\r\n \r\n xmin <- min(hour[1])\r\n xmax <- max(hour[length(hour)])\r\n \r\n predicted2 <- data.frame(hour=time_point_exp$hour)\r\n predicted2_ribbon <- data.frame(hour=time_point_exp$hour)\r\n\r\n pred_conf <- predict(model, predicted2, interval=\"prediction\",level=0.95)\r\n \r\n pred_conf2_SE <- predict(model, predicted2, se.fit=T)\r\n \r\n Fit <- pred_conf2_SE$fit\r\n df <- pred_conf2_SE$df\r\n SE_fit <- pred_conf2_SE$se.fit\r\n Residual_fit <- pred_conf2_SE$residual.scale\r\n \r\n Space_minus <- function(Fit,SE_fit){\r\n Fit-sqrt(SE_fit^2+Residual_fit^2)*qt(0.950,df)\r\n }\r\n Space_plus <- function(Fit,SE_fit){\r\n Fit+sqrt(SE_fit^2+Residual_fit^2)*qt(0.950,df)\r\n }\r\n SE_test <- function(Fit,SE_fit){\r\n sqrt(SE_fit^2+Residual_fit^2)\r\n }\r\n test_minus <- Space_minus(Fit,SE_fit)\r\n test_plus <- Space_plus(Fit,SE_fit)\r\n test_SE <- SE_test(Fit,SE_fit)\r\n \r\n SE_table <- data.frame(hour=time_point_exp$hour,exp=SE_fit)\r\n SE_model <- lm((SE_table$exp) ~ SE_table$hour - 1)\r\n SE_model_coef <- (summary(SE_model))$coefficients[1]\r\n SE_half_life <- SE_model_coef*half_life\r\n\r\n SE_fitting_curve <- sqrt(SE_half_life^2 + Residual_fit^2)\r\n SD_fitting_curve <- SE_fitting_curve * sqrt(data_point-1)\r\n \r\n half_life_exp_lm_minus <- exp(log(0.5)-SD_fitting_curve)\r\n half_life_exp_lm_plus <- exp(log(0.5)+SD_fitting_curve)\r\n half_life_plus <- -log(half_life_exp_lm_minus)/coef\r\n half_life_minus <- -log(half_life_exp_lm_plus)/coef\r\n SD_for_test <- half_life_plus - half_life\r\n SD_for_test <- half_life - half_life_minus\r\n \r\n N_for_p <- append(N_for_p,data_point)\r\n SD_for_p <- append(SD_for_p, SD_for_test)\r\n X_for_p <- append(X_for_p, half_life)\r\n \r\n cat(\"\\t\", sep=\"\\t\", file=output_file, append=T)\r\n cat(SD_fitting_curve,half_life_exp_lm_minus,half_life_exp_lm_plus,SD_for_test, sep=\"\\t\", file=output_file, append=T)\r\n \r\n #model1_pred <- function(x)\r\n #{\r\n # mRNA_exp <- (x * hour)\r\n #}\r\n #SE_data <- data.frame(hour=hour,exp=model1_pred(SE_model_coef))\r\n \r\n #pred_conf <- predict(model, predicted2, interval=\"confidence\",level=0.95)\r\n predicted2$exp <- exp(as.vector(as.matrix(pred_conf[,1])))\r\n predicted2_ribbon$exp_minus <- exp(as.vector(as.matrix(pred_conf[,2])))\r\n predicted2_ribbon$exp_plus <- exp(as.vector(as.matrix(pred_conf[,3])))\r\n\r\n p.fitting <- p.fitting + geom_line(data=predicted2,\r\n mapping=(aes(x=hour, y=exp)),\r\n size=1.2,\r\n colour=fig_color)\r\n p.fitting <- p.fitting + geom_ribbon(data=predicted2_ribbon,\r\n mapping=aes(x=hour,ymin=exp_minus,ymax=exp_plus),\r\n alpha=0.1,\r\n fill=fig_color)\r\n p.fitting <- p.fitting + ggtitle(gene_name)\r\n p.fitting <- p.fitting + xlab(\"Time\")\r\n p.fitting <- p.fitting + ylab(\"Relative RPKM (Time0 = 1)\")\r\n p.fitting <- p.fitting + xlim(0,12)\r\n ybreaks <- seq(0,10,0.1)[2:101]\r\n p.fitting <- p.fitting + scale_y_log10(breaks=ybreaks,labels=ybreaks)\r\n plot(p.fitting)\r\n }else{\r\n cat(\"few_data\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n flg_for_p <- 1\r\n }\r\n }else{ ###TEST###\r\n cat(\"low_expresion\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n flg_for_p <- 1\r\n }\r\n flg = 1\r\n }\r\n t_test <- \"NA\"\r\n p_value <- \"NA\"\r\n if(flg_for_p != 1){\r\n t_test <- tsum.test(mean.x=X_for_p[1], s.x=SD_for_p[1], n.x=N_for_p[1],\r\n mean.y=X_for_p[2], s.y=SD_for_p[2], n.y=N_for_p[2])\r\n p_value <- t_test$p.value\r\n }\r\n cat(\"\\t\", sep=\"\\t\", file=output_file, append=T)\r\n cat(p_value,\"\\n\", sep=\"\\t\", file=output_file, append=T)\r\n dev.off() #close_fig\r\n plot.new()\r\n }\r\n}\r\n", "meta": {"hexsha": "f85ad4f01f8b46e73d984c238ecd58399a73242d", "size": 22230, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Z7_Draw_fitting_curve.r", "max_stars_repo_name": "ChristophRau/BridgeR", "max_stars_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_stars_repo_licenses": ["MIT"], "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/Z7_Draw_fitting_curve.r", "max_issues_repo_name": "ChristophRau/BridgeR", "max_issues_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_issues_repo_licenses": ["MIT"], "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/Z7_Draw_fitting_curve.r", "max_forks_repo_name": "ChristophRau/BridgeR", "max_forks_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.9392523364, "max_line_length": 253, "alphanum_fraction": 0.4282950967, "num_tokens": 4687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23171579230926337}} {"text": "#' Estimate cell counts from a reference\n#'\n#' Estimate cell type ratios from methylation profiles of purified cell populations\n#' (Infinium HumanMethylation450 BeadChip).\n#'\n#' @param object An object created by \\code{\\link{meffil.create.qc.object}()}.\n#' @param verbose If \\code{TRUE}, then status messages are printed during execution\n#' (Default: \\code{FALSE}).\n#' @param cell.type.reference Character string name of the cell type reference\n#' to use for estimating cell counts. \n#' See \\code{\\link{meffil.list.cell.type.references}()} for a list of available\n#' references. New references can be created using\n#' \\code{\\link{meffil.create.cell.type.reference}()}. \n#' @return A list:\n#' - \\code{counts} Cell count estimates.\n#' - \\code{beta} Normalized methylation levels of sites used to differentiate\n#' - \\code{reference} Name of the cell type reference used.\n#' between reference cell types.\n#'\n#' Results should be nearly identical to \\code{\\link[minfi]{estimateCellCounts}()}.\n#' \n#' @export\nmeffil.estimate.cell.counts <- function(qc.object, cell.type.reference, verbose=T) {\n stopifnot(is.qc.object(qc.object))\n stopifnot(is.character(cell.type.reference) && cell.type.reference %in% meffil.list.cell.type.references())\n\n reference.object <- get.cell.type.reference(cell.type.reference)\n\n if (is.null(qc.object$featureset)) { ## backwards compatibility\n qc.object$chip <- qc.object$featureset <- \"450k\"\n } \n \n rg <- read.rg(qc.object$basename, verbose=verbose)\n probes <- meffil.probe.info(qc.object$chip, reference.object$featureset)\n rg <- background.correct(rg, probes, verbose=verbose)\n rg <- dye.bias.correct(rg, probes, qc.object$dye.intensity, verbose=verbose)\n mu <- rg.to.mu(rg, probes)\n\n estimate.cell.counts.from.mu(mu, cell.type.reference, verbose)\n}\n\nestimate.cell.counts.from.mu <- function(mu, cell.type.reference, verbose=F) {\n stopifnot(is.character(cell.type.reference) && cell.type.reference %in% meffil.list.cell.type.references())\n\n reference.object <- get.cell.type.reference(cell.type.reference)\n\n mu <- quantile.normalize.signals(mu, reference.object$subsets, reference.object$quantiles, verbose=F)\n beta <- get.beta(mu$M, mu$U)\n beta <- beta[rownames(reference.object$beta)]\n counts <- estimate.cell.counts.from.beta(beta, reference.object$beta)\n \n list(class=\"cell.counts\",\n version=packageVersion(\"meffil\"),\n counts=counts,\n beta=beta,\n reference=cell.type.reference)\n} \n\nis.cell.count.object <- function(object)\n is.list(object) &&\n (\"class\" %in% names(object) && object$class == \"cell.counts\"\n || \"origin\" %in% names(object) && object$origin == \"meffil.estimate.cell.counts\") ## backwards compatibility\n\nquantile.normalize.signals <- function(mu, subsets, quantiles, verbose=F) {\n stopifnot(is.mu(mu))\n stopifnot(length(subsets) == length(quantiles))\n stopifnot(all(names(subsets) %in% names(quantiles)))\n\n for (subset.name in names(subsets)) {\n subset <- subsets[[subset.name]]\n for (target in c(\"M\",\"U\")) {\n data <- matrix(mu[[target]][subset])\n full.quantiles <- quantiles[[subset.name]][[target]]\n full.quantiles <- approx(1:length(full.quantiles), full.quantiles, 1:length(data))$y\n mu[[target]][subset] <- preprocessCore::normalize.quantiles.use.target(data,full.quantiles)\n }\n }\n mu\n}\n\n## Input:\n## beta[CpG] = methylation level of the CpG in the sample\n## beta.cell.types[CpG,cell type] = methylation level of CpG in the cell type\n##\n## Output:\n## counts[cell type] = proportion of cell type in the sample\n## that minimizes ( beta - beta.cell.types * counts )^2\n## subject to counts >= 0.\n##\n## Based on code from PMID 22568884.\nestimate.cell.counts.from.beta <- function(beta, beta.cell.types) {\n stopifnot(length(beta) == nrow(beta.cell.types))\n \n ## Let r = counts[cell type],\n ## b = beta[cpg]\n ## bc = beta.cell.types[cpg,cell type]\n ## for a given sample.\n ## We want to find r >= 0 that minimizes (b - bc r)^2.\n ## The unknown r is quadratic in the expression so\n ## we need a quadratic program solver.\n ## \n ## We use the function solve.QP(D,d,A,b0).\n ## It finds a vector b1 that minimizes\n ## b1T D b1 - 2 dT b1 subject to AT b1 >= b0.\n ## We need to put (b - bc r)^2 into this form.\n ##\n ## (b - bc r)^2\n ## = (b - bc r)T (b - bc r)\n ## = bT b - 2 bT bc r - rT bcT bc r\n ## <=> finding r to minimize -2 bT bc r + rT (bcT bc) r\n ## = rT (bcT bc) r - 2 (bcT b)T r\n ## <=> solve.QP(bcT bc, bcT b, I, z) where I = identity matrix, z = 0\n require(quadprog)\n I <- diag(ncol(beta.cell.types))\n zero <- rep(0, ncol(beta.cell.types))\n cpg.idx <- which(!is.na(beta))\n bcT.x.bc <- t(beta.cell.types[cpg.idx,]) %*% beta.cell.types[cpg.idx,]\n bcT.x.b <- t(beta.cell.types[cpg.idx,]) %*% matrix(beta[cpg.idx], nrow=length(cpg.idx))\n counts <- solve.QP(bcT.x.bc, bcT.x.b, I, zero)$sol\n names(counts) <- colnames(beta.cell.types)\n counts\n}\n\n#' Estimate cell counts for a beta matrix from a reference\n#'\n#' Estimate cell type ratios from methylation profiles of purified cell populations\n#' (Infinium HumanMethylation450 BeadChip).\n#'\n#' @param beta Matrix of Illumina 450K methylation levels (rows = CpG sites, columns = subjects).\n#' @param verbose If \\code{TRUE}, then status messages are printed during execution\n#' (Default: \\code{FALSE}).\n#' @param cell.type.reference Character string name of the cell type reference\n#' to use for estimating cell counts. \n#' See \\code{\\link{meffil.list.cell.type.references}()} for a list of available\n#' references. New references can be created using\n#' \\code{\\link{meffil.create.cell.type.reference}()}. \n#' @return A matrix of cell count estimates.\n#'\n#' Results should be nearly identical to \\code{\\link[minfi]{estimateCellCounts}()}.\n#' \n#' @export\nmeffil.estimate.cell.counts.from.betas <- function(beta, cell.type.reference, verbose=F) {\n stopifnot(is.matrix(beta))\n reference.object <- get.cell.type.reference(cell.type.reference)\n \n beta <- quantile.normalize.betas(beta, reference.object$subsets, reference.object$quantiles, verbose=verbose)\n\n cpg.sites <- intersect(rownames(beta), rownames(reference.object$beta))\n stopifnot(length(cpg.sites) > 0)\n \n beta <- beta[cpg.sites,]\n reference.beta <- reference.object$beta[cpg.sites,]\n\n t(apply(beta, 2, estimate.cell.counts.from.beta, reference.beta))\n} \n\nquantile.normalize.betas <- function(beta, subsets, quantiles, verbose=F) {\n stopifnot(is.matrix(beta))\n stopifnot(length(subsets) == length(quantiles))\n stopifnot(all(names(subsets) %in% names(quantiles)))\n \n for (subset.name in names(subsets)) {\n subset <- intersect(subsets[[subset.name]], rownames(beta))\n if (length(subset) == 0)\n stop(paste(\"subset\", subset.name, \"and beta matrix have no features in common\"))\n full.quantiles <- quantiles[[subset.name]]$beta\n full.quantiles <- approx(1:length(full.quantiles), full.quantiles, 1:length(subset))$y\n beta[subset,] <- preprocessCore::normalize.quantiles.use.target(beta[subset,,drop=F],\n full.quantiles)\n }\n beta\n}\n", "meta": {"hexsha": "dc30606c322448f4ad3cb795e07020f9f89e9ca8", "size": 7338, "ext": "r", "lang": "R", "max_stars_repo_path": "R/estimate-cell-counts.r", "max_stars_repo_name": "RichardJActon/meffil_duplicate", "max_stars_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/estimate-cell-counts.r", "max_issues_repo_name": "RichardJActon/meffil_duplicate", "max_issues_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "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/estimate-cell-counts.r", "max_forks_repo_name": "RichardJActon/meffil_duplicate", "max_forks_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "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": 42.4161849711, "max_line_length": 113, "alphanum_fraction": 0.6633960207, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22812457749095041}} {"text": "library(diagram)\nlibrary(lubridate)\nlibrary(seraphim)\nlibrary(treeio)\nlibrary(viridis)\n\nanalysis_date = \"270221\"\nwritingFiles = FALSE; savingPlots = FALSE\n\npostcodes = shapefile(\"Shapefiles_study_area/England_postcode_districts.shp\"); crs(postcodes) = CRS(\"+init=epsg:27700\")\nUTLAs = crop(spTransform(shapefile(\"Shapefiles_study_area/UTLA_administrative_areas.shp\"), crs(postcodes)), postcodes)\nregions = shapefile(\"Shapefiles_study_area/England_defined_regions_2.shp\")\npop = projectRaster(raster(\"WorldPop_pop_raster.tif\"), crs=crs(postcodes)); pop[] = log(pop[])\n\n# 1. Preparing the continuous phylogeographic analysis (RRW, Cauchy model)\n\ntree = read.nexus(paste0(\"TreeTime_\",analysis_date,\".tre\"))\nmetadata = read.csv(paste0(\"Metadata_England.csv\"))\nall_collection_dates = dmy(gsub(\"\\\\/\",\"-\",metadata[,\"sample_date\"]))\nprint(c(min(all_collection_dates),max(all_collection_dates)))\nif (!file.exists(paste0(\"Sampling_\",analysis_date,\".csv\")))\n\t{\n\t\tsamplingData = matrix(nrow=length(tree$tip.label), ncol=5)\n\t\tcolnames(samplingData) = c(\"sequence_ID\",\"collection_date\",\"postcode\",\"longitude\",\"latitude\")\n\t\tsamplingData[,\"sequence_ID\"] = gsub(\"'\",\"\",tree$tip.label); i = 1\n\t\tfor (i in i:dim(samplingData)[1])\n\t\t\t{\n\t\t\t\tindex = which(metadata[,\"name\"]==samplingData[i,\"sequence_ID\"])\n\t\t\t\tif (length(index) == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsamplingData[i,\"collection_date\"] = decimal_date(dmy(gsub(\"\\\\/\",\"-\",metadata[index,\"sample_date\"])))\n\t\t\t\t\t\tsamplingData[i,\"postcode\"] = metadata[index,\"postcode\"]\n\t\t\t\t\t\tindices = which(postcodes@data[,\"PostDist\"]==samplingData[i,\"postcode\"])\n\t\t\t\t\t\tif (length(indices) > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmaxArea = 0; polIndex1 = 0; polIndex2 = 0\n\t\t\t\t\t\t\t\tfor (j in 1:length(indices))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (k in 1:length(postcodes@polygons[[indices[j]]]@Polygons))\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tif (maxArea < postcodes@polygons[[indices[j]]]@Polygons[[k]]@area)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmaxArea = postcodes@polygons[[indices[j]]]@Polygons[[k]]@area; polIndex1 = indices[j]; polIndex2 = k\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpol = postcodes@polygons[[polIndex1]]@Polygons[[polIndex2]]\n\t\t\t\t\t\t\t\tp = Polygon(pol@coords); ps = Polygons(list(p),1); sps = SpatialPolygons(list(ps))\n\t\t\t\t\t\t\t\tpol = sps; # proj4string(pol) = postcodes@proj4string\n\t\t\t\t\t\t\t\t# samplingData[i,c(\"longitude\",\"latitude\")] = coordinates(pol) # to avoid a jitter:\n\t\t\t\t\t\t\t\tsamplingData[i,c(\"longitude\",\"latitude\")] = spsample(pol, 1, type=\"random\")@coords\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\twrite.csv(samplingData, paste0(\"Sampling_\",analysis_date,\".csv\"), quote=F, row.names=F); print(c(i,dim(samplingData)[1]))\n\t}\t\nsamplingData = read.csv(paste0(\"Sampling_\",analysis_date,\".csv\"), head=T); clusters2 = list(); clusters2[[1]] = samplingData\ntemplate = scan(\"RRW_template_file.xml\", what=\"\", sep=\"\\n\", quiet=T, blank.lines.skip=F)\ntemplate = gsub(\"All_clades\",\"TreeTime_090221\",template); xml = c()\nsink(file=paste0(\"TreeTime_\",analysis_date,\".xml\"))\nfor (i in 1:length(template))\n\t{\n\t\tcat(template[i],\"\\n\")\n\t\tif (grepl(\"Insert taxa blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tfor (k in 1:dim(clusters2[[j]])[1])\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (!is.na(clusters2[[j]][k,\"longitude\"]))\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",clusters2[[j]][k,\"latitude\"],\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",clusters2[[j]][k,\"longitude\"],\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",clusters2[[j]][k,\"latitude\"],\" \",clusters2[[j]][k,\"longitude\"],\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert alignment blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tfor (k in 1:dim(clusters2[[j]])[1])\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (!is.na(clusters2[[j]][k,\"longitude\"]))\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\tNNNN\\n\")\n\t\t\t\t\t\t\t\t\t\t\t\tcat(\"\\t\\t\\n\")\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert pattern blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert starting tree blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\ttips = clusters2[[j]][,\"sequence_ID\"]; tips = tips[which(!is.na(clusters2[[j]][,\"longitude\"]))]\n\t\t\t\t\t\t\t\ttre = tree; tips_to_drop = tre$tip.label[which(!gsub(\"'\",\"\",tre$tip.label)%in%tips)]\n\t\t\t\t\t\t\t\tif (length(tips_to_drop) > 0) tre = ape::drop.tip(tre, tips_to_drop)\n\t\t\t\t\t\t\t\ttre = multi2di(tre); tree$edge.length[which(tree$edge.length==0)] = 0.5\n\t\t\t\t\t\t\t\twrite.tree(tre, paste0(\"Empirical_tree_RRW.tre\"))\n\t\t\t\t\t\t\t\ttre = scan(paste0(\"Empirical_tree_RRW.tre\"), what=\"\", sep=\"\\n\", quiet=T)\n\t\t\t\t\t\t\t\ttxt = c(\"#NEXUS\",\"begin trees;\",paste0(\"\\ttree tree_1 = [&R] \",tre),\"end;\")\n\t\t\t\t\t\t\t\twrite(txt, paste0(\"Empirical_tree_RRW.tre\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert tree model blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert arbitraryBranchRates blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert distributionLikelihood blocks 1\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert coordinates.traitLikelihood blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert continuousDiffusionStatistic blocks 1\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert scaleOperator blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert precisionGibbsOperator blocks\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert distributionLikelihood blocks 2\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert multivariateTraitLikelihood blocks 1\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert continuousDiffusionStatistic blocks 2\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"Insert multivariateTraitLikelihood blocks 2\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\tif (grepl(\"\",template[i]))\n\t\t\t{\n\t\t\t\tfor (j in 1:length(clusters2))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((dim(clusters2[[j]])[1] >= 3)&(sum(!is.na(clusters2[[j]][,\"longitude\"])) >= 3))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(paste0(\"\\t\\t\\t\\t\",\"\\n\"))\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t\tcat(\"\\t\\t\",\"\\n\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t}\nsink(NULL)\n\n# 2. Extracting spatio-temporal information embedded in MCC and posterior trees\n\nif (!file.exists(paste0(\"TreeTime_\",analysis_date,\".csv\")))\n\t{\n\t\tsource(\"MCC_tree_extraction.r\")\n\t\tsamplingData = read.csv(paste0(\"Sampling_\",analysis_date,\".csv\"), head=T)\n\t\tsamplingData = samplingData[which(!is.na(samplingData[,\"longitude\"])),]\n\t\tmostRecentSamplingDatum = max(samplingData[,\"collection_date\"])\n\t\tmcc_tre = readAnnotatedNexus(paste0(\"TreeTime_\",analysis_date,\".tree\"))\n\t\tmcc = MCC_tree_extraction(mcc_tre, mostRecentSamplingDatum)\n\t\twrite.csv(mcc, paste0(\"TreeTime_\",analysis_date,\".csv\"), quote=F, row.names=F)\n\t\t\t# before continuing, longitude/latitude columns have to be inverted in the CSV file\n\t\tmidYears = matrix(nrow=dim(mcc)[1], ncol=1)\n\t\tmidYears[,1] = (mcc[,\"startYear\"]+mcc[,\"endYear\"])/2\n\t\tcolnames(midYears) = c(\"midYear\"); mcc = cbind(mcc, midYears)\n\t\tstart_and_end_UTLAs = matrix(nrow=dim(mcc)[1], ncol=2)\n\t\tcolnames(start_and_end_UTLAs) = c(\"startUTLA\",\"endUTLA\")\n\t\tfor (i in 1:dim(UTLAs@data)[1])\n\t\t\t{\n\t\t\t\tmaxArea = 0; polIndex = 0; # print(i)\n\t\t\t\tfor (j in 1:length(UTLAs@polygons[[i]]@Polygons))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (maxArea < UTLAs@polygons[[i]]@Polygons[[j]]@area)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmaxArea = UTLAs@polygons[[i]]@Polygons[[j]]@area; polIndex = j\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tpol = UTLAs@polygons[[i]]@Polygons[[polIndex]]\n\t\t\t\tindices = which(point.in.polygon(mcc[,\"startLon\"],mcc[,\"startLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\t\t\tstart_and_end_UTLAs[indices,\"startUTLA\"] = UTLAs@data[i,\"NUMBER\"]\n\t\t\t\tindices = which(point.in.polygon(mcc[,\"endLon\"],mcc[,\"endLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\t\t\tstart_and_end_UTLAs[indices,\"endUTLA\"] = UTLAs@data[i,\"NUMBER\"]\n\t\t\t}\n\t\tstart_and_end_regions = matrix(nrow=dim(mcc)[1], ncol=2)\n\t\tcolnames(start_and_end_regions) = c(\"startRegion\",\"endRegion\")\n\t\tfor (i in 1:(dim(regions@data)[1]-1))\n\t\t\t{\n\t\t\t\tmaxArea = 0; polIndex = 0; # print(i)\n\t\t\t\tfor (j in 1:length(regions@polygons[[i]]@Polygons))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (maxArea < regions@polygons[[i]]@Polygons[[j]]@area)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmaxArea = regions@polygons[[i]]@Polygons[[j]]@area; polIndex = j\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tpol = regions@polygons[[i]]@Polygons[[polIndex]]\n\t\t\t\tindices = which(point.in.polygon(mcc[,\"startLon\"],mcc[,\"startLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\t\t\tif (length(indices) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (sum(!is.na(start_and_end_regions[indices,\"startRegion\"])) != 0) print(c(i,1))\n\t\t\t\t\t\tstart_and_end_regions[indices,\"startRegion\"] = regions@data[i,\"Merged_loc\"]\n\t\t\t\t\t}\n\t\t\t\tindices = which(point.in.polygon(mcc[,\"endLon\"],mcc[,\"endLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\t\t\tif (length(indices) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (sum(!is.na(start_and_end_regions[indices,\"endRegion\"])) != 0) print(c(i,2))\n\t\t\t\t\t\tstart_and_end_regions[indices,\"endRegion\"] = regions@data[i,\"Merged_loc\"]\n\t\t\t\t\t}\n\t\t\t}\n\t\tmcc = cbind(mcc, start_and_end_UTLAs, start_and_end_regions)\n\t\tstartCoords = mcc[,c(\"startLon\",\"startLat\")]; coordinates(startCoords) = c(\"startLon\",\"startLat\")\n\t\tproj4string(startCoords) = CRS(\"+init=epsg:27700\"); startCoords = spTransform(startCoords, CRS(\"+init=epsg:4326\"))\n\t\tendCoords = mcc[,c(\"endLon\",\"endLat\")]; coordinates(endCoords) = c(\"endLon\",\"endLat\")\n\t\tproj4string(endCoords) = CRS(\"+init=epsg:27700\"); endCoords = spTransform(endCoords, CRS(\"+init=epsg:4326\"))\n\t\tgeographicDistances = matrix(nrow=dim(startCoords@coords)[1], ncol=1); colnames(geographicDistances) = c(\"geoDist_km\")\n\t\tfor (i in 1:dim(geographicDistances)[1])\n\t\t\t{\n\t\t\t\tgeographicDistances[i,1] = rdist.earth(cbind(startCoords@coords[i,1],startCoords@coords[i,2]), cbind(endCoords@coords[i,1],endCoords@coords[i,2]), miles=F)\n\t\t\t}\n\t\tmcc = cbind(mcc, geographicDistances)\n\t\twrite.csv(mcc, paste0(\"TreeTime_\",analysis_date,\".csv\"), quote=F, row.names=F)\n\t}\telse\t\t{\n\t\tmcc = read.csv(paste0(\"TreeTime_\",analysis_date,\".csv\"), head=T)\n\t}\nmcc = mcc[-which((is.na(mcc[,\"startUTLA\"]))|(is.na(mcc[,\"endUTLA\"]))),]\nmcc = mcc[order(mcc[,\"endYear\"]),]\n\n# 3. Generating the dispersal history graphs (mapped MCC trees, 80% HPD polygons)\n\nif (savingPlots)\n\t{\n\t\tcolourScale = rev(colorRampPalette(brewer.pal(11,\"BrBG\"))(141)[16:116])\n\t\tcolourScale = rev(colorRampPalette(brewer.pal(11,\"RdYlBu\"))(141)[16:116])\n\t\tcolourScale = gsub(\"FF\",\"\",viridis::viridis(101)[1:101])\n\t\tminYear = min(mcc[,\"startYear\"]); maxYear = max(mcc[,\"endYear\"])\n\t\tstartYears_indices = (((mcc[,\"startYear\"]-minYear)/(maxYear-minYear))*100)+1\n\t\tendYears_indices = (((mcc[,\"endYear\"]-minYear)/(maxYear-minYear))*100)+1\n\t\tstartYears_colours = colourScale[startYears_indices]\n\t\tendYears_colours = colourScale[endYears_indices]\n\t\tplottingInternalNodes = TRUE; plotLegend = TRUE\n\t\tUTLA_sampled_sequences = matrix(nrow=dim(UTLAs@data)[1], ncol=1)\n\t\tfor (i in 1:dim(UTLA_sampled_sequences)[1])\n\t\t\t{\n\t\t\t\tUTLA_sampled_sequences[i,1] = length(which((!mcc[,\"node2\"]%in%mcc[,\"node1\"])&(mcc[,\"endUTLA\"]==UTLAs@data[i,\"NUMBER\"])))\n\t\t\t}\n\t\tUTLA_all_introductions = matrix(nrow=dim(UTLAs@data)[1], ncol=1)\n\t\tfor (i in 1:dim(UTLA_all_introductions)[1])\n\t\t\t{\n\t\t\t\tUTLA_all_introductions[i,1] = length(which((mcc[,\"startUTLA\"]!=UTLAs@data[i,\"NUMBER\"])&(mcc[,\"endUTLA\"]==UTLAs@data[i,\"NUMBER\"])))\n\t\t\t}\n\t\tpdf(\"Figure_A4_OLD.pdf\", width=3, height=3.5)\n\t\tpar(oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tminVal = 0; maxVal = max(UTLA_sampled_sequences)\n\t\tindices = (((UTLA_sampled_sequences[,1]-minVal)/(maxVal-minVal))*100)+1\n\t\tcols = rev(colourScale)[indices]; cols[which(UTLA_sampled_sequences[,1]==0)] = NA\n\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\tplot(UTLAs, border=\"white\", col=cols, add=T, lwd=0.2)\n\t\tif (plotLegend == TRUE)\n\t\t\t{\n\t\t\t\trast = raster(matrix(nrow=1, ncol=2)); rast[1] = 1; rast[2] = max(UTLA_sampled_sequences)\n\t\t\t\tplot(rast, legend.only=T, add=T, col=rev(colourScale), legend.width=0.5, legend.shrink=0.3, smallplot=c(0.45,0.94,0.114,0.125),\n\t\t\t\t\t legend.args=list(text=\"\", cex=0.6, line=0.3, col=\"gray30\"), horizontal=T,\n\t\t\t\t axis.args=list(cex.axis=0.5, lwd=0, lwd.tick=0.2, tck=-0.9, col.axis=\"gray30\", line=0, mgp=c(0,-0.20,0)))\n\t\t\t}\n\t\tdev.off()\n\t\tpdf(\"Figure_A4_NEW.pdf\", width=3, height=3.5)\n\t\tpar(oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tminVal = 0; maxVal = max(UTLA_all_introductions)\n\t\tindices = (((UTLA_all_introductions[,1]-minVal)/(maxVal-minVal))*100)+1\n\t\tcols = rev(colourScale)[indices]; cols[which(UTLA_all_introductions[,1]==0)] = NA\n\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\tplot(UTLAs, border=\"white\", col=cols, add=T, lwd=0.2)\n\t\tif (plotLegend == TRUE)\n\t\t\t{\n\t\t\t\trast = raster(matrix(nrow=1, ncol=2)); rast[1] = 1; rast[2] = max(UTLA_all_introductions)\n\t\t\t\tplot(rast, legend.only=T, add=T, col=rev(colourScale), legend.width=0.5, legend.shrink=0.3, smallplot=c(0.45,0.94,0.114,0.125),\n\t\t\t\t\t legend.args=list(text=\"\", cex=0.6, line=0.3, col=\"gray30\"), horizontal=T,\n\t\t\t\t axis.args=list(cex.axis=0.5, lwd=0, lwd.tick=0.2, tck=-0.9, col.axis=\"gray30\", line=0, mgp=c(0,-0.20,0)))\n\t\t\t}\n\t\tdev.off()\t\n\t\tpdf(\"Figure_A2_NEW.pdf\", width=6, height=7)\n\t\tpar(oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\tplot(UTLAs, border=\"white\", col=NA, add=T, lwd=0.4)\n\t\tselectedBranches = 1:dim(mcc)[1]; cexNode = 0.3\n\t\tfor (i in selectedBranches)\n\t\t\t{\n\t\t\t\tcurvedarrow(cbind(mcc[i,\"startLon\"],mcc[i,\"startLat\"]), cbind(mcc[i,\"endLon\"],mcc[i,\"endLat\"]), arr.length=0,\n\t\t\t\t\t\t arr.width=0, lwd=0.1, lty=1, lcol=\"gray10\", arr.col=NA, arr.pos=F, curve=0.1, dr=NA, endhead=F)\n\t\t\t}\n\t\tfor (i in rev(selectedBranches))\n\t\t\t{\n\t\t\t\tif (plottingInternalNodes == TRUE)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (mcc[i,\"node2\"]%in%mcc[,\"node1\"])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpoints(mcc[i,\"endLon\"], mcc[i,\"endLat\"], pch=16, col=endYears_colours[i], cex=cexNode)\n\t\t\t\t\t\t\t\tpoints(mcc[i,\"endLon\"], mcc[i,\"endLat\"], pch=1, col=\"gray10\", cex=cexNode, lwd=0.1)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tif (!mcc[i,\"node2\"]%in%mcc[,\"node1\"])\n\t\t\t\t\t{\n\t\t\t\t\t\tpoints(mcc[i,\"endLon\"], mcc[i,\"endLat\"], pch=16, col=endYears_colours[i], cex=cexNode)\n\t\t\t\t\t\tpoints(mcc[i,\"endLon\"], mcc[i,\"endLat\"], pch=1, col=\"gray10\", cex=cexNode, lwd=0.1)\n\t\t\t\t\t}\n\t\t\t}\n\t\trootIndex = which(!mcc[,\"node1\"]%in%mcc[,\"node2\"])[1]\n\t\tpoints(mcc[i,\"startLon\"], mcc[i,\"startLat\"], pch=16, col=startYears_colours[rootIndex], cex=cexNode)\n\t\tpoints(mcc[i,\"startLon\"], mcc[i,\"startLat\"], pch=1, col=\"gray10\", cex=cexNode, lwd=0.1)\n\t\tif (plotLegend == TRUE)\n\t\t\t{\n\t\t\t\tselectedDates = decimal_date(ymd(c(\"2020-09-01\",\"2020-10-01\",\"2020-11-01\",\"2020-12-01\",\"2021-01-01\")))\n\t\t\t\tselectedLabels = c(\"01-09-20\",\"01-10-20\",\"01-11-20\",\"01-12-20\",\"01-01-21\")\n\t\t\t\trast = raster(matrix(nrow=1, ncol=2)); rast[1] = min(mcc[,\"startYear\"]); rast[2] = max(mcc[,\"endYear\"])\n\t\t\t\tplot(rast, legend.only=T, add=T, col=colourScale, legend.width=0.5, legend.shrink=0.3, smallplot=c(0.46,0.92,0.106,0.112),\n\t\t\t\t\t legend.args=list(text=\"\", cex=0.55, line=0.3, col=\"gray30\"), horizontal=T,\n\t\t\t\t axis.args=list(cex.axis=0.6, lwd=0, lwd.tick=0.2, tck=-1, col.axis=\"gray30\", line=0, mgp=c(0,-0.1,0),\n\t\t\t\t at=selectedDates, labels=selectedLabels))\n\t\t\t}\n\t\tdev.off()\n\t\tpdf(\"Figure_A1_NEW.pdf\", width=8, height=9)\n\t\tpar(mfrow=c(2,2), oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\"); cexNode = 0.35\n\t\tcutOffs = c(decimal_date(dmy(c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\"))))\n\t\tdates = c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\")\n\t\tfor (h in 1:length(cutOffs))\n\t\t\t{\n\t\t\t\tplot(postcodes, border=NA, col=\"gray95\", lwd=0.01)\n\t\t\t\tplot(UTLAs, border=\"white\", col=NA, add=T, lwd=0.4)\n\t\t\t\tselectedBranches = which(mcc[,\"endYear\"]=dates[i])&(mcc[,\"midYear\"]=dates[i])&(mcc[,\"endYear\"] 0)\n\t\t\t{\n\t\t\t\ttab2[i,\"all_lineage_dispersal\"] = dim(sub1)[1]\n\t\t\t\tsub2 = sub1[which(sub1[,\"startRegion\"]==\"Greater_London\"),]\n\t\t\t\tif (dim(sub2)[1] > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\ttab2[i,\"lineage_exports_London\"] = dim(sub2[which(sub2[,\"endRegion\"]!=\"Greater_London\"),])[1]\n\t\t\t\t\t\tsub3 = sub2[which(sub2[,\"geoDist_km\"]>=5),]\n\t\t\t\t\t\tif (dim(sub3)[1] > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttab2[i,\"median_distance_London\"] = median(sub3[,\"geoDist_km\"])\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tsub2 = sub1[which(sub1[,\"startRegion\"]!=\"Greater_London\"),]\n\t\t\t\tif (dim(sub2)[1] > 0)\n\t\t\t\t\t{\ntab2[i,\"lineage_exports_London\"] = dim(sub2[which(sub2[,\"endRegion\"]!=\"Greater_London\"),])[1]\n\t\t\t\t\t\tsub3 = sub2[which(sub2[,\"geoDist_km\"]>=5),]\n\t\t\t\t\t\tif (dim(sub3)[1] > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttab2[i,\"median_distance_notLondon\"] = median(sub3[,\"geoDist_km\"])\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t}\nif (writingFiles)\n\t{\n\t\ttmp = matrix(nrow=dim(tab2)[1], ncol=1); tmp[,1] = tab2[,\"lineage_exports_London\"]\n\t\ttmp[,1] = round(tab2[,\"lineage_exports_London\"]/tab2[,\"all_lineage_dispersal\"], 3)\n\t\tallLabels = gsub(\"\\\\/\",\"-\",gsub(\"\\\\/20\",\"\\\\/\",tab1[,\"week_start\"]))\n\t\trow.names(tmp) = allLabels; colnames(tmp) = c(\"ratio_exports_from_London_vs_all\")\n\t\twrite.csv(tmp, \"Ratios_between_exports_from_London_and_all_dispersal_events.csv\", quote=F)\n\t}\ntab3 = matrix(nrow=dim(tab1)[1], ncol=9)\ncolnames(tab3) = regions@data[1:9,\"Merged_loc\"]\nfor (i in 1:dim(tab1)[1])\n\t{\n\t\tif (i != dim(tab1)[1])\n\t\t\t{\n\t\t\t\tending_day = dates[i+1]\n\t\t\t}\telse\t{\n\t\t\t\tending_day = mostRecentSamplingDatum+1/365\n\t\t\t}\n\t\tsub1 = mcc[which((mcc[,\"endYear\"]>=dates[i])&(mcc[,\"endYear\"] 0)\n\t\t\t{\n\t\t\t\tfor (j in 1:dim(tab3)[2])\n\t\t\t\t\t{\n\t\t\t\t\t\tsub2 = sub1[which((sub1[,\"startRegion\"]!=colnames(tab3)[j])&(sub1[,\"endRegion\"]==colnames(tab3)[j])),]\n\t\t\t\t\t\tif (dim(sub2)[1] > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsub3 = mcc[which((mcc[,\"startRegion\"]==colnames(tab3)[j])&(mcc[,\"endRegion\"]==colnames(tab3)[j])),]\n\t\t\t\t\t\t\t\tnberOfSamplesConnectedToEachIntroduction = rep(NA, dim(sub2)[1])\n\t\t\t\t\t\t\t\tfor (k in 1:dim(sub2)[1])\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tsub4 = sub2[k,]; allBranchesScreened = FALSE\n\t\t\t\t\t\t\t\t\t\twhile (allBranchesScreened == FALSE)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tif (sum((sub3[,\"node1\"]%in%sub4[,\"node2\"])&(!sub3[,\"node1\"]%in%sub4[,\"node1\"])) > 0)\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsub4 = rbind(sub4, sub3[which((sub3[,\"node1\"]%in%sub4[,\"node2\"])&(!sub3[,\"node1\"]%in%sub4[,\"node1\"])),])\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\telse\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tallBranchesScreened = TRUE\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tsub5 = sub4[which(!sub4[,\"node2\"]%in%sub4[,\"node1\"]),]\n\t\t\t\t\t\t\t\t\t\tnberOfSamplesConnectedToEachIntroduction[k] = dim(sub5)[1]\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\ttab3[i,j] = round(mean(nberOfSamplesConnectedToEachIntroduction),2)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t}\ntab3 = tab3[,c(\"Kent\",\"Greater_London\",\"Norfolk\",\"Birmingham\",\"Greater_Manchester\",\"Cumbria\")]\nallLabels = gsub(\"\\\\/\",\"-\",gsub(\"\\\\/20\",\"\\\\/\",tab1[,\"week_start\"])); row.names(tab3) = allLabels\nif (writingFiles) write.csv(tab3, \"Mean_number_of_samples_resulting_from_introduction_events.csv\", quote=F)\nif (savingPlots)\n\t{\n\t\tpdf(\"Figure_A3_NEW.pdf\", width=3.75, height=2.3)\n\t\tpar(oma=c(0,0,0,0), mar=c(3,2,0,2), lwd=0.2, col=\"gray30\")\n\t\tplot(1:dim(tab2)[1], tab2[,\"lineage_exports_London\"], type=\"l\", lwd=0.3, col=\"red\", axes=F, ann=F)\n\t\tpoints(1:dim(tab2)[1], tab2[,\"lineage_exports_London\"], cex=0.6, pch=16, col=\"red\")\n\t\taxis(side=1, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.45,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\", las=2, at=1:dim(tab2)[1], labels=allLabels)\n\t\taxis(side=2, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.25,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"red\", col=\"gray30\")\n\t\ttitle(ylab=\"B.1.1.7 lineage exports\", cex.lab=0.7, mgp=c(1.1,0,0), col.lab=\"red\")\n\t\tpar(new=T)\n\t\tplot(1:dim(tab2)[1], tab2[,1], type=\"l\", lwd=0.3, col=\"gray30\", axes=F, ann=F); points(1:dim(tab2)[1], tab2[,1], cex=0.6, pch=16, col=\"gray30\")\n\t\taxis(side=4, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.10,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\")\n\t\tdev.off()\n\t\tpdf(\"Figure_B3_NEW.pdf\", width=7, height=2.0)\n\t\tpar(oma=c(0,0,0,0), mar=c(3,2,0,0), lwd=0.2, col=\"gray30\")\n\t\tplot(1:(dim(tab2)[1]-1), tab2[1:(dim(tab2)[1]-1),\"median_distance_notLondon\"], ylim=c(0,30), type=\"l\", lwd=0.3, col=\"gray30\", axes=F, ann=F)\n\t\tpoints(1:(dim(tab2)[1]-1), tab2[1:(dim(tab2)[1]-1),\"median_distance_notLondon\"], cex=0.6, pch=16, col=\"gray30\")\n\t\tlines(1:(dim(tab2)[1]-1), tab2[1:(dim(tab2)[1]-1),\"median_distance_London\"], lwd=0.3, col=\"red\")\n\t\tpoints(1:(dim(tab2)[1]-1), tab2[1:(dim(tab2)[1]-1),\"median_distance_London\"], cex=0.6, pch=16, col=\"red\")\n\t\taxis(side=1, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.45,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\", las=2, at=1:dim(tab2)[1], labels=allLabels)\n\t\taxis(side=2, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.25,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\")\n\t\ttitle(ylab=\"median distance (km)\", cex.lab=0.7, mgp=c(1.1,0,0), col.lab=\"gray30\")\n\t\tdev.off()\n\t\ttmp = matrix(nrow=dim(tab2)[1], ncol=1); tmp[,1] = tab2[,\"lineage_exports_London\"]\n\t\ttmp[,1] = round(tab2[,\"lineage_exports_London\"]/tab2[,\"all_lineage_dispersal\"], 3)\n\t\tpdf(\"Figure_B4_NEW.pdf\", width=7, height=2.0)\n\t\tpar(oma=c(0,0,0,0), mar=c(3,2,0,0), lwd=0.2, col=\"gray30\")\n\t\tplot(1:(dim(tab2)[1]-1), tmp[1:(dim(tab2)[1]-1),1], ylim=c(0,0.27), type=\"l\", lwd=0.3, col=\"gray30\", axes=F, ann=F)\n\t\tpoints(1:(dim(tab2)[1]-1), tmp[1:(dim(tab2)[1]-1),1], cex=0.6, pch=16, col=\"gray30\")\n\t\taxis(side=1, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.45,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\", las=2, at=1:dim(tab2)[1], labels=allLabels)\n\t\taxis(side=2, lwd.tick=0.2, cex.axis=0.6, mgp=c(0,0.25,0), lwd=0.2, tck=-0.03, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\")\n\t\ttitle(ylab=\"ratio London/all exports\", cex.lab=0.7, mgp=c(1.1,0,0), col.lab=\"gray30\")\n\t\tdev.off()\n\t}\n\n# 5. Analysing the introduction events in the different UTLA or region polygons\n\nmonths = c(\"09\",\"10\",\"11\",\"12\",\"01\")\nyears = c(2020,2020,2020,2020,2021)\nmaxDays = c(30,31,30,31,13)\ndays1 = c(); days2 = c()\nfor (i in 1:length(months))\n\t{\n\t\tif (years[i] == 2020) day_time = 1/366\n\t\tif (years[i] == 2021) day_time = 1/365\n\t\tdays1 = c(days1, paste(c(paste0(\"0\",1:9),10:maxDays[i]),months[i],years[i],sep=\"-\"))\n\t\tdays2 = c(days2, decimal_date(dmy(paste(c(paste0(\"0\",1:9),10:maxDays[i]),months[i],years[i],sep=\"-\")))+day_time)\n\t}\n\n\t# 5.1. Analysing the daily numbers of introductions per UTLA\n\nUTLA_introductions = matrix(nrow=dim(UTLAs@data)[1], ncol=length(days2)-1)\nrow.names(UTLA_introductions) = UTLAs@data[,\"NUMBER\"]\ncolnames(UTLA_introductions) = days1[1:(length(days1)-1)]\nfor (i in 1:dim(UTLA_introductions)[1])\n\t{\n\t\tsub = mcc[which((mcc[,\"startUTLA\"]!=UTLAs@data[i,\"NUMBER\"])&(mcc[,\"endUTLA\"]==UTLAs@data[i,\"NUMBER\"])),]\n\t\tfor (d in 2:length(days2))\n\t\t\t{\n\t\t\t\tUTLA_introductions[i,d-1] = length(which((sub[\"endYear\"]>days2[d-1])&(sub[\"endYear\"]<=days2[d])))\n\t\t\t}\n\t}\nwrite.csv(UTLA_introductions, \"UTLA_introductions.csv\", quote=F)\nif (savingPlots)\n\t{\n\t\tdays = decimal_date(dmy(colnames(UTLA_introductions)))\n\t\tUTLA_cumulative_introductions = matrix(nrow=dim(UTLA_introductions)[1], ncol=dim(UTLA_introductions)[2])\n\t\tUTLA_cumulative_introductions[,1] = UTLA_introductions[,2]\n\t\tfor (i in 2:dim(UTLA_introductions)[2]) UTLA_cumulative_introductions[,i] = UTLA_cumulative_introductions[,i-1]+UTLA_introductions[,i]\n\t\tUTLA_all_introductions = matrix(nrow=dim(UTLA_introductions)[1], ncol=1)\n\t\tfor (i in 1:dim(UTLA_introductions)[1]) UTLA_all_introductions[i,1] = sum(UTLA_introductions[i,])\n\t\tminVal = 0; maxVal = max(UTLA_cumulative_introductions)\n\t\tcolourScale = rev(gsub(\"FF\",\"\",viridis(101))); plotLegend = TRUE\n\t\tcutOffs = c(decimal_date(dmy(c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\"))))\n\t\tdates = c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\")\n\t\tpdf(\"Figure_A1_alternative.pdf\", width=3, height=3.5)\n\t\tpar(oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tindex = which(days<=cutOffs[1])[length(which(days<=cutOffs[1]))]\n\t\tindices = (((UTLA_cumulative_introductions[,index]-minVal)/(maxVal-minVal))*100)+1\n\t\tcols = colourScale[indices]; cols[which(UTLA_cumulative_introductions[,index]==0)] = NA\n\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\tplot(UTLAs, border=\"white\", col=cols, add=T, lwd=0.2)\n\t\tmtext(dates[1], line=-12, at=225000, cex=0.65, col=\"gray30\")\n\t\tdev.off()\n\t\tpdf(\"Figure_C4_alternative.pdf\", width=3, height=3.5)\n\t\tpar(oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tindex = which(days<=cutOffs[4])[length(which(days<=cutOffs[4]))]\n\t\tindices = (((UTLA_cumulative_introductions[,index]-minVal)/(maxVal-minVal))*100)+1\n\t\tcols = colourScale[indices]; cols[which(UTLA_cumulative_introductions[,index]==0)] = NA\n\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\tplot(UTLAs, border=\"white\", col=cols, add=T, lwd=0.2)\n\t\tif (plotLegend == TRUE)\n\t\t\t{\n\t\t\t\trast = raster(matrix(nrow=1, ncol=2)); rast[1] = 1; rast[2] = maxVal\n\t\t\t\tplot(rast, legend.only=T, add=T, col=rev(colourScale), legend.width=0.5, legend.shrink=0.3, smallplot=c(0.45,0.94,0.114,0.125),\n\t\t\t\t\t legend.args=list(text=\"\", cex=0.6, line=0.3, col=\"gray30\"), horizontal=T,\n\t\t\t\t axis.args=list(cex.axis=0.5, lwd=0, lwd.tick=0.2, tck=-0.9, col.axis=\"gray30\", line=0, mgp=c(0,-0.20,0)))\n\t\t\t}\n\t\tmtext(dates[4], line=-12, at=225000, cex=0.65, col=\"gray30\")\n\t\tdev.off()\t\t\n\t\tpdf(\"Figure_D_alternative.pdf\", width=8, height=9)\n\t\tpar(mfrow=c(2,2), oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\"); cexNode = 0.35\n\t\tfor (h in 1:length(cutOffs))\n\t\t\t{\n\t\t\t\tindex = which(days<=cutOffs[h])[length(which(days<=cutOffs[h]))]\n\t\t\t\tindices = (((UTLA_cumulative_introductions[,index]-minVal)/(maxVal-minVal))*100)+1\n\t\t\t\tcols = colourScale[indices]; cols[which(UTLA_cumulative_introductions[,index]==0)] = NA\n\t\t\t\tplot(postcodes, border=NA, col=\"gray90\", lwd=0.01)\n\t\t\t\tplot(UTLAs, border=\"white\", col=cols, add=T, lwd=0.1)\n\t\t\t\tif ((plotLegend == TRUE)&(h==length(cutOffs)))\n\t\t\t\t\t{\n\t\t\t\t\t\trast = raster(matrix(nrow=1, ncol=2)); rast[1] = minVal; rast[2] = maxVal\n\t\t\t\t\t\tplot(rast, legend.only=T, add=T, col=colourScale, legend.width=0.5, legend.shrink=0.3, smallplot=c(0.45,0.88,0.098,0.110),\n\t\t\t\t\t\t\t legend.args=list(text=\"\", cex=0.8, line=0.3, col=\"gray30\"), horizontal=T,\n\t\t\t\t \t\t \t axis.args=list(cex.axis=0.8, lwd=0, lwd.tick=0.2, tck=-0.9, col.axis=\"gray30\", line=0, mgp=c(0,0.15,0), at=seq(0,600,200)))\n\t\t\t\t\t}\n\t\t\t\tmtext(dates[h], line=-18.5, at=225000, cex=0.7, col=\"gray30\")\n\t\t\t}\n\t\tdev.off()\n\t}\n\n\t# 5.2. Analysing the daily numbers of lineage transitions between UTLAs or regions\n\nif (!file.exists(\"UTLA_allTransitions.rds\"))\n\t{\n\t\tUTLA_transition_matrices = list(); dates = days1[1:(length(days1)-1)]\n\t\tfor (d in 2:length(days2))\n\t\t\t{\n\t\t\t\tsub = mcc[which((mcc[\"endYear\"]>days2[d-1])&(mcc[\"endYear\"]<=days2[d])),]\n\t\t\t\tUTLA_transition_matrix = matrix(nrow=dim(UTLAs)[1], ncol=dim(UTLAs)[1])\n\t\t\t\trow.names(UTLA_transition_matrix) = UTLAs@data[,\"NUMBER\"]\n\t\t\t\tcolnames(UTLA_transition_matrix) = UTLAs@data[,\"NUMBER\"]\n\t\t\t\tfor (i in 1:dim(UTLAs)[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (j in 1:dim(UTLAs)[1])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tUTLA_transition_matrix[i,j] = length(which((sub[,\"startUTLA\"]==UTLAs@data[i,\"NUMBER\"])&(sub[,\"endUTLA\"]==UTLAs@data[j,\"NUMBER\"])))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tUTLA_transition_matrices[[d-1]] = UTLA_transition_matrix\n\t\t\t}\n\t\trdsObject = list(); rdsObject[[1]] = dates; rdsObject[[2]] = UTLA_transition_matrices\n\t\tsaveRDS(rdsObject, \"UTLA_allTransitions.rds\")\n\t}\telse\t\t{\n\t\trdsObject = readRDS(\"UTLA_allTransitions.rds\")\n\t\tUTLA_transition_matrices = rdsObject[[2]]\n\t}\nif (!file.exists(\"Region_allTransitions.rds\"))\n\t{\n\t\tregion_transition_matrices = list(); dates = days1[1:(length(days1)-1)]\n\t\tfor (d in 2:length(days2))\n\t\t\t{\n\t\t\t\tsub = mcc[which((mcc[\"endYear\"]>days2[d-1])&(mcc[\"endYear\"]<=days2[d])),]\n\t\t\t\tregion_transition_matrix = matrix(nrow=dim(regions@data)[1], ncol=dim(regions@data)[1])\n\t\t\t\trow.names(region_transition_matrix) = regions@data[,\"Merged_loc\"]\n\t\t\t\tcolnames(region_transition_matrix) = regions@data[,\"Merged_loc\"]\n\t\t\t\tfor (i in 1:dim(regions@data)[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (j in 1:dim(regions@data)[1])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tregion_transition_matrix[i,j] = length(which((sub[,\"startRegion\"]==regions@data[i,\"Merged_loc\"])&(sub[,\"endRegion\"]==regions@data[j,\"Merged_loc\"])))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tregion_transition_matrices[[d-1]] = region_transition_matrix\n\t\t\t}\n\t\trdsObject = list(); rdsObject[[1]] = dates; rdsObject[[2]] = region_transition_matrices\n\t\tsaveRDS(rdsObject, \"Region_allTransitions.rds\")\n\t}\telse\t\t{\n\t\trdsObject = readRDS(\"Region_allTransitions.rds\")\n\t\tregion_transition_matrices = rdsObject[[2]]\n\t}\ncentroidRegions = matrix(nrow=9, ncol=2)\nfor (i in 1:dim(centroidRegions)[1])\n\t{\n\t\tmaxArea = 0; polIndex = 0\n\t\tfor (j in 1:length(regions@polygons[[i]]@Polygons))\n\t\t\t{\n\t\t\t\tif (maxArea < regions@polygons[[i]]@Polygons[[j]]@area)\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxArea = regions@polygons[[i]]@Polygons[[j]]@area; polIndex = j\n\t\t\t\t\t}\n\t\t\t}\n\t\tpol = regions@polygons[[i]]@Polygons[[polIndex]]\n\t\tp = Polygon(pol@coords); ps = Polygons(list(p),1); sps = SpatialPolygons(list(ps))\n\t\tcentroidRegions[i,] = coordinates(sps)\n\t}\nif (savingPlots)\n\t{\n\t\tdates1 = c(\"01-09-20\",\"05-11-20\",\"01-12-20\",\"20-12-20\"); \n\t\tdates2 = c(\"05-11-20\",\"01-12-20\",\"20-12-20\",\"12-01-21\")\n\t\tregions_mod = gBuffer(regions, byid=T, width=0); regions_mod = gSimplify(regions_mod, 10)\n\t\tcumulated_transitions = matrix(0, nrow=dim(regions@data)[1], ncol=dim(regions@data)[1])\n\t\tfor (i in 1:(length(days2)-1)) cumulated_transitions[] = cumulated_transitions[]+region_transition_matrices[[i]][]\n\t\tmaxNberOfCumulatedLocalTransitions = max(cumulated_transitions)\n\t\tdiag(cumulated_transitions) = 0; maxNberOfCumulatedTransitions = max(cumulated_transitions)\n\t\tcumulated_transitions[cumulated_transitions[]==0] = NA; minNberOfCumulatedTransitions = min(cumulated_transitions, na.rm=T)\n\t\tpdf(\"Figure_B1a_NEW.pdf\", width=8, height=2.5)\n\t\tpar(mfrow=c(1,4), oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tcutOffs = c(decimal_date(dmy(c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\"))))\n\t\tvMax1 = 0; vMax2 = 0; ratios = c(); cexNode = 0.35\n\t\tfor (h in 1:length(cutOffs))\n\t\t\t{ \n\t\t\t\tif (h > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tstarting_day = cutOffs[h-1]\n\t\t\t\t\t}\telse\t{\n\t\t\t\t\t\tstarting_day = decimal_date(dmy(\"01_09-2020\"))\n\t\t\t\t\t}\n\t\t\t\tcumulated_transitions = matrix(0, nrow=dim(regions@data)[1], ncol=dim(regions@data)[1])\n\t\t\t\tindex1 = which(days2>starting_day)[1]; index2 = which(days2<=cutOffs[h])[length(which(days2<=cutOffs[h]))]\n\t\t\t\tfor (i in index1:index2) cumulated_transitions[] = cumulated_transitions[]+region_transition_matrices[[i]][]\n\t\t\t\tcumulated_transitions = cumulated_transitions[1:9,1:9]\n\t\t\t\tplot(regions_mod, border=\"white\", col=c(rep(\"gray85\",9),\"gray95\"), lwd=0.4)\n\t\t\t\tfor (i in 1:dim(cumulated_transitions)[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tif (cumulated_transitions[i,i] != 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tindices = c(1:dim(cumulated_transitions)[1]); indices = indices[which(indices!=i)]\n\t\t\t\t\t\t\t\tcexValue = (cumulated_transitions[i,i]/maxNberOfCumulatedLocalTransitions)*40\n\t\t\t\t\t\t\t\tif (vMax1 < (cumulated_transitions[i,i]/sum(cumulated_transitions[indices,i])))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (sum(cumulated_transitions[indices,i]) != 0)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tvMax1 = (cumulated_transitions[i,i]/sum(cumulated_transitions[indices,i]))\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcexValue = (cumulated_transitions[i,i]/sum(cumulated_transitions[indices,i]))/5.3\n\t\t\t\t\t\t\t\tratios = c(ratios, (cumulated_transitions[i,i]/sum(cumulated_transitions[indices,i])))\n\t\t\t\t\t\t\t\tpoints(centroidRegions[i,1], centroidRegions[i,2], cex=cexValue, pch=16, lwd=0.0, col=rgb(1,0,0,0.3,1))\n\t\t\t\t\t\t\t\tpoints(centroidRegions[i,1], centroidRegions[i,2], cex=cexValue, pch=1, lwd=0.3, col=rgb(1,0,0,1,1))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tfor (i in 1:dim(cumulated_transitions)[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (j in 1:dim(cumulated_transitions)[1])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif ((i != j)&(cumulated_transitions[i,j] >= 1))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tarrCol = \"gray30\"; arrPos = 0.45; arrType = \"triangle\"\n\t\t\t\t\t\t\t\t\t\tif (vMax2 < cumulated_transitions[i,j]) vMax2 = cumulated_transitions[i,j]\n\t\t\t\t\t\t\t\t\t\tLWD = (((log(cumulated_transitions[i,j])-4)/(log(maxNberOfCumulatedTransitions)-4))*6)+0.1\n\t\t\t\t\t\t\t\t\t\tarrow = (0.15*(log(cumulated_transitions[i,j])/log(maxNberOfCumulatedTransitions)))+0.002\n\t\t\t\t\t\t\t\t\t\tif (cumulated_transitions[i,j] < 3) { arrow = 0; arrCol = NA; arrPos = F; arrType = \"none\" }\n\t\t\t\t\t\t\t\t\t\tcurvedarrow(cbind(centroidRegions[i,1],centroidRegions[i,2]), cbind(centroidRegions[j,1],centroidRegions[j,2]), arr.length=0.1,\n\t\t\t\t\t\t\t\t \t\t\t\t\tarr.width=arrow, lwd=LWD, lty=1, lcol=\"gray30\", arr.col=arrCol, arr.pos=arrPos, curve=0.13, dr=NA, endhead=F, arr.type=arrType)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tmtext(dates1[h], line=-12.8, at=225000, cex=0.55, col=\"gray30\")\n\t\t\t\tmtext(dates2[h], line=-13.7, at=225000, cex=0.55, col=\"gray30\")\n\t\t\t}\n\t\tdev.off()\n\t\tpdf(\"Figure_B1b_NEW.pdf\", width=8, height=2.5)\n\t\tpar(mfrow=c(1,4), oma=c(0,0,0,0), mar=c(0,0,0,0), lwd=0.2, col=\"gray30\")\n\t\tplot(regions_mod, border=\"white\", col=c(rep(\"gray85\",9),\"gray95\"), lwd=0.4)\n\t\tv = 10; LWD = (((log(v)-4)/(log(maxNberOfCumulatedTransitions)-4))*6)+0.1; arrow = (0.15*(log(v)/log(maxNberOfCumulatedTransitions)))+0.002\n\t\tcurvedarrow(cbind(300000,600000),cbind(400000,600000), arr.length=0.1,arr.width=arrow, lwd=LWD, lty=1, lcol=\"gray30\", arr.col=\"gray30\", arr.pos=0.5, curve=0, dr=NA, endhead=F, arr.type=\"triangle\")\n\t\tv = 50; LWD = (((log(v)-4)/(log(maxNberOfCumulatedTransitions)-4))*6)+0.1; arrow = (0.15*(log(v)/log(maxNberOfCumulatedTransitions)))+0.002\n\t\tcurvedarrow(cbind(300000,500000),cbind(400000,500000), arr.length=0.1,arr.width=arrow, lwd=LWD, lty=1, lcol=\"gray30\", arr.col=\"gray30\", arr.pos=0.5, curve=0, dr=NA, endhead=F, arr.type=\"triangle\")\n\t\tv = 100; LWD = (((log(v)-4)/(log(maxNberOfCumulatedTransitions)-4))*6)+0.1; arrow = (0.15*(log(v)/log(maxNberOfCumulatedTransitions)))+0.002\n\t\tcurvedarrow(cbind(300000,400000),cbind(400000,400000), arr.length=0.1,arr.width=arrow, lwd=LWD, lty=1, lcol=\"gray30\", arr.col=\"gray30\", arr.pos=0.5, curve=0, dr=NA, endhead=F, arr.type=\"triangle\")\n\t\tv = 200; LWD = (((log(v)-4)/(log(maxNberOfCumulatedTransitions)-4))*6)+0.1; arrow = (0.15*(log(v)/log(maxNberOfCumulatedTransitions)))+0.002\n\t\tcurvedarrow(cbind(300000,300000),cbind(400000,300000), arr.length=0.1,arr.width=arrow, lwd=LWD, lty=1, lcol=\"gray30\", arr.col=\"gray30\", arr.pos=0.5, curve=0, dr=NA, endhead=F, arr.type=\"triangle\")\n\t\tplot(regions_mod, border=\"white\", col=c(rep(\"gray85\",9),\"gray95\"), lwd=0.4)\n\t\tv = 10; cexValue = v/5.3; points(300000, 600000, cex=cexValue, pch=16, lwd=0.0, col=rgb(1,0,0,0.3,1)); points(300000, 600000, cex=cexValue, pch=1, lwd=0.3, col=rgb(1,0,0,1,1))\n\t\tv = 20; cexValue = v/5.3; points(300000, 500000, cex=cexValue, pch=16, lwd=0.0, col=rgb(1,0,0,0.3,1)); points(300000, 500000, cex=cexValue, pch=1, lwd=0.3, col=rgb(1,0,0,1,1))\n\t\tv = 50; cexValue = v/5.3; points(300000, 400000, cex=cexValue, pch=16, lwd=0.0, col=rgb(1,0,0,0.3,1)); points(300000, 400000, cex=cexValue, pch=1, lwd=0.3, col=rgb(1,0,0,1,1))\n\t\tdev.off()\n\t\tpdf(\"Figure_B2_NEW.pdf\", width=8, height=2.0); xMin = 50; xMax = 550\n\t\tpar(mfrow=c(1,4), oma=c(0,0,0,0), mar=c(2.2,1.5,1,1), lwd=0.2, col=\"gray30\"); cexNode = 0.35\n\t\tcutOffs = c(decimal_date(dmy(c(\"05-11-2020\",\"01-12-2020\",\"20-12-2020\",\"12-01-2021\")))); cols1 = list(); cols2 = list()\n\t\tcols1[[1]] = rgb(222,67,39,255,maxColorValue=255); cols2[[1]] = rgb(222,67,39,150,maxColorValue=255)\n\t\tcols1[[2]] = rgb(150,150,150,255,maxColorValue=255); cols2[[2]] = rgb(150,150,150,150,maxColorValue=255)\n\t\tfor (h in 1:length(cutOffs))\n\t\t\t{\n\t\t\t\tif (h > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tstarting_day = cutOffs[h-1]\n\t\t\t\t\t}\telse\t{\n\t\t\t\t\t\tstarting_day = 0\n\t\t\t\t\t}\n\t\t\t\tsub = mcc[which((mcc[,\"midYear\"]>starting_day)&(mcc[,\"midYear\"]<=cutOffs[h])),]\n\t\t\t\tdistances1 = sub[which(sub[,\"startRegion\"]==\"Greater_London\"),\"geoDist_km\"]\n\t\t\t\tdistances2 = sub[which(sub[,\"startRegion\"]!=\"Greater_London\"),\"geoDist_km\"]\n\t\t\t\tdistances1 = distances1[distances1[]>=xMin]; distances2 = distances2[distances2[]>=xMin]\n\t\t\t\thist(distances1, breaks=seq(xMin,xMax,by=(xMax-xMin)/50), col=cols2[[1]], border=\"gray30\", lwd=0.1, xlim=c(xMin,xMax), axes=F, ann=F)\n\t\t\t\thist(distances2, breaks=seq(xMin,xMax,by=(xMax-xMin)/50), col=cols2[[2]], border=\"gray30\", lwd=0.1, add=T)\n\t\t\t\taxis(side=1, lwd.tick=0.2, cex.axis=0.7, mgp=c(0,0.10,0), lwd=0.2, tck=-0.02, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\", at=seq(0,600,100))\n\t\t\t\taxis(side=2, lwd.tick=0.2, cex.axis=0.7, mgp=c(0,0.25,0), lwd=0.2, tck=-0.02, col.tick=\"gray30\", col.axis=\"gray30\", col=\"gray30\")\n\t\t\t\ttitle(xlab=\"distance (km)\", cex.lab=0.9, mgp=c(1.1,0,0), col.lab=\"gray30\")\n\t\t\t\tif (h == 1) title(ylab=\"frequency\", cex.lab=0.9, mgp=c(1.5,0,0), col.lab=\"gray30\")\n\t\t\t\tmtext(dates1[h], line=-1.1, at=300, cex=0.6, col=\"gray30\")\n\t\t\t\tmtext(dates2[h], line=-2.0, at=300, cex=0.6, col=\"gray30\")\n\t\t\t}\n\t\tdev.off()\n\t}\n\n# 6. Additional analysis of B.1.1.7 introduction events (on a weekly basis)\n\nfourRegions = shapefile(\"Shapefiles_study_area/England_4selected_regions.shp\")\nfour_selected_regions = gsub(\" \",\"_\",fourRegions@data[,\"LAD20NM\"])\nstart_end_selected_regions = matrix(nrow=dim(mcc)[1], ncol=2)\ncolnames(start_end_selected_regions) = c(\"startSelectedRegion\",\"endSelectedRegion\")\nfor (i in 1:dim(fourRegions@data)[1])\n\t{\n\t\tmaxArea = 0; polIndex = 0; # print(i)\n\t\tfor (j in 1:length(fourRegions@polygons[[i]]@Polygons))\n\t\t\t{\n\t\t\t\tif (maxArea < fourRegions@polygons[[i]]@Polygons[[j]]@area)\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxArea = fourRegions@polygons[[i]]@Polygons[[j]]@area; polIndex = j\n\t\t\t\t\t}\n\t\t\t}\n\t\tpol = fourRegions@polygons[[i]]@Polygons[[polIndex]]\n\t\tindices = which(point.in.polygon(mcc[,\"startLon\"],mcc[,\"startLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\tif (length(indices) > 0)\n\t\t\t{\n\t\t\t\tif (sum(!is.na(start_end_selected_regions[indices,\"startSelectedRegion\"])) != 0) print(c(i,2))\n\t\t\t\tstart_end_selected_regions[indices,\"startSelectedRegion\"] = gsub(\" \",\"_\",fourRegions@data[i,\"LAD20NM\"])\n\t\t\t}\n\t\tindices = which(point.in.polygon(mcc[,\"endLon\"],mcc[,\"endLat\"],pol@coords[,1],pol@coords[,2])==1)\n\t\tif (length(indices) > 0)\n\t\t\t{\n\t\t\t\tif (sum(!is.na(start_end_selected_regions[indices,\"endSelectedRegion\"])) != 0) print(c(i,2))\n\t\t\t\tstart_end_selected_regions[indices,\"endSelectedRegion\"] = gsub(\" \",\"_\",fourRegions@data[i,\"LAD20NM\"])\n\t\t\t}\n\t}\nstart_end_selected_regions[which(is.na(start_end_selected_regions[,1])),1] = \"other\"\nstart_end_selected_regions[which(is.na(start_end_selected_regions[,2])),2] = \"other\"\nmcc = mcc[,1:17]; mcc = cbind(mcc, start_end_selected_regions)\ntab1 = read.csv(\"London_stats_MK.csv\", head=T)\ndates = decimal_date(dmy(gsub(\"\\\\/\",\"-\",tab1[,\"week_start\"])))\ntab1 = tab1[order(dates),]; dates = dates[order(dates)]\ntab2 = matrix(0, nrow=dim(tab1)[1], ncol=length(four_selected_regions))\ncolnames(tab2) = four_selected_regions\nsamplingData = read.csv(paste0(\"Sampling_\",analysis_date,\".csv\"), head=T)\nsamplingData = samplingData[which(!is.na(samplingData[,\"longitude\"])),]\nmostRecentSamplingDatum = max(samplingData[,\"collection_date\"])\nusingMidBranchTimes = FALSE\nfor (i in 1:dim(tab1)[1])\n\t{\n\t\tif (i != dim(tab1)[1])\n\t\t\t{\n\t\t\t\tending_day = dates[i+1]\n\t\t\t}\telse\t{\n\t\t\t\tending_day = mostRecentSamplingDatum+1/365\n\t\t\t}\n\t\tif (usingMidBranchTimes == TRUE) sub1 = mcc[which((mcc[,\"midYear\"]>=dates[i])&(mcc[,\"midYear\"]=dates[i])&(mcc[,\"endYear\"] 0)\n\t\t\t{\n\t\t\t\tfor (j in 1:length(four_selected_regions))\n\t\t\t\t\t{\n\t\t\t\t\t\tsub2 = sub1[which(sub1[,\"endSelectedRegion\"]==four_selected_regions[j]),]\n\t\t\t\t\t\tif (dim(sub2)[1] > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttab2[i,four_selected_regions[j]] = dim(sub2[which(sub2[,\"startSelectedRegion\"]!=four_selected_regions[j]),])[1]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t}\nif (writingFiles)\n\t{\n\t\tallLabels = gsub(\"\\\\/\",\"-\",gsub(\"\\\\/20\",\"\\\\/\",tab1[,\"week_start\"])); row.names(tab2) = allLabels\n\t\twrite.csv(tab2, \"B117_lineage_introduction_events_in_4_specific_regions.csv\", quote=F)\n\t}\n\ntab1 = read.csv(\"London_stats_MK.csv\", head=T)\ndates = decimal_date(dmy(gsub(\"\\\\/\",\"-\",tab1[,\"week_start\"])))\ntab1 = tab1[order(dates),]; dates = dates[order(dates)]\ntab2 = matrix(0, nrow=dim(tab1)[1], ncol=dim(UTLAs@data)[1])\ncolnames(tab2) = UTLAs@data[,\"CODE\"]\nsamplingData = read.csv(paste0(\"Sampling_\",analysis_date,\".csv\"), head=T)\nsamplingData = samplingData[which(!is.na(samplingData[,\"longitude\"])),]\nmostRecentSamplingDatum = max(samplingData[,\"collection_date\"])\nusingMidBranchTimes = FALSE\nfor (i in 1:dim(tab1)[1])\n\t{\n\t\tif (i != dim(tab1)[1])\n\t\t\t{\n\t\t\t\tending_day = dates[i+1]\n\t\t\t}\telse\t{\n\t\t\t\tending_day = mostRecentSamplingDatum+1/365\n\t\t\t}\n\t\tif (usingMidBranchTimes == TRUE) sub1 = mcc[which((mcc[,\"midYear\"]>=dates[i])&(mcc[,\"midYear\"]=dates[i])&(mcc[,\"endYear\"] 0)\n\t\t\t{\n\t\t\t\tfor (j in 1:dim(UTLAs@data)[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tsub2 = sub1[which(sub1[,\"endUTLA\"]==UTLAs@data[j,\"NUMBER\"]),]\n\t\t\t\t\t\tif (dim(sub2)[1] > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttab2[i,j] = dim(sub2[which(sub2[,\"startUTLA\"]!=UTLAs@data[j,\"NUMBER\"]),])[1]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t}\nif (writingFiles)\n\t{\n\t\tallLabels = gsub(\"\\\\/\",\"-\",gsub(\"\\\\/20\",\"\\\\/\",tab1[,\"week_start\"])); row.names(tab2) = allLabels\n\t\twrite.csv(tab2, \"B117_lineage_introduction_events_in_UTLAs.csv\", quote=F)\n\t}\n\n", "meta": {"hexsha": "14b35d872a3846508d240ddf88229d3a63776bee", "size": 51263, "ext": "r", "lang": "R", "max_stars_repo_path": "Visualisations_and_analysis_scripts/Phylogeographic_visualisations_and_analyses/Phylogenetic_analyses.r", "max_stars_repo_name": "COG-UK/B.1.1.7_spatial_analysis_UK", "max_stars_repo_head_hexsha": "30b48c4202a4a28862efa5727965cd7a52c63dad", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Visualisations_and_analysis_scripts/Phylogeographic_visualisations_and_analyses/Phylogenetic_analyses.r", "max_issues_repo_name": "COG-UK/B.1.1.7_spatial_analysis_UK", "max_issues_repo_head_hexsha": "30b48c4202a4a28862efa5727965cd7a52c63dad", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Visualisations_and_analysis_scripts/Phylogeographic_visualisations_and_analyses/Phylogenetic_analyses.r", "max_forks_repo_name": "COG-UK/B.1.1.7_spatial_analysis_UK", "max_forks_repo_head_hexsha": "30b48c4202a4a28862efa5727965cd7a52c63dad", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-09T13:54:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T20:34:20.000Z", "avg_line_length": 49.3863198459, "max_line_length": 257, "alphanum_fraction": 0.6215008876, "num_tokens": 18515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2213952064555695}} {"text": "#########################################################################################\r\n# License Agreement\r\n# \r\n# THIS WORK IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE \r\n# (\"CCPL\" OR \"LICENSE\"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER \r\n# APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE \r\n# OR COPYRIGHT LAW IS PROHIBITED.\r\n# \r\n# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE \r\n# BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED \r\n# TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN \r\n# CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.\r\n#\r\n# BASELIne: Bayesian Estimation of Antigen-Driven Selection in Immunoglobulin Sequences\r\n# Coded by: Mohamed Uduman & Gur Yaari\r\n# Copyright 2012 Kleinstein Lab\r\n# Version: 1.3 (01/23/2014)\r\n#########################################################################################\r\n\r\n# Global variables \r\n \r\n FILTER_BY_MUTATIONS = 1000\r\n\r\n # Nucleotides\r\n NUCLEOTIDES = c(\"A\",\"C\",\"G\",\"T\")\r\n \r\n # Amino Acids\r\n AMINO_ACIDS <- c(\"F\", \"F\", \"L\", \"L\", \"S\", \"S\", \"S\", \"S\", \"Y\", \"Y\", \"*\", \"*\", \"C\", \"C\", \"*\", \"W\", \"L\", \"L\", \"L\", \"L\", \"P\", \"P\", \"P\", \"P\", \"H\", \"H\", \"Q\", \"Q\", \"R\", \"R\", \"R\", \"R\", \"I\", \"I\", \"I\", \"M\", \"T\", \"T\", \"T\", \"T\", \"N\", \"N\", \"K\", \"K\", \"S\", \"S\", \"R\", \"R\", \"V\", \"V\", \"V\", \"V\", \"A\", \"A\", \"A\", \"A\", \"D\", \"D\", \"E\", \"E\", \"G\", \"G\", \"G\", \"G\")\r\n names(AMINO_ACIDS) <- c(\"TTT\", \"TTC\", \"TTA\", \"TTG\", \"TCT\", \"TCC\", \"TCA\", \"TCG\", \"TAT\", \"TAC\", \"TAA\", \"TAG\", \"TGT\", \"TGC\", \"TGA\", \"TGG\", \"CTT\", \"CTC\", \"CTA\", \"CTG\", \"CCT\", \"CCC\", \"CCA\", \"CCG\", \"CAT\", \"CAC\", \"CAA\", \"CAG\", \"CGT\", \"CGC\", \"CGA\", \"CGG\", \"ATT\", \"ATC\", \"ATA\", \"ATG\", \"ACT\", \"ACC\", \"ACA\", \"ACG\", \"AAT\", \"AAC\", \"AAA\", \"AAG\", \"AGT\", \"AGC\", \"AGA\", \"AGG\", \"GTT\", \"GTC\", \"GTA\", \"GTG\", \"GCT\", \"GCC\", \"GCA\", \"GCG\", \"GAT\", \"GAC\", \"GAA\", \"GAG\", \"GGT\", \"GGC\", \"GGA\", \"GGG\")\r\n names(AMINO_ACIDS) <- names(AMINO_ACIDS)\r\n\r\n #Amino Acid Traits\r\n #\"*\" \"A\" \"C\" \"D\" \"E\" \"F\" \"G\" \"H\" \"I\" \"K\" \"L\" \"M\" \"N\" \"P\" \"Q\" \"R\" \"S\" \"T\" \"V\" \"W\" \"Y\"\r\n #B = \"Hydrophobic/Burried\" N = \"Intermediate/Neutral\" S=\"Hydrophilic/Surface\") \r\n TRAITS_AMINO_ACIDS_CHOTHIA98 <- c(\"*\",\"N\",\"B\",\"S\",\"S\",\"B\",\"N\",\"N\",\"B\",\"S\",\"B\",\"B\",\"S\",\"N\",\"S\",\"S\",\"N\",\"N\",\"B\",\"B\",\"N\")\r\n names(TRAITS_AMINO_ACIDS_CHOTHIA98) <- sort(unique(AMINO_ACIDS))\r\n TRAITS_AMINO_ACIDS <- array(NA,21)\r\n \r\n # Codon Table\r\n CODON_TABLE <- as.data.frame(matrix(NA,ncol=64,nrow=12))\r\n\r\n # Substitution Model: Smith DS et al. 1996\r\n substitution_Literature_Mouse <- matrix(c(0, 0.156222928, 0.601501588, 0.242275484, 0.172506739, 0, 0.241239892, 0.586253369, 0.54636291, 0.255795364, 0, 0.197841727, 0.290240811, 0.467680608, 0.24207858, 0),nrow=4,byrow=T,dimnames=list(NUCLEOTIDES,NUCLEOTIDES))\r\n substitution_Flu_Human <- matrix(c(0,0.2795596,0.5026927,0.2177477,0.1693210,0,0.3264723,0.5042067,0.4983549,0.3328321,0,0.1688130,0.2021079,0.4696077,0.3282844,0),4,4,byrow=T,dimnames=list(NUCLEOTIDES,NUCLEOTIDES))\r\n substitution_Flu25_Human <- matrix(c(0,0.2580641,0.5163685,0.2255674,0.1541125,0,0.3210224,0.5248651,0.5239281,0.3101292,0,0.1659427,0.1997207,0.4579444,0.3423350,0),4,4,byrow=T,dimnames=list(NUCLEOTIDES,NUCLEOTIDES))\r\n load(\"FiveS_Substitution.RData\")\r\n\r\n # Mutability Models: Shapiro GS et al. 2002\r\n triMutability_Literature_Human <- matrix(c(0.24, 1.2, 0.96, 0.43, 2.14, 2, 1.11, 1.9, 0.85, 1.83, 2.36, 1.31, 0.82, 0.52, 0.89, 1.33, 1.4, 0.82, 1.83, 0.73, 1.83, 1.62, 1.53, 0.57, 0.92, 0.42, 0.42, 1.47, 3.44, 2.58, 1.18, 0.47, 0.39, 1.12, 1.8, 0.68, 0.47, 2.19, 2.35, 2.19, 1.05, 1.84, 1.26, 0.28, 0.98, 2.37, 0.66, 1.58, 0.67, 0.92, 1.76, 0.83, 0.97, 0.56, 0.75, 0.62, 2.26, 0.62, 0.74, 1.11, 1.16, 0.61, 0.88, 0.67, 0.37, 0.07, 1.08, 0.46, 0.31, 0.94, 0.62, 0.57, 0.29, NA, 1.44, 0.46, 0.69, 0.57, 0.24, 0.37, 1.1, 0.99, 1.39, 0.6, 2.26, 1.24, 1.36, 0.52, 0.33, 0.26, 1.25, 0.37, 0.58, 1.03, 1.2, 0.34, 0.49, 0.33, 2.62, 0.16, 0.4, 0.16, 0.35, 0.75, 1.85, 0.94, 1.61, 0.85, 2.09, 1.39, 0.3, 0.52, 1.33, 0.29, 0.51, 0.26, 0.51, 3.83, 2.01, 0.71, 0.58, 0.62, 1.07, 0.28, 1.2, 0.74, 0.25, 0.59, 1.09, 0.91, 1.36, 0.45, 2.89, 1.27, 3.7, 0.69, 0.28, 0.41, 1.17, 0.56, 0.93, 3.41, 1, 1, NA, 5.9, 0.74, 2.51, 2.24, 2.24, 1.95, 3.32, 2.34, 1.3, 2.3, 1, 0.66, 0.73, 0.93, 0.41, 0.65, 0.89, 0.65, 0.32, NA, 0.43, 0.85, 0.43, 0.31, 0.31, 0.23, 0.29, 0.57, 0.71, 0.48, 0.44, 0.76, 0.51, 1.7, 0.85, 0.74, 2.23, 2.08, 1.16, 0.51, 0.51, 1, 0.5, NA, NA, 0.71, 2.14), nrow=64,byrow=T)\r\n triMutability_Literature_Mouse <- matrix(c(1.31, 1.35, 1.42, 1.18, 2.02, 2.02, 1.02, 1.61, 1.99, 1.42, 2.01, 1.03, 2.02, 0.97, 0.53, 0.71, 1.19, 0.83, 0.96, 0.96, 0, 1.7, 2.22, 0.59, 1.24, 1.07, 0.51, 1.68, 3.36, 3.36, 1.14, 0.29, 0.33, 0.9, 1.11, 0.63, 1.08, 2.07, 2.27, 1.74, 0.22, 1.19, 2.37, 1.15, 1.15, 1.56, 0.81, 0.34, 0.87, 0.79, 2.13, 0.49, 0.85, 0.97, 0.36, 0.82, 0.66, 0.63, 1.15, 0.94, 0.85, 0.25, 0.93, 1.19, 0.4, 0.2, 0.44, 0.44, 0.88, 1.06, 0.77, 0.39, 0, 0, 0, 0, 0, 0, 0.43, 0.43, 0.86, 0.59, 0.59, 0, 1.18, 0.86, 2.9, 1.66, 0.4, 0.2, 1.54, 0.43, 0.69, 1.71, 0.68, 0.55, 0.91, 0.7, 1.71, 0.09, 0.27, 0.63, 0.2, 0.45, 1.01, 1.63, 0.96, 1.48, 2.18, 1.2, 1.31, 0.66, 2.13, 0.49, 0, 0, 0, 2.97, 2.8, 0.79, 0.4, 0.5, 0.4, 0.11, 1.68, 0.42, 0.13, 0.44, 0.93, 0.71, 1.11, 1.19, 2.71, 1.08, 3.43, 0.4, 0.67, 0.47, 1.02, 0.14, 1.56, 1.98, 0.53, 0.33, 0.63, 2.06, 1.77, 1.46, 3.74, 2.93, 2.1, 2.18, 0.78, 0.73, 2.93, 0.63, 0.57, 0.17, 0.85, 0.52, 0.31, 0.31, 0, 0, 0.51, 0.29, 0.83, 0.54, 0.28, 0.47, 0.9, 0.99, 1.24, 2.47, 0.73, 0.23, 1.13, 0.24, 2.12, 0.24, 0.33, 0.83, 1.41, 0.62, 0.28, 0.35, 0.77, 0.17, 0.72, 0.58, 0.45, 0.41), nrow=64,byrow=T)\r\n triMutability_Names <- c(\"AAA\", \"AAC\", \"AAG\", \"AAT\", \"ACA\", \"ACC\", \"ACG\", \"ACT\", \"AGA\", \"AGC\", \"AGG\", \"AGT\", \"ATA\", \"ATC\", \"ATG\", \"ATT\", \"CAA\", \"CAC\", \"CAG\", \"CAT\", \"CCA\", \"CCC\", \"CCG\", \"CCT\", \"CGA\", \"CGC\", \"CGG\", \"CGT\", \"CTA\", \"CTC\", \"CTG\", \"CTT\", \"GAA\", \"GAC\", \"GAG\", \"GAT\", \"GCA\", \"GCC\", \"GCG\", \"GCT\", \"GGA\", \"GGC\", \"GGG\", \"GGT\", \"GTA\", \"GTC\", \"GTG\", \"GTT\", \"TAA\", \"TAC\", \"TAG\", \"TAT\", \"TCA\", \"TCC\", \"TCG\", \"TCT\", \"TGA\", \"TGC\", \"TGG\", \"TGT\", \"TTA\", \"TTC\", \"TTG\", \"TTT\")\r\n load(\"FiveS_Mutability.RData\")\r\n\r\n# Functions\r\n # Translate codon to amino acid\r\n translateCodonToAminoAcid<-function(Codon){\r\n return(AMINO_ACIDS[Codon])\r\n }\r\n\r\n # Translate amino acid to trait change\r\n translateAminoAcidToTraitChange<-function(AminoAcid){\r\n return(TRAITS_AMINO_ACIDS[AminoAcid])\r\n }\r\n \r\n # Initialize Amino Acid Trait Changes\r\n initializeTraitChange <- function(traitChangeModel=1,species=1,traitChangeFileName=NULL){\r\n if(!is.null(traitChangeFileName)){\r\n tryCatch(\r\n traitChange <- read.delim(traitChangeFileName,sep=\"\\t\",header=T)\r\n , error = function(ex){\r\n cat(\"Error|Error reading trait changes. Please check file name/path and format.\\n\")\r\n q()\r\n }\r\n )\r\n }else{\r\n traitChange <- TRAITS_AMINO_ACIDS_CHOTHIA98\r\n }\r\n TRAITS_AMINO_ACIDS <<- traitChange\r\n } \r\n \r\n # Read in formatted nucleotide substitution matrix\r\n initializeSubstitutionMatrix <- function(substitutionModel,species,subsMatFileName=NULL){\r\n if(!is.null(subsMatFileName)){\r\n tryCatch(\r\n subsMat <- read.delim(subsMatFileName,sep=\"\\t\",header=T)\r\n , error = function(ex){\r\n cat(\"Error|Error reading substitution matrix. Please check file name/path and format.\\n\")\r\n q()\r\n }\r\n )\r\n if(sum(apply(subsMat,1,sum)==1)!=4) subsMat = t(apply(subsMat,1,function(x)x/sum(x)))\r\n }else{\r\n if(substitutionModel==1)subsMat <- substitution_Literature_Mouse\r\n if(substitutionModel==2)subsMat <- substitution_Flu_Human \r\n if(substitutionModel==3)subsMat <- substitution_Flu25_Human \r\n \r\n }\r\n\r\n if(substitutionModel==0){\r\n subsMat <- matrix(1,4,4)\r\n subsMat[,] = 1/3\r\n subsMat[1,1] = 0\r\n subsMat[2,2] = 0\r\n subsMat[3,3] = 0\r\n subsMat[4,4] = 0\r\n }\r\n \r\n \r\n NUCLEOTIDESN = c(NUCLEOTIDES,\"N\", \"-\")\r\n if(substitutionModel==5){\r\n subsMat <- FiveS_Substitution\r\n return(subsMat)\r\n }else{\r\n subsMat <- rbind(subsMat,rep(NA,4),rep(NA,4))\r\n return( matrix(data.matrix(subsMat),6,4,dimnames=list(NUCLEOTIDESN,NUCLEOTIDES) ) )\r\n }\r\n }\r\n\r\n \r\n # Read in formatted Mutability file\r\n initializeMutabilityMatrix <- function(mutabilityModel=1, species=1,mutabilityMatFileName=NULL){\r\n if(!is.null(mutabilityMatFileName)){\r\n tryCatch(\r\n mutabilityMat <- read.delim(mutabilityMatFileName,sep=\"\\t\",header=T)\r\n , error = function(ex){\r\n cat(\"Error|Error reading mutability matrix. Please check file name/path and format.\\n\")\r\n q()\r\n }\r\n )\r\n }else{\r\n mutabilityMat <- triMutability_Literature_Human\r\n if(species==2) mutabilityMat <- triMutability_Literature_Mouse\r\n }\r\n\r\n if(mutabilityModel==0){ mutabilityMat <- matrix(1,64,3)}\r\n \r\n if(mutabilityModel==5){\r\n mutabilityMat <- FiveS_Mutability\r\n return(mutabilityMat)\r\n }else{\r\n return( matrix( data.matrix(mutabilityMat), 64, 3, dimnames=list(triMutability_Names,1:3)) )\r\n }\r\n }\r\n\r\n # Read FASTA file formats\r\n # Modified from read.fasta from the seqinR package\r\n baseline.read.fasta <-\r\n function (file = system.file(\"sequences/sample.fasta\", package = \"seqinr\"), \r\n seqtype = c(\"DNA\", \"AA\"), as.string = FALSE, forceDNAtolower = TRUE, \r\n set.attributes = TRUE, legacy.mode = TRUE, seqonly = FALSE, \r\n strip.desc = FALSE, sizeof.longlong = .Machine$sizeof.longlong, \r\n endian = .Platform$endian, apply.mask = TRUE) \r\n {\r\n seqtype <- match.arg(seqtype)\r\n \r\n lines <- readLines(file)\r\n \r\n if (legacy.mode) {\r\n comments <- grep(\"^;\", lines)\r\n if (length(comments) > 0) \r\n lines <- lines[-comments]\r\n }\r\n \r\n \r\n ind_groups<-which(substr(lines, 1L, 3L) == \">>>\")\r\n lines_mod<-lines\r\n \r\n if(!length(ind_groups)){\r\n lines_mod<-c(\">>>All sequences combined\",lines) \r\n }\r\n \r\n ind_groups<-which(substr(lines_mod, 1L, 3L) == \">>>\")\r\n \r\n lines <- array(\"BLA\",dim=(length(ind_groups)+length(lines_mod)))\r\n id<-sapply(1:length(ind_groups),function(i)ind_groups[i]+i-1)+1\r\n lines[id] <- \"THIS IS A FAKE SEQUENCE\"\r\n lines[-id] <- lines_mod\r\n rm(lines_mod)\r\n \r\n \t\tind <- which(substr(lines, 1L, 1L) == \">\")\r\n nseq <- length(ind)\r\n if (nseq == 0) {\r\n stop(\"no line starting with a > character found\")\r\n } \r\n start <- ind + 1\r\n end <- ind - 1\r\n \r\n while( any(which(ind%in%end)) ){\r\n ind=ind[-which(ind%in%end)]\r\n nseq <- length(ind)\r\n if (nseq == 0) {\r\n stop(\"no line starting with a > character found\")\r\n } \r\n start <- ind + 1\r\n end <- ind - 1 \r\n }\r\n \r\n end <- c(end[-1], length(lines))\r\n sequences <- lapply(seq_len(nseq), function(i) paste(lines[start[i]:end[i]], collapse = \"\"))\r\n if (seqonly) \r\n return(sequences)\r\n nomseq <- lapply(seq_len(nseq), function(i) {\r\n \r\n #firstword <- strsplit(lines[ind[i]], \" \")[[1]][1]\r\n substr(lines[ind[i]], 2, nchar(lines[ind[i]]))\r\n \r\n })\r\n if (seqtype == \"DNA\") {\r\n if (forceDNAtolower) {\r\n sequences <- as.list(tolower(chartr(\".\",\"-\",sequences)))\r\n }else{\r\n sequences <- as.list(toupper(chartr(\".\",\"-\",sequences)))\r\n }\r\n }\r\n if (as.string == FALSE) \r\n sequences <- lapply(sequences, s2c)\r\n if (set.attributes) {\r\n for (i in seq_len(nseq)) {\r\n Annot <- lines[ind[i]]\r\n if (strip.desc) \r\n Annot <- substr(Annot, 2L, nchar(Annot))\r\n attributes(sequences[[i]]) <- list(name = nomseq[[i]], \r\n Annot = Annot, class = switch(seqtype, AA = \"SeqFastaAA\", \r\n DNA = \"SeqFastadna\"))\r\n }\r\n }\r\n names(sequences) <- nomseq\r\n return(sequences)\r\n }\r\n\r\n \r\n # Replaces non FASTA characters in input files with N \r\n replaceNonFASTAChars <-function(inSeq=\"ACGTN-AApA\"){\r\n gsub('[^ACGTNacgt[:punct:]-[:punct:].]','N',inSeq,perl=TRUE)\r\n } \r\n \r\n # Find the germlines in the FASTA list\r\n germlinesInFile <- function(seqIDs){\r\n firstChar = sapply(seqIDs,function(x){substr(x,1,1)})\r\n secondChar = sapply(seqIDs,function(x){substr(x,2,2)})\r\n return(firstChar==\">\" & secondChar!=\">\")\r\n }\r\n \r\n # Find the groups in the FASTA list\r\n groupsInFile <- function(seqIDs){\r\n sapply(seqIDs,function(x){substr(x,1,2)})==\">>\"\r\n }\r\n\r\n # In the process of finding germlines/groups, expand from the start to end of the group\r\n expandTillNext <- function(vecPosToID){ \r\n IDs = names(vecPosToID)\r\n posOfInterests = which(vecPosToID)\r\n \r\n expandedID = rep(NA,length(IDs))\r\n expandedIDNames = gsub(\">\",\"\",IDs[posOfInterests])\r\n startIndexes = c(1,posOfInterests[-1])\r\n stopIndexes = c(posOfInterests[-1]-1,length(IDs))\r\n expandedID = unlist(sapply(1:length(startIndexes),function(i){\r\n rep(i,stopIndexes[i]-startIndexes[i]+1)\r\n }))\r\n names(expandedID) = unlist(sapply(1:length(startIndexes),function(i){\r\n rep(expandedIDNames[i],stopIndexes[i]-startIndexes[i]+1)\r\n })) \r\n return(expandedID) \r\n }\r\n \r\n # Process FASTA (list) to return a matrix[input, germline)\r\n processInputAdvanced <- function(inputFASTA){\r\n \r\n seqIDs = names(inputFASTA)\r\n numbSeqs = length(seqIDs)\r\n posGermlines1 = germlinesInFile(seqIDs)\r\n numbGermlines = sum(posGermlines1)\r\n posGroups1 = groupsInFile(seqIDs)\r\n numbGroups = sum(posGroups1)\r\n consDef = NA\r\n \r\n if(numbGermlines==0){\r\n posGermlines = 2\r\n numbGermlines = 1 \r\n }\r\n \r\n glPositionsSum = cumsum(posGermlines1)\r\n glPositions = table(glPositionsSum)\r\n #Find the position of the conservation row\r\n consDefPos = as.numeric(names(glPositions[names(glPositions)!=0 & glPositions==1]))+1 \r\n if( length(consDefPos)> 0 ){\r\n consDefID = match(consDefPos, glPositionsSum) \r\n #The coservation rows need to be pulled out and stores seperately \r\n consDef = inputFASTA[consDefID]\r\n inputFASTA = inputFASTA[-consDefID]\r\n \r\n seqIDs = names(inputFASTA)\r\n numbSeqs = length(seqIDs)\r\n posGermlines1 = germlinesInFile(seqIDs)\r\n numbGermlines = sum(posGermlines1)\r\n posGroups1 = groupsInFile(seqIDs)\r\n numbGroups = sum(posGroups1)\r\n if(numbGermlines==0){\r\n posGermlines = 2\r\n numbGermlines = 1 \r\n } \r\n }\r\n \r\n posGroups <- expandTillNext(posGroups1)\r\n posGermlines <- expandTillNext(posGermlines1)\r\n posGermlines[posGroups1] = 0\r\n names(posGermlines)[posGroups1] = names(posGroups)[posGroups1]\r\n posInput = rep(TRUE,numbSeqs)\r\n posInput[posGroups1 | posGermlines1] = FALSE\r\n \r\n matInput = matrix(NA, nrow=sum(posInput), ncol=2)\r\n rownames(matInput) = seqIDs[posInput]\r\n colnames(matInput) = c(\"Input\",\"Germline\")\r\n \r\n vecInputFASTA = unlist(inputFASTA) \r\n matInput[,1] = vecInputFASTA[posInput]\r\n matInput[,2] = vecInputFASTA[ which( names(inputFASTA)%in%paste(\">\",names(posGermlines)[posInput],sep=\"\") )[ posGermlines[posInput]] ]\r\n \r\n germlines = posGermlines[posInput]\r\n groups = posGroups[posInput]\r\n \r\n return( list(\"matInput\"=matInput, \"germlines\"=germlines, \"groups\"=groups, \"conservationDefinition\"=consDef )) \r\n }\r\n\r\n\r\n # Replace leading and trailing dashes in the sequence\r\n replaceLeadingTrailingDashes <- function(x,readEnd){\r\n iiGap = unlist(gregexpr(\"-\",x[1]))\r\n ggGap = unlist(gregexpr(\"-\",x[2])) \r\n #posToChange = intersect(iiGap,ggGap)\r\n \r\n \r\n seqIn = replaceLeadingTrailingDashesHelper(x[1])\r\n seqGL = replaceLeadingTrailingDashesHelper(x[2])\r\n seqTemplate = rep('N',readEnd)\r\n seqIn <- c(seqIn,seqTemplate[(length(seqIn)+1):readEnd])\r\n seqGL <- c(seqGL,seqTemplate[(length(seqGL)+1):readEnd])\r\n# if(posToChange!=-1){\r\n# seqIn[posToChange] = \"-\"\r\n# seqGL[posToChange] = \"-\"\r\n# }\r\n \r\n seqIn = c2s(seqIn[1:readEnd])\r\n seqGL = c2s(seqGL[1:readEnd])\r\n \r\n lenGL = nchar(seqGL)\r\n if(lenGL seqLen )\r\n \t trimmedSeq = substr(seqToTrim,1, ( (getCodonPos(seqLen)[1])-1 ) )\r\n \r\n return(trimmedSeq)\r\n }\r\n \r\n # Given a nuclotide position, returns the pos of the 3 nucs that made the codon\r\n # e.g. nuc 86 is part of nucs 85,86,87\r\n getCodonPos <- function(nucPos){\r\n codonNum = (ceiling(nucPos/3))*3\r\n return( (codonNum-2):codonNum)\r\n }\r\n \r\n # Given a nuclotide position, returns the codon number\r\n # e.g. nuc 86 = codon 29\r\n getCodonNumb <- function(nucPos){\r\n return( ceiling(nucPos/3) )\r\n }\r\n \r\n # Given a codon, returns all the nuc positions that make the codon\r\n getCodonNucs <- function(codonNumb){\r\n getCodonPos(codonNumb*3)\r\n } \r\n\r\n computeCodonTable <- function(testID=1){\r\n \r\n if(testID<=4){ \r\n # Pre-compute every codons\r\n intCounter = 1\r\n for(pOne in NUCLEOTIDES){\r\n for(pTwo in NUCLEOTIDES){\r\n for(pThree in NUCLEOTIDES){\r\n codon = paste(pOne,pTwo,pThree,sep=\"\")\r\n colnames(CODON_TABLE)[intCounter] = codon\r\n intCounter = intCounter + 1\r\n CODON_TABLE[,codon] = mutationTypeOptimized(cbind(permutateAllCodon(codon),rep(codon,12)))\r\n } \r\n }\r\n }\r\n chars = c(\"N\",\"A\",\"C\",\"G\",\"T\", \"-\")\r\n for(a in chars){\r\n for(b in chars){\r\n for(c in chars){\r\n if(a==\"N\" | b==\"N\" | c==\"N\"){ \r\n #cat(paste(a,b,c),sep=\"\",\"\\n\") \r\n CODON_TABLE[,paste(a,b,c,sep=\"\")] = rep(NA,12)\r\n }\r\n } \r\n }\r\n }\r\n \r\n chars = c(\"-\",\"A\",\"C\",\"G\",\"T\")\r\n for(a in chars){\r\n for(b in chars){\r\n for(c in chars){\r\n if(a==\"-\" | b==\"-\" | c==\"-\"){ \r\n #cat(paste(a,b,c),sep=\"\",\"\\n\") \r\n CODON_TABLE[,paste(a,b,c,sep=\"\")] = rep(NA,12)\r\n }\r\n } \r\n }\r\n }\r\n CODON_TABLE <<- as.matrix(CODON_TABLE)\r\n }\r\n }\r\n \r\n collapseClone <- function(vecInputSeqs,glSeq,readEnd,nonTerminalOnly=0){\r\n #print(length(vecInputSeqs))\r\n vecInputSeqs = unique(vecInputSeqs) \r\n if(length(vecInputSeqs)==1){\r\n return( list( c(vecInputSeqs,glSeq), F) )\r\n }else{\r\n charInputSeqs <- sapply(vecInputSeqs, function(x){\r\n s2c(x)[1:readEnd]\r\n })\r\n charGLSeq <- s2c(glSeq)\r\n matClone <- sapply(1:readEnd, function(i){\r\n posNucs = unique(charInputSeqs[i,])\r\n posGL = charGLSeq[i]\r\n error = FALSE \r\n if(posGL==\"-\" & sum(!(posNucs%in%c(\"-\",\"N\")))==0 ){\r\n return(c(\"-\",error))\r\n }\r\n if(length(posNucs)==1)\r\n return(c(posNucs[1],error))\r\n else{\r\n if(\"N\"%in%posNucs){\r\n error=TRUE\r\n }\r\n if(sum(!posNucs[posNucs!=\"N\"]%in%posGL)==0){\r\n return( c(posGL,error) ) \r\n }else{\r\n #return( c(sample(posNucs[posNucs!=\"N\"],1),error) ) \r\n if(nonTerminalOnly==0){\r\n return( c(sample(charInputSeqs[i,charInputSeqs[i,]!=\"N\" & charInputSeqs[i,]!=posGL],1),error) ) \r\n }else{\r\n posNucs = charInputSeqs[i,charInputSeqs[i,]!=\"N\" & charInputSeqs[i,]!=posGL]\r\n posNucsTable = table(posNucs)\r\n if(sum(posNucsTable>1)==0){\r\n return( c(posGL,error) )\r\n }else{\r\n return( c(sample( posNucs[posNucs%in%names(posNucsTable)[posNucsTable>1]],1),error) )\r\n }\r\n }\r\n \r\n }\r\n } \r\n })\r\n \r\n \r\n #print(length(vecInputSeqs)) \r\n return(list(c(c2s(matClone[1,]),glSeq),\"TRUE\"%in%matClone[2,]))\r\n }\r\n }\r\n\r\n # Compute the expected for each sequence-germline pair\r\n getExpectedIndividual <- function(matInput){\r\n if( any(grep(\"multicore\",search())) ){ \r\n facGL <- factor(matInput[,2])\r\n facLevels = levels(facGL)\r\n LisGLs_MutabilityU = mclapply(1:length(facLevels), function(x){\r\n computeMutabilities(facLevels[x])\r\n })\r\n facIndex = match(facGL,facLevels)\r\n \r\n LisGLs_Mutability = mclapply(1:nrow(matInput), function(x){\r\n cInput = rep(NA,nchar(matInput[x,1]))\r\n cInput[s2c(matInput[x,1])!=\"N\"] = 1\r\n LisGLs_MutabilityU[[facIndex[x]]] * cInput \r\n })\r\n \r\n LisGLs_Targeting = mclapply(1:dim(matInput)[1], function(x){\r\n computeTargeting(matInput[x,2],LisGLs_Mutability[[x]])\r\n })\r\n \r\n LisGLs_MutationTypes = mclapply(1:length(matInput[,2]),function(x){\r\n #print(x)\r\n computeMutationTypes(matInput[x,2])\r\n })\r\n \r\n LisGLs_Exp = mclapply(1:dim(matInput)[1], function(x){\r\n computeExpected(LisGLs_Targeting[[x]],LisGLs_MutationTypes[[x]])\r\n })\r\n \r\n ul_LisGLs_Exp = unlist(LisGLs_Exp) \r\n return(matrix(ul_LisGLs_Exp,ncol=4,nrow=(length(ul_LisGLs_Exp)/4),byrow=T))\r\n }else{\r\n facGL <- factor(matInput[,2])\r\n facLevels = levels(facGL)\r\n LisGLs_MutabilityU = lapply(1:length(facLevels), function(x){\r\n computeMutabilities(facLevels[x])\r\n })\r\n facIndex = match(facGL,facLevels)\r\n \r\n LisGLs_Mutability = lapply(1:nrow(matInput), function(x){\r\n cInput = rep(NA,nchar(matInput[x,1]))\r\n cInput[s2c(matInput[x,1])!=\"N\"] = 1\r\n LisGLs_MutabilityU[[facIndex[x]]] * cInput \r\n })\r\n \r\n LisGLs_Targeting = lapply(1:dim(matInput)[1], function(x){\r\n computeTargeting(matInput[x,2],LisGLs_Mutability[[x]])\r\n })\r\n \r\n LisGLs_MutationTypes = lapply(1:length(matInput[,2]),function(x){\r\n #print(x)\r\n computeMutationTypes(matInput[x,2])\r\n })\r\n \r\n LisGLs_Exp = lapply(1:dim(matInput)[1], function(x){\r\n computeExpected(LisGLs_Targeting[[x]],LisGLs_MutationTypes[[x]])\r\n })\r\n \r\n ul_LisGLs_Exp = unlist(LisGLs_Exp) \r\n return(matrix(ul_LisGLs_Exp,ncol=4,nrow=(length(ul_LisGLs_Exp)/4),byrow=T))\r\n \r\n }\r\n }\r\n\r\n # Compute mutabilities of sequence based on the tri-nucleotide model\r\n computeMutabilities <- function(paramSeq){\r\n seqLen = nchar(paramSeq)\r\n seqMutabilites = rep(NA,seqLen)\r\n \r\n gaplessSeq = gsub(\"-\", \"\", paramSeq)\r\n gaplessSeqLen = nchar(gaplessSeq)\r\n gaplessSeqMutabilites = rep(NA,gaplessSeqLen)\r\n \r\n if(mutabilityModel!=5){\r\n pos<- 3:(gaplessSeqLen)\r\n subSeq = substr(rep(gaplessSeq,gaplessSeqLen-2),(pos-2),(pos+2)) \r\n gaplessSeqMutabilites[pos] = \r\n tapply( c(\r\n getMutability( substr(subSeq,1,3), 3) , \r\n getMutability( substr(subSeq,2,4), 2), \r\n getMutability( substr(subSeq,3,5), 1) \r\n ),rep(1:(gaplessSeqLen-2),3),mean,na.rm=TRUE\r\n )\r\n #Pos 1\r\n subSeq = substr(gaplessSeq,1,3)\r\n gaplessSeqMutabilites[1] = getMutability(subSeq , 1)\r\n #Pos 2\r\n subSeq = substr(gaplessSeq,1,4)\r\n gaplessSeqMutabilites[2] = mean( c(\r\n getMutability( substr(subSeq,1,3), 2) , \r\n getMutability( substr(subSeq,2,4), 1) \r\n ),na.rm=T\r\n ) \r\n seqMutabilites[which(s2c(paramSeq)!=\"-\")]<- gaplessSeqMutabilites\r\n return(seqMutabilites)\r\n }else{\r\n \r\n pos<- 3:(gaplessSeqLen)\r\n subSeq = substr(rep(gaplessSeq,gaplessSeqLen-2),(pos-2),(pos+2)) \r\n gaplessSeqMutabilites[pos] = sapply(subSeq,function(x){ getMutability5(x) }, simplify=T)\r\n seqMutabilites[which(s2c(paramSeq)!=\"-\")]<- gaplessSeqMutabilites\r\n return(seqMutabilites)\r\n }\r\n\r\n }\r\n\r\n # Returns the mutability of a triplet at a given position\r\n getMutability <- function(codon, pos=1:3){\r\n triplets <- rownames(mutability)\r\n mutability[ match(codon,triplets) ,pos]\r\n }\r\n\r\n getMutability5 <- function(fivemer){\r\n return(mutability[fivemer])\r\n }\r\n\r\n # Returns the substitution probabilty\r\n getTransistionProb <- function(nuc){\r\n substitution[nuc,]\r\n }\r\n\r\n getTransistionProb5 <- function(fivemer){ \r\n if(any(which(fivemer==colnames(substitution)))){\r\n return(substitution[,fivemer])\r\n }else{\r\n return(array(NA,4))\r\n }\r\n }\r\n\r\n # Given a nuc, returns the other 3 nucs it can mutate to\r\n canMutateTo <- function(nuc){\r\n NUCLEOTIDES[- which(NUCLEOTIDES==nuc)]\r\n }\r\n \r\n # Given a nucleotide, returns the probabilty of other nucleotide it can mutate to \r\n canMutateToProb <- function(nuc){\r\n substitution[nuc,canMutateTo(nuc)]\r\n }\r\n\r\n # Compute targeting, based on precomputed mutatbility & substitution \r\n computeTargeting <- function(param_strSeq,param_vecMutabilities){\r\n\r\n if(substitutionModel!=5){\r\n vecSeq = s2c(param_strSeq)\r\n matTargeting = sapply( 1:length(vecSeq), function(x) { param_vecMutabilities[x] * getTransistionProb(vecSeq[x]) } ) \r\n #matTargeting = apply( rbind(vecSeq,param_vecMutabilities),2, function(x) { as.vector(as.numeric(x[2]) * getTransistionProb(x[1])) } )\r\n dimnames( matTargeting ) = list(NUCLEOTIDES,1:(length(vecSeq))) \r\n return (matTargeting)\r\n }else{\r\n \r\n seqLen = nchar(param_strSeq)\r\n seqsubstitution = matrix(NA,ncol=seqLen,nrow=4)\r\n paramSeq <- param_strSeq\r\n gaplessSeq = gsub(\"-\", \"\", paramSeq)\r\n gaplessSeqLen = nchar(gaplessSeq)\r\n gaplessSeqSubstitution = matrix(NA,ncol=gaplessSeqLen,nrow=4) \r\n \r\n pos<- 3:(gaplessSeqLen)\r\n subSeq = substr(rep(gaplessSeq,gaplessSeqLen-2),(pos-2),(pos+2)) \r\n gaplessSeqSubstitution[,pos] = sapply(subSeq,function(x){ getTransistionProb5(x) }, simplify=T)\r\n seqsubstitution[,which(s2c(paramSeq)!=\"-\")]<- gaplessSeqSubstitution\r\n #matTargeting <- param_vecMutabilities %*% seqsubstitution\r\n matTargeting <- sweep(seqsubstitution,2,param_vecMutabilities,`*`)\r\n dimnames( matTargeting ) = list(NUCLEOTIDES,1:(seqLen)) \r\n return (matTargeting) \r\n }\r\n } \r\n\r\n # Compute the mutations types \r\n computeMutationTypes <- function(param_strSeq){\r\n #cat(param_strSeq,\"\\n\")\r\n #vecSeq = trimToLastCodon(param_strSeq)\r\n lenSeq = nchar(param_strSeq)\r\n vecCodons = sapply({1:(lenSeq/3)}*3-2,function(x){substr(param_strSeq,x,x+2)})\r\n matMutationTypes = matrix( unlist(CODON_TABLE[,vecCodons]) ,ncol=lenSeq,nrow=4, byrow=F)\r\n dimnames( matMutationTypes ) = list(NUCLEOTIDES,1:(ncol(matMutationTypes)))\r\n return(matMutationTypes) \r\n } \r\n computeMutationTypesFast <- function(param_strSeq){\r\n matMutationTypes = matrix( CODON_TABLE[,param_strSeq] ,ncol=3,nrow=4, byrow=F)\r\n #dimnames( matMutationTypes ) = list(NUCLEOTIDES,1:(length(vecSeq)))\r\n return(matMutationTypes) \r\n } \r\n mutationTypeOptimized <- function( matOfCodons ){\r\n apply( matOfCodons,1,function(x){ mutationType(x[2],x[1]) } ) \r\n } \r\n\r\n # Returns a vector of codons 1 mutation away from the given codon\r\n permutateAllCodon <- function(codon){\r\n cCodon = s2c(codon)\r\n matCodons = t(array(cCodon,dim=c(3,12)))\r\n matCodons[1:4,1] = NUCLEOTIDES\r\n matCodons[5:8,2] = NUCLEOTIDES\r\n matCodons[9:12,3] = NUCLEOTIDES\r\n apply(matCodons,1,c2s)\r\n }\r\n\r\n # Given two codons, tells you if the mutation is R or S (based on your definition)\r\n mutationType <- function(codonFrom,codonTo){\r\n if(testID==4){\r\n if( is.na(codonFrom) | is.na(codonTo) | is.na(translateCodonToAminoAcid(codonFrom)) | is.na(translateCodonToAminoAcid(codonTo)) ){\r\n return(NA)\r\n }else{\r\n mutationType = \"S\"\r\n if( translateAminoAcidToTraitChange(translateCodonToAminoAcid(codonFrom)) != translateAminoAcidToTraitChange(translateCodonToAminoAcid(codonTo)) ){\r\n mutationType = \"R\" \r\n }\r\n if(translateCodonToAminoAcid(codonTo)==\"*\" | translateCodonToAminoAcid(codonFrom)==\"*\"){\r\n mutationType = \"Stop\"\r\n }\r\n return(mutationType)\r\n } \r\n }else if(testID==5){ \r\n if( is.na(codonFrom) | is.na(codonTo) | is.na(translateCodonToAminoAcid(codonFrom)) | is.na(translateCodonToAminoAcid(codonTo)) ){\r\n return(NA)\r\n }else{\r\n if(codonFrom==codonTo){\r\n mutationType = \"S\"\r\n }else{\r\n codonFrom = s2c(codonFrom)\r\n codonTo = s2c(codonTo) \r\n mutationType = \"Stop\"\r\n nucOfI = codonFrom[which(codonTo!=codonFrom)]\r\n if(nucOfI==\"C\"){\r\n mutationType = \"R\" \r\n }else if(nucOfI==\"G\"){\r\n mutationType = \"S\"\r\n }\r\n }\r\n return(mutationType)\r\n }\r\n }else{\r\n if( is.na(codonFrom) | is.na(codonTo) | is.na(translateCodonToAminoAcid(codonFrom)) | is.na(translateCodonToAminoAcid(codonTo)) ){\r\n return(NA)\r\n }else{\r\n mutationType = \"S\"\r\n if( translateCodonToAminoAcid(codonFrom) != translateCodonToAminoAcid(codonTo) ){\r\n mutationType = \"R\" \r\n }\r\n if(translateCodonToAminoAcid(codonTo)==\"*\" | translateCodonToAminoAcid(codonFrom)==\"*\"){\r\n mutationType = \"Stop\"\r\n }\r\n return(mutationType)\r\n } \r\n } \r\n }\r\n\r\n \r\n #given a mat of targeting & it's corresponding mutationtypes returns \r\n #a vector of Exp_RCDR,Exp_SCDR,Exp_RFWR,Exp_RFWR\r\n computeExpected <- function(paramTargeting,paramMutationTypes){\r\n # Replacements\r\n RPos = which(paramMutationTypes==\"R\") \r\n #FWR\r\n Exp_R_FWR = sum(paramTargeting[ RPos[which(FWR_Nuc_Mat[RPos]==T)] ],na.rm=T)\r\n #CDR\r\n Exp_R_CDR = sum(paramTargeting[ RPos[which(CDR_Nuc_Mat[RPos]==T)] ],na.rm=T)\r\n # Silents\r\n SPos = which(paramMutationTypes==\"S\") \r\n #FWR\r\n Exp_S_FWR = sum(paramTargeting[ SPos[which(FWR_Nuc_Mat[SPos]==T)] ],na.rm=T)\r\n #CDR\r\n Exp_S_CDR = sum(paramTargeting[ SPos[which(CDR_Nuc_Mat[SPos]==T)] ],na.rm=T)\r\n \r\n return(c(Exp_R_CDR,Exp_S_CDR,Exp_R_FWR,Exp_S_FWR))\r\n }\r\n \r\n # Count the mutations in a sequence\r\n # each mutation is treated independently \r\n analyzeMutations2NucUri_website <- function( rev_in_matrix ){\r\n paramGL = rev_in_matrix[2,]\r\n paramSeq = rev_in_matrix[1,] \r\n \r\n #Fill seq with GL seq if gapped\r\n #if( any(paramSeq==\"-\") ){\r\n # gapPos_Seq = which(paramSeq==\"-\")\r\n # gapPos_Seq_ToReplace = gapPos_Seq[paramGL[gapPos_Seq] != \"-\"]\r\n # paramSeq[gapPos_Seq_ToReplace] = paramGL[gapPos_Seq_ToReplace]\r\n #}\r\n \r\n \r\n #if( any(paramSeq==\"N\") ){\r\n # gapPos_Seq = which(paramSeq==\"N\")\r\n # gapPos_Seq_ToReplace = gapPos_Seq[paramGL[gapPos_Seq] != \"N\"]\r\n # paramSeq[gapPos_Seq_ToReplace] = paramGL[gapPos_Seq_ToReplace]\r\n #} \r\n \r\n analyzeMutations2NucUri( matrix(c( paramGL, paramSeq ),2,length(paramGL),byrow=T) )\r\n \r\n }\r\n\r\n #1 = GL \r\n #2 = Seq\r\n analyzeMutations2NucUri <- function( in_matrix=matrix(c(c(\"A\",\"A\",\"A\",\"C\",\"C\",\"C\"),c(\"A\",\"G\",\"G\",\"C\",\"C\",\"A\")),2,6,byrow=T) ){\r\n paramGL = in_matrix[2,]\r\n paramSeq = in_matrix[1,]\r\n paramSeqUri = paramGL\r\n #mutations = apply(rbind(paramGL,paramSeq), 2, function(x){!x[1]==x[2]})\r\n mutations_val = paramGL != paramSeq \r\n if(any(mutations_val)){\r\n mutationPos = {1:length(mutations_val)}[mutations_val] \r\n mutationPos = mutationPos[sapply(mutationPos, function(x){!any(paramSeq[getCodonPos(x)]==\"N\")})]\r\n length_mutations =length(mutationPos)\r\n mutationInfo = rep(NA,length_mutations)\r\n if(any(mutationPos)){ \r\n\r\n pos<- mutationPos\r\n pos_array<-array(sapply(pos,getCodonPos))\r\n codonGL = paramGL[pos_array]\r\n \r\n codonSeq = sapply(pos,function(x){\r\n seqP = paramGL[getCodonPos(x)]\r\n muCodonPos = {x-1}%%3+1 \r\n seqP[muCodonPos] = paramSeq[x]\r\n return(seqP)\r\n }) \r\n GLcodons = apply(matrix(codonGL,length_mutations,3,byrow=TRUE),1,c2s)\r\n Seqcodons = apply(codonSeq,2,c2s)\r\n mutationInfo = apply(rbind(GLcodons , Seqcodons),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n names(mutationInfo) = mutationPos\r\n }\r\n if(any(!is.na(mutationInfo))){\r\n return(mutationInfo[!is.na(mutationInfo)]) \r\n }else{\r\n return(NA)\r\n }\r\n \r\n \r\n }else{\r\n return (NA)\r\n }\r\n }\r\n \r\n processNucMutations2 <- function(mu){\r\n if(!is.na(mu)){\r\n #R\r\n if(any(mu==\"R\")){\r\n Rs = mu[mu==\"R\"]\r\n nucNumbs = as.numeric(names(Rs))\r\n R_CDR = sum(as.integer(CDR_Nuc[nucNumbs]),na.rm=T)\r\n R_FWR = sum(as.integer(FWR_Nuc[nucNumbs]),na.rm=T) \r\n }else{\r\n R_CDR = 0\r\n R_FWR = 0\r\n } \r\n \r\n #S\r\n if(any(mu==\"S\")){\r\n Ss = mu[mu==\"S\"]\r\n nucNumbs = as.numeric(names(Ss))\r\n S_CDR = sum(as.integer(CDR_Nuc[nucNumbs]),na.rm=T)\r\n S_FWR = sum(as.integer(FWR_Nuc[nucNumbs]),na.rm=T) \r\n }else{\r\n S_CDR = 0\r\n S_FWR = 0\r\n } \r\n \r\n \r\n retVec = c(R_CDR,S_CDR,R_FWR,S_FWR)\r\n retVec[is.na(retVec)]=0\r\n return(retVec)\r\n }else{\r\n return(rep(0,4))\r\n }\r\n } \r\n \r\n \r\n ## Z-score Test\r\n computeZScore <- function(mat, test=\"Focused\"){\r\n matRes <- matrix(NA,ncol=2,nrow=(nrow(mat)))\r\n if(test==\"Focused\"){\r\n #Z_Focused_CDR\r\n #P_Denom = sum( mat[1,c(5,6,8)], na.rm=T )\r\n P = apply(mat[,c(5,6,8)],1,function(x){(x[1]/sum(x))})\r\n R_mean = apply(cbind(mat[,c(1,2,4)],P),1,function(x){x[4]*(sum(x[1:3]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,1] = (mat[,1]-R_mean)/R_sd\r\n \r\n #Z_Focused_FWR\r\n #P_Denom = sum( mat[1,c(7,6,8)], na.rm=T )\r\n P = apply(mat[,c(7,6,8)],1,function(x){(x[1]/sum(x))})\r\n R_mean = apply(cbind(mat[,c(3,2,4)],P),1,function(x){x[4]*(sum(x[1:3]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,2] = (mat[,3]-R_mean)/R_sd\r\n }\r\n \r\n if(test==\"Local\"){\r\n #Z_Focused_CDR\r\n #P_Denom = sum( mat[1,c(5,6,8)], na.rm=T )\r\n P = apply(mat[,c(5,6)],1,function(x){(x[1]/sum(x))})\r\n R_mean = apply(cbind(mat[,c(1,2)],P),1,function(x){x[3]*(sum(x[1:2]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,1] = (mat[,1]-R_mean)/R_sd\r\n \r\n #Z_Focused_FWR\r\n #P_Denom = sum( mat[1,c(7,6,8)], na.rm=T )\r\n P = apply(mat[,c(7,8)],1,function(x){(x[1]/sum(x))})\r\n R_mean = apply(cbind(mat[,c(3,4)],P),1,function(x){x[3]*(sum(x[1:2]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,2] = (mat[,3]-R_mean)/R_sd\r\n }\r\n \r\n if(test==\"Imbalanced\"){\r\n #Z_Focused_CDR\r\n #P_Denom = sum( mat[1,c(5,6,8)], na.rm=T )\r\n P = apply(mat[,5:8],1,function(x){((x[1]+x[2])/sum(x))})\r\n R_mean = apply(cbind(mat[,1:4],P),1,function(x){x[5]*(sum(x[1:4]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,1] = (mat[,1]-R_mean)/R_sd\r\n \r\n #Z_Focused_FWR\r\n #P_Denom = sum( mat[1,c(7,6,8)], na.rm=T )\r\n P = apply(mat[,5:8],1,function(x){((x[3]+x[4])/sum(x))})\r\n R_mean = apply(cbind(mat[,1:4],P),1,function(x){x[5]*(sum(x[1:4]))})\r\n R_sd=sqrt(R_mean*(1-P))\r\n matRes[,2] = (mat[,3]-R_mean)/R_sd\r\n } \r\n \r\n matRes[is.nan(matRes)] = NA\r\n return(matRes)\r\n }\r\n\r\n # Return a p-value for a z-score\r\n z2p <- function(z){\r\n p=NA\r\n if( !is.nan(z) && !is.na(z)){ \r\n if(z>0){\r\n p = (1 - pnorm(z,0,1))\r\n } else if(z<0){\r\n p = (-1 * pnorm(z,0,1))\r\n } else{\r\n p = 0.5\r\n }\r\n }else{\r\n p = NA\r\n }\r\n return(p)\r\n } \r\n \r\n \r\n ## Bayesian Test\r\n\r\n # Fitted parameter for the bayesian framework\r\nBAYESIAN_FITTED<-c(0.407277142798302, 0.554007336744485, 0.63777155771234, 0.693989162719009, 0.735450014674917, 0.767972534429806, 0.794557287143399, 0.816906816601605, 0.83606796225341, 0.852729446430296, 0.867370424541641, 0.880339760590323, 0.891900995024999, 0.902259181289864, 0.911577919359,0.919990301665853, 0.927606458124537, 0.934518806350661, 0.940805863754375, 0.946534836475715, 0.951763691199255, 0.95654428191308, 0.960920179487397, 0.964930893680829, 0.968611312149038, 0.971992459313836, 0.975102110004818, 0.977964943023096, 0.980603428208439, 0.983037660179428, 0.985285800977406, 0.987364285326685, 0.989288037855441, 0.991070478823525, 0.992723699729969, 0.994259575477392, 0.995687688867975, 0.997017365051493, 0.998257085153047, 0.999414558305388, 1.00049681357804, 1.00151036237481, 1.00246080204981, 1.00335370751909, 1.0041939329768, 1.0049859393417, 1.00573382091263, 1.00644127217376, 1.00711179729107, 1.00774845526417, 1.00835412715854, 1.00893143010366, 1.00948275846309, 1.01001030293661, 1.01051606798079, 1.01100188771288, 1.01146944044216, 1.01192026195449, 1.01235575766094, 1.01277721370986)\r\n CONST_i <- sort(c(((2^(seq(-39,0,length.out=201)))/2)[1:200],(c(0:11,13:99)+0.5)/100,1-(2^(seq(-39,0,length.out=201)))/2))\r\n \r\n # Given x, M & p, returns a pdf \r\n calculate_bayes <- function ( x=3, N=10, p=0.33,\r\n i=CONST_i,\r\n max_sigma=20,length_sigma=4001\r\n ){\r\n if(!0%in%N){\r\n G <- max(length(x),length(N),length(p))\r\n x=array(x,dim=G)\r\n N=array(N,dim=G)\r\n p=array(p,dim=G)\r\n sigma_s<-seq(-max_sigma,max_sigma,length.out=length_sigma)\r\n sigma_1<-log({i/{1-i}}/{p/{1-p}})\r\n index<-min(N,60)\r\n y<-dbeta(i,x+BAYESIAN_FITTED[index],N+BAYESIAN_FITTED[index]-x)*(1-p)*p*exp(sigma_1)/({1-p}^2+2*p*{1-p}*exp(sigma_1)+{p^2}*exp(2*sigma_1))\r\n if(!sum(is.na(y))){\r\n tmp<-approx(sigma_1,y,sigma_s)$y\r\n tmp/sum(tmp)/{2*max_sigma/{length_sigma-1}}\r\n }else{\r\n return(NA)\r\n }\r\n }else{\r\n return(NA)\r\n }\r\n } \r\n # Given a mat of observed & expected, return a list of CDR & FWR pdf for selection\r\n computeBayesianScore <- function(mat, test=\"Focused\", max_sigma=20,length_sigma=4001){\r\n flagOneSeq = F\r\n if(nrow(mat)==1){\r\n mat=rbind(mat,mat)\r\n flagOneSeq = T\r\n }\r\n if(test==\"Focused\"){\r\n #CDR\r\n P = c(apply(mat[,c(5,6,8)],1,function(x){(x[1]/sum(x))}),0.5)\r\n N = c(apply(mat[,c(1,2,4)],1,function(x){(sum(x))}),0)\r\n X = c(mat[,1],0)\r\n bayesCDR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesCDR = bayesCDR[-length(bayesCDR)]\r\n \r\n #FWR\r\n P = c(apply(mat[,c(7,6,8)],1,function(x){(x[1]/sum(x))}),0.5)\r\n N = c(apply(mat[,c(3,2,4)],1,function(x){(sum(x))}),0)\r\n X = c(mat[,3],0)\r\n bayesFWR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesFWR = bayesFWR[-length(bayesFWR)] \r\n }\r\n \r\n if(test==\"Local\"){\r\n #CDR\r\n P = c(apply(mat[,c(5,6)],1,function(x){(x[1]/sum(x))}),0.5)\r\n N = c(apply(mat[,c(1,2)],1,function(x){(sum(x))}),0)\r\n X = c(mat[,1],0)\r\n bayesCDR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesCDR = bayesCDR[-length(bayesCDR)]\r\n \r\n #FWR\r\n P = c(apply(mat[,c(7,8)],1,function(x){(x[1]/sum(x))}),0.5)\r\n N = c(apply(mat[,c(3,4)],1,function(x){(sum(x))}),0)\r\n X = c(mat[,3],0)\r\n bayesFWR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesFWR = bayesFWR[-length(bayesFWR)] \r\n } \r\n \r\n if(test==\"Imbalanced\"){\r\n #CDR\r\n P = c(apply(mat[,c(5:8)],1,function(x){((x[1]+x[2])/sum(x))}),0.5)\r\n N = c(apply(mat[,c(1:4)],1,function(x){(sum(x))}),0)\r\n X = c(apply(mat[,c(1:2)],1,function(x){(sum(x))}),0)\r\n bayesCDR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesCDR = bayesCDR[-length(bayesCDR)]\r\n \r\n #FWR\r\n P = c(apply(mat[,c(5:8)],1,function(x){((x[3]+x[4])/sum(x))}),0.5)\r\n N = c(apply(mat[,c(1:4)],1,function(x){(sum(x))}),0)\r\n X = c(apply(mat[,c(3:4)],1,function(x){(sum(x))}),0)\r\n bayesFWR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesFWR = bayesFWR[-length(bayesFWR)] \r\n }\r\n\r\n if(test==\"ImbalancedSilent\"){\r\n #CDR\r\n P = c(apply(mat[,c(6,8)],1,function(x){((x[1])/sum(x))}),0.5)\r\n N = c(apply(mat[,c(2,4)],1,function(x){(sum(x))}),0)\r\n X = c(apply(mat[,c(2,4)],1,function(x){(x[1])}),0)\r\n bayesCDR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesCDR = bayesCDR[-length(bayesCDR)]\r\n \r\n #FWR\r\n P = c(apply(mat[,c(6,8)],1,function(x){((x[2])/sum(x))}),0.5)\r\n N = c(apply(mat[,c(2,4)],1,function(x){(sum(x))}),0)\r\n X = c(apply(mat[,c(2,4)],1,function(x){(x[2])}),0)\r\n bayesFWR = apply(cbind(X,N,P),1,function(x){calculate_bayes(x=x[1],N=x[2],p=x[3],max_sigma=max_sigma,length_sigma=length_sigma)}) \r\n bayesFWR = bayesFWR[-length(bayesFWR)] \r\n }\r\n \r\n if(flagOneSeq==T){\r\n bayesCDR = bayesCDR[1] \r\n bayesFWR = bayesFWR[1]\r\n }\r\n return( list(\"CDR\"=bayesCDR, \"FWR\"=bayesFWR) )\r\n }\r\n \r\n ##Covolution\r\n break2chunks<-function(G=1000){\r\n base<-2^round(log(sqrt(G),2),0)\r\n return(c(rep(base,floor(G/base)-1),base+G-(floor(G/base)*base)))\r\n } \r\n \r\n PowersOfTwo <- function(G=100){\r\n exponents <- array()\r\n i = 0\r\n while(G > 0){\r\n i=i+1\r\n exponents[i] <- floor( log2(G) )\r\n G <- G-2^exponents[i]\r\n }\r\n return(exponents)\r\n }\r\n \r\n convolutionPowersOfTwo <- function( cons, length_sigma=4001 ){\r\n G = ncol(cons)\r\n if(G>1){\r\n for(gen in log(G,2):1){\r\n ll<-seq(from=2,to=2^gen,by=2)\r\n sapply(ll,function(l){cons[,l/2]<<-weighted_conv(cons[,l],cons[,l-1],length_sigma=length_sigma)})\r\n }\r\n }\r\n return( cons[,1] )\r\n }\r\n \r\n convolutionPowersOfTwoByTwos <- function( cons, length_sigma=4001,G=1 ){\r\n if(length(ncol(cons))) G<-ncol(cons)\r\n groups <- PowersOfTwo(G)\r\n matG <- matrix(NA, ncol=length(groups), nrow=length(cons)/G )\r\n startIndex = 1\r\n for( i in 1:length(groups) ){\r\n stopIndex <- 2^groups[i] + startIndex - 1\r\n if(stopIndex!=startIndex){\r\n matG[,i] <- convolutionPowersOfTwo( cons[,startIndex:stopIndex], length_sigma=length_sigma )\r\n startIndex = stopIndex + 1\r\n }\r\n else {\r\n if(G>1) matG[,i] <- cons[,startIndex:stopIndex]\r\n else matG[,i] <- cons\r\n #startIndex = stopIndex + 1\r\n }\r\n }\r\n return( list( matG, groups ) )\r\n }\r\n \r\n weighted_conv<-function(x,y,w=1,m=100,length_sigma=4001){\r\n lx<-length(x)\r\n ly<-length(y)\r\n if({lx1){\r\n while( i1 & Length_Postrior<=Threshold){\r\n cons = matrix(unlist(listPosteriors),length(listPosteriors[[1]]),length(listPosteriors))\r\n listMatG <- convolutionPowersOfTwoByTwos(cons,length_sigma=length_sigma)\r\n y<-calculate_bayesGHelper(listMatG,length_sigma=length_sigma)\r\n return( y/sum(y)/(2*max_sigma/(length_sigma-1)) )\r\n }else if(Length_Postrior==1) return(listPosteriors[[1]])\r\n else if(Length_Postrior==0) return(NA)\r\n else {\r\n cons = matrix(unlist(listPosteriors),length(listPosteriors[[1]]),length(listPosteriors))\r\n y = fastConv(cons,max_sigma=max_sigma, length_sigma=length_sigma )\r\n return( y/sum(y)/(2*max_sigma/(length_sigma-1)) )\r\n }\r\n }\r\n\r\n fastConv<-function(cons, max_sigma=20, length_sigma=4001){\r\n chunks<-break2chunks(G=ncol(cons))\r\n if(ncol(cons)==3) chunks<-2:1\r\n index_chunks_end <- cumsum(chunks)\r\n index_chunks_start <- c(1,index_chunks_end[-length(index_chunks_end)]+1)\r\n index_chunks <- cbind(index_chunks_start,index_chunks_end)\r\n \r\n case <- sum(chunks!=chunks[1])\r\n if(case==1) End <- max(1,((length(index_chunks)/2)-1))\r\n else End <- max(1,((length(index_chunks)/2)))\r\n \r\n firsts <- sapply(1:End,function(i){\r\n \t indexes<-index_chunks[i,1]:index_chunks[i,2]\r\n \t convolutionPowersOfTwoByTwos(cons[ ,indexes])[[1]]\r\n \t })\r\n if(case==0){\r\n \tresult<-calculate_bayesGHelper( convolutionPowersOfTwoByTwos(firsts) )\r\n }else if(case==1){\r\n last<-list(calculate_bayesGHelper(\r\n convolutionPowersOfTwoByTwos( cons[ ,index_chunks[length(index_chunks)/2,1]:index_chunks[length(index_chunks)/2,2]] )\r\n ),0)\r\n result_first<-calculate_bayesGHelper(convolutionPowersOfTwoByTwos(firsts))\r\n result<-calculate_bayesGHelper(\r\n list(\r\n cbind(\r\n result_first,last[[1]]),\r\n c(log(index_chunks_end[length(index_chunks)/2-1],2),log(index_chunks[length(index_chunks)/2,2]-index_chunks[length(index_chunks)/2,1]+1,2))\r\n )\r\n )\r\n }\r\n return(as.vector(result))\r\n }\r\n \r\n # Computes the 95% CI for a pdf\r\n calcBayesCI <- function(Pdf,low=0.025,up=0.975,max_sigma=20, length_sigma=4001){\r\n if(length(Pdf)!=length_sigma) return(NA)\r\n sigma_s=seq(-max_sigma,max_sigma,length.out=length_sigma)\r\n cdf = cumsum(Pdf)\r\n cdf = cdf/cdf[length(cdf)] \r\n return( c(sigma_s[findInterval(low,cdf)-1] , sigma_s[findInterval(up,cdf)]) ) \r\n }\r\n \r\n # Computes a mean for a pdf\r\n calcBayesMean <- function(Pdf,max_sigma=20,length_sigma=4001){\r\n if(length(Pdf)!=length_sigma) return(NA)\r\n sigma_s=seq(-max_sigma,max_sigma,length.out=length_sigma)\r\n norm = {length_sigma-1}/2/max_sigma\r\n return( (Pdf%*%sigma_s/norm) ) \r\n }\r\n \r\n # Returns the mean, and the 95% CI for a pdf\r\n calcBayesOutputInfo <- function(Pdf,low=0.025,up=0.975,max_sigma=20, length_sigma=4001){\r\n if(is.na(Pdf)) \r\n return(rep(NA,3)) \r\n bCI = calcBayesCI(Pdf=Pdf,low=low,up=up,max_sigma=max_sigma,length_sigma=length_sigma)\r\n bMean = calcBayesMean(Pdf=Pdf,max_sigma=max_sigma,length_sigma=length_sigma)\r\n return(c(bMean, bCI))\r\n } \r\n\r\n # Computes the p-value of a pdf\r\n computeSigmaP <- function(Pdf, length_sigma=4001, max_sigma=20){\r\n if(length(Pdf)>1){\r\n norm = {length_sigma-1}/2/max_sigma\r\n pVal = {sum(Pdf[1:{{length_sigma-1}/2}]) + Pdf[{{length_sigma+1}/2}]/2}/norm\r\n if(pVal>0.5){\r\n pVal = pVal-1\r\n }\r\n return(pVal)\r\n }else{\r\n return(NA)\r\n }\r\n } \r\n \r\n # Compute p-value of two distributions\r\n compareTwoDistsFaster <-function(sigma_S=seq(-20,20,length.out=4001), N=10000, dens1=runif(4001,0,1), dens2=runif(4001,0,1)){\r\n #print(c(length(dens1),length(dens2)))\r\n if(length(dens1)>1 & length(dens2)>1 ){\r\n dens1<-dens1/sum(dens1)\r\n dens2<-dens2/sum(dens2)\r\n cum2 <- cumsum(dens2)-dens2/2\r\n tmp<- sum(sapply(1:length(dens1),function(i)return(dens1[i]*cum2[i])))\r\n #print(tmp)\r\n if(tmp>0.5)tmp<-tmp-1\r\n return( tmp )\r\n }\r\n else {\r\n return(NA)\r\n }\r\n #return (sum(sapply(1:N,function(i)(sample(sigma_S,1,prob=dens1)>sample(sigma_S,1,prob=dens2))))/N)\r\n } \r\n \r\n # get number of seqeunces contributing to the sigma (i.e. seqeunces with mutations)\r\n numberOfSeqsWithMutations <- function(matMutations,test=1){\r\n if(test==4)test=2\r\n cdrSeqs <- 0\r\n fwrSeqs <- 0 \r\n if(test==1){#focused\r\n cdrMutations <- apply(matMutations, 1, function(x){ sum(x[c(1,2,4)]) })\r\n fwrMutations <- apply(matMutations, 1, function(x){ sum(x[c(3,4,2)]) })\r\n if( any(which(cdrMutations>0)) ) cdrSeqs <- sum(cdrMutations>0)\r\n if( any(which(fwrMutations>0)) ) fwrSeqs <- sum(fwrMutations>0) \r\n }\r\n if(test==2){#local\r\n cdrMutations <- apply(matMutations, 1, function(x){ sum(x[c(1,2)]) })\r\n fwrMutations <- apply(matMutations, 1, function(x){ sum(x[c(3,4)]) })\r\n if( any(which(cdrMutations>0)) ) cdrSeqs <- sum(cdrMutations>0)\r\n if( any(which(fwrMutations>0)) ) fwrSeqs <- sum(fwrMutations>0) \r\n }\r\n return(c(\"CDR\"=cdrSeqs, \"FWR\"=fwrSeqs))\r\n} \r\n\r\n\r\n\r\nshadeColor <- function(sigmaVal=NA,pVal=NA){\r\n if(is.na(sigmaVal) & is.na(pVal)) return(NA)\r\n if(is.na(sigmaVal) & !is.na(pVal)) sigmaVal=sign(pVal)\r\n if(is.na(pVal) || pVal==1 || pVal==0){\r\n returnColor = \"#FFFFFF\";\r\n }else{\r\n colVal=abs(pVal);\r\n \r\n if(sigmaVal<0){ \r\n if(colVal>0.1)\r\n returnColor = \"#CCFFCC\";\r\n if(colVal<=0.1)\r\n returnColor = \"#99FF99\";\r\n if(colVal<=0.050)\r\n returnColor = \"#66FF66\";\r\n if(colVal<=0.010)\r\n returnColor = \"#33FF33\";\r\n if(colVal<=0.005)\r\n returnColor = \"#00FF00\";\r\n \r\n }else{\r\n if(colVal>0.1)\r\n returnColor = \"#FFCCCC\";\r\n if(colVal<=0.1)\r\n returnColor = \"#FF9999\";\r\n if(colVal<=0.05)\r\n returnColor = \"#FF6666\";\r\n if(colVal<=0.01)\r\n returnColor = \"#FF3333\";\r\n if(colVal<0.005)\r\n returnColor = \"#FF0000\";\r\n }\r\n }\r\n \r\n return(returnColor)\r\n}\r\n\r\n\r\n\r\nplotHelp <- function(xfrac=0.05,yfrac=0.05,log=FALSE){\r\n if(!log){\r\n x = par()$usr[1]-(par()$usr[2]-par()$usr[1])*xfrac\r\n y = par()$usr[4]+(par()$usr[4]-par()$usr[3])*yfrac\r\n }else {\r\n if(log==2){\r\n x = par()$usr[1]-(par()$usr[2]-par()$usr[1])*xfrac\r\n y = 10^((par()$usr[4])+((par()$usr[4])-(par()$usr[3]))*yfrac)\r\n }\r\n if(log==1){\r\n x = 10^((par()$usr[1])-((par()$usr[2])-(par()$usr[1]))*xfrac)\r\n y = par()$usr[4]+(par()$usr[4]-par()$usr[3])*yfrac\r\n }\r\n if(log==3){\r\n x = 10^((par()$usr[1])-((par()$usr[2])-(par()$usr[1]))*xfrac)\r\n y = 10^((par()$usr[4])+((par()$usr[4])-(par()$usr[3]))*yfrac)\r\n }\r\n }\r\n return(c(\"x\"=x,\"y\"=y))\r\n}\r\n\r\n# SHMulation\r\n\r\n # Based on targeting, introduce a single mutation & then update the targeting \r\n oneMutation <- function(){\r\n # Pick a postion + mutation\r\n posMutation = sample(1:(seqGermlineLen*4),1,replace=F,prob=as.vector(seqTargeting))\r\n posNucNumb = ceiling(posMutation/4) # Nucleotide number\r\n posNucKind = 4 - ( (posNucNumb*4) - posMutation ) # Nuc the position mutates to\r\n \r\n #mutate the simulation sequence\r\n seqSimVec <- s2c(seqSim)\r\n seqSimVec[posNucNumb] <- NUCLEOTIDES[posNucKind]\r\n seqSim <<- c2s(seqSimVec)\r\n \r\n #update Mutability, Targeting & MutationsTypes\r\n updateMutabilityNTargeting(posNucNumb)\r\n \r\n #return(c(posNucNumb,NUCLEOTIDES[posNucKind])) \r\n return(posNucNumb)\r\n } \r\n \r\n updateMutabilityNTargeting <- function(position){\r\n min_i<-max((position-2),1)\r\n max_i<-min((position+2),nchar(seqSim))\r\n min_ii<-min(min_i,3)\r\n \r\n #mutability - update locally\r\n seqMutability[(min_i):(max_i)] <<- computeMutabilities(substr(seqSim,position-4,position+4))[(min_ii):(max_i-min_i+min_ii)]\r\n \r\n \r\n #targeting - compute locally\r\n seqTargeting[,min_i:max_i] <<- computeTargeting(substr(seqSim,min_i,max_i),seqMutability[min_i:max_i]) \r\n seqTargeting[is.na(seqTargeting)] <<- 0\r\n #mutCodonPos = getCodonPos(position) \r\n mutCodonPos = seq(getCodonPos(min_i)[1],getCodonPos(max_i)[3])\r\n #cat(mutCodonPos,\"\\n\") \r\n mutTypeCodon = getCodonPos(position)\r\n seqMutationTypes[,mutTypeCodon] <<- computeMutationTypesFast( substr(seqSim,mutTypeCodon[1],mutTypeCodon[3]) ) \r\n # Stop = 0\r\n if(any(seqMutationTypes[,mutCodonPos]==\"Stop\",na.rm=T )){\r\n seqTargeting[,mutCodonPos][seqMutationTypes[,mutCodonPos]==\"Stop\"] <<- 0\r\n }\r\n \r\n \r\n #Selection\r\n selectedPos = (min_i*4-4)+(which(seqMutationTypes[,min_i:max_i]==\"R\")) \r\n # CDR\r\n selectedCDR = selectedPos[which(matCDR[selectedPos]==T)]\r\n seqTargeting[selectedCDR] <<- seqTargeting[selectedCDR] * exp(selCDR)\r\n seqTargeting[selectedCDR] <<- seqTargeting[selectedCDR]/baseLineCDR_K\r\n \r\n # FWR\r\n selectedFWR = selectedPos[which(matFWR[selectedPos]==T)]\r\n seqTargeting[selectedFWR] <<- seqTargeting[selectedFWR] * exp(selFWR)\r\n seqTargeting[selectedFWR] <<- seqTargeting[selectedFWR]/baseLineFWR_K \r\n \r\n } \r\n \r\n\r\n\r\n # Validate the mutation: if the mutation has not been sampled before validate it, else discard it. \r\n validateMutation <- function(){ \r\n if( !(mutatedPos%in%mutatedPositions) ){ # if it's a new mutation\r\n uniqueMutationsIntroduced <<- uniqueMutationsIntroduced + 1\r\n mutatedPositions[uniqueMutationsIntroduced] <<- mutatedPos \r\n }else{\r\n if(substr(seqSim,mutatedPos,mutatedPos)==substr(seqGermline,mutatedPos,mutatedPos)){ # back to germline mutation\r\n mutatedPositions <<- mutatedPositions[-which(mutatedPositions==mutatedPos)]\r\n uniqueMutationsIntroduced <<- uniqueMutationsIntroduced - 1\r\n } \r\n }\r\n } \r\n \r\n \r\n \r\n # Places text (labels) at normalized coordinates \r\n myaxis <- function(xfrac=0.05,yfrac=0.05,log=FALSE,w=\"text\",cex=1,adj=1,thecol=\"black\"){\r\n par(xpd=TRUE)\r\n if(!log)\r\n text(par()$usr[1]-(par()$usr[2]-par()$usr[1])*xfrac,par()$usr[4]+(par()$usr[4]-par()$usr[3])*yfrac,w,cex=cex,adj=adj,col=thecol)\r\n else {\r\n if(log==2)\r\n text(\r\n par()$usr[1]-(par()$usr[2]-par()$usr[1])*xfrac,\r\n 10^((par()$usr[4])+((par()$usr[4])-(par()$usr[3]))*yfrac),\r\n w,cex=cex,adj=adj,col=thecol)\r\n if(log==1)\r\n text(\r\n 10^((par()$usr[1])-((par()$usr[2])-(par()$usr[1]))*xfrac),\r\n par()$usr[4]+(par()$usr[4]-par()$usr[3])*yfrac,\r\n w,cex=cex,adj=adj,col=thecol)\r\n if(log==3)\r\n text(\r\n 10^((par()$usr[1])-((par()$usr[2])-(par()$usr[1]))*xfrac),\r\n 10^((par()$usr[4])+((par()$usr[4])-(par()$usr[3]))*yfrac),\r\n w,cex=cex,adj=adj,col=thecol)\r\n }\r\n par(xpd=FALSE)\r\n }\r\n \r\n \r\n \r\n # Count the mutations in a sequence\r\n analyzeMutations <- function( inputMatrixIndex, model = 0 , multipleMutation=0, seqWithStops=0){\r\n\r\n paramGL = s2c(matInput[inputMatrixIndex,2])\r\n paramSeq = s2c(matInput[inputMatrixIndex,1]) \r\n \r\n #if( any(paramSeq==\"N\") ){\r\n # gapPos_Seq = which(paramSeq==\"N\")\r\n # gapPos_Seq_ToReplace = gapPos_Seq[paramGL[gapPos_Seq] != \"N\"]\r\n # paramSeq[gapPos_Seq_ToReplace] = paramGL[gapPos_Seq_ToReplace]\r\n #} \r\n mutations_val = paramGL != paramSeq \r\n \r\n if(any(mutations_val)){\r\n mutationPos = which(mutations_val)#{1:length(mutations_val)}[mutations_val] \r\n length_mutations =length(mutationPos)\r\n mutationInfo = rep(NA,length_mutations)\r\n \r\n pos<- mutationPos\r\n pos_array<-array(sapply(pos,getCodonPos))\r\n codonGL = paramGL[pos_array]\r\n codonSeqWhole = paramSeq[pos_array]\r\n codonSeq = sapply(pos,function(x){\r\n seqP = paramGL[getCodonPos(x)]\r\n muCodonPos = {x-1}%%3+1 \r\n seqP[muCodonPos] = paramSeq[x]\r\n return(seqP)\r\n })\r\n GLcodons = apply(matrix(codonGL,length_mutations,3,byrow=TRUE),1,c2s)\r\n SeqcodonsWhole = apply(matrix(codonSeqWhole,length_mutations,3,byrow=TRUE),1,c2s) \r\n Seqcodons = apply(codonSeq,2,c2s)\r\n \r\n mutationInfo = apply(rbind(GLcodons , Seqcodons),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n names(mutationInfo) = mutationPos \r\n \r\n mutationInfoWhole = apply(rbind(GLcodons , SeqcodonsWhole),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n names(mutationInfoWhole) = mutationPos\r\n\r\n mutationInfo <- mutationInfo[!is.na(mutationInfo)]\r\n mutationInfoWhole <- mutationInfoWhole[!is.na(mutationInfoWhole)]\r\n \r\n if(any(!is.na(mutationInfo))){ \r\n \r\n #Filter based on Stop (at the codon level)\r\n if(seqWithStops==1){\r\n nucleotidesAtStopCodons = names(mutationInfoWhole[mutationInfoWhole!=\"Stop\"])\r\n mutationInfo = mutationInfo[nucleotidesAtStopCodons]\r\n mutationInfoWhole = mutationInfo[nucleotidesAtStopCodons]\r\n }else{\r\n countStops = sum(mutationInfoWhole==\"Stop\")\r\n if(seqWithStops==2 & countStops==0) mutationInfo = NA\r\n if(seqWithStops==3 & countStops>0) mutationInfo = NA\r\n } \r\n \r\n if(any(!is.na(mutationInfo))){\r\n #Filter mutations based on multipleMutation\r\n if(multipleMutation==1 & !is.na(mutationInfo)){\r\n mutationCodons = getCodonNumb(as.numeric(names(mutationInfoWhole)))\r\n tableMutationCodons <- table(mutationCodons)\r\n codonsWithMultipleMutations <- as.numeric(names(tableMutationCodons[tableMutationCodons>1]))\r\n if(any(codonsWithMultipleMutations)){\r\n #remove the nucleotide mutations in the codons with multiple mutations\r\n mutationInfo <- mutationInfo[!(mutationCodons %in% codonsWithMultipleMutations)]\r\n #replace those codons with Ns in the input sequence\r\n paramSeq[unlist(lapply(codonsWithMultipleMutations, getCodonNucs))] = \"N\"\r\n matInput[inputMatrixIndex,1] <<- c2s(paramSeq)\r\n }\r\n }\r\n\r\n #Filter mutations based on the model\r\n if(any(mutationInfo)==T | is.na(any(mutationInfo))){ \r\n \r\n if(model==1 & !is.na(mutationInfo)){\r\n mutationInfo <- mutationInfo[mutationInfo==\"S\"]\r\n } \r\n if(any(mutationInfo)==T | is.na(any(mutationInfo))) return(mutationInfo)\r\n else return(NA)\r\n }else{\r\n return(NA)\r\n }\r\n }else{\r\n return(NA)\r\n }\r\n \r\n \r\n }else{\r\n return(NA)\r\n }\r\n \r\n \r\n }else{\r\n return (NA)\r\n } \r\n } \r\n\r\n analyzeMutationsFixed <- function( inputArray, model = 0 , multipleMutation=0, seqWithStops=0){\r\n\r\n paramGL = s2c(inputArray[2])\r\n paramSeq = s2c(inputArray[1]) \r\n inputSeq <- inputArray[1]\r\n #if( any(paramSeq==\"N\") ){\r\n # gapPos_Seq = which(paramSeq==\"N\")\r\n # gapPos_Seq_ToReplace = gapPos_Seq[paramGL[gapPos_Seq] != \"N\"]\r\n # paramSeq[gapPos_Seq_ToReplace] = paramGL[gapPos_Seq_ToReplace]\r\n #} \r\n mutations_val = paramGL != paramSeq \r\n \r\n if(any(mutations_val)){\r\n mutationPos = which(mutations_val)#{1:length(mutations_val)}[mutations_val] \r\n length_mutations =length(mutationPos)\r\n mutationInfo = rep(NA,length_mutations)\r\n \r\n pos<- mutationPos\r\n pos_array<-array(sapply(pos,getCodonPos))\r\n codonGL = paramGL[pos_array]\r\n codonSeqWhole = paramSeq[pos_array]\r\n codonSeq = sapply(pos,function(x){\r\n seqP = paramGL[getCodonPos(x)]\r\n muCodonPos = {x-1}%%3+1 \r\n seqP[muCodonPos] = paramSeq[x]\r\n return(seqP)\r\n })\r\n GLcodons = apply(matrix(codonGL,length_mutations,3,byrow=TRUE),1,c2s)\r\n SeqcodonsWhole = apply(matrix(codonSeqWhole,length_mutations,3,byrow=TRUE),1,c2s) \r\n Seqcodons = apply(codonSeq,2,c2s)\r\n \r\n mutationInfo = apply(rbind(GLcodons , Seqcodons),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n names(mutationInfo) = mutationPos \r\n \r\n mutationInfoWhole = apply(rbind(GLcodons , SeqcodonsWhole),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n names(mutationInfoWhole) = mutationPos\r\n\r\n mutationInfo <- mutationInfo[!is.na(mutationInfo)]\r\n mutationInfoWhole <- mutationInfoWhole[!is.na(mutationInfoWhole)]\r\n \r\n if(any(!is.na(mutationInfo))){ \r\n \r\n #Filter based on Stop (at the codon level)\r\n if(seqWithStops==1){\r\n nucleotidesAtStopCodons = names(mutationInfoWhole[mutationInfoWhole!=\"Stop\"])\r\n mutationInfo = mutationInfo[nucleotidesAtStopCodons]\r\n mutationInfoWhole = mutationInfo[nucleotidesAtStopCodons]\r\n }else{\r\n countStops = sum(mutationInfoWhole==\"Stop\")\r\n if(seqWithStops==2 & countStops==0) mutationInfo = NA\r\n if(seqWithStops==3 & countStops>0) mutationInfo = NA\r\n } \r\n \r\n if(any(!is.na(mutationInfo))){\r\n #Filter mutations based on multipleMutation\r\n if(multipleMutation==1 & !is.na(mutationInfo)){\r\n mutationCodons = getCodonNumb(as.numeric(names(mutationInfoWhole)))\r\n tableMutationCodons <- table(mutationCodons)\r\n codonsWithMultipleMutations <- as.numeric(names(tableMutationCodons[tableMutationCodons>1]))\r\n if(any(codonsWithMultipleMutations)){\r\n #remove the nucleotide mutations in the codons with multiple mutations\r\n mutationInfo <- mutationInfo[!(mutationCodons %in% codonsWithMultipleMutations)]\r\n #replace those codons with Ns in the input sequence\r\n paramSeq[unlist(lapply(codonsWithMultipleMutations, getCodonNucs))] = \"N\"\r\n #matInput[inputMatrixIndex,1] <<- c2s(paramSeq)\r\n inputSeq <- c2s(paramSeq)\r\n }\r\n }\r\n \r\n #Filter mutations based on the model\r\n if(any(mutationInfo)==T | is.na(any(mutationInfo))){ \r\n \r\n if(model==1 & !is.na(mutationInfo)){\r\n mutationInfo <- mutationInfo[mutationInfo==\"S\"]\r\n } \r\n if(any(mutationInfo)==T | is.na(any(mutationInfo))) return(list(mutationInfo,inputSeq))\r\n else return(list(NA,inputSeq))\r\n }else{\r\n return(list(NA,inputSeq))\r\n }\r\n }else{\r\n return(list(NA,inputSeq))\r\n }\r\n \r\n \r\n }else{\r\n return(list(NA,inputSeq))\r\n }\r\n \r\n \r\n }else{\r\n return (list(NA,inputSeq))\r\n } \r\n } \r\n \r\n # triMutability Background Count\r\n buildMutabilityModel <- function( inputMatrixIndex, model=0 , multipleMutation=0, seqWithStops=0, stopMutations=0){\r\n \r\n #rowOrigMatInput = matInput[inputMatrixIndex,] \r\n seqGL = gsub(\"-\", \"\", matInput[inputMatrixIndex,2])\r\n seqInput = gsub(\"-\", \"\", matInput[inputMatrixIndex,1]) \r\n #matInput[inputMatrixIndex,] <<- cbind(seqInput,seqGL)\r\n tempInput <- cbind(seqInput,seqGL)\r\n seqLength = nchar(seqGL) \r\n list_analyzeMutationsFixed<- analyzeMutationsFixed(tempInput, model, multipleMutation, seqWithStops)\r\n mutationCount <- list_analyzeMutationsFixed[[1]]\r\n seqInput <- list_analyzeMutationsFixed[[2]]\r\n BackgroundMatrix = mutabilityMatrix\r\n MutationMatrix = mutabilityMatrix \r\n MutationCountMatrix = mutabilityMatrix \r\n if(!is.na(mutationCount)){\r\n if((stopMutations==0 & model==0) | (stopMutations==1 & (sum(mutationCount==\"Stop\")0)) ){ \r\n \r\n fivermerStartPos = 1:(seqLength-4)\r\n fivemerLength <- length(fivermerStartPos)\r\n fivemerGL <- substr(rep(seqGL,length(fivermerStartPos)),(fivermerStartPos),(fivermerStartPos+4))\r\n fivemerSeq <- substr(rep(seqInput,length(fivermerStartPos)),(fivermerStartPos),(fivermerStartPos+4))\r\n \r\n #Background\r\n for(fivemerIndex in 1:fivemerLength){\r\n fivemer = fivemerGL[fivemerIndex]\r\n if(!any(grep(\"N\",fivemer))){\r\n fivemerCodonPos = fivemerCodon(fivemerIndex)\r\n fivemerReadingFrameCodon = substr(fivemer,fivemerCodonPos[1],fivemerCodonPos[3]) \r\n fivemerReadingFrameCodonInputSeq = substr(fivemerSeq[fivemerIndex],fivemerCodonPos[1],fivemerCodonPos[3]) \r\n \r\n # All mutations model\r\n #if(!any(grep(\"N\",fivemerReadingFrameCodon))){\r\n if(model==0){\r\n if(stopMutations==0){\r\n if(!any(grep(\"N\",fivemerReadingFrameCodonInputSeq)))\r\n BackgroundMatrix[fivemer] <- (BackgroundMatrix[fivemer] + 1) \r\n }else{\r\n if( !any(grep(\"N\",fivemerReadingFrameCodonInputSeq)) & translateCodonToAminoAcid(fivemerReadingFrameCodon)!=\"*\" ){\r\n positionWithinCodon = which(fivemerCodonPos==3)#positionsWithinCodon[(fivemerCodonPos[1]%%3)+1]\r\n BackgroundMatrix[fivemer] <- (BackgroundMatrix[fivemer] + probNonStopMutations[fivemerReadingFrameCodon,positionWithinCodon])\r\n }\r\n }\r\n }else{ # Only silent mutations\r\n if( !any(grep(\"N\",fivemerReadingFrameCodonInputSeq)) & translateCodonToAminoAcid(fivemerReadingFrameCodon)!=\"*\" & translateCodonToAminoAcid(fivemerReadingFrameCodonInputSeq)==translateCodonToAminoAcid(fivemerReadingFrameCodon)){\r\n positionWithinCodon = which(fivemerCodonPos==3)\r\n BackgroundMatrix[fivemer] <- (BackgroundMatrix[fivemer] + probSMutations[fivemerReadingFrameCodon,positionWithinCodon])\r\n }\r\n }\r\n #}\r\n }\r\n }\r\n \r\n #Mutations\r\n if(stopMutations==1) mutationCount = mutationCount[mutationCount!=\"Stop\"]\r\n if(model==1) mutationCount = mutationCount[mutationCount==\"S\"] \r\n mutationPositions = as.numeric(names(mutationCount))\r\n mutationCount = mutationCount[mutationPositions>2 & mutationPositions<(seqLength-1)]\r\n mutationPositions = mutationPositions[mutationPositions>2 & mutationPositions<(seqLength-1)]\r\n countMutations = 0 \r\n for(mutationPosition in mutationPositions){\r\n fivemerIndex = mutationPosition-2\r\n fivemer = fivemerSeq[fivemerIndex]\r\n GLfivemer = fivemerGL[fivemerIndex]\r\n fivemerCodonPos = fivemerCodon(fivemerIndex)\r\n fivemerReadingFrameCodon = substr(fivemer,fivemerCodonPos[1],fivemerCodonPos[3]) \r\n fivemerReadingFrameCodonGL = substr(GLfivemer,fivemerCodonPos[1],fivemerCodonPos[3])\r\n if(!any(grep(\"N\",fivemer)) & !any(grep(\"N\",GLfivemer))){\r\n if(model==0){\r\n countMutations = countMutations + 1 \r\n MutationMatrix[GLfivemer] <- (MutationMatrix[GLfivemer] + 1)\r\n MutationCountMatrix[GLfivemer] <- (MutationCountMatrix[GLfivemer] + 1) \r\n }else{\r\n if( translateCodonToAminoAcid(fivemerReadingFrameCodonGL)!=\"*\" ){\r\n countMutations = countMutations + 1\r\n positionWithinCodon = which(fivemerCodonPos==3)\r\n glNuc = substr(fivemerReadingFrameCodonGL,positionWithinCodon,positionWithinCodon)\r\n inputNuc = substr(fivemerReadingFrameCodon,positionWithinCodon,positionWithinCodon)\r\n MutationMatrix[GLfivemer] <- (MutationMatrix[GLfivemer] + substitution[glNuc,inputNuc])\r\n MutationCountMatrix[GLfivemer] <- (MutationCountMatrix[GLfivemer] + 1) \r\n } \r\n } \r\n } \r\n }\r\n \r\n seqMutability = MutationMatrix/BackgroundMatrix\r\n seqMutability = seqMutability/sum(seqMutability,na.rm=TRUE)\r\n #cat(inputMatrixIndex,\"\\t\",countMutations,\"\\n\")\r\n return(list(\"seqMutability\" = seqMutability,\"numbMutations\" = countMutations,\"seqMutabilityCount\" = MutationCountMatrix, \"BackgroundMatrix\"=BackgroundMatrix)) \r\n \r\n } \r\n }\r\n \r\n } \r\n \r\n #Returns the codon position containing the middle nucleotide\r\n fivemerCodon <- function(fivemerIndex){\r\n codonPos = list(2:4,1:3,3:5)\r\n fivemerType = fivemerIndex%%3\r\n return(codonPos[[fivemerType+1]])\r\n }\r\n\r\n #returns probability values for one mutation in codons resulting in R, S or Stop\r\n probMutations <- function(typeOfMutation){ \r\n matMutationProb <- matrix(0,ncol=3,nrow=125,dimnames=list(words(alphabet = c(NUCLEOTIDES,\"N\"), length=3),c(1:3))) \r\n for(codon in rownames(matMutationProb)){\r\n if( !any(grep(\"N\",codon)) ){\r\n for(muPos in 1:3){\r\n matCodon = matrix(rep(s2c(codon),3),nrow=3,ncol=3,byrow=T)\r\n glNuc = matCodon[1,muPos]\r\n matCodon[,muPos] = canMutateTo(glNuc) \r\n substitutionRate = substitution[glNuc,matCodon[,muPos]]\r\n typeOfMutations = apply(rbind(rep(codon,3),apply(matCodon,1,c2s)),2,function(x){mutationType(c2s(x[1]),c2s(x[2]))}) \r\n matMutationProb[codon,muPos] <- sum(substitutionRate[typeOfMutations==typeOfMutation])\r\n }\r\n }\r\n }\r\n \r\n return(matMutationProb) \r\n }\r\n \r\n \r\n \r\n \r\n#Mapping Trinucleotides to fivemers\r\nmapTriToFivemer <- function(triMutability=triMutability_Literature_Human){\r\n rownames(triMutability) <- triMutability_Names\r\n Fivemer<-rep(NA,1024)\r\n names(Fivemer)<-words(alphabet=NUCLEOTIDES,length=5)\r\n Fivemer<-sapply(names(Fivemer),function(Word)return(sum( c(triMutability[substring(Word,3,5),1],triMutability[substring(Word,2,4),2],triMutability[substring(Word,1,3),3]),na.rm=TRUE)))\r\n Fivemer<-Fivemer/sum(Fivemer)\r\n return(Fivemer)\r\n}\r\n\r\ncollapseFivemerToTri<-function(Fivemer,Weights=MutabilityWeights,position=1,NUC=\"A\"){\r\n Indices<-substring(names(Fivemer),3,3)==NUC\r\n Factors<-substring(names(Fivemer[Indices]),(4-position),(6-position))\r\n tapply(which(Indices),Factors,function(i)weighted.mean(Fivemer[i],Weights[i],na.rm=TRUE))\r\n}\r\n\r\n\r\n\r\nCountFivemerToTri<-function(Fivemer,Weights=MutabilityWeights,position=1,NUC=\"A\"){\r\n Indices<-substring(names(Fivemer),3,3)==NUC\r\n Factors<-substring(names(Fivemer[Indices]),(4-position),(6-position))\r\n tapply(which(Indices),Factors,function(i)sum(Weights[i],na.rm=TRUE))\r\n}\r\n\r\n#Uses the real counts of the mutated fivemers\r\nCountFivemerToTri2<-function(Fivemer,Counts=MutabilityCounts,position=1,NUC=\"A\"){\r\n Indices<-substring(names(Fivemer),3,3)==NUC\r\n Factors<-substring(names(Fivemer[Indices]),(4-position),(6-position))\r\n tapply(which(Indices),Factors,function(i)sum(Counts[i],na.rm=TRUE))\r\n}\r\n\r\nbootstrap<-function(x=c(33,12,21),M=10000,alpha=0.05){\r\nN<-sum(x)\r\nif(N){\r\np<-x/N\r\nk<-length(x)-1\r\ntmp<-rmultinom(M, size = N, prob=p)\r\ntmp_p<-apply(tmp,2,function(y)y/N)\r\n(apply(tmp_p,1,function(y)quantile(y,c(alpha/2/k,1-alpha/2/k))))\r\n}\r\nelse return(matrix(0,2,length(x)))\r\n}\r\n\r\n\r\n\r\n\r\nbootstrap2<-function(x=c(33,12,21),n=10,M=10000,alpha=0.05){\r\n\r\nN<-sum(x)\r\nk<-length(x)\r\ny<-rep(1:k,x)\r\ntmp<-sapply(1:M,function(i)sample(y,n))\r\nif(n>1)tmp_p<-sapply(1:M,function(j)sapply(1:k,function(i)sum(tmp[,j]==i)))/n\r\nif(n==1)tmp_p<-sapply(1:M,function(j)sapply(1:k,function(i)sum(tmp[j]==i)))/n\r\n(apply(tmp_p,1,function(z)quantile(z,c(alpha/2/(k-1),1-alpha/2/(k-1)))))\r\n}\r\n\r\n\r\n\r\np_value<-function(x=c(33,12,21),M=100000,x_obs=c(2,5,3)){\r\nn=sum(x_obs)\r\nN<-sum(x)\r\nk<-length(x)\r\ny<-rep(1:k,x)\r\ntmp<-sapply(1:M,function(i)sample(y,n))\r\nif(n>1)tmp_p<-sapply(1:M,function(j)sapply(1:k,function(i)sum(tmp[,j]==i)))\r\nif(n==1)tmp_p<-sapply(1:M,function(j)sapply(1:k,function(i)sum(tmp[j]==i)))\r\ntmp<-rbind(sapply(1:3,function(i)sum(tmp_p[i,]>=x_obs[i])/M),\r\nsapply(1:3,function(i)sum(tmp_p[i,]<=x_obs[i])/M))\r\nsapply(1:3,function(i){if(tmp[1,i]>=tmp[2,i])return(-tmp[2,i])else return(tmp[1,i])})\r\n}\r\n\r\n#\"D:\\\\Sequences\\\\IMGT Germlines\\\\Human_SNPless_IGHJ.FASTA\"\r\n# Remove SNPs from IMGT germline segment alleles\r\ngenerateUnambiguousRepertoire <- function(repertoireInFile,repertoireOutFile){\r\n repertoireIn <- read.fasta(repertoireInFile, seqtype=\"DNA\",as.string=T,set.attributes=F,forceDNAtolower=F)\r\n alleleNames <- sapply(names(repertoireIn),function(x)strsplit(x,\"|\",fixed=TRUE)[[1]][2])\r\n SNPs <- tapply(repertoireIn,sapply(alleleNames,function(x)strsplit(x,\"*\",fixed=TRUE)[[1]][1]),function(x){\r\n Indices<-NULL\r\n for(i in 1:length(x)){\r\n firstSeq = s2c(x[[1]])\r\n iSeq = s2c(x[[i]])\r\n Indices<-c(Indices,which(firstSeq[1:320]!=iSeq[1:320] & firstSeq[1:320]!=\".\" & iSeq[1:320]!=\".\" ))\r\n }\r\n return(sort(unique(Indices)))\r\n })\r\n repertoireOut <- repertoireIn\r\n repertoireOut <- lapply(names(repertoireOut), function(repertoireName){\r\n alleleName <- strsplit(repertoireName,\"|\",fixed=TRUE)[[1]][2]\r\n geneSegmentName <- strsplit(alleleName,\"*\",fixed=TRUE)[[1]][1]\r\n alleleSeq <- s2c(repertoireOut[[repertoireName]])\r\n alleleSeq[as.numeric(unlist(SNPs[geneSegmentName]))] <- \"N\"\r\n alleleSeq <- c2s(alleleSeq)\r\n repertoireOut[[repertoireName]] <- alleleSeq\r\n })\r\n names(repertoireOut) <- names(repertoireIn)\r\n write.fasta(repertoireOut,names(repertoireOut),file.out=repertoireOutFile) \r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n############\r\ngroupBayes2 = function(indexes, param_resultMat){\r\n \r\n BayesGDist_Focused_CDR = calculate_bayesG( x=param_resultMat[indexes,1], N=apply(param_resultMat[indexes,c(1,2,4)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[1]/(x[1]+x[2]+x[4])}))\r\n BayesGDist_Focused_FWR = calculate_bayesG( x=param_resultMat[indexes,3], N=apply(param_resultMat[indexes,c(3,2,4)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[3]/(x[3]+x[2]+x[4])}))\r\n #BayesGDist_Local_CDR = calculate_bayesG( x=param_resultMat[indexes,1], N=apply(param_resultMat[indexes,c(1,2)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[1]/(x[1]+x[2])}))\r\n #BayesGDist_Local_FWR = calculate_bayesG( x=param_resultMat[indexes,3], N=apply(param_resultMat[indexes,c(3,4)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[3]/(x[3]+x[4])}))\r\n #BayesGDist_Global_CDR = calculate_bayesG( x=param_resultMat[indexes,1], N=apply(param_resultMat[indexes,c(1,2,3,4)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[1]/(x[1]+x[2]+x[3]+x[4])}))\r\n #BayesGDist_Global_FWR = calculate_bayesG( x=param_resultMat[indexes,3], N=apply(param_resultMat[indexes,c(1,2,3,4)],1,sum,na.rm=T), p=apply(param_resultMat[indexes,5:8],1,function(x){x[3]/(x[1]+x[2]+x[3]+x[4])}))\r\n return ( list(\"BayesGDist_Focused_CDR\"=BayesGDist_Focused_CDR,\r\n \"BayesGDist_Focused_FWR\"=BayesGDist_Focused_FWR) )\r\n #\"BayesGDist_Local_CDR\"=BayesGDist_Local_CDR,\r\n #\"BayesGDist_Local_FWR\" = BayesGDist_Local_FWR))\r\n# \"BayesGDist_Global_CDR\" = BayesGDist_Global_CDR,\r\n# \"BayesGDist_Global_FWR\" = BayesGDist_Global_FWR) )\r\n\r\n\r\n}\r\n\r\n\r\ncalculate_bayesG <- function( x=array(), N=array(), p=array(), max_sigma=20, length_sigma=4001){\r\n G <- max(length(x),length(N),length(p))\r\n x=array(x,dim=G)\r\n N=array(N,dim=G)\r\n p=array(p,dim=G)\r\n\r\n indexOfZero = N>0 & p>0\r\n N = N[indexOfZero]\r\n x = x[indexOfZero]\r\n p = p[indexOfZero] \r\n G <- length(x)\r\n \r\n if(G){\r\n \r\n cons<-array( dim=c(length_sigma,G) )\r\n if(G==1) {\r\n return(calculate_bayes(x=x[G],N=N[G],p=p[G],max_sigma=max_sigma,length_sigma=length_sigma))\r\n }\r\n else {\r\n for(g in 1:G) cons[,g] <- calculate_bayes(x=x[g],N=N[g],p=p[g],max_sigma=max_sigma,length_sigma=length_sigma)\r\n listMatG <- convolutionPowersOfTwoByTwos(cons,length_sigma=length_sigma)\r\n y<-calculate_bayesGHelper(listMatG,length_sigma=length_sigma)\r\n return( y/sum(y)/(2*max_sigma/(length_sigma-1)) )\r\n }\r\n }else{\r\n return(NA)\r\n }\r\n}\r\n\r\n\r\ncalculate_bayesGHelper <- function( listMatG,length_sigma=4001 ){\r\n matG <- listMatG[[1]] \r\n groups <- listMatG[[2]]\r\n i = 1 \r\n resConv <- matG[,i]\r\n denom <- 2^groups[i]\r\n if(length(groups)>1){\r\n while( i0)) ){ \r\n \r\n# ONEmerStartPos = 1:(seqLength)\r\n# ONEmerLength <- length(ONEmerStartPos)\r\n ONEmerGL <- s2c(seqGL)\r\n ONEmerSeq <- s2c(seqInput)\r\n \r\n #Background\r\n for(ONEmerIndex in 1:seqLength){\r\n ONEmer = ONEmerGL[ONEmerIndex]\r\n if(ONEmer!=\"N\"){\r\n ONEmerCodonPos = getCodonPos(ONEmerIndex)\r\n ONEmerReadingFrameCodon = c2s(ONEmerGL[ONEmerCodonPos]) \r\n ONEmerReadingFrameCodonInputSeq = c2s(ONEmerSeq[ONEmerCodonPos] ) \r\n \r\n # All mutations model\r\n #if(!any(grep(\"N\",ONEmerReadingFrameCodon))){\r\n if(model==0){\r\n if(stopMutations==0){\r\n if(!any(grep(\"N\",ONEmerReadingFrameCodonInputSeq)))\r\n BackgroundMatrix[ONEmer] <- (BackgroundMatrix[ONEmer] + 1) \r\n }else{\r\n if( !any(grep(\"N\",ONEmerReadingFrameCodonInputSeq)) & translateCodonToAminoAcid(ONEmerReadingFrameCodonInputSeq)!=\"*\"){\r\n positionWithinCodon = which(ONEmerCodonPos==ONEmerIndex)#positionsWithinCodon[(ONEmerCodonPos[1]%%3)+1]\r\n BackgroundMatrix[ONEmer] <- (BackgroundMatrix[ONEmer] + probNonStopMutations[ONEmerReadingFrameCodon,positionWithinCodon])\r\n }\r\n }\r\n }else{ # Only silent mutations\r\n if( !any(grep(\"N\",ONEmerReadingFrameCodonInputSeq)) & translateCodonToAminoAcid(ONEmerReadingFrameCodonInputSeq)!=\"*\" & translateCodonToAminoAcid(ONEmerReadingFrameCodonInputSeq)==translateCodonToAminoAcid(ONEmerReadingFrameCodon) ){\r\n positionWithinCodon = which(ONEmerCodonPos==ONEmerIndex)\r\n BackgroundMatrix[ONEmer] <- (BackgroundMatrix[ONEmer] + probSMutations[ONEmerReadingFrameCodon,positionWithinCodon])\r\n }\r\n }\r\n }\r\n }\r\n }\r\n \r\n #Mutations\r\n if(stopMutations==1) mutationCount = mutationCount[mutationCount!=\"Stop\"]\r\n if(model==1) mutationCount = mutationCount[mutationCount==\"S\"] \r\n mutationPositions = as.numeric(names(mutationCount))\r\n mutationCount = mutationCount[mutationPositions>2 & mutationPositions<(seqLength-1)]\r\n mutationPositions = mutationPositions[mutationPositions>2 & mutationPositions<(seqLength-1)]\r\n countMutations = 0 \r\n for(mutationPosition in mutationPositions){\r\n ONEmerIndex = mutationPosition\r\n ONEmer = ONEmerSeq[ONEmerIndex]\r\n GLONEmer = ONEmerGL[ONEmerIndex]\r\n ONEmerCodonPos = getCodonPos(ONEmerIndex)\r\n ONEmerReadingFrameCodon = c2s(ONEmerSeq[ONEmerCodonPos]) \r\n ONEmerReadingFrameCodonGL =c2s(ONEmerGL[ONEmerCodonPos]) \r\n if(!any(grep(\"N\",ONEmer)) & !any(grep(\"N\",GLONEmer))){\r\n if(model==0){\r\n countMutations = countMutations + 1 \r\n MutationMatrix[GLONEmer] <- (MutationMatrix[GLONEmer] + 1)\r\n MutationCountMatrix[GLONEmer] <- (MutationCountMatrix[GLONEmer] + 1) \r\n }else{\r\n if( translateCodonToAminoAcid(ONEmerReadingFrameCodonGL)!=\"*\" ){\r\n countMutations = countMutations + 1\r\n positionWithinCodon = which(ONEmerCodonPos==ONEmerIndex)\r\n glNuc = substr(ONEmerReadingFrameCodonGL,positionWithinCodon,positionWithinCodon)\r\n inputNuc = substr(ONEmerReadingFrameCodon,positionWithinCodon,positionWithinCodon)\r\n MutationMatrix[GLONEmer] <- (MutationMatrix[GLONEmer] + substitution[glNuc,inputNuc])\r\n MutationCountMatrix[GLONEmer] <- (MutationCountMatrix[GLONEmer] + 1) \r\n } \r\n } \r\n } \r\n }\r\n \r\n seqMutability = MutationMatrix/BackgroundMatrix\r\n seqMutability = seqMutability/sum(seqMutability,na.rm=TRUE)\r\n #cat(inputMatrixIndex,\"\\t\",countMutations,\"\\n\")\r\n return(list(\"seqMutability\" = seqMutability,\"numbMutations\" = countMutations,\"seqMutabilityCount\" = MutationCountMatrix, \"BackgroundMatrix\"=BackgroundMatrix)) \r\n# tmp<-list(\"seqMutability\" = seqMutability,\"numbMutations\" = countMutations,\"seqMutabilityCount\" = MutationCountMatrix)\r\n } \r\n }\r\n \r\n################\r\n# $Id: trim.R 989 2006-10-29 15:28:26Z ggorjan $\r\n\r\ntrim <- function(s, recode.factor=TRUE, ...)\r\n UseMethod(\"trim\", s)\r\n\r\ntrim.default <- function(s, recode.factor=TRUE, ...)\r\n s\r\n\r\ntrim.character <- function(s, recode.factor=TRUE, ...)\r\n{\r\n s <- sub(pattern=\"^ +\", replacement=\"\", x=s)\r\n s <- sub(pattern=\" +$\", replacement=\"\", x=s)\r\n s\r\n}\r\n\r\ntrim.factor <- function(s, recode.factor=TRUE, ...)\r\n{\r\n levels(s) <- trim(levels(s))\r\n if(recode.factor) {\r\n dots <- list(x=s, ...)\r\n if(is.null(dots$sort)) dots$sort <- sort\r\n s <- do.call(what=reorder.factor, args=dots)\r\n }\r\n s\r\n}\r\n\r\ntrim.list <- function(s, recode.factor=TRUE, ...)\r\n lapply(s, trim, recode.factor=recode.factor, ...)\r\n\r\ntrim.data.frame <- function(s, recode.factor=TRUE, ...)\r\n{\r\n s[] <- trim.list(s, recode.factor=recode.factor, ...)\r\n s\r\n}\r\n#######################################\r\n# Compute the expected for each sequence-germline pair by codon \r\ngetExpectedIndividualByCodon <- function(matInput){ \r\nif( any(grep(\"multicore\",search())) ){ \r\n facGL <- factor(matInput[,2])\r\n facLevels = levels(facGL)\r\n LisGLs_MutabilityU = mclapply(1:length(facLevels), function(x){\r\n computeMutabilities(facLevels[x])\r\n })\r\n facIndex = match(facGL,facLevels)\r\n \r\n LisGLs_Mutability = mclapply(1:nrow(matInput), function(x){\r\n cInput = rep(NA,nchar(matInput[x,1]))\r\n cInput[s2c(matInput[x,1])!=\"N\"] = 1\r\n LisGLs_MutabilityU[[facIndex[x]]] * cInput \r\n })\r\n \r\n LisGLs_Targeting = mclapply(1:dim(matInput)[1], function(x){\r\n computeTargeting(matInput[x,2],LisGLs_Mutability[[x]])\r\n })\r\n \r\n LisGLs_MutationTypes = mclapply(1:length(matInput[,2]),function(x){\r\n #print(x)\r\n computeMutationTypes(matInput[x,2])\r\n })\r\n \r\n LisGLs_R_Exp = mclapply(1:nrow(matInput), function(x){\r\n Exp_R <- rollapply(as.zoo(1:readEnd),width=3,by=3,\r\n function(codonNucs){ \r\n RPos = which(LisGLs_MutationTypes[[x]][,codonNucs]==\"R\") \r\n sum( LisGLs_Targeting[[x]][,codonNucs][RPos], na.rm=T ) \r\n }\r\n ) \r\n })\r\n \r\n LisGLs_S_Exp = mclapply(1:nrow(matInput), function(x){\r\n Exp_S <- rollapply(as.zoo(1:readEnd),width=3,by=3,\r\n function(codonNucs){ \r\n SPos = which(LisGLs_MutationTypes[[x]][,codonNucs]==\"S\") \r\n sum( LisGLs_Targeting[[x]][,codonNucs][SPos], na.rm=T )\r\n }\r\n ) \r\n }) \r\n \r\n Exp_R = matrix(unlist(LisGLs_R_Exp),nrow=nrow(matInput),ncol=readEnd/3,T) \r\n Exp_S = matrix(unlist(LisGLs_S_Exp),nrow=nrow(matInput),ncol=readEnd/3,T) \r\n return( list( \"Expected_R\"=Exp_R, \"Expected_S\"=Exp_S) )\r\n }else{\r\n facGL <- factor(matInput[,2])\r\n facLevels = levels(facGL)\r\n LisGLs_MutabilityU = lapply(1:length(facLevels), function(x){\r\n computeMutabilities(facLevels[x])\r\n })\r\n facIndex = match(facGL,facLevels)\r\n \r\n LisGLs_Mutability = lapply(1:nrow(matInput), function(x){\r\n cInput = rep(NA,nchar(matInput[x,1]))\r\n cInput[s2c(matInput[x,1])!=\"N\"] = 1\r\n LisGLs_MutabilityU[[facIndex[x]]] * cInput \r\n })\r\n \r\n LisGLs_Targeting = lapply(1:dim(matInput)[1], function(x){\r\n computeTargeting(matInput[x,2],LisGLs_Mutability[[x]])\r\n })\r\n \r\n LisGLs_MutationTypes = lapply(1:length(matInput[,2]),function(x){\r\n #print(x)\r\n computeMutationTypes(matInput[x,2])\r\n })\r\n \r\n LisGLs_R_Exp = lapply(1:nrow(matInput), function(x){\r\n Exp_R <- rollapply(as.zoo(1:readEnd),width=3,by=3,\r\n function(codonNucs){ \r\n RPos = which(LisGLs_MutationTypes[[x]][,codonNucs]==\"R\") \r\n sum( LisGLs_Targeting[[x]][,codonNucs][RPos], na.rm=T ) \r\n }\r\n ) \r\n })\r\n \r\n LisGLs_S_Exp = lapply(1:nrow(matInput), function(x){\r\n Exp_S <- rollapply(as.zoo(1:readEnd),width=3,by=3,\r\n function(codonNucs){ \r\n SPos = which(LisGLs_MutationTypes[[x]][,codonNucs]==\"S\") \r\n sum( LisGLs_Targeting[[x]][,codonNucs][SPos], na.rm=T )\r\n }\r\n ) \r\n }) \r\n \r\n Exp_R = matrix(unlist(LisGLs_R_Exp),nrow=nrow(matInput),ncol=readEnd/3,T) \r\n Exp_S = matrix(unlist(LisGLs_S_Exp),nrow=nrow(matInput),ncol=readEnd/3,T) \r\n return( list( \"Expected_R\"=Exp_R, \"Expected_S\"=Exp_S) ) \r\n }\r\n}\r\n\r\n# getObservedMutationsByCodon <- function(listMutations){\r\n# numbSeqs <- length(listMutations) \r\n# obsMu_R <- matrix(0,nrow=numbSeqs,ncol=readEnd/3,dimnames=list(c(1:numbSeqs),c(1:(readEnd/3))))\r\n# obsMu_S <- obsMu_R\r\n# temp <- mclapply(1:length(listMutations), function(i){\r\n# arrMutations = listMutations[[i]]\r\n# RPos = as.numeric(names(arrMutations)[arrMutations==\"R\"])\r\n# RPos <- sapply(RPos,getCodonNumb) \r\n# if(any(RPos)){\r\n# tabR <- table(RPos)\r\n# obsMu_R[i,as.numeric(names(tabR))] <<- tabR\r\n# } \r\n# \r\n# SPos = as.numeric(names(arrMutations)[arrMutations==\"S\"])\r\n# SPos <- sapply(SPos,getCodonNumb)\r\n# if(any(SPos)){\r\n# tabS <- table(SPos)\r\n# obsMu_S[i,names(tabS)] <<- tabS\r\n# } \r\n# }\r\n# )\r\n# return( list( \"Observed_R\"=obsMu_R, \"Observed_S\"=obsMu_S) ) \r\n# }\r\n\r\ngetObservedMutationsByCodon <- function(listMutations){\r\n numbSeqs <- length(listMutations) \r\n obsMu_R <- matrix(0,nrow=numbSeqs,ncol=readEnd/3,dimnames=list(c(1:numbSeqs),c(1:(readEnd/3))))\r\n obsMu_S <- obsMu_R\r\n temp <- lapply(1:length(listMutations), function(i){\r\n arrMutations = listMutations[[i]]\r\n RPos = as.numeric(names(arrMutations)[arrMutations==\"R\"])\r\n RPos <- sapply(RPos,getCodonNumb) \r\n if(any(RPos)){\r\n tabR <- table(RPos)\r\n obsMu_R[i,as.numeric(names(tabR))] <<- tabR\r\n } \r\n \r\n SPos = as.numeric(names(arrMutations)[arrMutations==\"S\"])\r\n SPos <- sapply(SPos,getCodonNumb)\r\n if(any(SPos)){\r\n tabS <- table(SPos)\r\n obsMu_S[i,names(tabS)] <<- tabS\r\n } \r\n }\r\n )\r\n return( list( \"Observed_R\"=obsMu_R, \"Observed_S\"=obsMu_S) ) \r\n}\r\n\r\n", "meta": {"hexsha": "186e3d212e5a4ff4c1a8a5467fb5a3508f69b28c", "size": 98107, "ext": "r", "lang": "R", "max_stars_repo_path": "HTGTSrep/external_software/baseline/Baseline_Functions_Version1.3.r", "max_stars_repo_name": "Yyx2626/HTGTSrep", "max_stars_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-08T05:12:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:53:03.000Z", "max_issues_repo_path": "HTGTSrep/external_software/baseline/Baseline_Functions_Version1.3.r", "max_issues_repo_name": "Yyx2626/HTGTSrep", "max_issues_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-05T04:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T15:02:37.000Z", "max_forks_repo_path": "HTGTSrep/external_software/baseline/Baseline_Functions_Version1.3.r", "max_forks_repo_name": "Yyx2626/HTGTSrep", "max_forks_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-30T12:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:24:53.000Z", "avg_line_length": 42.916447944, "max_line_length": 1174, "alphanum_fraction": 0.5564128961, "num_tokens": 29959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2179355714609501}} {"text": "#functions used to calculate differentiation between two populations or diversity statistics within populations\n# make sure the output file is already written in format (header):\n# population1\tpopulation2\tstatistic\tchromosome\tstart\tend\tnumber_sites\tnumber_variable_sites\tcalculated_stat\n# e.g., write(c(\"pop1\", \"pop2\", \"stat\", \"chr\", \"start\", \"end\", \"number_sites\", \"number_variable_sites\", \"calculated_stat\"), ncolumns=9, file=outname, sep=\"\\t\")\n\n# input is simplified vcf (entire vcf) and 3-column popmap (ordered the same as the vcf) and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\nheterozygosity <- function(xxx, popmap, outname, filename) {\n\toptions(scipen=999)\n\txxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n\tfor(a in 1:nrow(popmap)) {\n\t\toutput_rep <- c(popmap[a,1], \"none\", \"heterozygosity\", strsplit(filename, \":\")[[1]][1], \n\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]))\n\t\t# select this individual\n\t\ta_rep <- xxx[,a+3]\n\t\t# remove missing genotypes\n\t\ta_rep <- a_rep[a_rep != \"./.\"]\n\t\t# count number of sites\n\t\ta_total <- length(a_rep)\n\t\t# remove phasing information\n\t\ta_rep <- gsub(\"\\\\|\", \"/\", a_rep)\n\t\t# find number of heterozygous sites\n\t\ta_het <- length(a_rep[a_rep == \"0/1\"])\n\t\t# add to output\n\t\toutput_rep <- c(output_rep, a_total, a_het, a_het/a_total)\n\t\twrite(output_rep, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t}\n}\n\n\n# function to determine if a site is only missing data for a population (used across rows of vcf)\n# used in differentiation function\ntotal_missing <- function(xxx) {\n\treturn(length(xxx[xxx != \"./.\"]) > 0)\n}\t\n# function to determine if a site has any missing data (used across rows of vcf)\nany_missing <- function(xxx) {\n\treturn(length(xxx[xxx == \"./.\"]) > 0)\n}\t\t\n# function to determine if a site is polymorphic (to be applied across rows) after removing missing\n# used in differentiation function\npolymorphic_function2 <- function(xxx) {\n\txxx <- xxx[xxx != \"./.\"]\n\treturn(length(unique(xxx)))\n}\t\t\t\n\n# input is two simplified vcfs (subsampled to single population), already filtered for invariant/biallelic SNPs, \n# the names of the populations, and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\n# fst is calculation of Reich et al. 2009\n# fst is the reich et al. 2009 estimator for small sample sizes\n# equation presented nicer in Willing et al. 2012 page 9\n\n\ndifferentiation <- function(xxx1, xxx2, popname1, popname2, outname, filename) {\n\t# remove phasing information\n\tfor(a in 1:ncol(xxx1)) {\n\t\txxx1[,a] <- gsub(\"\\\\|\", \"/\", xxx1[,a])\n\t}\n\tfor(a in 1:ncol(xxx2)) {\n\t\txxx2[,a] <- gsub(\"\\\\|\", \"/\", xxx2[,a])\n\t}\n\t\n\t# remove sites that are completely missing from either population\n\tkeep1 <- apply(xxx1, 1, total_missing)\n\tkeep2 <- apply(xxx2, 1, total_missing)\n\txxx1 <- xxx1[keep1 == TRUE & keep2 == TRUE, ]\n\tif(is.null(dim(xxx1))) { xxx1 <- as.matrix(xxx1) }\n\txxx2 <- xxx2[keep1 == TRUE & keep2 == TRUE, ]\n\tif(is.null(dim(xxx2))) { xxx2 <- as.matrix(xxx2) }\n\t\n\t# count the total number of included genotyped sites at this point\n\tn_sites <- nrow(xxx1)\n\t\n\t# combine the two matrices to find sites that are variant w/in and between the two pops\n\txxx_combined <- cbind(xxx1, xxx2)\n\tvariant_sites <- apply(xxx_combined, 1, polymorphic_function2)\n\t\n\t# keep only variant sites\n\txxx1_variant <- xxx1[variant_sites > 1, ]\n\tif(is.null(dim(xxx1_variant))) { xxx1_variant <- as.matrix(xxx1_variant) }\n\txxx2_variant <- xxx2[variant_sites > 1, ]\n\tif(is.null(dim(xxx2_variant))) { xxx2_variant <- as.matrix(xxx2_variant) }\n\t\n\t# count the number of variant sites\n\tn_variant_sites <- nrow(xxx1_variant)\n\t\n\t# loop for each polymorphic site to calculate dxy\n\tdxy_all <- list()\n\tfor(a in 1:nrow(xxx1_variant)) {\n\t\ta_rep1 <- as.character(xxx1_variant[a,])\n\t\ta_rep2 <- as.character(xxx2_variant[a,])\n\t\t\n\t\t# remove missing\n\t\ta_rep1 <- a_rep1[a_rep1 != \"./.\"]\n\t\ta_rep2 <- a_rep2[a_rep2 != \"./.\"]\n\t\t\n\t\t# measure proportion of reference allele \n\t\ta_ref1 <- (length(a_rep1[a_rep1 == \"0/0\"]) * 2 + length(a_rep1[a_rep1 == \"0/1\"]) * 1) / (length(a_rep1) * 2)\n\t\ta_ref2 <- (length(a_rep2[a_rep2 == \"0/0\"]) * 2 + length(a_rep2[a_rep2 == \"0/1\"]) * 1) / (length(a_rep2) * 2)\n\t\t\n\t\t# calc dxy\n\t\tdxy_all[[a]] <- a_ref1 * (1 - a_ref2) + a_ref2 * (1 - a_ref1)\n\t}\n\tdxy_all <- sum(unlist(dxy_all)) / n_sites\n\t\n\t\n\t# loop for each polymorphic site to calculate fst\n\tnumerator_all <- list()\n\tdenominator_all <- list()\n\tfor(a in 1:nrow(xxx1_variant)) {\n\t\ta_rep1 <- as.character(xxx1_variant[a,])\n\t\ta_rep2 <- as.character(xxx2_variant[a,])\n\t\t\n\t\t# remove missing\n\t\ta_rep1 <- a_rep1[a_rep1 != \"./.\"]\n\t\ta_rep2 <- a_rep2[a_rep2 != \"./.\"]\n\n\t\t# number of individuals per population\n\t\tpop1_ind_count <- length(a_rep1) \n\t\tpop2_ind_count <- length(a_rep2)\n\t\t\n\t\t# non-reference allele counts\n\t\talt_allele_count1 <- (2 * length(a_rep1[a_rep1 == \"1/1\"]) + 1 * length(a_rep1[a_rep1 == \"0/1\"]))\n\t\talt_allele_count2 <- (2 * length(a_rep2[a_rep2 == \"1/1\"]) + 1 * length(a_rep2[a_rep2 == \"0/1\"]))\n\n\t\t# total allele counts\n\t\tall_allele_count1 <- 2 * length(a_rep1)\n\t\tall_allele_count2 <- 2 * length(a_rep2)\n\n\t\t# expected heterozygosity for each population\n\t\texpected_het1 <- (alt_allele_count1 * (all_allele_count1 - alt_allele_count1)) / \n\t\t\t(all_allele_count1 * (all_allele_count1 - 1))\n\t\texpected_het2 <- (alt_allele_count2 * (all_allele_count2 - alt_allele_count2)) / \n\t\t\t(all_allele_count2 * (all_allele_count2 - 1))\n\n\t\t# find the fst numerator and denominator values for this snp (they all get summed and divided for \n\t\t# the final estimate)\n\t\tnumerator_all[[a]] <- (alt_allele_count1 / (2 * pop1_ind_count) - \n\t\t\talt_allele_count2 / (2 * pop2_ind_count))^2 - (expected_het1 / (2 * pop1_ind_count)) - \n\t\t\t(expected_het2 / (2 * pop2_ind_count))\n\t\tdenominator_all[[a]] <- numerator_all[[a]] + expected_het1 + expected_het2\t\t\n\t}\n\t# calculate total fst for this window\n\tfst_all <- sum(unlist(numerator_all)) / sum(unlist(denominator_all))\n\t\n\t# write to output for dxy and fst\n\toutput_rep1 <- c(popname1, popname2, \"Dxy\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_variant_sites, dxy_all)\n\toutput_rep2 <- c(popname1, popname2, \"Fst\", strsplit(filename, \":\")[[1]][1], \n\t\t\t\tas.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n\t\t\t\tas.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]),\n\t\t\t\tn_sites, n_variant_sites, fst_all)\n\twrite(output_rep1, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\twrite(output_rep2, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n\t\n}\n\n\n\t\t", "meta": {"hexsha": "2f57b1b8a06180717b63a17216a14e70cb2b4741", "size": 6876, "ext": "r", "lang": "R", "max_stars_repo_path": "02_trim_process_genotype/07_calc_windows/window_stat_calculations.r", "max_stars_repo_name": "jdmanthey/ethiopia_grv_birds", "max_stars_repo_head_hexsha": "aa92cb4cd223c5142466eab64c2ca69da8f032db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_trim_process_genotype/07_calc_windows/window_stat_calculations.r", "max_issues_repo_name": "jdmanthey/ethiopia_grv_birds", "max_issues_repo_head_hexsha": "aa92cb4cd223c5142466eab64c2ca69da8f032db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_trim_process_genotype/07_calc_windows/window_stat_calculations.r", "max_forks_repo_name": "jdmanthey/ethiopia_grv_birds", "max_forks_repo_head_hexsha": "aa92cb4cd223c5142466eab64c2ca69da8f032db", "max_forks_repo_licenses": ["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.6727272727, "max_line_length": 159, "alphanum_fraction": 0.6799011053, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21752196561616224}} {"text": "## Created on Monday, November 2, 2020 at 10:38pm EST by WeekendEditor on WeekendEditorMachine.\n## Copyright (c) 2020, SomeWeekendReading. All rights reserved. As if you care.\n\n##\n## Research question: Does the MWRA's metagenomic measurement of SARS-COV-2 RNA in\n## wastewater predict later hospitalization or death rates or positive test rates?\n##\n## Hypotheses: hospitalization & death rates might work; positive test rates probably\n## won't, due to changes in test availability, test type, and testing policy.\n##\n## Data sources (2020-Nov-02):\n## - Mass COVID hospitalization/death rates from:\n## https://covidtracking.com/data/state/massachusetts\n## - MWRA metagenomics painfully extracted, almost by hand, from a PDF at:\n## http://www.mwra.com/biobot/biobotdata.htm\n##\n## Did not consider test positivity rates, since testing has changed from basically unavailable\n## to somewhat available, and the reporting has been spotty enough to make the numbers useless.\n##\n## *** NB: on 2020-09-02 and -07, in hosp/death dataset, hospIncr is NEGATIVE! This is in\n## the orignal data, where hospitalizedIncrease on 2020-09-02 is -91, for some reason.\n##\n\ntoolsDir <- \"../../tools\" # Various tools available from author\nsource(file.path(toolsDir, \"pipeline-tools.r\")) # Pipeline construction tools\nsource(file.path(toolsDir, \"graphics-tools.r\")) # Various graphics hacks\n\nlibrary(\"lubridate\") # For round_date()\nlibrary(\"zoo\") # For rollmean()\n\ndoit <- function(## Inputs\n dataDir = \"./data\",\n mwraDataFile = \"MWRAData20201027-NSdata.tsv\",\n covidDataFile = \"massachusetts-history.csv\",\n covidDataEmpties = c(\"inIcuCumulative\",\n\n \"negativeTestsAntibody\", \"negativeTestsPeopleAntibody\",\n \"negativeTestsViral\",\n\n \"onVentilatorCumulative\",\n\n \"positiveTestsAntibody\", \"positiveTestsAntigen\",\n \"positiveTestsPeopleAntibody\", \"positiveTestsPeopleAntigen\",\n\n \"totalTestEncountersViral\", \"totalTestsAntibody\",\n \"totalTestsAntigen\"),\n waveDate = as.Date(\"2020-07-01\", format = \"%Y-%m-%d\"),\n\n ## Outputs\n resultsDir = \"./results\",\n txFile = \"mwra-covid-transcript.txt\",\n jointDataFile = \"mwra-covid-joint-data.tsv\",\n nsPlotFile = \"plot-north-south.png\",\n medPlotFile = \"plot-med-loads-vs-RNA.png\") {\n\n reportStructure <- function(df) { # Report structure of a dataframe\n cat(sprintf(\"\\n - Structure:\\n o %d rows\\n o %d columns: %s\",\n nrow(df), ncol(df), paste(colnames(df), collapse = \", \")))\n } # Basically shape + column names\n\n loadMWRAData <- function(dataDir, mwraDataFile) { # Load the MWRA's metagenomic data\n f <- file.path(dataDir, mwraDataFile) # Painfully hand-extracted from a PDF\n cat(sprintf(\"* Reading MWRA wastewater RNA data from %s\", f))\n df <- subset(transform(read.table(f, sep = \"\\t\", header = TRUE, comment.char = \"#\"),\n Sample.Date = as.Date(as.character(Sample.Date), format = \"%m/%d/%Y\")),\n select = c(Sample.Date, Southern.7.sample.avg, Northern.7.sample.avg))\n colnames(df)[1:3] <- c(\"Date\", \"South.7\", \"North.7\")\n\n reportStructure(df) # See what fish we caught\n df # Return the data\n } #\n\n loadCOVIDData <- function(dataDir, covidDataFile, covidDataEmpties) {\n f <- file.path(dataDir, covidDataFile) #\n cat(sprintf(\"\\n* Reading Mass COVID data from %s\", f))\n df <- transform(read.table(f, sep = \",\", header = TRUE),\n date = as.Date(as.character(date), format = \"%Y-%m-%d\"))\n sapply(covidDataEmpties, function(emptyCol) { stopifnot(all(is.na(df[, emptyCol]))) })\n df <- subset(df, select = c(date, deathIncrease, hospitalizedIncrease))\n df <- df[order(df$\"date\"), ] # Sort by date, shorten column names\n colnames(df)[1:3] <- c(\"Date\", \"deadIncr\", \"hospIncr\")\n\n weekMeanNDec <- function(x, n) { round(rollmean(x, 7, NA, align = \"right\"), digits = n) }\n stopifnot(all(diff(df$\"Date\") == 1)) # Check no missing dates\n df <- subset(transform(df, # 7 day rolling mean, exploit no missing dates\n deadIncr.7 = weekMeanNDec(deadIncr, 1),\n hospIncr.7 = weekMeanNDec(hospIncr, 1)),\n select = -c(deadIncr, hospIncr)) #\n\n reportStructure(df) # See what we caught\n df # Return the data\n } #\n\n makeJointData <- function(mwraData, covidData, resultsDir, jointDataFile) {\n cat(\"\\n* Constructing inner join on dates\") # Combine RNA and medical load data\n df <- merge(mwraData, covidData, by = \"Date\", all = FALSE)\n df <- df[order(df$\"Date\"), ] # Sort it by date\n df <- subset(df, subset = complete.cases(df)) # Drop initial 6 rows (no 7 day average)\n cat(\"\\n - Complete cases only, to drop the initial 6 rows w/o 7 day trailing means\")\n ## Combine North & South districts by mean to get overall RNA measure\n df <- transform(df, RNA.7 = round((North.7 + South.7) / 2.0, digits = 1))\n df <- df[, c(\"Date\", \"North.7\", \"South.7\", \"RNA.7\", \"hospIncr.7\", \"deadIncr.7\")]\n\n f <- file.path(resultsDir, jointDataFile) # Save it away for peer review\n saveDataframe(df, f) #\n cat(sprintf(\"\\n - Saved to %s\", f)) #\n\n reportStructure(df) # See what we caught\n df # Return the data\n } #\n\n plotNorthSouth <- function(jointData, resultsDir, nsPlotFile) {\n dateRange <- c(floor_date(min(jointData$\"Date\"), \"month\"),\n ceiling_date(max(jointData$\"Date\"), \"month\"))\n f <- file.path(resultsDir, nsPlotFile) #\n withPNG(f, 850, 400, FALSE, function() { #\n withPars(function() { #\n rnaCols <- c(\"blue\", \"gray\") #\n rnaNames <- c(\"North\", \"South\") #\n matplot(x = jointData$\"Date\", # North & south RNA vs time\n y = subset(jointData, select = sapply(rnaNames, function(c) { sprintf(\"%s.7\", c) })),\n type = \"p\", pch = 21, col = \"black\", bg = rnaCols, log = \"y\", cex = 1.5,\n xaxt = \"n\", xlab = NA, ylab = \"RNA (wk avg, log scale)\",\n main = \"RNA Levels vs Time\") #\n axis.Date(1, x = dateRange, format = \"%Y-%m-%d\")\n legend(\"topright\", bg = \"antiquewhite\", inset = 0.01,\n pch = 21, pt.bg = rnaCols, pt.cex = 2, legend = rnaNames)\n\n scatterplotWithDensities(xs = jointData$\"South.7\", ys = jointData$\"North.7\",\n bgs = \"steelblue\", cex = 1.5, log = \"xy\",\n regressionColor = NULL, # doesn't work on log scale\n xlab = \"South RNA (log scale)\", ylab = \"North RNA (log scale)\",\n main = as.expression(bquote(bold(paste(\n \"RNA Correlation: \",\n bolditalic(R)^2 == .(\n sprintf(\"%.0f\", #\n 100.0 * cor(jointData$\"North.7\",\n jointData$\"South.7\")^2)),\n \"%\"))))) #\n\n title(main = \"MWRA Wastewater RNA: North vs South\", outer = TRUE)\n\n }, pty = \"m\", # Maximal plotting area\n bg = \"transparent\", # Transparent background\n mar = c(7, 4, 2, 1), # Margins (e.g., to hold date labels)\n mgp = c(2.5, 0.5, 0), # Axis title, label, tick\n mfrow = c(1, 2), # 1x2 array of plots\n oma = c(0, 0, 1, 0), # Make room at top for overall title\n ps = 16, # Larget type size for file capture\n las = 2) # Labels perpendicular to axes\n }) # End file capture\n cat(sprintf(\"* Plot of north vs south RNA to %s\", f))\n TRUE # Flag that it was done\n } #\n\n plotMedLoadsVsRNA <- function(jointData, waveDate, resultsDir, medPlotFile) {\n dateRange <- c(floor_date(min(jointData$\"Date\"), \"month\"),\n ceiling_date(max(jointData$\"Date\"), \"month\"))\n f <- file.path(resultsDir, medPlotFile) #\n withPNG(f, 850, 400, FALSE, function() { #\n withPars(function() { #\n medNames <- c(\"hospIncr.7\", \"deadIncr.7\") #\n medCols <- c(\"green\", \"red\") #\n matplot(x = jointData$\"Date\", # Mean RNA, hospitalizations, deaths vs time\n y = subset(jointData, select = c(\"RNA.7\", medNames)),\n type = \"p\", pch = 21, col = \"black\", bg = c(\"steelblue\", medCols), cex = 1.5,\n xaxt = \"n\", xlab = NA, ylab = \"Medical Loads & RNA\",\n main = \"Medical Loads & RNA vs Time\") #\n axis.Date(1, x = dateRange, format = \"%Y-%m-%d\")\n abline(v = waveDate, lty = \"dashed\", col = \"black\")\n text(x = c(as.Date(\"2020-06-01\", format = \"%Y-%m-%d\"),\n as.Date(\"2020-08-01\", format = \"%Y-%m-%d\")),\n y = c(200, 200), #\n adj = c(0.5, 0.5), #\n labels = c(\"Wave 1\", \"Wave 2\")) #\n text(x = c(as.Date(\"2020-06-01\", format = \"%Y-%m-%d\"),\n as.Date(\"2020-09-01\", format = \"%Y-%m-%d\")),\n y = c(175, 175), #\n adj = c(0.5, 0.5), #\n labels = c(\"Tracks RNA\", \"Does NOT Track RNA\"))\n legend(\"topright\", bg = \"antiquewhite\", inset = 0.01,\n pch = 21, pt.bg = c(\"steelblue\", medCols), pt.cex = 2,\n legend = c(\"RNA\", \"Hospitalized\", \"Dead\"))\n\n wave1Data <- subset(jointData, subset = Date <= waveDate)\n wave2Data <- subset(jointData, subset = Date > waveDate)\n matplot(x = wave1Data$\"RNA.7\", # Hospitalizations, deaths, vs mean RNA\n y = subset(wave1Data, select = medNames),\n pch = 21, type = \"p\", col = \"black\", bg = medCols, cex = 1.5,\n xlim = range(jointData$\"RNA.7\"), #\n ylim = range(subset(jointData, select = medNames)),\n xlab = \"RNA (wk avg)\", ylab = \"Medical Load (wk avg)\",\n main = \"Medical Loads vs RNA\") #\n points(x = wave2Data$\"RNA.7\", y = wave2Data$\"hospIncr.7\",\n pch = 22, type = \"p\", col = \"black\", bg = \"lightgreen\", cex = 1.5)\n points(x = wave2Data$\"RNA.7\", y = wave2Data$\"deadIncr.7\",\n pch = 22, type = \"p\", col = \"black\", bg = \"pink\", cex = 1.5)\n text(x = 50, y = 150, labels = \"Wave 1: Tracks RNA\", srt = 45)\n text(x = 160, y = 0, labels = \"Wave 2: Does NOT Track RNA\")\n legend(\"topleft\", bg = \"antiquewhite\", inset = 0.01, ncol = 2, pt.cex = 2,\n pch = c(21, 21, 22, 22),#\n pt.bg = c(medCols, \"lightgreen\", \"pink\"),\n legend = c(\"Wave 1 Hospitalized\", \"Wave 1 Dead\",\n \"Wave 2 Hospitalized\", \"Wave 2 Dead\"))\n\n title(main = \"MWRA Wastewater RNA and Medical Loads\", outer = TRUE)\n\n }, pty = \"m\", # Maximal plotting area\n bg = \"transparent\", # Transparent background\n mar = c(7, 4, 2, 1), # Margins (e.g., to hold date labels)\n mgp = c(2.5, 0.5, 0), # Axis title, label, tick\n mfrow = c(1, 2), # 1x2 array of plots\n oma = c(0, 0, 1, 0), # Make room at top for overall title\n ps = 16, # Larget type size for file capture\n las = 2) # Labels perpendicular to axes\n }) # End file capture\n cat(sprintf(\"\\n* Plot of medical loads vs RNA to %s\", f))\n TRUE # Flag that it was done\n } #\n\n showWaveCorrelations <- function(jointData, waveDate) {\n\n cat(\"\\n* Correlations, using all data:\\n\") # Correlation matrix for all times\n print(round(cor(subset(jointData, select = -Date)), digits = 2))\n\n cat(\"\\n* Correlations, first wave data:\\n\") # Correlation matrix for first wave only\n print(round(cor(subset(jointData, subset = Date <= waveDate, select = -Date)), digits = 2))\n\n cat(\"\\n* Correlations, second wave data:\\n\") # Correlation matrix for second wave only\n print(round(cor(subset(jointData, subset = Date > waveDate, select = -Date)), digits = 2))\n } #\n\n withTranscript(dataDir, resultsDir, txFile, \"MWRA COVID Analysis\", function() {\n\n heraldPhase(\"Archival\") # For peer review\n archiveAnalysisScript(resultsDir, \"./2020-11-04-wastewater-coronavirus-rna-vs-medical-loads-analysis.r\")\n\n heraldPhase(\"Loading datasets and constructing joint dataset\")\n maybeAssign(\"mwraData\", function() { loadMWRAData(dataDir, mwraDataFile) })\n maybeAssign(\"covidData\", function() { loadCOVIDData(dataDir, covidDataFile, covidDataEmpties) })\n maybeAssign(\"jointData\", function() { # Assemble via inner join on dates\n makeJointData(mwraData, covidData, resultsDir, jointDataFile)\n }) #\n cat(\"\\n\") #\n ## *** NB: missing dates, due to missing dates in MWRA RNA data:\n ## > diff(jointData$\"Date\")\n\n heraldPhase(\"Exploratory plots\") # See the general shape of the data\n maybeAssign(\"nsPlotDone\", function() { plotNorthSouth(jointData, resultsDir, nsPlotFile) })\n maybeAssign(\"medPlotDone\", function() { #\n plotMedLoadsVsRNA(jointData, waveDate, resultsDir, medPlotFile)\n }) #\n showWaveCorrelations(jointData, waveDate) # Look @ change in correlations?!\n cat(\"\\n\") #\n\n ## We would do something like this, except the data is clearly telling us we don't understand it!\n ## *** cross-correlation with time lags up to 21 days\n ## *** regressions\n ## *** time series MA(q) models\n\n }) # End of transcript capture\n} #\n", "meta": {"hexsha": "85a5511b4be9923e2f66f384719db2f6db191f93", "size": 15924, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2020-11-04-wastewater-coronavirus-rna-vs-medical-loads-analysis.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/2020-11-04-wastewater-coronavirus-rna-vs-medical-loads-analysis.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-10-14T16:09:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T21:01:06.000Z", "max_forks_repo_path": "assets/2020-11-04-wastewater-coronavirus-rna-vs-medical-loads-analysis.r", "max_forks_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_forks_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.5475285171, "max_line_length": 108, "alphanum_fraction": 0.4867495604, "num_tokens": 3884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21588846511546625}} {"text": "#### Functions for cancer cell fraction estimation #####\n\nidentify.mut.copy.number.ascat <- function(x, sub.mat.mut, sub.mat.copy) {\n mut <- sub.mat.mut[x, , drop = FALSE]\n ww <- which(as.numeric(sub.mat.copy$Chr) == as.numeric(mut$Chr)\n & as.numeric(sub.mat.copy$Start) <= as.numeric(mut$Start_position)\n & as.numeric(sub.mat.copy$End) >= as.numeric(mut$Start_position))\n copy <- sub.mat.copy[ww, , drop = FALSE]\n\n\n mutation_id <- paste(mut$Patient, mut$Chr, mut$Start_position, mut$Reference, sep = \":\")\n ref_counts <- mut$Ref_freq\n var_counts <- mut$Variant_freq\n normal_cn <- 2\n patient <- mut$Patient\n Reference_Base <- mut$Reference\n Alternate_Base <- mut$Alternate\n\n if (nrow(copy) != 1) {\n minor_cn <- NA\n major_cn <- NA\n output <- data.frame(mutation_id,\n ref_counts,\n var_counts,\n normal_cn,\n minor_cn,\n major_cn,\n patient,\n Reference_Base,\n Alternate_Base,\n stringsAsFactors = FALSE\n )\n return(output)\n }\n\n minor_cn <- min(c(copy$nA, copy$nB))\n major_cn <- max(c(copy$nA, copy$nB))\n\n\n output <- data.frame(mutation_id,\n ref_counts,\n var_counts,\n normal_cn,\n minor_cn,\n major_cn,\n patient,\n Reference_Base,\n Alternate_Base,\n stringsAsFactors = FALSE\n )\n\n return(output)\n}\n\n#######\n\n# earlyORlate <- function(patient, complete.mutation.table, purity) {\n# \n# \n# # First of all load the needed packaged\n# #\n# suppressPackageStartupMessages(library(sequenza))\n# suppressPackageStartupMessages(library(bootstrap))\n# suppressPackageStartupMessages(library(boot))\n# \n# # Get the table ready, with only information for specific patient\n# mut.table <- complete.mutation.table[complete.mutation.table$patient == patient, ]\n# \n# # and all the other stuff\n# cellularity <- as.numeric(purity)\n# major.cn <- unlist(mut.table$major_cn)\n# abs.cn <- unlist(mut.table$minor_cn) + unlist(mut.table$major_cn)\n# depth.t <- unlist(mut.table$ref_counts) + unlist(mut.table$var_counts)\n# max.cn <- max(abs.cn)\n# VAF <- unlist(mut.table$var_counts) / (unlist(mut.table$var_counts) + unlist(mut.table$ref_counts))\n# \n# # Estimate theoretical VAFs for each type of copy number\n# types <- types.matrix(CNt.min = 1, CNt.max = max.cn, CNn = 2)\n# types.xy <- types.matrix(CNt.min = 1, CNt.max = max.cn, CNn = 1)\n# types <- rbind(types, types.xy)\n# types <- types[types$Mt >= 1, ]\n# types$F <- 0\n# for (i in 1:nrow(types)) {\n# types$F[i] <- theoretical.mufreq(\n# cellularity = cellularity,\n# CNn = types$CNn[i], CNt = types$CNt[i],\n# Mt = types$Mt[i]\n# )\n# }\n# \n# # Let's create some functions that can estimate whether early or late\n# \n# get.Mt <- function(F, depth.t, types, CNt, CNn, Mt) {\n# types <- types[types$CNn == CNn, ]\n# l <- sequenza:::mufreq.dpois(\n# mufreq = F, types$F[types$CNt == CNt & types$Mt <= Mt],\n# depth.t = depth.t\n# )\n# l <- l / sum(l)\n# L <- data.frame(l = l, Mt = types$Mt[types$CNt == CNt & types$Mt <= Mt])\n# }\n# \n# get.conf <- function(F, depth.t) {\n# conf.int <- cbind(\n# prop.test(round(F * depth.t, 0), depth.t)$conf[1],\n# prop.test(round(F * depth.t, 0), depth.t)$conf[2]\n# )\n# return(conf.int)\n# }\n# \n# bootstrap.cf <- function(Vaf, cellularity, CNn, CNt, depth.t) {\n# # print(i)\n# if (Vaf == 1) {\n# conf.int <- cbind(\n# prop.test(round(Vaf * depth.t, 0), depth.t)$conf[1],\n# prop.test(round(Vaf * depth.t, 0), depth.t)$conf[2]\n# )\n# \n# lower <- get.mut.mult(Vaf = conf.int[1], cellularity = cellularity, CNt = CNt, CNn = CNn)\n# higher <- get.mut.mult(Vaf = conf.int[2], cellularity = cellularity, CNt = CNt, CNn = CNn)\n# conf.int <- cbind(lower, higher)\n# return(conf.int)\n# }\n# \n# x <- c(rep(1, round(Vaf * depth.t, 0)), rep(0, (depth.t - round(Vaf * depth.t, 0))))\n# theta <- function(x, i) {\n# data <- x[i]\n# est <- sum(data) / length(data)\n# mut.multi <- (est * 1 / cellularity) * ((cellularity * CNt) + CNn * (1 - cellularity))\n# return(mut.multi)\n# }\n# \n# bt.res <- boot(x, theta, R = 1000)\n# bt.ci <- boot.ci(bt.res, type = \"norm\")\n# out <- c(bt.ci$normal[2], bt.ci$normal[3])\n# \n# return(out)\n# }\n# \n# \n# get.mut.mult <- function(CNt, Vaf, cellularity, CNn) {\n# return((Vaf * 1 / cellularity) * ((cellularity * CNt) + CNn * (1 - cellularity)))\n# }\n# \n# \n# get.cancer.cell.fraction <- function(Max.Likelihood, mut.mult) {\n# predicted.Mtn <- Max.Likelihood[, \"Mt\"]\n# ccf <- mut.mult / predicted.Mtn\n# return(ccf)\n# }\n# \n# absolute.cancer.cell.fraction <- function(n.alt, depth, purity, local.copy.number) {\n# f.function <- function(c, purity, local.copy.number) {\n# return((purity * c) / (2 * (1 - purity) + purity * local.copy.number))\n# }\n# x <- dbinom(n.alt, depth, prob = sapply(seq(0.01, 1, length.out = 100), f.function, purity, local.copy.number))\n# if (min(x) == 0) {\n# x[length(x)] <- 1\n# }\n# \n# names(x) <- seq(0.01, 1, length.out = 100)\n# sub.cint <- function(x, prob = 0.95, n.alt, depth) {\n# xnorm <- x / sum(x)\n# xsort <- sort(xnorm, decreasing = TRUE)\n# xcumLik <- cumsum(xsort)\n# n <- sum(xcumLik < prob) + 1\n# LikThresh <- xsort[n]\n# cint <- x[xnorm >= LikThresh]\n# all <- as.numeric(names(x))\n# cellu <- as.numeric(names(cint))\n# l.t <- cellu[1]\n# r.t <- cellu[length(cellu)]\n# m <- cellu[which.max(cint)]\n# \n# prob.subclonal <- sum(xnorm[1:90]) # 1-prop.test(n.alt,depth,p=f.function(1,purity,local.copy.number),alternative='less')$p.val\n# prob.clonal <- sum(xnorm[91:100]) # 1-prop.test(n.alt,depth,p=f.function(1,purity,local.copy.number),alternative='greater')$p.val\n# \n# data.frame(left = l.t, est = m, right = r.t, prob.subclonal = prob.subclonal, prob.clonal = prob.clonal)\n# }\n# \n# \n# return(sub.cint(x, n.alt = n.alt, depth = depth))\n# }\n# \n# absolute.cancer.cell.mtcpn <- function(n.alt, depth, purity, local.copy.number, mtcpn) {\n# f.function <- function(c, purity, local.copy.number) {\n# return((purity * c) / (2 * (1 - purity) + purity * local.copy.number))\n# }\n# x <- dbinom(n.alt, depth, prob = sapply(seq(0.01, as.numeric(mtcpn), length.out = (100)), f.function, purity, local.copy.number))\n# if (min(x) == 0) {\n# x[length(x)] <- 1\n# }\n# \n# names(x) <- seq(0.01, 1, length.out = 100)\n# sub.cint <- function(x, prob = 0.95, n.alt, depth) {\n# xnorm <- x / sum(x)\n# xsort <- sort(xnorm, decreasing = TRUE)\n# xcumLik <- cumsum(xsort)\n# n <- sum(xcumLik < prob) + 1\n# LikThresh <- xsort[n]\n# cint <- x[xnorm >= LikThresh]\n# all <- as.numeric(names(x))\n# cellu <- as.numeric(names(cint))\n# l.t <- cellu[1]\n# r.t <- cellu[length(cellu)]\n# m <- cellu[which.max(cint)]\n# \n# prob.subclonal <- sum(xnorm[1:90]) # 1-prop.test(n.alt,depth,p=f.function(1,purity,local.copy.number),alternative='less')$p.val\n# prob.clonal <- sum(xnorm[91:100]) # 1-prop.test(n.alt,depth,p=f.function(1,purity,local.copy.number),alternative='greater')$p.val\n# \n# data.frame(left = l.t, est = m, right = r.t, prob.subclonal = prob.subclonal, prob.clonal = prob.clonal)\n# }\n# \n# \n# return(sub.cint(x, n.alt = n.alt, depth = depth))\n# }\n# # add an absolute estimate of the cancer cell fraction\n# \n# get.all.mut.info <- function(i) {\n# # print(i)\n# # First estimate the VAF confidence intervals\n# obs.VAF <- VAF[i]\n# mut.conf.0.05 <- get.conf(F = VAF[i], depth.t = depth.t[i])[1]\n# mut.conf.0.95 <- get.conf(F = VAF[i], depth.t = depth.t[i])[2]\n# \n# if (abs.cn[i] == 0) {\n# output <- cbind(obs.VAF,\n# mut.conf.0.05,\n# mut.conf.0.95,\n# mut.multi = NA,\n# mut.multi.0.05 = NA,\n# mut.multi.bstr.0.05 = NA,\n# mut.multi.0.95 = NA,\n# mut.multi.bstr.0.95 = NA,\n# Exp.Cpn = NA,\n# Exp.Cpn.Likelihood = NA,\n# ccf = NA,\n# ccf.0.05 = NA,\n# ccf.btstr.0.05 = NA,\n# ccf.0.95 = NA,\n# ccf.btstr.0.95 = NA,\n# absolute.ccf = NA,\n# absolute.ccf.0.05 = NA,\n# absoltue.ccf.0.95 = NA,\n# prob.subclonal = NA,\n# prob.clonal = NA,\n# timing = \"Not.Poss\"\n# )\n# return(output)\n# }\n# \n# # Next estimate the likelihood relating to which copy number the mutation has\n# L <- get.Mt(\n# F = VAF[i],\n# depth.t = depth.t[i], CNt = abs.cn[i],\n# types = types, CNn = unlist(mut.table$normal_cn[i]),\n# Mt = major.cn[i]\n# )\n# \n# # Next determine the mut multiplicity\n# mut.multi <- get.mut.mult(CNt = abs.cn[i], Vaf = VAF[i], cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n# mut.multi.0.05 <- get.mut.mult(CNt = abs.cn[i], Vaf = mut.conf.0.05, cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n# mut.multi.0.95 <- get.mut.mult(CNt = abs.cn[i], Vaf = mut.conf.0.95, cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n# mut.multi.bstr <- bootstrap.cf(Vaf = VAF[i], cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]), CNt = abs.cn[i], depth.t = depth.t[i])\n# mut.multi.bstr.0.05 <- mut.multi.bstr[1]\n# mut.multi.bstr.0.95 <- mut.multi.bstr[2]\n# \n# if (is.na(L$l)[1]) {\n# output <- cbind(obs.VAF,\n# mut.conf.0.05,\n# mut.conf.0.95,\n# mut.multi,\n# mut.multi.0.05,\n# mut.multi.bstr.0.05,\n# mut.multi.0.95,\n# mut.multi.bstr.0.95,\n# Exp.Cpn = NA,\n# Exp.Cpn.Likelihood = NA,\n# ccf = NA,\n# ccf.0.05 = NA,\n# ccf.btstr.0.05 = NA,\n# ccf.0.95 = NA,\n# ccf.btstr.0.95 = NA,\n# absolute.ccf = NA,\n# absolute.ccf.0.05 = NA,\n# absoltue.ccf.0.95 = NA,\n# prob.subclonal = NA,\n# prob.clonal = NA,\n# timing = \"Not.Poss\"\n# )\n# return(output)\n# }\n# \n# # Now determine which likelihood should be used\n# Max.Likelihood <- L[which.max(L$l), ]\n# absolute.calc <- absolute.cancer.cell.fraction(n.alt = unlist(mut.table$var_counts)[i], depth = depth.t[i], purity = cellularity, local.copy.number = abs.cn[i])\n# absolute.ccf.0.05 <- absolute.calc[1]\n# absolute.ccf.0.95 <- absolute.calc[3]\n# absolute.ccf <- absolute.calc[2]\n# prob.subclonal <- absolute.calc[4]\n# prob.clonal <- absolute.calc[5]\n# \n# \n# \n# \n# # Next determine the cancer cell fraction\n# ccf <- get.cancer.cell.fraction(Max.Likelihood, mut.multi)\n# ccf.0.05 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.0.05)\n# ccf.btstr.0.05 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.bstr.0.05)\n# \n# ccf.0.95 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.0.95)\n# ccf.btstr.0.95 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.bstr.0.95)\n# \n# # Next determine the late cancer cell fraction\n# # Make sure you also output the theoretical Copy (i.e. what it's closest to using maximum likelihood)\n# expected.copy <- Max.Likelihood[2]\n# \n# \n# # Finally also make a suggestion about whether the mutation is early late or not possible to tell\n# \n# \n# if (Max.Likelihood$Mt > 1) {\n# timing <- \"early\"\n# }\n# \n# if (Max.Likelihood$Mt <= 1) {\n# timing <- \"late\"\n# }\n# \n# if (major.cn[i] <= 1) {\n# timing <- \"Not.Poss\"\n# }\n# \n# \n# \n# \n# # Let's put this all together and output it\n# output <- data.frame(obs.VAF,\n# mut.conf.0.05,\n# mut.conf.0.95,\n# mut.multi,\n# mut.multi.0.05,\n# mut.multi.bstr.0.05,\n# mut.multi.0.95,\n# mut.multi.bstr.0.95,\n# Exp.Cpn = Max.Likelihood$Mt,\n# Exp.Cpn.Likelihood = Max.Likelihood$l,\n# ccf,\n# ccf.0.05,\n# ccf.btstr.0.05,\n# ccf.0.95,\n# ccf.btstr.0.95,\n# absolute.ccf,\n# absolute.ccf.0.05,\n# absolute.ccf.0.95,\n# prob.subclonal,\n# prob.clonal,\n# timing,\n# stringsAsFactors = FALSE\n# )\n# \n# # output <- data.frame(output,stringsAsFactors=FALSE)\n# return(output)\n# }\n# \n# output <- t(sapply(1:nrow(mut.table), get.all.mut.info))\n# output <- data.frame(output, stringsAsFactors = FALSE)\n# \n# colnames(output) <- c(\n# \"obs.VAF\",\n# \"mut.conf.0.05\",\n# \"mut.conf.0.95\",\n# \"mut.multi\",\n# \"mut.multi.0.05\",\n# \"mut.multi.bstr.0.05\",\n# \"mut.multi.0.95\",\n# \"mut.multi.bstr.0.95\",\n# \"Exp.Cpn\",\n# \"Exp.Cpn.Likelihood\",\n# \"ccf\",\n# \"ccf.0.05\",\n# \"ccf.btstr.0.05\",\n# \"ccf.0.95\",\n# \"ccf.btstr.0.95\",\n# \"absolute.ccf\",\n# \"absolute.ccf.0.05\",\n# \"absolute.ccf.0.95\",\n# \"prob.subclonal\",\n# \"prob.clonal\",\n# \"timing\"\n# )\n# \n# \n# out <- cbind(mut.table, output)\n# return(out)\n# }\n\nearlyORlate.strict <- function(patient, complete.mutation.table, purity) {\n\n # The following function is very similar indeed to the function above\n # However, there is one important difference\n # For this function, copy number states where the minor allele =1 are not classified as late.\n\n # First of all load the needed packaged\n #\n suppressPackageStartupMessages(library(sequenza))\n suppressPackageStartupMessages(library(bootstrap))\n suppressPackageStartupMessages(library(boot))\n\n # Get the table ready, with only information for specific patient\n mut.table <- complete.mutation.table[complete.mutation.table$patient == patient, ]\n\n # and all the other stuff\n cellularity <- as.numeric(purity)\n major.cn <- unlist(mut.table$major_cn)\n abs.cn <- unlist(mut.table$minor_cn) + unlist(mut.table$major_cn)\n minor.cn <- unlist(mut.table$minor_cn)\n depth.t <- unlist(mut.table$ref_counts) + unlist(mut.table$var_counts)\n max.cn <- max(abs.cn)\n VAF <- unlist(mut.table$var_counts) / (unlist(mut.table$var_counts) + unlist(mut.table$ref_counts))\n\n # Use sequenza to estimate theoretical VAFs for each type of copy number\n types <- types.matrix(CNt.min = 1, CNt.max = max.cn, CNn = 2)\n types.xy <- types.matrix(CNt.min = 1, CNt.max = max.cn, CNn = 1)\n types <- rbind(types, types.xy)\n types <- types[types$Mt >= 1, ]\n types$F <- 0\n for (i in 1:nrow(types)) {\n types$F[i] <- theoretical.mufreq(\n cellularity = cellularity,\n CNn = types$CNn[i], CNt = types$CNt[i],\n Mt = types$Mt[i]\n )\n }\n\n # Let's create some functions that can estimate whether early or late\n\n get.Mt <- function(F, depth.t, types, CNt, CNn, Mt) {\n types <- types[types$CNn == CNn, ]\n l <- sequenza:::mufreq.dpois(\n mufreq = F, types$F[types$CNt == CNt & types$Mt <= Mt],\n depth.t = depth.t\n )\n l <- l / sum(l)\n L <- data.frame(l = l, Mt = types$Mt[types$CNt == CNt & types$Mt <= Mt])\n }\n\n get.conf <- function(F, depth.t) {\n conf.int <- cbind(\n prop.test(round(F * depth.t, 0), depth.t)$conf[1],\n prop.test(round(F * depth.t, 0), depth.t)$conf[2]\n )\n return(conf.int)\n }\n\n bootstrap.cf <- function(Vaf, cellularity, CNn, CNt, depth.t) {\n # print(i)\n if (Vaf == 1) {\n conf.int <- cbind(\n prop.test(round(Vaf * depth.t, 0), depth.t)$conf[1],\n prop.test(round(Vaf * depth.t, 0), depth.t)$conf[2]\n )\n\n lower <- get.mut.mult(Vaf = conf.int[1], cellularity = cellularity, CNt = CNt, CNn = CNn)\n higher <- get.mut.mult(Vaf = conf.int[2], cellularity = cellularity, CNt = CNt, CNn = CNn)\n conf.int <- cbind(lower, higher)\n return(conf.int)\n }\n\n x <- c(rep(1, round(Vaf * depth.t, 0)), rep(0, (depth.t - round(Vaf * depth.t, 0))))\n theta <- function(x, i) {\n data <- x[i]\n est <- sum(data) / length(data)\n mut.multi <- (est * 1 / cellularity) * ((cellularity * CNt) + CNn * (1 - cellularity))\n return(mut.multi)\n }\n\n bt.res <- boot(x, theta, R = 1000)\n bt.ci <- boot.ci(bt.res, type = \"norm\")\n out <- c(bt.ci$normal[2], bt.ci$normal[3])\n\n return(out)\n }\n\n\n get.mut.mult <- function(CNt, Vaf, cellularity, CNn) {\n return((Vaf * 1 / cellularity) * ((cellularity * CNt) + CNn * (1 - cellularity)))\n }\n\n\n get.cancer.cell.fraction <- function(Max.Likelihood, mut.mult) {\n predicted.Mtn <- Max.Likelihood[, \"Mt\"]\n ccf <- mut.mult / predicted.Mtn\n return(ccf)\n }\n\n get.all.mut.info <- function(i) {\n # print(i)\n # First estimate the VAF confidence intervals\n obs.VAF <- VAF[i]\n mut.conf.0.05 <- get.conf(F = VAF[i], depth.t = depth.t[i])[1]\n mut.conf.0.95 <- get.conf(F = VAF[i], depth.t = depth.t[i])[2]\n\n if (abs.cn[i] == 0) {\n output <- cbind(obs.VAF,\n mut.conf.0.05,\n mut.conf.0.95,\n mut.multi = NA,\n mut.multi.0.05 = NA,\n mut.multi.bstr.0.05 = NA,\n mut.multi.0.95 = NA,\n mut.multi.bstr.0.95 = NA,\n Exp.Cpn = NA,\n Exp.Cpn.Likelihood = NA,\n ccf = NA,\n ccf.0.05 = NA,\n ccf.btstr.0.05 = NA,\n ccf.0.95 = NA,\n ccf.btstr.0.95 = NA,\n timing = \"Not.Poss\"\n )\n return(output)\n }\n\n # Next estimate the likelihood relating to which copy number the mutation has\n L <- get.Mt(\n F = VAF[i],\n depth.t = depth.t[i], CNt = abs.cn[i],\n types = types, CNn = unlist(mut.table$normal_cn[i]),\n Mt = major.cn[i]\n )\n\n # Next determine the mut multiplicity\n mut.multi <- get.mut.mult(CNt = abs.cn[i], Vaf = VAF[i], cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n mut.multi.0.05 <- get.mut.mult(CNt = abs.cn[i], Vaf = mut.conf.0.05, cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n mut.multi.0.95 <- get.mut.mult(CNt = abs.cn[i], Vaf = mut.conf.0.95, cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]))\n mut.multi.bstr <- bootstrap.cf(Vaf = VAF[i], cellularity = cellularity, CNn = unlist(mut.table$normal_cn[i]), CNt = abs.cn[i], depth.t = depth.t[i])\n mut.multi.bstr.0.05 <- mut.multi.bstr[1]\n mut.multi.bstr.0.95 <- mut.multi.bstr[2]\n\n\n if (is.na(L$l)[1]) {\n output <- cbind(obs.VAF,\n mut.conf.0.05,\n mut.conf.0.95,\n mut.multi,\n mut.multi.0.05,\n mut.multi.bstr.0.05,\n mut.multi.0.95,\n mut.multi.bstr.0.95,\n Exp.Cpn = NA,\n Exp.Cpn.Likelihood = NA,\n ccf = NA,\n ccf.0.05 = NA,\n ccf.btstr.0.05 = NA,\n ccf.0.95 = NA,\n ccf.btstr.0.95 = NA,\n timing = \"Not.Poss\"\n )\n return(output)\n }\n\n # Now determine which likelihood should be used\n Max.Likelihood <- L[which.max(L$l), ]\n\n\n\n\n\n # Next determine the cancer cell fraction\n ccf <- get.cancer.cell.fraction(Max.Likelihood, mut.multi)\n ccf.0.05 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.0.05)\n ccf.btstr.0.05 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.bstr.0.05)\n\n ccf.0.95 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.0.95)\n ccf.btstr.0.95 <- get.cancer.cell.fraction(Max.Likelihood, mut.multi.bstr.0.95)\n\n # Next determine the late cancer cell fraction\n # Make sure you also output the theoretical Copy (i.e. what it's closest to using maximum likelihood)\n expected.copy <- Max.Likelihood[2]\n\n # Finally also make a suggestion about whether the mutation is early late or not possible to tell\n\n timing <- \"Not.Poss\"\n\n if (Max.Likelihood$Mt > 1) {\n timing <- \"early\"\n }\n\n if (Max.Likelihood$Mt <= 1 & minor.cn[i] != 1) {\n timing <- \"late\"\n }\n\n if (major.cn[i] <= 1) {\n timing <- \"Not.Poss\"\n }\n\n\n\n\n # Let's put this all together and output it\n output <- cbind(obs.VAF,\n mut.conf.0.05,\n mut.conf.0.95,\n mut.multi,\n mut.multi.0.05,\n mut.multi.bstr.0.05,\n mut.multi.0.95,\n mut.multi.bstr.0.95,\n Exp.Cpn = Max.Likelihood$Mt,\n Exp.Cpn.Likelihood = Max.Likelihood$l,\n ccf,\n ccf.0.05,\n ccf.btstr.0.05,\n ccf.0.95,\n ccf.btstr.0.95,\n timing\n )\n\n return(output)\n }\n\n output <- t(sapply(1:nrow(mut.table), get.all.mut.info))\n\n colnames(output) <- c(\n \"obs.VAF\",\n \"mut.conf.0.05\",\n \"mut.conf.0.95\",\n \"mut.multi\",\n \"mut.multi.0.05\",\n \"mut.multi.bstr.0.05\",\n \"mut.multi.0.95\",\n \"mut.multi.bstr.0.95\",\n \"Exp.Cpn\",\n \"Exp.Cpn.Likelihood\",\n \"ccf\",\n \"ccf.0.05\",\n \"ccf.btstr.0.05\",\n \"ccf.0.95\",\n \"ccf.btstr.0.95\",\n \"timing\"\n )\n\n\n out <- cbind(mut.table, output)\n return(out)\n}\n\n\n#### Plotting ######\nplot.EarlyOrLate <- function(seg.mat.patient,\n TCGA.earlyLate,\n TCGA.purity,\n TCGA.barcode,\n max.cpn = 5,\n min.probes = 10,\n sub.clonal = 1) {\n seg.mat.patient$Chromosome <- as.numeric(as.character(seg.mat.patient$Chromosome))\n seg.mat.patient$StartPosition <- as.numeric(as.character(seg.mat.patient$StartPosition))\n seg.mat.patient$EndPosition <- as.numeric(as.character(seg.mat.patient$EndPosition))\n seg.mat.patient$nr.probes <- as.numeric(as.character(seg.mat.patient$nr.probes))\n\n chrom.length.copy <- fun.chrom.length(seg.mat.patient[, 2:4])\n chrom.segs <- fun.add.chrom(seg.mat.patient[, 2:4], chrom.length.copy)\n seg.mat.plot <- seg.mat.patient\n seg.mat.plot[, 2:4] <- chrom.segs\n major <- seg.mat.plot$Copy.Number - seg.mat.plot$min.allele\n seg.mat.plot <- cbind(seg.mat.plot, major)\n seg.mat.plot <- seg.mat.plot[seg.mat.plot$nr.probes >= min.probes, ]\n\n\n # Order correctly\n TCGA.plot <- TCGA.earlyLate\n Chromosome <- as.numeric(do.call(rbind, strsplit(unlist(TCGA.earlyLate$mutation_id), split = \":\"))[, 2])\n Start_pos <- as.numeric(do.call(rbind, strsplit(unlist(TCGA.earlyLate$mutation_id), split = \":\"))[, 3])\n TCGA.plot <- cbind(TCGA.plot, Chromosome, Start_pos)\n TCGA.plot <- data.frame(apply(TCGA.plot, 2, unlist), stringsAsFactors = FALSE)\n\n min.x <- 0\n min.y <- -0.25\n max.y <- max.cpn + 1\n max.x <- as.numeric(max(seg.mat.plot$EndPosition))\n\n # Make sure any copy numbers that are too high are still included\n seg.mat.plot$major <- ifelse(seg.mat.plot$major > max.cpn, max.cpn, seg.mat.plot$major)\n seg.mat.plot$min.allele <- ifelse(seg.mat.plot$min.allele > max.cpn, max.cpn, seg.mat.plot$min.allele)\n TCGA.plot$mut.multi <- ifelse(TCGA.plot$mut.multi > max.cpn, max.cpn, TCGA.plot$mut.multi)\n\n # layout(rbind(1,2))\n # par(mar=c(5,5,5,5))\n plot(1,\n xlim = c(min.x, max.x),\n ylim = c(min.y, max.y),\n type = \"n\",\n xaxt = \"n\",\n yaxs = \"i\",\n yaxt = \"n\",\n xaxs = \"i\",\n ylab = \"\",\n xlab = \"\",\n lwd = 2,\n bty = \"n\"\n )\n\n box(lwd = 0.5)\n\n axis(\n side = 2,\n at = seq(0, max.cpn, by = 1),\n labels = c(seq(0, max.cpn - 1, by = 1), paste(\">\", max.cpn, sep = \"\")),\n las = 2,\n cex.axis = 0.7,\n lwd = 0.5\n )\n\n mtext(\n text = TCGA.barcode,\n side = 3,\n line = 2\n )\n\n\n\n # Now plot each segment\n fun.plot.segment <- function(x, seg.mat.plot) {\n # print(x)\n # start with major allele\n x0 <- as.numeric(seg.mat.plot[x, \"StartPosition\"])\n x1 <- as.numeric(seg.mat.plot[x, \"EndPosition\"])\n y0 <- seg.mat.plot[x, \"major\"] + 0.05\n y1 <- y0\n\n\n segments(x0, y0, x1, y1, col = \"black\", lwd = 2.4)\n\n x0 <- as.numeric(seg.mat.plot[x, \"StartPosition\"])\n x1 <- as.numeric(seg.mat.plot[x, \"EndPosition\"])\n y0 <- as.numeric(seg.mat.plot[x, \"min.allele\"]) - 0.05\n y1 <- y0\n\n\n segments(x0, y0, x1, y1, col = \"#009E73\", lwd = 2.4)\n }\n\n sapply(1:nrow(seg.mat.plot), fun.plot.segment, seg.mat.plot)\n # Draw lines to separate the different chromosomes\n for (i in sort(unique(as.numeric(seg.mat.plot$Chromosome))))\n {\n abline(\n v = max(as.numeric(seg.mat.plot[seg.mat.plot$Chromosome == i, \"EndPosition\"])),\n lwd = 0.5\n )\n # ,lty='dashed')\n }\n\n # We need to update the\n TCGA.plot <- TCGA.plot[order(as.numeric(TCGA.plot$Chromosome), as.numeric(TCGA.plot$Start_pos)), ]\n\n TCGA.plot$Start_pos <- as.numeric(fun.add.chrom(cbind(TCGA.plot$Chromosome, TCGA.plot$Start_pos, TCGA.plot$Start_pos), chrom.length.copy)[, 2])\n\n # Let's add the mutations\n # Start with early mutations\n early.muts <- TCGA.plot[TCGA.plot$timing %in% c(\"early\"), ]\n early.clonal <- early.muts[early.muts$absoltue.ccf.0.95 >= sub.clonal, ]\n early.subclonal <- early.muts[early.muts$absoltue.ccf.0.95 < sub.clonal, ]\n\n late.muts <- TCGA.plot[TCGA.plot$timing %in% c(\"late\"), ]\n late.clonal <- late.muts[late.muts$absoltue.ccf.0.95 >= sub.clonal, ]\n late.subclonal <- late.muts[late.muts$absoltue.ccf.0.95 < sub.clonal, ]\n\n nontimed.muts <- TCGA.plot[!TCGA.plot$mutation_id %in% c(early.muts$mutation_id, late.muts$mutation_id), ]\n nontimed.clonal <- nontimed.muts[nontimed.muts$absoltue.ccf.0.95 >= sub.clonal, ]\n nontimed.subclonal <- nontimed.muts[nontimed.muts$absoltue.ccf.0.95 < sub.clonal, ]\n\n\n # let's determine early or late or not possible\n plot.earlyORlateCol <- function(x, timed.muts, nontimed = FALSE) {\n # print(x)\n mut <- timed.muts[x, , drop = FALSE]\n \n # fix bug: some data of mut.multi.bstr.0.95 are NA, which will induce to error.\n if (any(is.na(mut$mut.multi.bstr.0.95))) {\n return(NULL)\n }\n\n # determine cell multiplicity\n mut.multiplicity <- mut$mut.multi\n # mut.multiplicity <- mut.multiplicity*(as.numeric(mut$minor_cn)+as.numeric(mut$major_cn))\n\n if (nontimed) {\n if (as.numeric(mut$mut.multi.bstr.0.95) < sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.7,\n pch = 17,\n col = \"#99999965\"\n ) # cannot be determined\n }\n\n if (as.numeric(mut$mut.multi.bstr.0.95) >= sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.8,\n pch = 16,\n col = \"#99999995\"\n ) # cannot be determined\n }\n }\n\n if (!nontimed) {\n # is it an early event?\n if (mut$timing == \"early\") {\n # is it subclonal\n if (as.numeric(mut$mut.multi.bstr.0.95) < sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.7,\n pch = 17,\n col = \"#0072B245\"\n ) # early event\n }\n\n # is it clonal\n if (as.numeric(mut$mut.multi.bstr.0.95) >= sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.9,\n pch = 16,\n col = \"#0072B295\"\n ) # early event\n }\n }\n\n if (mut$timing == \"late\") {\n if (as.numeric(mut$mut.multi.bstr.0.95) < sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.7,\n pch = 17,\n col = \"#D55E0045\"\n ) # late event\n }\n\n if (as.numeric(mut$mut.multi.bstr.0.95) >= sub.clonal) {\n points(mut$Start_pos,\n mut.multiplicity,\n cex = 0.9,\n pch = 16,\n col = \"#D55E0095\"\n ) # late event\n }\n }\n }\n }\n\n\n if (nrow(early.muts) >= 1) {\n sapply(1:nrow(early.muts), plot.earlyORlateCol, early.muts)\n }\n if (nrow(late.muts) >= 1) {\n sapply(1:nrow(late.muts), plot.earlyORlateCol, late.muts)\n }\n if (nrow(nontimed.muts) >= 1) {\n sapply(1:nrow(nontimed.muts), plot.earlyORlateCol, nontimed.muts, nontimed = TRUE)\n }\n\n\n\n mtext(\n side = 3,\n at = fun.chrom.mean(seg.mat.plot[, 2:4]),\n text = sort(unique(seg.mat.plot[, 2])),\n cex = seq(0.6, 0.4, length.out = length(unique(seg.mat.plot[, 2]))),\n line = -1\n # ,lwd=0.5\n )\n}\n\n\n\n\n#########################################################################################\n\n\nfun.chrom.length <- function(seg) {\n # This function returns the length of chromosome 1,...,22\n # seg: first three columns of the minimum conistent region matrix\n\n chrom.length <- c()\n for (i in sort(as.numeric(unique(seg[, 1])))) {\n sub.chrom <- subset(seg, seg[, 1] == i)\n chrom.length <- c(chrom.length, sub.chrom[nrow(sub.chrom), 3])\n }\n return(chrom.length)\n}\n\n#############################################################################################\n\nfun.add.chrom <- function(seg, chrom.length) {\n # This function adds the length of chromosome 1,...,(i - 1) to chromsomes 2,...,22\n # seg: first three columns of the minimum conistent region matrix\n # chrom.length: output of fun.chrom.length(...)\n\n # fix bug: Data type mismatch results in mismatched results.\n seg <- as.data.frame(seg)\n seg[, 1] <- as.numeric(seg[, 1])\n if (1 %in% seg[, 1]) {\n seg.tmp <- subset(seg, seg[, 1] == 1)\n } else {\n warning(\"In fun.add.chrom(), seg has no chromosome 1.\")\n seg.tmp <- matrix(NA, nrow = 0, ncol = ncol(seg))\n }\n for (i in 2:max(max(seg[, 1]), 3)) {\n if (!(i %in% seg[, 1])) {\n warning(stringr::str_interp(\"In fun.add.chrom(), seg has no chromosome ${i}.\"))\n next\n }\n sub.chrom <- subset(seg, seg[, 1] == i)\n sub.chrom[, 2] <- as.numeric(sub.chrom[, 2]) + sum(as.numeric(chrom.length[1:(i - 1)]))\n sub.chrom[, 3] <- as.numeric(sub.chrom[, 3]) + sum(as.numeric(chrom.length[1:(i - 1)]))\n seg.tmp <- rbind(seg.tmp, sub.chrom)\n }\n assertthat::assert_that(nrow(seg.tmp) == nrow(seg))\n return(seg.tmp)\n}\n\n####################################################################################################\n\nfun.smooth.score <- function(score, seg) {\n # This function applies smoothing (rollmean) to chromosome 1,...,22 separetely\n # score: score to be smoothed (e.g. correlation)\n # seg: Corresponding positions\n # window: window size for rollmean\n # The R package \"zoo\" is required\n score.tmp <- c()\n for (i in 1:22) {\n score.tmp <- c(score.tmp, rollmean(score[seg[, 1] == i], k = round(length(score[seg[, 1] == i]) / 10), na.pad = T))\n }\n\n\n return(score.tmp)\n}\n\n#######################################################################################################\n\nfun.chrom.mean <- function(seg) {\n # This function finds the middle of the positions for each chromosome.\n # seg: Matrix with three columns, containing the positions.\n chrom.mean <- c()\n for (i in sort(as.numeric(unique(seg[, 1])))) {\n sub.chrom <- subset(seg, seg[, 1] == i)\n chrom.mean <- c(chrom.mean, (min(sub.chrom[, 2]) + max(sub.chrom[, 3])) / 2)\n }\n return(chrom.mean)\n}\n\n#######################################################################################################\n\n\nplot.TCGA.sample.ccfs <- function(TCGA.earlyLate,\n clonal.cut.off = 1,\n spec.genes = NULL) {\n\n\n # get the patient\n cancer.patient <- data.frame(TCGA.earlyLate)\n\n # par(mfrow=c(2,1))\n layout(rbind(1, 2))\n par(mar = c(0.5, 5, 5, 5))\n # density(cancer.patient$ccf,bw='SJ')\n\n plot(density(as.numeric(cancer.patient$ccf), bw = \"SJ\"),\n xlim = c(0, 1.4),\n xaxt = \"n\",\n yaxt = \"n\"\n # ,xaxs='i'\n # ,yaxs='i'\n , xlab = \"\",\n ylab = \"Density (a.u.)\",\n main = cancer.patient$patient[1],\n lwd = 3\n )\n par(mar = c(5, 5, 0.5, 5))\n plot(as.numeric(cancer.patient$ccf),\n log(as.numeric(cancer.patient$var_counts) + as.numeric(cancer.patient$ref_counts)),\n ylim = c(log(5), log(1000)),\n xlim = c(0, 1.6),\n xaxt = \"n\",\n yaxt = \"n\"\n # ,xaxs='i'\n # ,yaxs='i'\n , xlab = \"Adjusted VAF\",\n ylab = \"Tumour Coverage\",\n main = \"\",\n lwd = 3,\n cex = 1.5,\n pch = 21,\n col = ifelse(as.numeric(cancer.patient$absolute.ccf.0.95) >= 1, \"#de2d2699\", \"#0072B299\"),\n bg = ifelse(cancer.patient$absolute.ccf.0.95 >= 1, \"#de2d2699\", \"#0072B299\")\n )\n\n\n # next plot the genes of interest\n if (!is.null(spec.genes)) {\n for (gene in spec.genes)\n {\n if (!gene %in% cancer.patient$Hugo_Symbol) {\n next\n }\n\n gene.mut <- cancer.patient[cancer.patient$Hugo_Symbol %in% gene, , drop = FALSE]\n gene.mut <- gene.mut[gene.mut$Variant_Classification %in% c(\n \"Missense_Mutation\",\n \"Nonsense_Mutation\",\n \"Splice_Site\",\n \"Frame_Shift_Del\",\n \"Translation_Start_Site\",\n \"Nonstop_Mutation\"\n ), , drop = FALSE]\n if (nrow(gene.mut) == 0) {\n next\n }\n\n points(gene.mut$ccf, log(gene.mut$var_counts + gene.mut$ref_counts),\n cex = 1.8,\n lwd = 3\n )\n text(gene.mut$ccf, log(gene.mut$var_counts + gene.mut$ref_counts),\n labels = gene,\n pos = 4,\n cex = 1,\n lwd = 3,\n font = 2\n )\n }\n }\n\n axis(side = 1, at = seq(0, 1.6, by = 0.2))\n cov.seq <- c(5, 10, 20, 50, 100, 200, 500, 1000)\n axis(side = 2, at = log(cov.seq), labels = cov.seq, las = 2)\n}\n", "meta": {"hexsha": "5d464e5537176222248fa3e748f01b778d8ea004", "size": 32614, "ext": "r", "lang": "R", "max_stars_repo_path": "R/main.functions.r", "max_stars_repo_name": "b-niu/EstimateClonality", "max_stars_repo_head_hexsha": "04a6f05b924a3196f6d9590b0304d8e9d3f196c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-10-02T03:56:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T03:56:39.000Z", "max_issues_repo_path": "R/main.functions.r", "max_issues_repo_name": "b-niu/EstimateClonality", "max_issues_repo_head_hexsha": "04a6f05b924a3196f6d9590b0304d8e9d3f196c1", "max_issues_repo_licenses": ["MIT"], "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/main.functions.r", "max_forks_repo_name": "b-niu/EstimateClonality", "max_forks_repo_head_hexsha": "04a6f05b924a3196f6d9590b0304d8e9d3f196c1", "max_forks_repo_licenses": ["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.2694151486, "max_line_length": 166, "alphanum_fraction": 0.5647574661, "num_tokens": 10485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21490684071289798}} {"text": "## Version of gamm using lme4 as fit engine. (c) Simon N. Wood 2009-20\n## Reparameterization trick as Wood (2004,2006). \n## fooling lmer using Fabian Scheipl's trick (now adapted for lme4 >1.0).\n\ngamm4.setup<-function(formula,pterms,\n data=stop(\"No data supplied to gamm.setup\"),knots=NULL)\n## set up the model matrix, penalty matrices and auxilliary information about the smoothing bases\n## needed for a gamm4 fit.\n## There is an implicit assumption that any rank deficient penalty does not penalize \n## the constant term in a basis. \n## 1. Calls gam.setup, as for a gam to produce object G suitable for estimating a gam.\n## 2. Works through smooth list, G$smooth, modifying so that... \n## i) Smooths are reparameterized to have a sequence of (portion of) identity matrix\n## penalties. \n## ii) 'random' list is accumulated containing random effect model matrices for terms. \n## iii) Sparse version of full model matrix in original parameterization is also accumulated\n## iv) Various indices are created for moving between the parameterizations.\n{ \n ## first simply call `gam.setup'....\n\n G <- mgcv:::gam.setup(formula,pterms,\n data=data,knots=knots,sp=NULL,\n min.sp=NULL,H=NULL,absorb.cons=TRUE,sparse.cons=0,gamm.call=TRUE)\n \n if (!is.null(G$L)) stop(\"gamm can not handle linked smoothing parameters (probably from use of `id' or adaptive smooths)\")\n # now perform re-parameterization...\n\n first.f.para <- G$nsdf+1 \n \n random <- list()\n \n if (G$nsdf>0) ind <- 1:G$nsdf else ind <- rep(0,0) \n X <- G$X[,ind,drop=FALSE] # accumulate fixed effects into here\n\n xlab <- rep(\"\",0)\n \n G$Xf <- as(X,\"dgCMatrix\") ## sparse version of full matrix, treating smooths as fixed\n\n first.para <- G$nsdf+1\n\n used.names <- names(data) ## keep track of all variable names already used\n\n if (G$m) for (i in 1:G$m) { ## work through the smooths\n \n sm <- G$smooth[[i]]\n sm$X <- G$X[,sm$first.para:sm$last.para,drop=FALSE]\n rasm <- mgcv::smooth2random(sm,used.names,type=2) ## convert smooth to random effect and fixed effects\n used.names <- c(used.names,names(rasm$rand)) \n\n sm$fixed <- rasm$fixed\n\n ## deal with creation of sparse full model matrix \n if (!is.null(sm$fac)) { \n flev <- levels(sm$fac) ## grouping factor for smooth\n n.lev <- length(flev)\n for (k in 1:n.lev) {\n G$Xf <- cbind2(G$Xf,as(sm$X*as.numeric(sm$fac==flev[k]),\"dgCMatrix\"))\n }\n } else { \n n.lev <- 1\n G$Xf <- cbind2(G$Xf,as(sm$X,\"dgCMatrix\"))\n }\n\n ## now append random effects to main list\n n.para <- 0 ## count random coefficients\n #rinc <- rind <- rep(0,0)\n if (!sm$fixed) {\n for (k in 1:length(rasm$rand)) n.para <- n.para + ncol(rasm$rand[[k]])\n sm$lmer.name <- names(rasm$rand)\n random <- c(random,rasm$rand)\n sm$trans.D <- rasm$trans.D\n sm$trans.U <- rasm$trans.U ## matrix mapping fit coefs back to original\n }\n\n ## ensure stored first and last para relate to G$Xf in expanded version\n\n sm$last.para <- first.para + ncol(rasm$Xf) + n.para - 1\n sm$first.para <- first.para\n first.para <- sm$last.para + 1 \n\n if (ncol(rasm$Xf)) {\n Xfnames <- rep(\"\",ncol(rasm$Xf)) \n k <- length(xlab)+1\n for (j in 1:ncol(rasm$Xf)) {\n xlab[k] <- Xfnames[j] <-\n new.name(paste(sm$label,\"Fx\",j,sep=\"\"),xlab)\n k <- k + 1\n } \n colnames(rasm$Xf) <- Xfnames\n }\n\n X <- cbind(X,rasm$Xf) # add fixed model matrix to overall fixed X\n \n sm$first.f.para <- first.f.para\n first.f.para <- first.f.para + ncol(rasm$Xf)\n sm$last.f.para <- first.f.para - 1 ## note less than sm$first.f.para => no fixed\n\n ## store indices of random parameters in smooth specific array\n sm$rind <- rasm$rind \n sm$rinc <- rasm$rinc \n\n sm$pen.ind <- rasm$pen.ind ## pen.ind==i TRUE for coef penalized by ith penalty\n\n sm$n.para <- n.para\n \n sm$X <- NULL ## delete model matrix\n \n G$smooth[[i]] <- sm ## replace smooth object with extended version \n }\n \n G$random <- random ## named list of random effect matrices\n G$X <- X ## fixed effects model matrix\n\n G\n} ## end of gamm4.setup\n\n\ngamm4 <- function(formula,random=NULL,family=gaussian(),data=list(),weights=NULL,\n subset=NULL,na.action,knots=NULL,drop.unused.levels=TRUE,REML=TRUE,\n control=NULL,start=NULL,verbose=0L,...) {\n# Routine to fit a GAMM to some data. Fixed and smooth terms are defined in the formula, but the wiggly \n# parts of the smooth terms are treated as random effects. The onesided formula random defines additional \n# random terms. \n\n\n if (!is.null(random)) {\n if (!inherits(random,\"formula\")) stop(\"gamm4 requires `random' to be a formula\")\n random.vars <- all.vars(random)\n } else random.vars <- NULL\n\n # create model frame.....\n gp <- interpret.gam(formula) # interpret the formula \n \n mf <- match.call(expand.dots=FALSE)\n \n mf$formula <- gp$fake.formula\n mf$REML <- mf$verbose <- mf$control <- mf$start <- mf$family <- mf$scale <-\n mf$knots <- mf$random <- mf$... <-NULL ## mf$weights?\n mf$drop.unused.levels <- drop.unused.levels\n mf[[1]] <- as.name(\"model.frame\")\n pmf <- mf\n gmf <- eval(mf, parent.frame()) # the model frame now contains all the data, for the gam part only \n gam.terms <- attr(gmf,\"terms\") # terms object for `gam' part of fit -- need this for prediction to work properly\n\n if (length(random.vars)) {\n mf$formula <- as.formula(paste(paste(deparse(gp$fake.formula,\n backtick = TRUE), collapse = \"\"), \"+\", paste(random.vars,\n collapse = \"+\")))\n mf <- eval(mf, parent.frame())\n } else mf <- gmf\n rm(gmf)\n\n if (nrow(mf)<2) stop(\"Not enough (non-NA) data to do anything meaningful\")\n \n ## summarize the *raw* input variables\n ## note can't use get_all_vars here -- buggy with matrices\n vars <- all.vars(gp$fake.formula[-2]) ## drop response here\n inp <- parse(text = paste(\"list(\", paste(vars, collapse = \",\"),\")\"))\n dl <- eval(inp, data, parent.frame())\n names(dl) <- vars ## list of all variables needed\n var.summary <- mgcv:::variable.summary(gp$pf,dl,nrow(mf)) ## summarize the input data\n\n ## lmer offset handling work around...\n mvars <- vars[!vars%in%names(mf)] ## variables not in mf raw -- can cause lmer problem\n if (length(mvars)>0) for (i in 1:length(mvars)) mf[[mvars[i]]] <- dl[[mvars[i]]] ## append raw versions to mf\n\n rm(dl) ## save space \n\n pmf$formula <- gp$pf\n pmf <- eval(pmf, parent.frame()) # pmf contains all data for non-smooth part \n pTerms <- attr(pmf,\"terms\")\n\n if (is.character(family)) family<-eval(parse(text=family))\n if (is.function(family)) family <- family()\n if (is.null(family$family)) stop(\"family not recognized\")\n if (family$family == \"gaussian\" && family$link == \"identity\") linear <- TRUE else linear <- FALSE\n # now call gamm4.setup \n\n G <- gamm4.setup(gp,pterms=pTerms,data=mf,knots=knots)\n \n G$var.summary <- var.summary \n\n n.sr <- length(G$random) # number of random smooths (i.e. s(...,fx=FALSE,...) terms)\n\n if (is.null(random)&&n.sr==0) \n stop(\"gamm4 models must have at least 1 smooth with unknown smoothing parameter or at least one other random effect\")\n\n offset.name <- attr(mf,\"names\")[attr(attr(mf,\"terms\"),\"offset\")]\n\n yname <- new.name(\"y\",names(mf))\n eval(parse(text=paste(\"mf$\",yname,\"<-G$y\",sep=\"\")))\n Xname <- new.name(\"X\",names(mf))\n eval(parse(text=paste(\"mf$\",Xname,\"<-G$X\",sep=\"\")))\n \n lme4.formula <- paste(yname,\"~\",Xname,\"-1\")\n if (length(offset.name)) \n { lme4.formula <- paste(lme4.formula,\"+\",offset.name) \n }\n\n ## Basic trick is to call (g)lFormula to set up model, with simple i.i.d. dummy random effects for the \n ## penalized component of each smooth. This results in columns of Z being produced for these dummy's,\n ## which can be over-written with the right thing. NOTE: that lambdat could also be modified, I think!!\n\n ## Add the random effect dummy variables for the smooth\n r.name <- names(G$random) \n if (n.sr) for (i in 1:n.sr) # adding the constructed variables to the model frame avoiding name duplication\n { mf[[r.name[i]]] <- factor(rep(1:ncol(G$random[[i]]),length=nrow(G$random[[i]])))\n lme4.formula <- paste(lme4.formula,\"+ (1|\",r.name[i],\")\")\n }\n \n if (!is.null(random)) { ## append the regular random effects\n lme4.formula <- paste(lme4.formula,\"+\",\n substring(paste(deparse(random,backtick=TRUE),collapse=\"\"),first=2))\n }\n \n lme4.formula <- as.formula(lme4.formula)\n\n if (is.null(control)) control <- if (linear) lmerControl() else glmerControl() \n\n ## NOTE: further arguments should be passed here... \n b <- if (linear) lFormula(lme4.formula,data=mf,weights=G$w,REML=REML,control=control,...) else \n glFormula(lme4.formula,data=mf,family=family,weights=G$w,control=control,...)\n\n \n if (n.sr) { ## Fabian Scheipl's trick of overwriting dummy slots revised for new structure\n tn <- names(b$reTrms$cnms) ## names associated with columns of Z (same order as Gp)\n ind <- 1:length(tn)\n sn <- names(G$random) ## names of smooth random components\n for (i in 1:n.sr) { ## loop through random effect smooths\n k <- ind[sn[i]==tn] ## which term should contain G$random[[i]] \n ii <- (b$reTrms$Gp[k]+1):b$reTrms$Gp[k+1]\n b$reTrms$Zt[ii,] <- as(t(G$random[[i]]),\"dgCMatrix\")\n b$reTrms$cnms[[k]] <- attr(G$random[[i]],\"s.label\") \n }\n }\n\n ## now do the actual fitting...\n ret <- list()\n #arg <- list(...)\n #arg <- arg[!(names(arg) %in% names(b))]\n #b <- c(b,arg) ## add '...' arguments for use with do.call\n b$control <- control; b$verbose=verbose; b$start=start\n if (linear) {\n ## Create the deviance function to be optimized:\n devfun <- do.call(mkLmerDevfun, b)\n ## Optimize the deviance function:\n opt <- optimizeLmer(devfun,start=start,verbose=verbose,control=control$optCtrl) ## previously bobyqa optimizer set, but now default\n ## Package up the results:\n ret$mer <- mkMerMod(environment(devfun), opt, b$reTrms, fr = b$fr)\n } else { ## generalized case...\n ## Create the deviance function for optimizing over theta:\n devfun <- do.call(mkGlmerDevfun, b)\n ## Optimize over theta using a rough approximation (i.e. nAGQ = 0):\n opt <- optimizeGlmer(devfun,start=start,verbose=verbose,control=control$optCtrl)\n ## Update the deviance function for optimizing over theta and beta:\n devfun <- updateGlmerDevfun(devfun, b$reTrms)\n ## Optimize over theta and beta:\n opt <- optimizeGlmer(devfun, stage=2,start=start,verbose=verbose,control=control$optCtrl)\n ## Package up the results:\n ret$mer <- mkMerMod(environment(devfun), opt, b$reTrms, fr = b$fr)\n }\n\n rm(b)\n\n ### .... fitting finished\n\n ## now fake a gam object \n \n object<-list(model=mf,formula=formula,smooth=G$smooth,nsdf=G$nsdf,family=family,\n df.null=nrow(G$X),y=getME(ret$mer,\"y\"),\n terms=gam.terms,pterms=G$pterms,xlevels=G$xlevels,\n contrasts=G$contrasts,assign=G$assign,na.action=attr(mf,\"na.action\"),\n cmX=G$cmX,var.summary=G$var.summary)\n pvars <- all.vars(delete.response(object$terms))\n object$pred.formula <- if (length(pvars)>0) reformulate(pvars) else NULL\n\n ## to unpack coefficients look at names(ret$lme$flist), ret$lme@Zt, ranef(), fixef()\n \n ## let the GAM coefficients in the original parameterization be beta,\n ## and let them be beta' in the fitting parameterization. \n ## Then beta = B beta'. B and B^{-1} can be efficiently accumulated\n ## and are useful for stable computation of the covariance matrix\n ## etc... \n \n B <- Matrix(0,ncol(G$Xf),ncol(G$Xf))\n diag(B) <- 1\n Xfp <- G$Xf\n ## Transform parameters back to the original space....\n bf <- as.numeric(lme4::fixef(ret$mer)) ## the fixed effects\n br <- lme4::ranef(ret$mer) ## a named list\n if (G$nsdf) p <- bf[1:G$nsdf] else p <- array(0,0) ## fixed parametric componet\n if (G$m>0) for (i in 1:G$m) {\n fx <- G$smooth[[i]]$fixed \n first <- G$smooth[[i]]$first.f.para; last <- G$smooth[[i]]$last.f.para\n if (first <=last) beta <- bf[first:last] else beta <- array(0,0)\n if (fx) b <- beta else { ## not fixed so need to undo transform of random effects etc. \n b <- rep(0,0)\n for (k in 1:length(G$smooth[[i]]$lmer.name)) ## collect all coefs associated with this smooth\n b <- c(b,as.numeric(br[[G$smooth[[i]]$lmer.name[k]]][[1]])) \n b <- b[G$smooth[[i]]$rind] ## make sure coefs are in order expected by smooth\n b <- c(b,beta) \n b <- G$smooth[[i]]$trans.D*b\n if (!is.null(G$smooth[[i]]$trans.U)) b <- G$smooth[[i]]$trans.U%*%b ## transform back to original \n }\n p <- c(p,b)\n \n ## now fill in B...\n ind <- G$smooth[[i]]$first.para:G$smooth[[i]]$last.para\n if (!fx) { \n D <- G$smooth[[i]]$trans.D\n if (is.null(G$smooth[[i]]$trans.U)) B[ind,ind] <- Diagonal(length(D),D) else\n B[ind,ind] <- t(D*t(G$smooth[[i]]$trans.U))\n }\n ## and finally transform G$Xf into fitting parameterization...\n Xfp[,ind] <- G$Xf[,ind,drop=FALSE]%*%B[ind,ind,drop=FALSE]\n\n }\n \n object$coefficients <- p\n\n ## need to drop smooths from Zt and then\n ## form Z'phiZ + I \\sigma^2\n\n vr <- lme4::VarCorr(ret$mer) ## list of ranef variance components in the same order as Gp\n \n scale <- as.numeric(attr(vr,\"sc\"))^2 ## get the scale parameter\n if (!is.finite(scale) || scale==1) { ## NOTE: better test???\n scale <- 1\n object$scale.estimated <- FALSE\n } else object$scale.estimated <- TRUE\n \n sp <- rep(-1,n.sr)\n\n Zt <- Matrix(0,0,ncol(getME(ret$mer,\"Zt\")))\n if (n.sr==0) sn <- NULL ## names by which smooths are known in mer\n rn <- names(vr)\n ind <- rep(0,0) ## index the non-smooth random effects among the random effects\n for (i in 1:length(vr)) {\n if (is.null(sn)||!rn[i]%in%sn) { ## append non smooth r.e.s to Zt\n Gp <- getME(ret$mer,\"Gp\") ## group index ends\n ind <- c(ind,(Gp[i]+1):Gp[i+1])\n } else if (!is.null(sn)) { ## extract smoothing parameters for smooth r.e.s\n k <- (1:n.sr)[rn[i]==sn] ## where in original smooth ordering is current smoothing param\n if (as.numeric(vr[[i]]>0)) sp[k] <- scale/as.numeric(vr[[i]]) else \n sp[k] <- 1e10\n }\n }\n\n if (length(ind)) { ## extract columns corresponding to non-smooth r.e.s \n Zt <- getME(ret$mer,\"Zt\")[ind,] ## extracting random effects model matrix\n root.phi <- getME(ret$mer,\"Lambdat\")[ind,ind] ## and corresponding sqrt of cov matrix (phi)\n }\n\n object$prior.weights <- G$w\n \n if (linear) {\n object$weights <- object$prior.weights \n V <- Diagonal(n=length(object$weights),x=scale/object$weights) \n } else { \n # mu <- getME(ret$mer,\"mu\")\n # eta <- family$linkfun(mu)\n object$weights <- ret$mer@resp$sqrtWrkWt()^2\n ## object$prior.weights*family$mu.eta(eta)^2/family$variance(mu)\n V <- Diagonal(x=1/object$weights)*scale\n #V <- Diagonal(x=scale*family$variance(mu)/object$prior.weights)\n }\n\n \n if (nrow(Zt)>0) V <- V + crossprod(root.phi%*%Zt)*scale ## data or pseudodata cov matrix, treating smooths as fixed now\n\n ## NOTE: Cholesky probably better in the following - then pivoting \n ## automatic when solving....\n\n R <- Matrix::chol(V,pivot=TRUE);piv <- attr(R,\"pivot\") \n\n G$Xf <- as(G$Xf,\"dgCMatrix\")\n Xfp <- as(Xfp,\"dgCMatrix\")\n \n if (is.null(piv)) {\n WX <- as(solve(t(R),Xfp),\"matrix\") ## V^{-.5}Xp -- fit parameterization\n XVX <- as(solve(t(R),G$Xf),\"matrix\") ## same in original parameterization \n } else {\n WX <- as(solve(t(R),Xfp[piv,]),\"matrix\") ## V^{-.5}Xp -- fit parameterization\n XVX <- as(solve(t(R),G$Xf[piv,]),\"matrix\") ## same in original parameterization\n }\n qrz <- qr(XVX,LAPACK=TRUE)\n object$R <- qr.R(qrz);object$R[,qrz$pivot] <- object$R\n\n XVX <- crossprod(object$R) ## X'V^{-1}X original parameterization\n\n object$sp <- sp\n \n colx <- ncol(G$Xf)\n Sp <- matrix(0,colx,colx) # penalty matrix - fit param\n first <- G$nsdf+1\n k <- 1\n if (G$m>0) for (i in 1:G$m) { # Accumulate the total penalty matrix\n if (!object$smooth[[i]]$fixed) {\n ii <- object$smooth[[i]]$first.para:object$smooth[[i]]$last.para ## index this smooth's params\n for (j in 1:length(object$smooth[[i]]$S)) { ## work through penalty list\n ind <- ii[object$smooth[[i]]$pen.ind == j] ## index of currently penalized\n diag(Sp)[ind] <- sqrt(object$sp[k]) ## diagonal penalty\n k <- k+1\n }\t\t\t\t\t\t\t\t\t\t\t\t\t\t }\n first <- last + 1 \n }\n \n ## Alternative cov matrix calculation. Basic\n ## idea is that cov matrix is computed stably in\n ## fitting parameterization, and then transformed to\n ## original parameterization. \n qrx <- qr(rbind(WX,Sp/sqrt(scale)),LAPACK=TRUE)\n Ri <- backsolve(qr.R(qrx),diag(ncol(WX)))\n ind <- qrx$pivot;ind[ind] <- 1:length(ind)## qrx$pivot\n Ri <- Ri[ind,] ## unpivoted square root of cov matrix in fitting parameterization Ri Ri' = cov\n Vb <- B%*%Ri; Vb <- Vb%*%t(Vb)\n\n object$edf<-rowSums(Vb*t(XVX))\n \n object$df.residual <- length(object$y) - sum(object$edf)\n\n object$sig2 <- scale\n if (linear) { object$method <- \"lmer.REML\"\n } else { object$method <- \"glmer.ML\"}\n\n object$Vp <- as(Vb,\"matrix\")\n \n object$Ve <- as(Vb%*%XVX%*%Vb,\"matrix\")\n \n class(object) <- \"gam\"\n \n ## Restore original smooth list, if it was split to deal with t2 terms...\n if (!is.null(G$original.smooth)) {\n object$smooth <- G$smooth <- G$original.smooth\n }\n\n ## If prediction parameterization differs from fit parameterization, transform now...\n ## (important for t2 smooths, where fit constraint is not good for component wise \n ## prediction s.e.s)\n\n if (!is.null(G$P)) {\n object$coefficients <- G$P %*% object$coefficients\n object$Vp <- G$P %*% object$Vp %*% t(G$P) \n object$Ve <- G$P %*% object$Ve %*% t(G$P) \n }\n\n object$linear.predictors <- predict.gam(object,type=\"link\")\n object$fitted.values <- object$family$linkinv(object$linear.predictors)\n \n object$residuals <- residuals(ret$mer) \n\n if (G$nsdf>0) term.names<-colnames(G$X)[1:G$nsdf] else term.names<-array(\"\",0)\n n.smooth<-length(G$smooth) \n if (n.smooth)\n for (i in 1:n.smooth)\n { k<-1\n for (j in object$smooth[[i]]$first.para:object$smooth[[i]]$last.para)\n { term.names[j]<-paste(object$smooth[[i]]$label,\".\",as.character(k),sep=\"\")\n k<-k+1\n }\n }\n names(object$coefficients) <- term.names # note - won't work on matrices!!\n names(object$edf) <- term.names\n names(object$sp) <- names(G$sp)\n\n object$gcv.ubre <- if (isREML(ret$mer)) REMLcrit(ret$mer) else deviance(ret$mer)\n\n if (!is.null(G$Xcentre)) object$Xcentre <- G$Xcentre ## any column centering applied to smooths\n\n ret$gam<-object\n class(ret) <- c(\"gamm4\",\"list\")\n ret\n\n} ## end of gamm4\n\n\n\n\n\n\n\nprint.gamm4.version <- function()\n{ library(help=gamm4)$info[[1]] -> version\n version <- version[pmatch(\"Version\",version)]\n um <- strsplit(version,\" \")[[1]]\n version <- um[nchar(um)>0][2]\n hello <- paste(\"This is gamm4 \",version,\"\\n\",sep=\"\")\n packageStartupMessage(hello)\n}\n\n.onAttach <- function(...) { \n print.gamm4.version()\n \n}\n\n.onUnload <- function(libpath) {}\n\n", "meta": {"hexsha": "2948b3b40e9aff3f1a5646d6d898edb41b57eef1", "size": 19486, "ext": "r", "lang": "R", "max_stars_repo_path": "R/gamm4.r", "max_stars_repo_name": "r-gam/gamm4", "max_stars_repo_head_hexsha": "4d0639587fc7d08310f64bd694efc1b4bc22f363", "max_stars_repo_licenses": ["MIT"], "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/gamm4.r", "max_issues_repo_name": "r-gam/gamm4", "max_issues_repo_head_hexsha": "4d0639587fc7d08310f64bd694efc1b4bc22f363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-10T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T12:40:18.000Z", "max_forks_repo_path": "R/gamm4.r", "max_forks_repo_name": "r-gam/gamm4", "max_forks_repo_head_hexsha": "4d0639587fc7d08310f64bd694efc1b4bc22f363", "max_forks_repo_licenses": ["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.1285140562, "max_line_length": 135, "alphanum_fraction": 0.6183413733, "num_tokens": 5945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.21402005130001384}} {"text": "model_updatecalendar <- function (cumulTT = 741.510096671757,\n calendarMoments = c('Sowing'),\n calendarDates = c('2007/3/21'),\n calendarCumuls = c(0.0),\n currentdate = '2007/3/27',\n phase = 1.0){\n #'- Name: UpdateCalendar -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Calendar Model\n #' * Author: Pierre Martre\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: Lists containing for each stage the date it occurs as well as a copy of all types of cumulated thermal times \n #'- inputs:\n #' * name: cumulTT\n #' ** description : cumul thermal times at current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 741.510096671757\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: calendarMoments\n #' ** description : List containing apparition of each stage\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** default : ['Sowing']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarDates\n #' ** description : List containing the dates of the wheat developmental phases\n #' ** variablecategory : state\n #' ** datatype : DATELIST\n #' ** default : ['2007/3/21']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarCumuls\n #' ** description : list containing for each stage occured its cumulated thermal times\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** default : [0.0]\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: currentdate\n #' ** description : current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DATE\n #' ** default : 2007/3/27\n #' ** unit : \n #' ** inputtype : variable\n #' * name: phase\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : variable\n #'- outputs:\n #' * name: calendarMoments\n #' ** description : List containing apparition of each stage\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** unit : \n #' * name: calendarDates\n #' ** description : List containing the dates of the wheat developmental phases\n #' ** variablecategory : state\n #' ** datatype : DATELIST\n #' ** unit : \n #' * name: calendarCumuls\n #' ** description : list containing for each stage occured its cumulated thermal times\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** unit : °C d\n if (phase >= 1.0 && phase < 2.0 && !('Emergence' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'Emergence')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase >= 2.0 && phase < 3.0 && !('FloralInitiation' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'FloralInitiation')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase >= 3.0 && phase < 4.0 && !('Heading' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'Heading')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase == 4.0 && !('Anthesis' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'Anthesis')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase == 4.5 && !('EndCellDivision' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'EndCellDivision')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase >= 5.0 && phase < 6.0 && !('EndGrainFilling' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'EndGrainFilling')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n else if ( phase >= 6.0 && phase < 7.0 && !('Maturity' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'Maturity')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n return (list (\"calendarMoments\" = calendarMoments,\"calendarDates\" = calendarDates,\"calendarCumuls\" = calendarCumuls))\n}", "meta": {"hexsha": "e05c7ca6d5d8d3c1adaf93ff33da11dc663b0601", "size": 6282, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Updatecalendar.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Updatecalendar.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Updatecalendar.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 51.4918032787, "max_line_length": 139, "alphanum_fraction": 0.4594078319, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21161838646710243}} {"text": "\n\n# Snow crab --- Areal unit modelling of habitat -- no reliance upon stmv fields\n\n\n###------------------------------------------------\n#OS Compatability\n###------------------------------------------------\n\n#The use of the BYM2 model precludes using Windows, must be run in Linux \n#Virtual box install of Ubuntu or Debian is likely easiest option\n#BZ- July 2020- There may be an option to allow Windows to run the CAR steps as found here:\n#http://brettklamer.com/diversions/statistical/faster-blas-in-r/\n#Not yet tested\n\n\n#Choose one- likely latter\n{\n year.assessment=lubridate::year(Sys.Date()) # year.assessment\n year.assessment=lubridate::year(Sys.Date()) -1 # or year previous to current\n}\n\n\n#To add a title to any carstm_plot, please see below example\n#carstm_plot( p=p, res=res, vn=vn, main=list(label=\"my plot title\", cex=2) )\n\n\n# -------------------------------------------------\n# Part 1 -- construct basic parameter list defining the main characteristics of the study\nrequire(aegis)\n\n p = bio.snowcrab::snowcrab_carstm( DS=\"parameters\", assessment.years=1999:year.assessment )\n\n # misc run params adjustments here:\n p$inla_num.threads = 6\n p$inla_blas.num.threads = 6\n\n plot.dir=file.path(p$modeldir,\"prediction.plots\", year.assessment)\n dir.create(plot.dir)\n# ------------------------------------------------\n# Part 2 -- polygon structure\n sppoly = areal_units( p=p ) # to reload\n plot(sppoly)\n spplot( sppoly, \"au_sa_km2\", main=\"AUID\", sp.layout=p$coastLayout )\n if (0) {\n # create if not yet made\n MS = snowcrab.db( p=p, DS=\"biological_data\" ) # domain is sse # the underlying observations/data\n # ensure if polys exist and create if required\n for (au in c(\"cfanorth\", \"cfasouth\", \"cfa4x\", \"cfaall\" )) plot(polygons_managementarea( species=\"snowcrab\", au))\n sppoly = areal_units( p=p, areal_units_constraint=MS[, c(\"lon\", \"lat\")], redo=TRUE ) # create constrained polygons with neighbourhood as an attribute\n coastLayout = aegis.coastline::coastline_layout( p=p, redo=TRUE )\n MS = NULL\n }\n\n\n# -------------------------------------------------\n# Part 3 -- create covariate field for bathymetry\n# bathymetry -- ensure the data assimilation in bathymetry is first completed :: 01.bathymetry_data.R\n# about 2 hrs to redo; 15 configs @ 0.5 hrs each\n\n pB = bathymetry_carstm( p=p, DS=\"parameters_override\" )\n M = bathymetry.db( p=pB, DS=\"aggregated_data\", redo=TRUE )\n M = bathymetry_carstm( p=pB, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n res = carstm_model( p=pB, M='bathymetry_carstm( p=pB, DS=\"carstm_inputs\" )', DS=\"redo\", carstm_model_label=\"production\" ) # run model and obtain predictions\n\n if (0) {\n # to use a saved instance\n res = carstm_model( p=pB, DS=\"carstm_modelled\", carstm_model_label=\"production\" ) # run model and obtain predictions\n fit = carstm_model( p=pB, DS=\"carstm_modelled_fit\", carstm_model_label=\"production\" ) # extract currently saved model fit\n # maps of some of the results\n vn = paste(pB$variabletomodel, \"predicted\", sep=\".\")\n zplot=sc_carstm_plot( p=pB, res=res, vn=vn )\n \n #to save map of predicted mean\n \n vn = paste(pB$variabletomodel, \"predicted_se\", sep=\".\")\n zplot=sc_carstm_plot( p=pB, res=res, vn=vn )\n \n vn = paste(pB$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n sc_carstm_plot( p=pB, res=res, vn=vn )\n\n vn = paste(pB$variabletomodel, \"random_auid_spatial\", sep=\".\")\n sc_carstm_plot( p=pB, res=res, vn=vn )\n\n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE, single=TRUE )\n\n #Framework Run (to 2018)\n \n # Time used:\n # Pre = 2.71, Running = 4366, Post = 3.26, Total = 4372\n # Fixed effects:\n # mean sd 0.025quant 0.5quant 0.975quant mode kld\n # (Intercept) 7.872 0 7.871 7.872 7.873 7.872 0\n\n # Random effects:\n # Name\t Model\n # auid BYM2 model\n\n # Model hyperparameters:\n # mean sd 0.025quant 0.5quant 0.975quant mode\n # Precision for the lognormal observations 4786.388 21.24 4744.647 4786.372 4828.230 4786.400\n # Precision for auid 1412.186 227.70 1091.296 1368.558 1964.898 1254.958\n # Phi for auid 0.979 0.02 0.924 0.986 0.999 0.996\n\n # Expected number of effective parameters(stdev): 3270.84(12.81)\n # Number of equivalent replicates : 33.03\n\n # Deviance Information Criterion (DIC) ...............: 1094943.11\n # Deviance Information Criterion (DIC, saturated) ....: 111315.40\n # Effective number of parameters .....................: 3271.74\n\n # Marginal log-Likelihood: -547965.21\n # Posterior marginals for the linear predictor and\n # the fitted values are computed\n\n\n }\n\n\n# -------------------------------------------------\n# Part 4 -- create covariate field for substrate\n# ensure the data assimilation in substrate is first completed :: 01.substrate_data.R\n# 25 configs @ 5 min each, total time 2 hrs\n pS = substrate_carstm(p=p, DS=\"parameters_override\" )\n M = substrate.db( p=pS, DS=\"aggregated_data\", redo=TRUE ) # used for data matching/lookup in other aegis projects that use substrate\n M = substrate_carstm( p=pS, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n res = carstm_model( p=pS, M='substrate_carstm( p=pS, DS=\"carstm_inputs\")', DS=\"redo\", carstm_model_label=\"production\" ) # run model and obtain predictions\n\n if(0) {\n res = carstm_model( p=pS, DS=\"carstm_modelled\", carstm_model_label=\"production\" ) # run model and obtain predictions\n fit = carstm_model( p=pS, DS=\"carstm_modelled_fit\", carstm_model_label=\"production\" ) # extract currently saved model fit\n summary(fit)\n\n# Fixed effects:\n# mean sd 0.025quant 0.5quant 0.975quant mode kld\n# (Intercept) -1.038 0.024 -1.086 -1.038 -0.991 -1.038 0\n\n# Random effects:\n# Name\t Model\n# inla.group(z, method = \"quantile\", n = 13) RW2 model\n# auid BYM2 model\n\n# Model hyperparameters:\n# mean sd 0.025quant 0.5quant 0.975quant mode\n# Precision for the lognormal observations 1.519 0.007 1.506 1.519 1.533 1.519\n# Precision for inla.group(z, method = \"quantile\", n = 13) 5.833 2.643 2.047 5.401 12.175 4.490\n# Precision for auid 0.903 0.110 0.714 0.893 1.144 0.871\n# Phi for auid 0.962 0.034 0.871 0.972 0.996 0.989\n\n# Expected number of effective parameters(stdev): 195.14(0.203)\n# Number of equivalent replicates : 493.07\n\n# Deviance Information Criterion (DIC) ...............: 34384.88\n# Deviance Information Criterion (DIC, saturated) ....: 96394.93\n# Effective number of parameters .....................: 196.18\n\n# Marginal log-Likelihood: -17603.13\n\n vn = paste(pS$variabletomodel, \"predicted\", sep=\".\")\n ssplot=sc_carstm_plot( p=pS, res=res, vn=vn, main=\"Substrate Grain Size\" ) # maps of some of the results\n ssplot\n \n #to save map of predicted mean\n fn=paste(\"substrate.predicted\", year.assessment,\"pdf\", sep=\".\" )\n pdf(file=paste(plot.dir, fn, sep=\"/\"))\n ssplot\n dev.off()\n \n vn = paste(pS$variabletomodel, \"predicted_se\", sep=\".\")\n sc_carstm_plot( p=pS, res=res, vn=vn )\n\n vn = paste(pS$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n sc_carstm_plot( p=pS, res=res, vn=vn )\n\n vn = paste(pS$variabletomodel, \"random_auid_spatial\", sep=\".\")\n sc_carstm_plot( p=pS, res=res, vn=vn )\n\n\n\n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE, single=TRUE )\n\n #------------\n # 6567.727 sec = 1.8hrs\n\n pS$carstm_model_label = \"production_inla.group_quantile_25\"\n # DIC:\n # Mean of Deviance ................. 33840.1\n # Deviance at Mean ................. 33636.8\n # Effective number of parameters ... 203.318\n # DIC .............................. 34043.4\n # DIC (Saturated):\n # Mean of Deviance ................. 95897.9\n # Deviance at Mean ................. 95694.6\n # Effective number of parameters ... 203.318\n # DIC .............................. 96101.3\n\n\n\n\n pS$carstm_model_label = \"production_inla.group_quantile_20\"\n # DIC:\n # \tMean of Deviance ................. 33995.4\n # \tDeviance at Mean ................. 33794.6\n # \tEffective number of parameters ... 200.881\n # \tDIC .............................. 34196.3\n # DIC (Saturated):\n # \tMean of Deviance ................. 96187.3\n # \tDeviance at Mean ................. 95986.4\n # \tEffective number of parameters ... 200.881\n # \tDIC .............................. 96388.2\n\n pS$carstm_modelcall = paste('\n inla(\n formula =', pS$variabletomodel, ' ~ 1\n + f( inla.group(z, method=\"quantile\", n=13) , model=\"rw2\", scale.model=TRUE, hyper=H$rw2)\n + f(auid, model=\"bym2\", graph=sppoly@nb, scale.model=TRUE, constr=TRUE, hyper=H$bym2),\n family = \"lognormal\",\n data= M,\n control.compute=list(dic=TRUE, config=TRUE),\n control.results=list(return.marginals.random=TRUE, return.marginals.predictor=TRUE ),\n control.predictor=list(compute=FALSE, link=1 ),\n control.fixed=H$fixed, # priors for fixed effects, generic is ok\n verbose=TRUE\n ) ' )\n res = carstm_model( p=pS, M='substrate_carstm( p=pS, DS=\"carstm_inputs\")', DS=\"redo\", carstm_model_label=pS$carstm_model_label ) # run model and obtain predictions\n fit = carstm_model( p=pS, DS=\"carstm_modelled_fit\", carstm_model_label=pS$carstm_model_label ) # extract currently saved model fit\n\n }\n\n\n\n\n# -------------------------------------------------\n# Part 5 -- create covariate field for temperature\n# ensure the data assimilation in temperature is first completed :: 01.temperature_data.R\n# total: 30 min, 80 configs .. fast\n# -------------------------------------------------\n# Part 1 -- construct basic parameter list defining the main characteristics of the study\n\n pT = temperature_carstm(p=p, DS=\"parameters_override\" )\n M = temperature.db( p=pT, DS=\"aggregated_data\", redo=TRUE ) # used for data matching/lookup in other aegis projects that use temperature\n M = temperature_carstm( p=pT, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n res = carstm_model( p=pT, M='temperature_carstm( p=pT, DS=\"carstm_inputs\")', DS=\"redo\", carstm_model_label=\"production\" ) # run model and obtain predictions\n if (0) {\n res = carstm_model( p=pT, DS=\"carstm_modelled\", carstm_model_label=\"production\" ) # run model and obtain predictions\n fit = carstm_model( p=pT, DS=\"carstm_modelled_fit\", carstm_model_label=\"production\" ) # extract currently saved model fit\n summary(fit)\n\n#Framework Model Summary (to 2018)\n#-------------------------------\n# Time used:\n# Pre = 2.99, Running = 612, Post = 7.01, Total = 622\n# Fixed effects:\n# mean sd 0.025quant 0.5quant 0.975quant mode kld\n# (Intercept) 4.52 0.285 3.937 4.522 5.089 4.524 0\n\n# Random effects:\n# Name\t Model\n# dyri AR1 model\n# inla.group(z, method = \"quantile\", n = 13) RW2 model\n# auid BYM2 model\n\n# Model hyperparameters:\n# mean sd 0.025quant 0.5quant 0.975quant mode\n# Precision for the Gaussian observations 0.504 0.005 0.495 0.504 0.514 0.504\n# Precision for dyri 6.302 2.551 2.482 5.935 12.346 5.158\n# Rho for dyri 0.725 0.121 0.447 0.740 0.913 0.780\n# Precision for inla.group(z, method = \"quantile\", n = 13) 0.413 0.111 0.243 0.396 0.676 0.365\n# Precision for auid 0.427 0.024 0.383 0.426 0.476 0.423\n# Phi for auid 0.427 0.034 0.355 0.429 0.488 0.439\n# GroupRho for auid 0.841 0.011 0.817 0.842 0.862 0.843\n\n# Expected number of effective parameters(stdev): 1860.76(37.35)\n# Number of equivalent replicates : 14.44\n\n# Deviance Information Criterion (DIC) ...............: 96494.96\n# Deviance Information Criterion (DIC, saturated) ....: 28729.33\n# Effective number of parameters .....................: 1862.94\n\n# Marginal log-Likelihood: -47560.07\n# Posterior marginals for the linear predictor and\n\n \n vn = paste(pT$variabletomodel, \"predicted\", sep=\".\")\n \n sc_carstm_plot( p=pT, res=res, vn=vn, time_match=list(year=\"2000\", dyear=\"0.85\", main=\"Temperature\" ) ) # maps of some of the results\n \n vn = paste(pT$variabletomodel, \"predicted_se\", sep=\".\")\n sc_carstm_plot( p=pT, res=res, vn=vn, time_match=list(year=\"2000\", dyear=\"0.85\" ) ) # maps of some of the results\n \n vn = paste(pT$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n sc_carstm_plot( p=pT, res=res, vn=vn, time_match=list(year=\"2000\" ) ) # maps of some of the results\n \n vn = paste(pT$variabletomodel, \"random_auid_spatial\", sep=\".\")\n sc_carstm_plot( p=pT, res=res, vn=vn, time_match=list(year=\"2000\" ) ) # maps of some of the results\n \n \n \n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE, single=TRUE )\n \n \n }\n \n #to plot predicted temperature maps for last six years\n \n recent=as.character((year.assessment-6): year.assessment)\n vn = paste(pT$variabletomodel, \"predicted\", sep=\".\")\n\n for (x in recent){\n fn=paste(x,\"t\", \"pdf\", sep=\".\")\n outfile=paste(plot.dir, fn, sep=\"/\")\n each.plot= sc_carstm_plot( p=pT, res=res, vn=vn, time_match=list(year=x, dyear=\"0.85\" ), main= )\n pdf(outfile)\n print(each.plot)\n dev.off()\n } \n \n\n\n\n# -------------------------------------------------\n# Part 6 -- create covariate field for species composition 1\n# ensure that survey data is assimilated : bio.snowcrab::01snowcb_data.R, aegis.survey::01.surveys.data.R , etc.\n# 30 min, 150 configs\n require(aegis.speciescomposition)\n require(carstm)\n\n pPC1 = speciescomposition_carstm(p=p, DS=\"parameters_override\", varnametomodel=\"pca1\" )\n M = speciescomposition_carstm( p=pPC1, DS=\"carstm_inputs\", varnametomodel=\"pca1\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n res = carstm_model( p=pPC1, M='speciescomposition_carstm( p=p, DS=\"carstm_inputs\", varnametomodel=\"pca1\" )', DS=\"redo\", carstm_model_label=\"production\" ) # run model and obtain predictions\n if (0) {\n res = carstm_model( p=pPC1, DS=\"carstm_modelled\", carstm_model_label=\"production\" ) # run model and obtain predictions\n fit = carstm_model( p=pPC1, DS=\"carstm_modelled_fit\", carstm_model_label=\"production\" ) # extract currently saved model fit\n summary(fit)\n \n plot( fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n\n vn = paste(pPC1$variabletomodel, \"predicted\", sep=\".\")\n sc_carstm_plot( p=pPC1, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results\n \n vn = paste(pPC1$variabletomodel, \"predicted_se\", sep=\".\")\n sc_carstm_plot( p=pPC1, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results\n\n vn = paste(pPC1$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n sc_carstm_plot( p=pPC1, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results , dyear=\"0.85\"\n \n vn = paste(pPC1$variabletomodel, \"random_auid_spatial\", sep=\".\")\n sc_carstm_plot( p=pPC1, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results , dyear=\"0.85\"\n\n \n#From Framework Run(up to 2018)\n# Time used:\n# Pre = 2.67, Running = 667, Post = 4.98, Total = 675\n# Fixed effects:\n# mean sd 0.025quant 0.5quant 0.975quant mode kld\n# (Intercept) 0.143 0.015 0.11 0.143 0.173 0.144 0\n\n# Random effects:\n# Name\t Model\n# dyri AR1 model\n# inla.group(t, method = \"quantile\", n = 13) RW2 model\n# inla.group(z, method = \"quantile\", n = 13) RW2 model\n# inla.group(substrate.grainsize, method = \"quantile\", n = 13) RW2 model\n# auid BYM2 model\n\n# Model hyperparameters:\n# mean sd 0.025quant 0.5quant\n# Precision for the Gaussian observations 1.91e+02 2.88e+00 185.644 1.91e+02\n# Precision for dyri 1.03e+03 6.60e+02 273.266 8.62e+02\n# Rho for dyri 5.50e-02 2.47e-01 -0.430 5.90e-02\n# Precision for inla.group(t, method = \"quantile\", n = 13) 1.70e+04 1.45e+04 2813.038 1.30e+04\n# Precision for inla.group(z, method = \"quantile\", n = 13) 1.61e+02 7.50e+01 53.252 1.49e+02\n# Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 7.29e+02 2.72e+03 9.795 1.95e+02\n# Precision for auid 1.71e+02 1.21e+01 147.609 1.71e+02\n# Phi for auid 5.19e-01 3.80e-02 0.442 5.20e-01\n# GroupRho for auid 9.19e-01 7.00e-03 0.905 9.19e-01\n# 0.975quant mode\n# Precision for the Gaussian observations 1.97e+02 191.036\n# Precision for dyri 2.75e+03 612.450\n# Rho for dyri 5.19e-01 0.069\n# Precision for inla.group(t, method = \"quantile\", n = 13) 5.54e+04 7245.080\n# Precision for inla.group(z, method = \"quantile\", n = 13) 3.41e+02 121.730\n# Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 4.73e+03 19.393\n# Precision for auid 1.95e+02 170.771\n# Phi for auid 5.92e-01 0.523\n# GroupRho for auid 9.33e-01 0.919\n\n# Expected number of effective parameters(stdev): 1129.49(30.74)\n# Number of equivalent replicates : 9.58\n\n# Deviance Information Criterion (DIC) ...............: -24998.14\n# Deviance Information Criterion (DIC, saturated) ....: 11953.32\n# Effective number of parameters .....................: 1132.66\n\n# Marginal log-Likelihood: 13670.07\n\n\n }\n\n\n\n\n\n# -------------------------------------------------\n# Part 7 -- create covariate field for species composition 2\n# ensure that survey data is assimilated : bio.snowcrab::01snowcb_data.R, aegis.survey::01.surveys.data.R ,\n# etc.30 min, 30 min\n\n pPC2 = speciescomposition_carstm(p=p, DS=\"parameters_override\", varnametomodel=\"pca2\" )\n M = speciescomposition_carstm( p=pPC2, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n res = carstm_model( p=pPC2, M='speciescomposition_carstm( p=p, DS=\"carstm_inputs\", varnametomodel=\"pca2\" )', DS=\"redo\" , carstm_model_label=\"production\" ) # run model and obtain predictions\n if (0) {\n res = carstm_model( p=pPC2, DS=\"carstm_modelled\", carstm_model_label=\"production\" ) # run model and obtain predictions\n fit = carstm_model( p=pPC2, DS=\"carstm_modelled_fit\", carstm_model_label=\"production\" ) # extract currently saved model fit\n summary(fit)\n plot( fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n\n vn = paste(pPC2$variabletomodel, \"predicted\", sep=\".\")\n sc_carstm_plot( p=pPC2, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results\n \n vn = paste(pPC2$variabletomodel, \"predicted_se\", sep=\".\")\n sc_carstm_plot( p=pPC2, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results\n\n vn = paste(pPC2$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n sc_carstm_plot( p=pPC2, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results , dyear=\"0.85\"\n \n vn = paste(pPC2$variabletomodel, \"random_auid_spatial\", sep=\".\")\n carstm_plot( p=pPC2, res=res, vn=vn, time_match=list(year=\"2017\" ), dyear=\"0.85\" ) # maps of some of the results , dyear=\"0.85\"\n\n # Time used:\n # Pre = 4.86, Running = 1768, Post = 11.8, Total = 1785\n # Fixed effects:\n # mean sd 0.025quant 0.5quant 0.975quant mode kld\n # (Intercept) 0.02 0.021 -0.024 0.02 0.065 0.02 0\n\n # Random effects:\n # Name\t Model\n # dyri AR1 model\n # inla.group(t, method = \"quantile\", n = 13) RW2 model\n # inla.group(z, method = \"quantile\", n = 13) RW2 model\n # inla.group(substrate.grainsize, method = \"quantile\", n = 13) RW2 model\n # auid BYM2 model\n\n # Model hyperparameters:\n # mean sd 0.025quant 0.5quant\n # Precision for the Gaussian observations 255.139 3.86e+00 247.336 255.239\n # Precision for dyri 972.573 5.21e+02 267.742 875.460\n # Rho for dyri 0.601 2.19e-01 0.123 0.627\n # Precision for inla.group(t, method = \"quantile\", n = 13) 7071.547 1.04e+04 757.266 4032.628\n # Precision for inla.group(z, method = \"quantile\", n = 13) 340.448 2.10e+02 109.684 285.481\n # Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 1267.298 1.65e+03 97.368 769.744\n # Precision for auid 398.917 3.31e+01 335.265 398.669\n # Phi for auid 0.538 7.00e-02 0.383 0.546\n # GroupRho for auid 0.914 8.00e-03 0.897 0.915\n # 0.975quant mode\n # Precision for the Gaussian observations 2.63e+02 255.632\n # Precision for dyri 2.25e+03 661.698\n # Rho for dyri 9.32e-01 0.750\n # Precision for inla.group(t, method = \"quantile\", n = 13) 3.22e+04 1784.791\n # Precision for inla.group(z, method = \"quantile\", n = 13) 8.90e+02 210.519\n # Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 5.51e+03 259.117\n # Precision for auid 4.65e+02 399.531\n # Phi for auid 6.53e-01 0.578\n # GroupRho for auid 9.30e-01 0.915\n\n # Expected number of effective parameters(stdev): 921.94(40.80)\n # Number of equivalent replicates : 11.74\n\n # Deviance Information Criterion (DIC) ...............: -28335.04\n # Deviance Information Criterion (DIC, saturated) ....: 11769.79\n # Effective number of parameters .....................: 928.42\n\n # Marginal log-Likelihood: 15491.21\n\n\n }\n\n\n\n# finished covariates ... move onto abundance index estimation\n\n\n\n# -------------------------------------------------\n# Part 8 -- Snow crab anbundance -- main mode used for production\n# 9 hrs 281 configs\n\n M = snowcrab_carstm( p=p, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n #To compare values of M, run the following line:\n #load(paste(p$modeldir, \"M.summary.rdata\", sep=\"/\"))\n \n M = NULL; gc()\n res = carstm_model( p=p, M='snowcrab_carstm( p=p, DS=\"carstm_inputs\" )' ) # 151 configs and long optim .. 19 hrs\n\n # m = get(\"inla.models\", INLA:::inla.get.inlaEnv())\n\t# m$latent$rw2$min.diff = NULL\n\t# assign(\"inla.models\", m, INLA:::inla.get.inlaEnv())\n\n\n # extract results\n res = carstm_model( p=p, DS=\"carstm_modelled\" ) # to load currently saved res\n fit = carstm_model( p=p, DS=\"carstm_modelled_fit\" ) # extract currently saved model fit\n summary(fit)\n\n\n\n# Time used:\n# Pre = 2.67, Running = 17238, Post = 3.15, Total = 17243\n# Fixed effects:\n# mean sd 0.025quant 0.5quant 0.975quant mode kld\n# (Intercept) 5.483 0.117 5.244 5.486 5.71 5.49 0\n\n# Random effects:\n# Name\t Model\n# dyri AR1 model\n# inla.group(t, method = \"quantile\", n = 13) RW2 model\n# inla.group(z, method = \"quantile\", n = 13) RW2 model\n# inla.group(substrate.grainsize, method = \"quantile\", n = 13) RW2 model\n# inla.group(pca1, method = \"quantile\", n = 13) RW2 model\n# inla.group(pca2, method = \"quantile\", n = 13) RW2 model\n# auid BYM2 model\n\n# Model hyperparameters:\n# mean sd 0.025quant 0.5quant 0.975quant\n# Precision for dyri 24.644 13.295 7.198 21.987 57.758\n# Rho for dyri -0.010 0.132 -0.273 -0.008 0.245\n# Precision for inla.group(t, method = \"quantile\", n = 13) 6.078 2.716 2.367 5.559 12.835\n# Precision for inla.group(z, method = \"quantile\", n = 13) 4.846 2.067 2.060 4.431 10.025\n# Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 0.243 0.081 0.125 0.229 0.439\n# Precision for inla.group(pca1, method = \"quantile\", n = 13) 7.210 3.278 2.842 6.549 15.399\n# Precision for inla.group(pca2, method = \"quantile\", n = 13) 20.402 9.195 8.012 18.592 43.366\n# Precision for auid 0.430 0.035 0.364 0.429 0.502\n# Phi for auid 0.688 0.056 0.571 0.691 0.790\n# GroupRho for auid 0.817 0.013 0.790 0.818 0.843\n# mode\n# Precision for dyri 16.790\n# Rho for dyri -0.001\n# Precision for inla.group(t, method = \"quantile\", n = 13) 4.642\n# Precision for inla.group(z, method = \"quantile\", n = 13) 3.734\n# Precision for inla.group(substrate.grainsize, method = \"quantile\", n = 13) 0.204\n# Precision for inla.group(pca1, method = \"quantile\", n = 13) 5.425\n# Precision for inla.group(pca2, method = \"quantile\", n = 13) 15.463\n# Precision for auid 0.427\n# Phi for auid 0.696\n# GroupRho for auid 0.818\n\n# Expected number of effective parameters(stdev): 1920.79(15.10)\n# Number of equivalent replicates : 3.96\n\n# Deviance Information Criterion (DIC) ...............: 47009.33\n# Deviance Information Criterion (DIC, saturated) ....: 28943.24\n# Effective number of parameters .....................: 1894.56\n\n# Marginal log-Likelihood: -23611.26\n# Posterior marginals for the linear predictor and\n# the fitted values are computed\n\n\n vn = paste(p$variabletomodel, \"predicted\", sep=\".\")\n carstm_plot( p=p, res=res, vn=vn, time_match=list(year=\"2000\" ) ) # maps of some of the results\n\n\n plot(fit)\n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE, single=TRUE )\n s = summary(fit)\n s$dic$dic\n s$dic$p.eff\n\n # maps of some of the results\n vn = paste(p$variabletomodel, \"random_sample_iid\", sep=\".\")\n if (exists(vn, res)) carstm_plot( p=p, res=res, vn=vn, time_match=list(year=\"1950\", dyear=\"0.05\") )\n\n vn = paste(p$variabletomodel, \"random_auid_nonspatial\", sep=\".\")\n if (exists(vn, res)) {\n res_dim = dim( res[[vn]] )\n if (res_dim == 1 ) time_match = NULL\n if (res_dim == 2 ) time_match = list(year=\"2000\")\n if (res_dim == 3 ) time_match = list(year=\"2000\", dyear=\"0.85\" )\n carstm_plot( p=p, res=res, vn=vn, time_match=time_match )\n }\n\n vn = paste(p$variabletomodel, \"random_auid_spatial\", sep=\".\")\n if (exists(vn, res)) {\n res_dim = dim( res[[vn]] )\n if (res_dim == 1 ) time_match = NULL\n if (res_dim == 2 ) time_match = list(year=\"2000\")\n if (res_dim == 3 ) time_match = list(year=\"2000\", dyear=\"0.85\" )\n sc_carstm_plot( p=p, res=res, vn=vn, time_match=time_match )\n }\n\n\n sppoly = areal_units( p=p ) # to reload\n M = snowcrab_carstm( p=p, DS=\"carstm_inputs\" )\n M$yr = M$year # req for meanweights\n\n # mean weight by auidxyear\n wgts = meanweights_by_arealunit(\n set=M[M$tag==\"observations\",],\n AUID=as.character( sppoly$AUID ),\n yrs=p$yrs,\n fillall=TRUE,\n annual_breakdown=TRUE,\n robustify_quantiles=c(0, 0.99) # high upper bounds are more dangerous\n )\n\n\n carstm_summary( p=p, operation=\"compute\", carstm_model_label=p$carstm_model_label, wgts=wgts )\n\n RES = carstm_summary(p=p, operation=\"load_timeseries\", carstm_model_label=p$carstm_model_label )\n\n bio = carstm_summary(p=p, operation=\"load_spacetime_biomass\", carstm_model_label=p$carstm_model_label )\n num = carstm_summary(p=p, operation=\"load_spacetime_number\", carstm_model_label=p$carstm_model_label )\n\n\n plot( cfaall ~ yrs, data=RES, lty=1, lwd=2.5, col=\"red\", type=\"b\", ylab=\"Biomass (kt)\", xlab=\"\")\n plot( cfasouth ~ yrs, data=RES, lty=1, lwd=2.5, col=\"red\", type=\"b\", ylab=\"Biomass (kt)\", xlab=\"\")\n plot( cfanorth ~ yrs, data=RES, lty=1, lwd=2.5, col=\"red\", type=\"b\", ylab=\"Biomass (kt)\", xlab=\"\")\n plot( cfa4x ~ yrs, data=RES, lty=1, lwd=2.5, col=\"red\", type=\"b\", ylab=\"Biomass (kt)\", xlab=\"\")\n\n \n p$boundingbox = list( xlim=p$corners$lon, ylim=p$corners$lat) # bounding box for plots using spplot\n\n p$coastLayout = aegis.coastline::coastline_layout(p=p)\n p$mypalette=RColorBrewer::brewer.pal(9, \"YlOrRd\")\n sppoly = areal_units( p=p ) # to reload\n\n\n # map it ..mean density\n vn = \"pred\"\n sppoly@data[,vn] = bio[,\"2017\"]\n brks = interval_break(X= sppoly[[vn]], n=length(p$mypalette), style=\"quantile\")\n spplot( sppoly, vn, col.regions=p$mypalette, main=vn, at=brks, sp.layout=p$coastLayout, col=\"transparent\" )\n\n #to save plots of the last six years:\n #Needs to be run in Windows or outside Linux Rstudio for now \n recent=as.character((year.assessment-6): year.assessment)\n \n for (x in recent){\n sppoly@data[,vn] = bio[,x]\n brks = interval_break(X= sppoly[[vn]], n=length(p$mypalette), style=\"quantile\")\n each.plot=spplot( sppoly, vn, col.regions=p$mypalette, main=x, at=brks, sp.layout=p$coastLayout, col=\"transparent\" )\n fn=paste(x,\"biomass\", \"pdf\", sep=\".\")\n outfile=paste(plot.dir, fn, sep=\"/\")\n pdf(outfile)\n print(each.plot)\n dev.off()\n } \n \n\n plot( fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n plot( fit$marginals.hyperpar$\"Phi for auid\", type=\"l\") # posterior distribution of phi nonspatial dominates\n plot( fit$marginals.hyperpar$\"Precision for auid\", type=\"l\")\n plot( fit$marginals.hyperpar$\"Precision for setno\", type=\"l\")\n\n\n\n\n\n# end\n", "meta": {"hexsha": "dc70ffb734ca7f5e416718d19242e9afac4a63aa", "size": 32089, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/scripts/03.abundance_estimation_carstm.r", "max_stars_repo_name": "PEDsnowcrab/bio.snowcrab", "max_stars_repo_head_hexsha": "813314691c33830f4bc4db9f9a2d1d5861581303", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inst/scripts/03.abundance_estimation_carstm.r", "max_issues_repo_name": "PEDsnowcrab/bio.snowcrab", "max_issues_repo_head_hexsha": "813314691c33830f4bc4db9f9a2d1d5861581303", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inst/scripts/03.abundance_estimation_carstm.r", "max_forks_repo_name": "PEDsnowcrab/bio.snowcrab", "max_forks_repo_head_hexsha": "813314691c33830f4bc4db9f9a2d1d5861581303", "max_forks_repo_licenses": ["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.2541353383, "max_line_length": 192, "alphanum_fraction": 0.5707251706, "num_tokens": 9650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.2075484689803764}} {"text": "# compare the ant host tree to each of the blochmannia gene trees\n\nlibrary(ape)\nlibrary(phytools)\nlibrary(seqinr)\noptions(scipen=999)\n\n# read in species tree\nspecies_tree <- read.nexus(\"camp_summed.tre\")\nspecies_tree <- midpoint.root(species_tree)\n# remove single quotes from tip labels\nspecies_tree$tip.label <- gsub(\"'\", \"\", species_tree$tip.label)\n# remove furthest outgroup \nspecies_tree <- drop.tip(species_tree, \"SRX5650044\")\n# rename tips to coincide with blochmannia trees\nspecies_tree$tip.label[species_tree$tip.label == \"C-028\"] <- \"28_vicinus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-005\"] <- \"5_vicinus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-029\"] <- \"29_vicinusunk\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-024\"] <- \"24_vicinusunk\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-056\"] <- \"56_herculeanus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-049\"] <- \"49_herculeanus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-050\"] <- \"50_herculeanus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-019\"] <- \"19_modoc\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-002\"] <- \"2_modoc\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-036\"] <- \"36_modoc\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-010\"] <- \"10_pennunk\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-016\"] <- \"16_pennunk\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-018\"] <- \"18_pennunk\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-003\"] <- \"3_laevigatus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-046\"] <- \"46_laevigatus\"\nspecies_tree$tip.label[species_tree$tip.label == \"SRX022802\"] <- \"floridanus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-006\"] <- \"6_ocreatus\"\nspecies_tree$tip.label[species_tree$tip.label == \"C-039\"] <- \"39_vicinus\"\nplot(species_tree)\n\n# identify the trees to read in and then parse out their names\nall_trees <- list.files(\"bloch_fasta_trees\", pattern=\"RAxML*\", full.names=T)\ntree_names <- substr(all_trees, 55, nchar(all_trees))\ntree_names <- sapply(strsplit(tree_names, \"\\\\.1_\"), \"[[\", 2)\ntree_names <- sapply(strsplit(tree_names, \"\\\\.tre\"), \"[[\", 1)\n\n# calculate the Kuhner and Felsenstein (1994) branch length score differences between blochmannia\n# genes and the ant species tree\nkf94 <- c()\nfor(a in 1:length(all_trees)) {\n\ta_rep <- read.tree(all_trees[a])\n\ta_rep <- midpoint.root(a_rep)\n\t# measure the Kuhner and Felsenstein (1994) branch length score\n\tkf94 <- c(kf94, dist.topo(species_tree, a_rep, method=\"score\")[1])\t\n}\n\n# define the species for measuring phylogenetic distance\nspecies_names <- c(\"tanaemyrmex\", \"camponotus\")\ngroups <- list()\ngroups[[1]] <- c(\"28_vicinus\", \"5_vicinus\", \"39_vicinus\", \"29_vicinusunk\", \"24_vicinusunk\")\ngroups[[2]] <- c(\"3_laevigatus\", \"46_laevigatus\", \"56_herculeanus\", \"49_herculeanus\", \"50_herculeanus\", \"19_modoc\", \"2_modoc\", \"36_modoc\", \"10_pennunk\", \"16_pennunk\", \"18_pennunk\")\ngroups[[3]] <- c(groups[[1]], groups[[2]])\n\n# loop for each tree\noutput <- c()\nhost_distances <- c()\nfor(a in 1:length(all_trees)) {\n\ta_rep <- read.tree(all_trees[a])\n\ta_rep <- midpoint.root(a_rep)\n\t# loop for each species\n\ttree_distances <- c()\n\tfor(g in 1:length(groups)) {\n\t\tgroup_of_interest <- groups[[g]]\n\t\t# calculate MRCA distance for each species (for the ant species tree)\n\t\tif(a == 1) {\n\t\t\t# calculate MRCA of entire group\n\t\t\ttotal_mrca <- getMRCA(species_tree, tip = group_of_interest)\n\t\t\t# calculate length of edges to reach common ancestor for each individual in group\n\t\t\t# and then average\n\t\t\tedge_lengths <- list()\n\t\t\tgroup_edge_lengths <- c()\n\t\t\tfor(b in 1:length(group_of_interest)) {\n\t\t\t\t# set edge length as zero to add to\n\t\t\t\tedge_lengths[[b]] <- 0\n\t\t\t\t# what is the number of this individual?\n\t\t\t\tb_number <- match(group_of_interest[b], species_tree$tip.label)\n\t\t\t\t\n\t\t\t\t# loop throup edge table until reaching MRCA\n\t\t\t\twhile_loop <- 0\n\t\t\t\twhile(while_loop != total_mrca) {\n\t\t\t\t\t# add edge length\n\t\t\t\t\tedge_lengths[[b]] <- edge_lengths[[b]] + species_tree$edge.length[species_tree$edge[,2]==b_number]\n\t\t\t\n\t\t\t\t\t# change new number to that node and update the while_loop object to the node\n\t\t\t\t\tb_number <- species_tree$edge[species_tree$edge[,2]==b_number,1]\n\t\t\t\t\twhile_loop <- b_number\n\t\t\t\t}\n\t\t\t\t# add the MRCA to the nodes_needed object\n\t\t\t\tgroup_edge_lengths <- c(group_edge_lengths, edge_lengths[[b]])\n\t\t\t}\n\n\t\t\t# calc the mean of the group edge lengths\n\t\t\tgroup_edge_lengths <- mean(group_edge_lengths)\n\t\t\t# add to vector\n\t\t\thost_distances <- c(host_distances, group_edge_lengths)\n\t\t}\n\t\t\n\t\t# calculate for the blochmannia tree\n\t\t# calculate MRCA of entire group\n\t\ttotal_mrca <- getMRCA(a_rep, tip = group_of_interest)\n\t\t# calculate length of edges to reach common ancestor for each individual in group\n\t\t# and then average\n\t\tedge_lengths <- list()\n\t\tgroup_edge_lengths <- c()\n\t\tfor(b in 1:length(group_of_interest)) {\n\t\t\t# set edge length as zero to add to\n\t\t\tedge_lengths[[b]] <- 0\n\t\t\t# what is the number of this individual?\n\t\t\tb_number <- match(group_of_interest[b], a_rep$tip.label)\n\t\t\t\n\t\t\t# loop throup edge table until reaching MRCA\n\t\t\twhile_loop <- 0\n\t\t\twhile(while_loop != total_mrca) {\n\t\t\t\t# add edge length\n\t\t\t\tedge_lengths[[b]] <- edge_lengths[[b]] + a_rep$edge.length[a_rep$edge[,2]==b_number]\n\t\t\n\t\t\t\t# change new number to that node and update the while_loop object to the node\n\t\t\t\tb_number <- a_rep$edge[a_rep$edge[,2]==b_number,1]\n\t\t\t\twhile_loop <- b_number\n\t\t\t}\n\t\t\t# add the MRCA to the nodes_needed object\n\t\t\tgroup_edge_lengths <- c(group_edge_lengths, edge_lengths[[b]])\n\t\t}\n\n\t\t# calc the mean of the group edge lengths\n\t\tgroup_edge_lengths <- mean(group_edge_lengths)\n\t\t# add to vector\n\t\ttree_distances <- c(tree_distances, group_edge_lengths)\n\t}\n\toutput <- rbind(output, tree_distances)\n}\t\n\n# mean blochmannia edge lengths / host phylogeny edge lengths\noutput[,1] <- output[,1] / host_distances[1]\noutput[,2] <- output[,2] / host_distances[2]\noutput[,3] <- output[,3] / host_distances[3]\n\n# add all outputs into a data frame\noutput2 <- data.frame(gene_number = as.numeric(sapply(strsplit(tree_names, \"_\"), \"[[\", 1)), gene_name = as.character(sapply(strsplit(tree_names, \"-\"), \"[[\", 2)), kf94 = kf94, bloch_tanaemyrmex_edge_length = output[,1], bloch_camponotus_edge_length = output[,2], edge_length = output[,3])\n\n\n# write output\nwrite.table(output2, file=\"blochmannia_tree_characteristics.txt\", sep=\"\\t\", quote=F, row.names=F, col.names=T)\n\n\n# read in output\nx <- read.table(\"blochmannia_tree_characteristics.txt\", stringsAsFactors=F, header=T)\n# order by gene number\nx <- x[order(x[,1]),]\n# get absolute rate estimates from Camponotus molecular evolution rate\nsummary(x$edge_length) * 1.983877e-09\n\n# read in outgroup annotations\nflor <- read.table(\"BX248583_floridanus_annotations.tsv\", stringsAsFactors=F, header=T, fill=T, row.names=NULL)\n# keep only annotations that are for \"CDS\"\nflor <- flor[flor[,2] == \"CDS\",]\n# sort\nflor <- flor[order(as.numeric(flor[,4])),]\n# redo row names\nrownames(flor) <- seq(from=1, to=nrow(flor), by=1)\n\n# check that gene IDs in object x match those in the floridanus annotations\ntest <- c()\nfor(a in 1:nrow(x)) {\n\tif(x[a,2] == flor[x[a,1],1]) {\n\t\ttest <- c(test, TRUE)\n\t} else {\n\t\tprint(a)\n\t\ttest <- c(test, FALSE)\n\t}\n}\n\n# if the above test matched everything, continue\n\n# extract locations for each gene (outgroup genome coordinates)\ncoords <- c()\nfor(a in 1:nrow(x)) {\n\tcoords <- c(coords, (as.numeric(flor[x[a,1],5]) + as.numeric(flor[x[a,1],4])) / 2)\n}\n# add to table\nx <- cbind(x[,1:2], coords, x[,3:6])\n\n### read in alignments to obtain sequence identity for each gene in the ingroup (excluding indels)\nx_files <- list.files(\"bloch_fasta_trees\", pattern=\"*_aligned_trimmed.fasta$\", full.names=T)\nx_files_numbers <- as.numeric(sapply(strsplit(x_files, \"_\"), \"[[\", 5))\n\n# percent identity for ingroup for each gene\npid <- list()\nfor(a in 1:nrow(x)) {\n\t# read in fasta alignment\n\ta_name <- x_files[match(x[a,1], x_files_numbers)]\n\ta_rep <- read.fasta(a_name)\n\t# remove outgroups\n\ta_rep <- a_rep[2:17]\n\t# pid\n\tpid_rep <- list()\n\tfor(b in 1:length(a_rep[[1]])) {\n\t\tif(length(unique(as.character(lapply(a_rep, \"[[\", b)))) == 1) {\n\t\t\tpid_rep[[b]] <- 1\n\t\t} else {\n\t\t\tpid_rep[[b]] <- 0\n\t\t}\n\t}\n\tpid[[a]] <- sum(unlist(pid_rep)) / length(a_rep[[1]])\n}\nPID <- unlist(pid)\n# add to data frame\nx <- cbind(x, PID)\n\n# percent identity for tanaemyrmex for each gene\npid <- list()\nfor(a in 1:nrow(x)) {\n\t# read in fasta alignment\n\ta_name <- x_files[match(x[a,1], x_files_numbers)]\n\ta_rep <- read.fasta(a_name)\n\t# keep only tanaemyrmex\n\ta_rep <- a_rep[names(a_rep) %in% groups[[1]]]\n\t# pid\n\tpid_rep <- list()\n\tfor(b in 1:length(a_rep[[1]])) {\n\t\tif(length(unique(as.character(lapply(a_rep, \"[[\", b)))) == 1) {\n\t\t\tpid_rep[[b]] <- 1\n\t\t} else {\n\t\t\tpid_rep[[b]] <- 0\n\t\t}\n\t}\n\tpid[[a]] <- sum(unlist(pid_rep)) / length(a_rep[[1]])\n}\nPID_tanaemyrmex <- unlist(pid)\n# add to data frame\nx <- cbind(x, PID_tanaemyrmex)\n\n# percent identity for camponotus for each gene\npid <- list()\nfor(a in 1:nrow(x)) {\n\t# read in fasta alignment\n\ta_name <- x_files[match(x[a,1], x_files_numbers)]\n\ta_rep <- read.fasta(a_name)\n\t# keep only camponotus\n\ta_rep <- a_rep[names(a_rep) %in% groups[[2]]]\n\t# pid\n\tpid_rep <- list()\n\tfor(b in 1:length(a_rep[[1]])) {\n\t\tif(length(unique(as.character(lapply(a_rep, \"[[\", b)))) == 1) {\n\t\t\tpid_rep[[b]] <- 1\n\t\t} else {\n\t\t\tpid_rep[[b]] <- 0\n\t\t}\n\t}\n\tpid[[a]] <- sum(unlist(pid_rep)) / length(a_rep[[1]])\n}\nPID_camponotus <- unlist(pid)\n# add to data frame\nx <- cbind(x, PID_camponotus)\n\n# write table output\nwrite.table(x, file=\"blochmannia_tree_characteristics2.txt\", sep=\"\\t\", quote=F, row.names=F, col.names=T)\n\n# 20kbp means for each stat\nwindow_coords <- seq(from=0, to=700000, by=20000)\nfor(a in 1:length(window_coords)) {\n\t# skip the last row\n\tif(a != length(window_coords)) {\n\t\ta_start <- window_coords[a]\n\t\ta_end <- window_coords[a+1]\n\t\ta_middle <- mean(c(window_coords[a+1], window_coords[a]))\n\t\ta_rep <- x[x$coords >= a_start & x$coords <= a_end,]\n\t\ta_rep <- c(a_middle, apply(a_rep[,4:ncol(a_rep)], 2, mean))\n\t\tif(a == 1) { \n\t\t\tx_windows <- a_rep\n\t\t} else {\n\t\t\tx_windows <- rbind(x_windows, a_rep)\n\t\t}\n\t}\n}\nx_windows <- as.data.frame(x_windows)\n\n\n\n\n\n\n\n\n\n\n#plot\npar(mar=c(2,5,1,1))\npar(mfrow=c(3,1))\nplot(x$coords, x$kf94, pch=19, cex=0.3, xaxt=\"n\", xlab=\"\", col=\"gray70\", ylab=\"KF94 Distance\")\nlines(x_windows$V1, x_windows$kf94, lty=2, lwd=2)\nplot(x$coords, x$bloch_tanaemyrmex_edge_length, pch=19, cex=0.3, ylim=c(0,50), xaxt=\"n\", xlab=\"\", col=\"lightblue\", ylab=\"Relative Evolution Rate\")\npoints(x$coords, x$bloch_camponotus_edge_length, pch=19, cex=0.3, col=\"lightcoral\")\npoints(x$coords, x$edge_length, pch=19, cex=0.3, col=\"gray70\")\nlines(x_windows$V1, x_windows$bloch_tanaemyrmex_edge_length, col=\"navyblue\", lwd=2)\nlines(x_windows$V1, x_windows$bloch_camponotus_edge_length, col=\"red3\", lwd=2)\nlines(x_windows$V1, x_windows$edge_length, lty=2, lwd=2)\nplot(x$coords, x$PID_tanaemyrmex*100, pch=19, cex=0.3, col=\"lightblue\", ylim=c(60, 100), ylab=\"Gene % Identity\")\npoints(x$coords, x$PID_camponotus*100, pch=19, cex=0.3, col=\"lightcoral\")\npoints(x$coords, x$PID*100, pch=19, cex=0.3, col=\"gray70\")\nlines(x_windows$V1, x_windows$PID_tanaemyrmex*100, col=\"navyblue\", lwd=2)\nlines(x_windows$V1, x_windows$PID_camponotus*100, col=\"red3\", lwd=2)\nlines(x_windows$V1, x_windows$PID*100, lty=2, lwd=2)\n", "meta": {"hexsha": "09a8cc3147f8a81dcbee6dca2f9d6aa82e6b4577", "size": 11330, "ext": "r", "lang": "R", "max_stars_repo_path": "02_blochmannia/15_compare_ant_blochmannia_trees.r", "max_stars_repo_name": "jdmanthey/camponotus_genomes1", "max_stars_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_blochmannia/15_compare_ant_blochmannia_trees.r", "max_issues_repo_name": "jdmanthey/camponotus_genomes1", "max_issues_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_blochmannia/15_compare_ant_blochmannia_trees.r", "max_forks_repo_name": "jdmanthey/camponotus_genomes1", "max_forks_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-29T16:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T16:29:49.000Z", "avg_line_length": 36.6666666667, "max_line_length": 287, "alphanum_fraction": 0.6946160635, "num_tokens": 3596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.20608814300693062}}