{"text": "#' ---\n#' title: \"Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions\"\n#' author: \"Judith Degen\"\n#' date: \"January 26, 2014\"\n#' ---\n\nlibrary(ggplot2)\nlibrary(wesanderson)\ntheme_set(theme_bw(18))\nsetwd(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/_journal_cognition/\")\nsource(\"rscripts/helpers.r\")\n\n## load priors for generating plots \npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nnrow(priorprobs)\n\n# prior all-state probability for each item\nprior_allprobs = priorprobs[,c(\"Item\",\"X15\")]\nrow.names(prior_allprobs) = prior_allprobs$Item\n\n# prior expectation for each item\ngathered_probs <- priorprobs %>%\n gather(State,Probability,X0:X15)\ngathered_probs$State = as.numeric(as.character(gsub(\"X\",\"\",gathered_probs$State)))\nprior_exps <- gathered_probs %>%\n group_by(Item) %>%\n summarise(exp.val=sum(State*Probability))\nprior_exps = as.data.frame(prior_exps)\nrow.names(prior_exps) = prior_exps$Item\nsummary(prior_exps)\n\n# histogram of expectations\nexps = ggplot(prior_exps, aes(x=exp.val)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"pics/priorexpectations-histogram.pdf\",width=5,height=3.7)\n\n# histogram of allstate-probs\nallprobs = ggplot(prior_allprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram.pdf\")\n\npdf(\"pics/priordistributions.pdf\",width=10,height=3.5)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n# load inferred priors (with guessing parameter)\nexps_inferred_phi = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/bayesian_model_comparison/priors/results/summary_priorBDA-binomials-phi_incrMH100000burn50000.csv\",sep=\",\", header=T, quote=\"\")\nexps_inferred_phi$X.Item. = gsub(\"\\\"\",\"\",exps_inferred_phi$X.Item.)\nrow.names(exps_inferred_phi) = exps_inferred_phi$X.Item.\nnrow(exps_inferred_phi)\nhead(exps_inferred_phi)\n\n# histogram of expectations\nexps = ggplot(exps_inferred_phi, aes(x=X.expectation.*15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"pics/priorexpectations-inferred-phi-histogram.pdf\",width=5,height=3.7)\n\n# load inferred priors (without guessing parameter)\nexps_inferred = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/bayesian_model_comparison/priors/results/summary_priorBDA-binomials_incrMH100000burn50000.csv\",sep=\",\", header=T, quote=\"\")\nexps_inferred$X.Item. = gsub(\"\\\"\",\"\",exps_inferred$X.Item.)\nrow.names(exps_inferred) = exps_inferred$X.Item.\nnrow(exps_inferred)\nhead(exps_inferred)\nrow.names(exps_inferred) = exps_inferred$X.Item.\n\n# histogram of expectations\nexps = ggplot(exps_inferred, aes(x=X.expectation.*15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"pics/priorexpectations-inferred-histogram.pdf\",width=5,height=3.7)\n\n\n### PLOT COMPREHENSION RESULTS\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nr$PriorExpectationProportion = prior_exps[as.character(r$Item),]$exp.val\nr$PriorExpectationProportionInferred = exps_inferred[as.character(r$Item),]$X.expectation.\nr$PriorExpectationProportionInferredPhi = exps_inferred_phi[as.character(r$Item),]$X.expectation.\n\ncor(r$PriorExpectationProportionInferred*15,r$PriorExpectationProportion)\ncor(r$PriorExpectationProportionInferredPhi*15,r$PriorExpectationProportion)\n# exclude people who weren't literal above some threshold\n# lit = droplevels(r[r$quantifier %in% c(\"All\",\"None\"),]) %>% \n# group_by(workerid,quantifier) %>%\n# summarise(Mean=mean(response))\n# lit = as.data.frame(lit)\n# lit = lit %>% spread(quantifier,Mean)\n# lit$Literal = as.factor(as.character(ifelse(lit$All > .80*15 & lit$None < .20*15,\"literal\",\"non-literal\")))\n# table(lit$Literal)\n# row.names(lit) = as.character(lit$workerid)\n# r$Literal = lit[as.character(r$workerid),]$Literal\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"empirical_exps.pdf\")#,width=5,height=3.7)\n\n# plot with inferred prior expectation on x axis\nagr = aggregate(ProportionResponse ~ PriorExpectationProportionInferred + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportionInferred*15, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"pics/empirical_exps_inferredprior.pdf\",width=7)#,width=5,height=3.7)\n\n# plot with inferred prior (phi) expectation on x axis\nagr = aggregate(ProportionResponse ~ PriorExpectationProportionInferredPhi + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)*15\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportionInferredPhi*15, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"pics/empirical_exps_inferredprior_phi.pdf\",width=7)#,width=5,height=3.7)\n\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\n#tmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nr$AllPriorProbability = prior_allprobs[as.character(r$Item),]$X15\ntmp=r\n#tmpub = droplevels(subset(tmp, Proportion == \"100\"))\n#tmpub$Quantifier = factor(x=tmpub$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\nub$Quantifier = factor(x=ub$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),breaks=seq(0,1,by=.2),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(name=\"Prior probability of all-state\") \np_eprobs\nggsave(file=\"empirical-allprobs.pdf\")#,width=5,height=3.7)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"pics/empirical-results.pdf\",width=13,height=5)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n### PLOT WONKY RESULTS\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/11_sinking-marbles-normal/results/data/r.RData\")\n\nr$PriorExpectation = prior_exps[as.character(r$Item),]$exp.val\nans = r %>%\n filter(quantifier %in% c(\"All\",\"None\",\"Some\")) %>%\n group_by(quantifier, Item, PriorExpectation) %>%\n summarise(mean.prop=mean(numWonky))\n\np_wempirical =ggplot(ans,aes(x=PriorExpectation,y=mean.prop,color=quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3])) +\n scale_y_continuous(limits=c(-0.1,1.2),breaks=seq(0,1,by=.2),name=\"Proportion of `wonky' judgments\") +\n scale_x_continuous(limits=c(0,15),breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \n\n# get wonky model predictions\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n#toplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$Quantifier, levels=c(\"all\",\"none\",\"some\"))\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier,shape=Quantifier)) +\n geom_point() + \n geom_smooth() + \n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n #scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(limits=c(0,15),breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(limits=c(-0.1,1.2),breaks=seq(0,1,by=.25),name=\"Predicted posterior wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wmodel\n\n\npdf(\"pics/wonkiness-results.pdf\",width=10,height=4)\n#grid.arrange(p_wmodel, p_wempirical, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ngrid.arrange(p_wmodel, p_wempirical, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n## PLOT SPEAKER RELIABILITY RESULTS\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/19_speaker_reliability_withins/results/data/r.RData\")\nr = r[!is.na(r$normresponse),]\nr$AllPriorProbability = prior_allprobs[as.character(r$Item),]$X15\n\nsome100 = droplevels(subset(r, Proportion == \"100\" & quantifier == \"Some\"))\nagr = aggregate(normresponse ~ AllPriorProbability + trial_type + Item,data=some100,FUN=mean)\nagr$CILow = aggregate(normresponse ~ AllPriorProbability + trial_type + Item,data=some100, FUN=ci.low)$normresponse\nagr$CIHigh = aggregate(normresponse ~ AllPriorProbability + trial_type + Item,data=some100,FUN=ci.high)$normresponse\nagr$YMin = agr$normresponse - agr$CILow\nagr$YMax = agr$normresponse + agr$CIHigh\n\np=ggplot(agr, aes(x=AllPriorProbability,y=normresponse, color=trial_type)) +\n geom_point() +\n geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n# geom_smooth(method=\"lm\") +\n scale_y_continuous(name=\"Posterior probability of all-state\") +\n scale_x_continuous(name=\"Prior probability of all-state\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3]),name=\"Trial type\",breaks=levels(agr$trial_type),labels=c(\"uninformative (court)\", \"unreliable (drunk)\", \"cooperative (sober)\"))\np\nggsave(\"pics/speakerreliabilityresults.pdf\",width=7,height=4)\n\n\n\nsome100$Reliability = as.factor(ifelse(some100$trial_type == \"sober\",\"reliable\",\"unreliable\"))\ncentered = cbind(some100, myCenter(some100[,c(\"AllPriorProbability\",\"Reliability\",\"Trial\")]))\nm = lmer(normresponse ~ cAllPriorProbability * cReliability + (cAllPriorProbability * cReliability | Item) + (cAllPriorProbability * cReliability | workerid), data=centered)\nsummary(m)\nsave(m, file=\"data/model.RData\")\n\nm = lmer(normresponse ~ cAllPriorProbability * trial_type + (1 | Item) + (1 | workerid), data=centered)\nsummary(m)\n\nm.trial = lmer(normresponse ~ cAllPriorProbability * cReliability * cTrial + (cAllPriorProbability * cReliability| Item) + (cAllPriorProbability * cReliability| workerid), data=centered)\nsummary(m.trial)\n\nm.trial.nopr = lmer(normresponse ~ cAllPriorProbability + cReliability + cTrial + cReliability:cTrial + cAllPriorProbability:cTrial + cAllPriorProbability:cReliability:cTrial + (cAllPriorProbability * cReliability| Item) + (cAllPriorProbability * cReliability| workerid), data=centered)\nsummary(m.trial.nopr)\n\nanova(m.trial.nopr,m.trial) # \n\nm.trial.nopt = lmer(normresponse ~ cAllPriorProbability + cReliability + cTrial + cAllPriorProbability:cReliability + cReliability:cTrial + cAllPriorProbability:cReliability:cTrial + (cAllPriorProbability * cReliability| Item) + (cAllPriorProbability * cReliability| workerid), data=centered)\nsummary(m.trial.nopr)\n\nanova(m.trial.nopt,m.trial)\n\n# spell out all the interactions\n#m.trial = lmer(normresponse ~ cAllPriorProbability + cReliability + cTrial + cAllPriorProbability:cReliability + cReliability:cTrial + cAllPriorProbability:cTrial + cAllPriorProbability:cReliability:cTrial + (cAllPriorProbability * cReliability| Item) + (cAllPriorProbability * cReliability| workerid), data=centered)\n\n\n# PLOT SPEAKER RELIABILITY RESULTS BY BLOCK\nagr = aggregate(normresponse ~ AllPriorProbability + trial_type + Item + block,data=some100,FUN=mean)\nagr$CILow = aggregate(normresponse ~ AllPriorProbability + trial_type + Item + block,data=some100, FUN=ci.low)$normresponse\nagr$CIHigh = aggregate(normresponse ~ AllPriorProbability + trial_type + Item + block,data=some100,FUN=ci.high)$normresponse\nagr$YMin = agr$normresponse - agr$CILow\nagr$YMax = agr$normresponse + agr$CIHigh\n\np=ggplot(agr, aes(x=AllPriorProbability,y=normresponse, color=trial_type)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_y_continuous(name=\"Posterior probability of all-state\") +\n scale_x_continuous(name=\"Prior probability of all-state\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3]),name=\"Trial type\",breaks=levels(agr$trial_type),labels=c(\"uninformative (court)\", \"unreliable (drunk)\", \"cooperative (sober)\")) +\n facet_wrap(~block)\np\nggsave(\"pics/speakerreliabilityresults-byblock.pdf\",width=12,height=4)\n\n\n\n#####################################\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\nlibrary(dplyr)\nlibrary(plyr)\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\npexpectations = ddply(toplot, .(Item), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = some\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5 & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData\")\nsummary(mp)\ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_r = toplot\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior mean all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior all-state probability\") \np_probs\nggsave(\"pred_probs.pdf\")\n\np_probs = ggplot(toplot_r, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Posterior all-state probability\") \np_probs\nggsave(\"pred_prob_rsa.pdf\")\n\n\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\n\npexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot_w = toplot\n\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData\")\ntoplot_r = toplot\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_r$PriorExpectation = toplot_r$PriorExpectation_smoothed*15\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\n\np_exps = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior mean number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Predicted posterior number of objects\") \np_exps\nggsave(\"pred_exps.pdf\")\n\np_exps = ggplot(toplot_r, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior expectation\") \np_exps\nggsave(\"pred_exps_rsa.pdf\")\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_exps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_exps_nolegend = p_exps + theme(legend.position=\"none\")\np_probs_nolegend = p_probs + theme(legend.position=\"none\")\n\npdf(\"rsa-predictions.pdf\",width=12,height=4.9)\ngrid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"empirical_exps.pdf\")#,width=5,height=3.7)\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\ntmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\nub$Quantifier = factor(x=ub$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(limits=c(0,1),name=\"Prior probability of all-state\") \np_eprobs\nggsave(file=\"empirical-allprobs.pdf\")#,width=5,height=3.7)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"empirical-results.pdf\",width=12,height=4.9)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n#toplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$Quantifier, levels=c(\"some\",\"all\",\"none\"))\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier,shape=Quantifier)) +\n geom_point() + \n geom_smooth() + \n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n #scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Predicted posterior wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wmodel\nggsave(\"model-wonkiness-uniform.pdf\",width=6.8,height=5)#,width=30,height=10)\n\n############\n# empirical wonkiness posteriors\n############\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData\")\nhead(r)\nnrow(r)\n\ntoplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN=\"mean\", data=r)\ntoplot = droplevels(subset(toplot, quantifier %in% c(\"All\",\"Some\",\"None\")))\ntoplot$Quantifier = factor(tolower(toplot$quantifier), levels=c(\"all\", \"none\",\"some\"))\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\ntoplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$quantifier, levels=c(\"Some\",\"All\",\"None\"))\n\np_wempirical = ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier,shape=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wempirical\nggsave(file=\"empirical-wonkiness.pdf\",width=6.8,height=5)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_wmodel + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_wmodel_nolegend = p_wmodel + theme(legend.position=\"none\")\np_wempirical_nolegend = p_wempirical + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"wonkiness-fullplot.pdf\",width=12,height=5)\ngrid.arrange(p_wmodel_nolegend, p_wempirical_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n## load four-step priors for generating appendix plots \npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/24_sinking-marbles-prior-fourstep/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nnrow(priorprobs)\n\n# prior all-state probability for each item\nprior_allprobs = priorprobs[,c(\"Item\",\"X15\")]\nrow.names(prior_allprobs) = prior_allprobs$Item\n\n# prior expectation for each item\ngathered_probs <- priorprobs %>%\n gather(State,Probability,X0:X15)\ngathered_probs$State = as.numeric(as.character(gsub(\"X\",\"\",gathered_probs$State)))\nprior_exps <- gathered_probs %>%\n group_by(Item) %>%\n summarise(exp.val=sum(State*Probability))\nprior_exps = as.data.frame(prior_exps)\nrow.names(prior_exps) = prior_exps$Item\nsummary(prior_exps)\n\n# histogram of expectations\nexps = ggplot(prior_exps, aes(x=exp.val)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"pics/priorexpectations-histogram-fourstep.pdf\",width=5,height=3.7)\n\n# histogram of allstate-probs\nallprobs = ggplot(prior_allprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram-fourstep.pdf\")\n\npdf(\"pics/priordistributions-fourstep.pdf\",width=10,height=3.5)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n", "meta": {"hexsha": "50a0164e57bd0946efedf43134e5548f5769814d", "size": 30024, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/_2015/_journal_cognition/rscripts/plots_new.r", "max_stars_repo_name": "thegricean/sinking-marbles", "max_stars_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/_2015/_journal_cognition/rscripts/plots_new.r", "max_issues_repo_name": "thegricean/sinking-marbles", "max_issues_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/_2015/_journal_cognition/rscripts/plots_new.r", "max_forks_repo_name": "thegricean/sinking-marbles", "max_forks_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.626446281, "max_line_length": 318, "alphanum_fraction": 0.7501998401, "num_tokens": 9110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.34919142709345613}} {"text": "# Compare current habitat temperatures\n# to upper thermal limits in marine and terrestrial species\n# Use operative temperature on land, use SST in ocean\n# Use temp at each location, rather than lat averages\n\nrequire(mgcv)\nrequire(data.table)\nrequire(lme4)\n\n##################\n# Functions\n##################\n\n# round a single value (x) to nearest value in a vector (y)\nroundto <- function(x, y){\n\ta <- abs(x - y)\n\ti <- which(a==min(a)) # can return 1 or 2 matches\n\treturn(y[i])\n}\n\n\n##################\n# Parameters\n##################\n# for adjusting max air temperature to account for elevation\nlapse <- 0.0055 # degC/m elevation. See Sunday et al. 2014 PNAS supplement\n\n#set Acclimation Response Ratio for terrestrial and marine organisms\n# from Gunderson and Stillman model-averaged results (Gunderson pers. comm.)\nARRland <- 0.11\nARRoce <- 0.24\n\n#################\n# Read in data\n#################\n\n# Measurements of upper thermal tolerance and NicheMapR (terrestrial microclimates)\ndat <- fread(file=\"output/dataset_1_hotwater_Nichemapped_GHCNDnonequil.csv\") # nonequilibrium Tb calculations. Built from dataset_1_hotwater_Nichemapped_GHCND.csv\n\n\t# fix column names\n\tsetnames(dat, c('tmax', 'REF_max', 'lat_max', 'long_max'), c('Tmax', 'citation', 'lat', 'lon'))\n\n\t# read in traits\n\ttraits <- fread('data/tmax_data/dataset_1_traits.csv')\n\n\t\t# fix benthopelagic and pelagic\n\t\ttraits[demers_pelag_fb == 'benthopelagic', demers_pelag := 'demersal']\n\t\ttraits[demers_pelag_fb == 'pelagic-neritic', demers_pelag := 'pelagic-neritic']\n\n\t# read in species-specific ARR\n\tarr <- fread('data/tmax_data/dataset_1_ARRs.tsv')\n\n\t\t# merge traits and arr\n\t\ttraits2 <- merge(traits, arr[, .(Genus, Species, ctmax_ARR_GS)], by=c('Genus', 'Species'), all.x=TRUE)\n\n\t# merge\ttraits and data\n\tdat <- merge(dat[,.(Genus, Species, Tmax, tmax_metric, tmax_acc, lat, lon, altitude, citation, Phylum, Class, Order, Family, NMGHCND_2m_shade_Tb95, NMGHCND_exposed_Tb95, NMGHCND_exposed_Tb_wet95, NMGHCND_shade_Tb_wet95)], traits2[, .(Genus, Species, thermy, Realm, Realm_detail, demers_pelag, mobility, weight, length, ctmax_ARR_GS)], all.x=TRUE, by=c('Genus', 'Species'))\n\t\tdim(dat)\n\n\n\t# trim out freshwater and intertidal\n\tdat <- dat[Realm %in% c('Marine', 'Terrestrial') & Genus != 'Gillichthys' & !(Realm_detail %in% c('catadromous', 'anadromous', 'amphidromous', 'freshwater')),]\n\t\tdim(dat)\n\n\t# re-order dat alphabetically\n\tdat <- dat[order(dat$Genus, dat$Species, dat$citation),]\n\n\t# how much trait data?\n\tdat[,sort(unique(Realm))]\n\tdat[Realm=='Marine', summary(length)]\n\tdat[Realm=='Marine', sort(unique(demers_pelag))]\n\tdat[Realm=='Marine', sort(unique(mobility))]\n\n# Elevation\n\tload('temp/elev.rdata') # elev data.frame 0.5x0.5\n\t\t\n# Current temperatures\n\t# read in climatologies for annual mean\n\tload('temp/lstclimatology.rdata') # lstclim (0.25x0.25)\n\tload('temp/sstclimatology.rdata') # sstclim\n#\t\tlstclimn <- lstclim\n#\t\tsstclimn <- sstclim\n#\n#\t# read in climatologies for summer mean\n\tload('temp/lstclimatology_warm3.rdata') # lstclimwarm3 (0.25x0.25 grid)\n\tload('temp/sstclimatology_warm3.rdata') # sstclimwarm3\n\t\tlstclimwarm3n <- lstclimwarm3\n\t\tsstclimwarm3n <- sstclimwarm3\n#\n#\t# read in climatology for the warmest month\n\tload('temp/sstclimatology_warmestmonth.rdata') # sstclimwarmestmo (0.25x0.25 grid)\n\tload('temp/lstclimatology_warmestmonth.rdata')\n\t\tlstclimwarmestmon <- lstclimwarmestmo\n\t\tsstclimwarmestmon <- sstclimwarmestmo\n\t\t\n\t# read in data for the 95% warmest daily maximum\n\tload('temp/tos95max.rdata') # tos95max (0.25x0.25 grid): ocean (95% warmest day + 50% DTR)\n\n\t# read in data for the warmest daily maximum\n\tload('temp/tosmax.rdata') # tosmax (0.25x0.25 grid): ocean (warmest day + 50% DTR)\n#\tload('temp/tasmax.rdata') # tasmax: air 0.25x0.25 (warmest daily max value averaged across any month). Use NicheMapR instead\n\n\n\n\n############################################################################################################\n# match habitat temperature to lat/lon of thermal tolerance (mostly for ocean since NicheMapR used on land\n############################################################################################################\n\n# Initialize columns for current habitat temperatures (those not from NicheMapR) and elevation\ndat$elev.grid <- dat$thab95hr <- dat$thabmaxmo <- dat$thabsum <- dat$thabann <- NA\n\n# Get lists of latitude and longitude values in the temperature data\nllons <- as.numeric(colnames(lstclimwarmestmon))\nllats <- as.numeric(rownames(lstclimwarmestmon))\nslons <- as.numeric(colnames(tosmax))\nslats <- as.numeric(rownames(tosmax))\n\nllonstep <- abs(diff(llons)[1])\nslonstep <- abs(diff(slons)[1])\nllatstep <- abs(diff(llats)[1])\nslatstep <- abs(diff(slats)[1])\n\n# Match each data point to temperature and elevation data based on lat/lon and habitat\nfor(i in 1:nrow(dat)){\n\tif(!is.na(dat$lat[i]) & !is.na(dat$lon[i])){\n\n\t\t# land\n\t\tif(dat$Realm[i]=='Terrestrial'){\n\t\t\tif(dat$lon[i] < 0){ # may need to correct lon to 0-360\n\t\t\t\tlons <- roundto(dat$lon[i] + 360, llons) # find the closest longitude (or lons)\n\t\t\t} else {\n\t\t\t\tlons <- roundto(dat$lon[i], llons) \n\t\t\t}\n\t\t\tlats <- roundto(dat$lat[i], llats) # find the closest latitudes (or latitudes)\n\t\t\t\n\t\t\t# look for grid cell with data\n\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # test\n\n\t\t\tif(is.na(ltemp)){ # if didn't get a value, try searching in a slightly wider area (may have moved off land in rounding)\n\t\t\t\tcat(paste('Going to wider search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\toriglats <- lats\n\t\t\t\toriglons <- lons\n\t\t\t\t\n\t\t\t\tif(all(lats > dat$lat[i])){ # move down one step if all rounded lats are greater\n\t\t\t\t\tlats <- c(lats, lats - llatstep)\n\t\t\t\t}\n\t\t\t\tif(all(lats < dat$lat[i])){\n\t\t\t\t\tlats <- c(lats, lats + llatstep)\n\t\t\t\t}\n\t\t\t\tif(all(lons > dat$lon[i])){\n\t\t\t\t\tlons <- c(lons, lons - llonstep)\n\t\t\t\t}\n\t\t\t\tif(all(lons < dat$lon[i])){\n\t\t\t\t\tlons <- c(lons, lons + llonstep)\n\t\t\t\t}\n\n\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t\n\t\t\t\t# take only the first element so that addition and subtraction work in following steps\n\t\t\t\toriglats <- lats[1]\n\t\t\t\toriglons <- lons[1]\n\n\t\t\t\tif(is.na(ltemp)){ # if still don't get a value, try searching in 9-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 9-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep, origlats, origlats+llatstep)\n\t\t\t\t\tlons <- c(origlons-llonstep, origlons, origlons+llonstep)\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){ # if still don't get a value, try searching in 25-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 25-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(2:1), origlats, origlats+llatstep*(1:2))\n\t\t\t\t\tlons <- c(origlons-llonstep*(2:1), origlons, origlons+llonstep*(1:2))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){ # if still don't get a value, try searching in 49-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 49-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(3:1), origlats, origlats+llatstep*(1:3))\n\t\t\t\t\tlons <- c(origlons-llonstep*(3:1), origlons, origlons+llonstep*(1:3))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){ # if still don't get a value, try searching in 81-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 81-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(4:1), origlats, origlats+llatstep*(1:4))\n\t\t\t\t\tlons <- c(origlons-llonstep*(4:1), origlons, origlons+llonstep*(1:4))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){\n\t\t\t\t\tcat(paste('\\tGoing to 121-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(5:1), origlats, origlats+llatstep*(1:5))\n\t\t\t\t\tlons <- c(origlons-llonstep*(5:1), origlons, origlons+llonstep*(1:5))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){\n\t\t\t\t\tcat(paste('\\tGoing to 169-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(6:1), origlats, origlats+llatstep*(1:6))\n\t\t\t\t\tlons <- c(origlons-llonstep*(6:1), origlons, origlons+llonstep*(1:6))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){\n\t\t\t\t\tcat(paste('\\tGoing to 225-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(7:1), origlats, origlats+llatstep*(1:7))\n\t\t\t\t\tlons <- c(origlons-llonstep*(7:1), origlons, origlons+llonstep*(1:7))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(ltemp)){\n\t\t\t\t\tcat(paste('\\tGoing to 289-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'on land\\n'))\n\t\t\t\t\tlats <- c(origlats-llatstep*(9:1), origlats, origlats+llatstep*(1:9))\n\t\t\t\t\tlons <- c(origlons-llonstep*(9:1), origlons, origlons+llonstep*(1:9))\n\t\t\t\t\tltemp <- mean(lstclimwarmestmon[as.character(lats), as.character(lons)], na.rm=TRUE) # land temp\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcat(paste('\\tltemp now', ltemp, '\\n'))\n\n\t\t\t}\n\n\t\t\t# for annual mean\n\t\t\tdat$thabann[i] <- mean(lstclim[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for summer mean\n\t\t\tdat$thabsum[i] <- mean(lstclimwarm3n[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for max month\n\t\t\tdat$thabmaxmo[i] <- mean(lstclimwarmestmo[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for elevation\n\t\t\tdat$elev.grid[i] <- mean(elev[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t}\n\n\t\t# ocean\n\t\tif(dat$Realm[i]=='Marine'){\n\t\t\tif(dat$lon[i] < 0){\n\t\t\t\tlons <- roundto(dat$lon[i] + 360, slons)\n\t\t\t} else {\n\t\t\t\tlons <- roundto(dat$lon[i], slons)\n\t\t\t}\n\t\t\tlats <- roundto(dat$lat[i], slats)\n\n\n\t\t\t# look for grid cell with data\n\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE) # ocean temp\n\n\t\t\tif(is.na(stemp)){ # if didn't get a value, try searching in a slightly wider area (may have moved off ocean in rounding)\n\t\t\t\tcat(paste('Going to wider search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\toriglats <- lats\n\t\t\t\toriglons <- lons\n\n\t\t\t\tif(all(lats > dat$lat[i])){ # move down one step if all rounded lats are greater\n\t\t\t\t\tlats <- c(lats, lats - slatstep)\n\t\t\t\t}\n\t\t\t\tif(all(lats < dat$lat[i])){\n\t\t\t\t\tlats <- c(lats, lats + slatstep)\n\t\t\t\t}\n\t\t\t\tif(all(lons > dat$lon[i])){\n\t\t\t\t\tlons <- c(lons, lons - slonstep)\n\t\t\t\t}\n\t\t\t\tif(all(lons < dat$lon[i])){\n\t\t\t\t\tlons <- c(lons, lons + slonstep)\n\t\t\t\t}\n\n\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE) # ocean temp\n\n\t\t\t\t# take only the first element so that addition and subtraction work in following steps\n\t\t\t\toriglats <- lats[1]\n\t\t\t\toriglons <- lons[1]\n\n\t\t\t\tif(is.na(stemp)){ # if still don't get a value, try searching in 9-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 9-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep, origlats, origlats+slatstep)\n\t\t\t\t\tlons <- c(origlons-slonstep, origlons, origlons+slonstep)\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE) # ocean temp\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ # if still don't get a value, try searching in 25-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 25-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(2:1), origlats, origlats+slatstep*(1:2))\n\t\t\t\t\tlons <- c(origlons-slonstep*(2:1), origlons, origlons+slonstep*(1:2))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ # if still don't get a value, try searching in 49-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 49-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(3:1), origlats, origlats+slatstep*(1:3))\n\t\t\t\t\tlons <- c(origlons-slonstep*(3:1), origlons, origlons+slonstep*(1:3))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ # if still don't get a value, try searching in 81-grid area\n\t\t\t\t\tcat(paste('\\tGoing to 81-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(4:1), origlats, origlats+slatstep*(1:4))\n\t\t\t\t\tlons <- c(origlons-slonstep*(4:1), origlons, origlons+slonstep*(1:4))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ \n\t\t\t\t\tcat(paste('\\tGoing to 121-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(5:1), origlats, origlats+slatstep*(1:5))\n\t\t\t\t\tlons <- c(origlons-slonstep*(5:1), origlons, origlons+slonstep*(1:5))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ \n\t\t\t\t\tcat(paste('\\tGoing to 169-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(6:1), origlats, origlats+slatstep*(1:6))\n\t\t\t\t\tlons <- c(origlons-slonstep*(6:1), origlons, origlons+slonstep*(1:6))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tif(is.na(stemp)){ \n\t\t\t\t\tcat(paste('\\tGoing to 225-grid search area for i=', i, dat$Genus[i], dat$Species[i], 'at sea\\n'))\n\t\t\t\t\tlats <- c(origlats-slatstep*(7:1), origlats, origlats+slatstep*(1:7))\n\t\t\t\t\tlons <- c(origlons-slonstep*(7:1), origlons, origlons+slonstep*(1:7))\n\t\t\t\t\tstemp <- mean(tosmax[as.character(lats), as.character(lons)], na.rm=TRUE)\n\t\t\t\t}\n\n\t\t\t\tcat(paste('\\tstemp now', stemp, '\\n'))\n\t\t\t}\n\n\t\t\t# for annual mean\n\t\t\tdat$thabann[i] <- mean(sstclim[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for summer mean\n\t\t\tdat$thabsum[i] <- mean(sstclimwarm3n[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for max month\n\t\t\tdat$thabmaxmo[i] <- mean(sstclimwarmestmo[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t\t# for 95% max hour\n\t\t\tdat$thab95hr[i] <- mean(tos95max[as.character(lats), as.character(lons)], na.rm=TRUE)\n\n\t\t}\n\n\t}\n}\n\n\n\t# check\n\tdat[,summary(thabann)]\n\tdat[,summary(thabsum)]\n\tdat[,summary(thabmaxmo)]\n\tdat[Realm=='Marine',summary(thabann)]\n\tdat[Realm=='Marine',summary(thab95hr)]\n\n\tdat[!is.na(NMGHCND_2m_shade_Tb95),summary(thabann)] # have NM data, but not thabann\n\n\tdat[Realm=='Marine' & is.na(thabann),]\n\n\n##############################################################\n# adjust terrestrial habitat temperatures based on elevation differences \n##############################################################\ndat[,thabann.adj := thabann]\ndat[,thabsum.adj := thabsum]\ndat[,thabmaxmo.adj := thabmaxmo]\n\ni <- dat[,!is.na(altitude) & !is.na(elev.grid) & Realm=='Terrestrial']\ndat[i,thabann.adj := thabann + lapse*(elev.grid - altitude)] # adjust for altitude offset from grid cell\ndat[i,thabsum.adj := thabsum + lapse*(elev.grid - altitude)] # adjust for altitude offset from grid cell\ndat[i,thabmaxmo.adj := thabmaxmo + lapse*(elev.grid - altitude)] # adjust for altitude offset from grid cell\n\n\n\n##############################################################################\n# adjust marine habitat temperatures based on behavioral thermoregulation\n##############################################################################\n# let marine species access cooler microhabitats through behavioral thermoregulation, down to -2degC (for warmest hours)\n\n# initialize columns\ndat[,thab95hr.marineBT := as.numeric(NA)]\ndat[Realm=='Marine',thab95hr.marineBT := thab95hr]\ndat[,thab95hr.marineBTmore := as.numeric(NA)]\ndat[Realm=='Marine',thab95hr.marineBTmore := thab95hr] # 50% more\ndat[,thab95hr.marineBTless := as.numeric(NA)]\ndat[Realm=='Marine',thab95hr.marineBTless := thab95hr] # 50% less\n\n# marine behavioral thermoregulation table\nmarBT <- data.table(mobility=c('swim', 'swim', 'swim', 'swim', 'swim', 'swim', 'crawl', 'crawl', 'sessile', 'sessile'), demers_pelag=c('pelagic-neritic', 'pelagic-neritic', 'demersal', 'pelagic', 'demersal', 'pelagic', 'demersal', 'demersal', 'demersal', 'demersal'), big=c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE), MBTrefuge=c(10, 3, 3, 10, 1, 10, 1, 0.5, 0, 0))\n\tmarBT\n\n# merge in the MBT table\ndat[,big := length>50] # mark the big species (>50cm)\ndat <- merge(dat, marBT, all.x=TRUE, by=c('demers_pelag', 'mobility', 'big'))\n\tnrow(dat)\n\n# calculate refugium temperatures\ndat[, thab95hr.marineBT := pmax(-2, thab95hr - MBTrefuge)] # for 95% warmest hour\ndat[, thab95hr.marineBTmore := pmax(-2, thab95hr - MBTrefuge*1.5)] # 50% more\ndat[, thab95hr.marineBTless := pmax(-2, thab95hr - MBTrefuge*0.5)] # 50% less\n\n\n############################################\n# adjust Tmax for acclimation temperature\n############################################\ndat[,tmax.accsum := as.numeric(NA)] # use summer temp for acclimation\ndat[,tmax.accsum.elev := as.numeric(NA)]\ndat[,tmax.accsumbyspp := as.numeric(NA)] # with species-specific ARRs\ndat[,tmax.accsumbyspp.elev := as.numeric(NA)]\n\n# if acclimation value is \"F\" (field?), set to missing\ndat[tmax_acc=='F', tmax_acc := as.character(NA)]\nif(class(dat$tmax_acc)!='numeric') dat[,tmax_acc := as.numeric(tmax_acc)]\n\n# adjust Tmax based on acclimation (average ARR)\nlnd <- dat[,Realm=='Terrestrial' & !is.na(tmax_acc)]\ndat[lnd, tmax.accsum := Tmax + ARRland*(thabsum-tmax_acc)] # adjust from acclimation temp to the summer temperature\ndat[lnd, tmax.accsum.elev := Tmax + ARRland*(thabsum.adj-tmax_acc)] # adjust from acclimation temp to the summer temperature. with elevation correction\n\noce <- dat[,Realm=='Marine' & !is.na(tmax_acc)]\ndat[oce, tmax.accsum := Tmax + ARRoce*(thabsum-tmax_acc)]\ndat[oce, tmax.accsum.elev := Tmax + ARRoce*(thabsum.adj-tmax_acc)]\n\n\t# no adjustment to Tmax where acclimation temp unknown\n\tdat[Realm=='Terrestrial' & is.na(tmax.accsum), tmax.accsum := Tmax]\n\tdat[Realm=='Terrestrial' & is.na(tmax.accsum.elev), tmax.accsum.elev := Tmax]\n\n\tdat[Realm=='Marine' & is.na(tmax.accsum), tmax.accsum := Tmax]\n\tdat[Realm=='Marine' & is.na(tmax.accsum.elev), tmax.accsum.elev := Tmax]\n\n\n# adjust Tmax based on species-specific ARRs\nlnd <- dat[,Realm=='Terrestrial' & !is.na(tmax_acc) & !is.na(ctmax_ARR_GS)]\ndat[lnd, tmax.accsumbyspp := Tmax + ctmax_ARR_GS*(thabsum-tmax_acc)]\ndat[lnd, tmax.accsumbyspp.elev := Tmax + ctmax_ARR_GS*(thabsum.adj-tmax_acc)]\n\noce <- dat[,Realm=='Marine' & !is.na(tmax_acc) & !is.na(ctmax_ARR_GS)]\ndat[oce, tmax.accsumbyspp := Tmax + ctmax_ARR_GS*(thabsum-tmax_acc)]\ndat[oce, tmax.accsumbyspp.elev := Tmax + ctmax_ARR_GS*(thabsum.adj-tmax_acc)]\n\n\n# Examine\ndat[,summary(Tmax)]\ndat[,summary(tmax.accsum)]\ndat[,summary(tmax.accsum.elev)]\ndat[,summary(tmax.accsumbyspp.elev)]\n\n\t# examine missing values\ndat[is.na(tmax.accsumbyspp),]\n\n\t# difference from uncorrected tmax\ndat[!is.na(tmax.accsum),.(mean=mean(Tmax - tmax.accsum), se=sd(Tmax - tmax.accsum)/sqrt(.N)), by=Realm]\n\n\t# difference from average ARR\ndat[!is.na(tmax.accsumbyspp),.(mean=mean(tmax.accsum - tmax.accsumbyspp), se=sd(tmax.accsum - tmax.accsumbyspp)/sqrt(.N))]\ndat[!is.na(tmax.accsumbyspp.elev),.(mean=mean(tmax.accsum.elev - tmax.accsumbyspp.elev), se=sd(tmax.accsum.elev - tmax.accsumbyspp.elev)/sqrt(.N))]\ndat[!is.na(tmax.accsumbyspp),.(N=.N)]\ndat[!is.na(tmax.accsumbyspp.elev),.(N=.N)]\n\n\n#\tdat[,plot(Tmax, tmax.accsum)]; abline(0,1)\n#\tdat[,plot(Tmax, tmax.accsum.elev)]; abline(0,1)\n#\tdat[,plot(tmax.accsum.elev, tmax.accsumbyspp.elev)]; abline(0,1)\n\t\tdat[,cor.test(tmax.accsum.elev, tmax.accsumbyspp.elev)]\n\n#####################################################################################\n# calculate thermal safety margin for each measurement of upper thermal tolerance\n#####################################################################################\n\n# thermal safety margin annual (elevation adjusted air temp/not, no tmax acclimation corrections)\n\t# body temp from air/water\ndat[, tsm_ann := Tmax - thabann] # air temperature no corrections\ndat[, tsm_ann_elev := Tmax - thabann.adj] # air temp elevation corrected, no acclimation\n\n# thermal safety margin summer (elevation adjusted air temp/not, no tmax acclimation corrections)\n\t# body temp from air/water climatologies\ndat[, tsm_sum := Tmax - thabsum] # air temperature no corrections\ndat[, tsm_sum_elev := Tmax - thabsum.adj] # air temp elevation corrected, no acclimation\n\n# thermal safety margin warmest month (elevation adjusted air temp/not, no tmax acclimation corrections)\n\t# body temp from air/water climatologies\ndat[, tsm_maxmo := Tmax - thabmaxmo] # air temperature no corrections\ndat[, tsm_maxmo_elev := Tmax - thabmaxmo.adj] # air temp elevation corrected, no acclimation\n\n\n# thermal safety margin 95% max hour (elevation adjusted air temp/not/NM, tmax acclimation corrected to summer/max month/none)\n\t# body temp from water climatologies (thab95hr not available on land)\ndat[, tsm_95hr_accsum := tmax.accsum - thab95hr] # water temp, acclimation to summer\n\n\t# body temp with marine behavioral thermoregulation (no sense to include elevation corrections since all ocean)\ndat[, tsm_95hr_marineBT := Tmax - thab95hr.marineBT]\ndat[, tsm_95hr_marineBT_accsum := tmax.accsum - thab95hr.marineBT]\ndat[, tsm_95hr_marineBT_accsumbyspp := tmax.accsumbyspp - thab95hr.marineBT]\n\ndat[, tsm_95hr_marineBTmore_accsum := tmax.accsum - thab95hr.marineBTmore] # more marine BT\ndat[, tsm_95hr_marineBTless_accsum := tmax.accsum - thab95hr.marineBTless] # less marine BT\n\n\n# thermal safety margin 95% GHCND max hour Tb calculation (only on land)\n\t# body temp from NM 2m shade (on land)\ndat[, tsm_NMGHCND_2m_shade_Tb95 := Tmax - NMGHCND_2m_shade_Tb95]\ndat[, tsm_NMGHCND_2m_shade_Tb95_accsum := tmax.accsum - NMGHCND_2m_shade_Tb95]\ndat[ ,tsm_NMGHCND_2m_shade_Tb95_accsum.elev := tmax.accsum.elev - NMGHCND_2m_shade_Tb95]\ndat[ ,tsm_NMGHCND_2m_shade_Tb95_accsumbyspp.elev := tmax.accsumbyspp.elev - NMGHCND_2m_shade_Tb95]\n\n\t# body temp from NM exposed (on land)\ndat[, tsm_NMGHCND_exposed_Tb95 := Tmax - NMGHCND_exposed_Tb95]\ndat[, tsm_NMGHCND_exposed_Tb95_accsum := tmax.accsum - NMGHCND_exposed_Tb95]\ndat[ ,tsm_NMGHCND_exposed_Tb95_accsum.elev := tmax.accsum.elev - NMGHCND_exposed_Tb95]\n\n\t# body temp from 100% wet skin sun in shade (on land)\ndat[, tsm_NMGHCND_shade_Tb_wet95 := Tmax - NMGHCND_shade_Tb_wet95]\ndat[, tsm_NMGHCND_shade_Tb_wet95_accsum := tmax.accsum - NMGHCND_shade_Tb_wet95]\ndat[, tsm_NMGHCND_shade_Tb_wet95_accsum.elev := tmax.accsum.elev - NMGHCND_shade_Tb_wet95]\ndat[, tsm_NMGHCND_shade_Tb_wet95_accsumbyspp.elev := tmax.accsumbyspp.elev - NMGHCND_shade_Tb_wet95]\n\n\n\n###########################\n# Add species types\n###########################\n\n# add species types\ndat[, animal.type := as.character(rep(NA, .N))]\ndat[Class=='Amphibia' & Realm=='Terrestrial', animal.type := 'amphibian']\ndat[Phylum=='Arthropoda' & Class %in% c('Insecta', 'Entognatha') & Realm=='Terrestrial', animal.type := 'insect']\ndat[Class %in% c('Malacostraca', 'Collembola', 'Gastropoda') & Realm=='Terrestrial', animal.type := 'other terrestrial invert']\ndat[Phylum=='Chordata' & Class %in% c('Reptilia', 'Archelosauria', 'Lepidosauria'), animal.type := 'reptile']\ndat[Phylum=='Arthropoda' & Class == 'Arachnida' & Realm=='Terrestrial', animal.type := 'spider']\n\ndat[Phylum=='Arthropoda' & Realm=='Marine', animal.type := 'crustacean']\ndat[Phylum=='Chordata' & Realm=='Marine', animal.type := 'fish']\ndat[Phylum=='Mollusca' & Realm=='Marine', animal.type := 'mollusc']\ndat[Phylum %in% c('Bryozoa', 'Echinodermata', 'Brachiopoda') & Realm=='Marine', animal.type := 'other marine invert']\n\n\t# any missing?\n\tdat[is.na(animal.type), sort(unique(paste(Realm, Phylum, Class)))]\n\tdat[is.na(animal.type), sort(unique(paste(Realm, Phylum, Class, Order)))]\n\n########################################\n# Make aggregate vectors of Te and TSM \n########################################\n\n## Tb\n\t# make a single vector of body temperatures (Tb) on land and at sea in favorable microclimates \n\t# (shade or wet skin on land, with behavioral thermoregulation at sea for all animals)\n\t# 95% max hour from GHCND\n\tdat[, tb_favorableGHCND95 := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tb_favorableGHCND95 := NMGHCND_2m_shade_Tb95]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tb_favorableGHCND95 := NMGHCND_shade_Tb_wet95]\n\tdat[Realm=='Marine', tb_favorableGHCND95 := thab95hr.marineBT]\n\n\t# make a single vector of body temperatures (Tb) on land and at sea in full sun\n\t# 95% max hour GHCND\n\tdat[, tb_sunGHCND95 := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tb_sunGHCND95 := NMGHCND_exposed_Tb95]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tb_sunGHCND95 := NMGHCND_exposed_Tb_wet95]\n\tdat[Realm=='Marine', tb_sunGHCND95 := thab95hr]\n\n## TSM\n\t# make a single vector of TSMs on land and at sea in full sun/at surface\n\t# use 95% GHCND Tb\n\t# includes acclimation to summer temperatures\n\tdat[, tsm_exposedGHCND95 := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial', tsm_exposedGHCND95 := tsm_NMGHCND_exposed_Tb95_accsum.elev]\n\tdat[Realm=='Marine', tsm_exposedGHCND95 := tsm_95hr_accsum]\n\n\t# use 95% warmest hour GHCND Tb for TSMs. favorable microclimates (shade or wet skin + behavioral thermoregulation)\n\tdat[, tsm_favorableGHCND95 := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95 := tsm_NMGHCND_2m_shade_Tb95_accsum.elev]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95 := tsm_NMGHCND_shade_Tb_wet95_accsum.elev]\n\tdat[Realm=='Marine', tsm_favorableGHCND95 := tsm_95hr_marineBT_accsum]\n\n\tdat[, tsm_favorableGHCND95_marBTmore := as.numeric(rep(NA, .N))] # more marine BT\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95_marBTmore := tsm_NMGHCND_2m_shade_Tb95_accsum.elev]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95_marBTmore := tsm_NMGHCND_shade_Tb_wet95_accsum.elev]\n\tdat[Realm=='Marine', tsm_favorableGHCND95_marBTmore := tsm_95hr_marineBTmore_accsum]\n\n\tdat[, tsm_favorableGHCND95_marBTless := as.numeric(rep(NA, .N))] # less marine BT\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95_marBTless := tsm_NMGHCND_2m_shade_Tb95_accsum.elev]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95_marBTless := tsm_NMGHCND_shade_Tb_wet95_accsum.elev]\n\tdat[Realm=='Marine', tsm_favorableGHCND95_marBTless := tsm_95hr_marineBTless_accsum]\n\n\t# sensitivity analysis: use species-specific ARRS\n\t# use 95% warmest hour GHCND for TSMs. favorable microclimates (shade or wet skin + behavioral thermoregulation)\n\tdat[, tsm_favorableGHCND95byspp := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95byspp := tsm_NMGHCND_2m_shade_Tb95_accsumbyspp.elev]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95byspp := tsm_NMGHCND_shade_Tb_wet95_accsumbyspp.elev]\n\tdat[Realm=='Marine', tsm_favorableGHCND95byspp := tsm_95hr_marineBT_accsumbyspp]\n\n\t# sensitivity analysis: make a single vector of TSMs on land and at sea in favorable microclimates\n\t# (shade or wet skin on land, WITHOUT behavioral thermoregulation at sea)\n\t# 95% warmest hour from GHCND Tb\n\t# includes acclimation to summer temperatures\n\tdat[, tsm_favorableGHCND95_nomarineBT := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95_nomarineBT := tsm_NMGHCND_2m_shade_Tb95_accsum.elev]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95_nomarineBT := tsm_NMGHCND_shade_Tb_wet95_accsum.elev]\n\tdat[Realm=='Marine', tsm_favorableGHCND95_nomarineBT := tsm_95hr_accsum]\n\n\t# make a single vector of TSMs on land and at sea in favorable microclimates\n\t# (shade or wet skin on land, with behavioral thermoregulation at sea)\n\t# 95% warmest hour from GHCND Tb\n\t# no acclimation: for comparison against maxmo, sum, and ann TSMs\n\tdat[, tsm_favorableGHCND95_noacc := as.numeric(rep(NA, .N))]\n\tdat[Realm=='Terrestrial' & animal.type!='amphibian', tsm_favorableGHCND95_noacc := tsm_NMGHCND_2m_shade_Tb95]\n\tdat[Realm=='Terrestrial' & animal.type=='amphibian', tsm_favorableGHCND95_noacc := tsm_NMGHCND_shade_Tb_wet95]\n\tdat[Realm=='Marine', tsm_favorableGHCND95_noacc := tsm_95hr_marineBT]\n\n\n#######################\n# write out\n#######################\nwrite.csv(dat, 'temp/warmingtolerance_byspecies.csv', row.names=FALSE)\n\n\n\n", "meta": {"hexsha": "eb644e7fd95c315e4871ae1b0ad4bbe0ff827c85", "size": 28733, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_calculations.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_calculations.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_calculations.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8727569331, "max_line_length": 387, "alphanum_fraction": 0.680993979, "num_tokens": 9588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190475, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.34843768662603847}} {"text": "#############################################################\n# Modelling dose - responses\n\nlibrary(drc)\nlibrary(mixtox)\nlibrary(bmdModeling)\nlibrary(synergyfinder)\nlibrary(multcomp)\nlibrary(bmd)\n\n# library(BIGL)\n\n#############################################################\n# Read and graphics\n\nlibrary(readxl)\nlibrary(ggplot2)\n\n#############################################################\n# Setup working directory\n\nsetwd(\"\")\n\n#############################################################\n# Setup working directory\n\nnames_end=excel_sheets(\"data/TOX_VIVO_CHICKEN.xls\")\n\nendlen=length(names_end)\n\ncases_ls=list()\n\nfor ( i in 1:endlen) {\n \n cases_ls[[i]]=as.data.frame(read_excel(\"data/TOX_VIVO_CHICKEN.xls\",names_end[i]))\n\n }\n\nsaveRDS(cases_ls,\"cases_ls.rds\")\n\n\n###############################################################################################\n# \n\ncases_ls_liv=list()\ncases_ls_mar=list()\n\nfor( i in 1:endlen) {\n cases_ls_liv[[i]]=cases_ls[[i]][which(cases_ls[[i]]$Specie==\"White Leghorn chickens\"),]\n cases_ls_mar[[i]]=cases_ls[[i]][which(cases_ls[[i]]$Specie==\"Marek chickens\"),]\n}\n\nsaveRDS(cases_ls_liv,\"cases_ls_liv.rds\")\nsaveRDS(cases_ls_mar,\"cases_ls_mar.rds\")\n\n############################################################\n# 'LL.3' and 'LL2.3' provide the three-parameter \n# log-logistic function where the lower limit is equal to 0. '\n\n############################################################\nold.par=par()\npar(old.par)\nset.seed(2)\nrange01 <- function(x){(x-min(x,na.rm=T))/(max(x,na.rm=T)-min(x,na.rm=T))}\n\n############################################################\n# BW gain\n# Marek\n\ndatamyc=cases_ls_mar[[1]]\ndataexpand=data.frame(Bodyweight_gain=rep(datamyc$Bodyweight_gain,100)+runif(length(datamyc$Bodyweight_gain)*100,-1.5,1.5)*rep(datamyc$Bodyweight_gain.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\n\n\n############################################################\n# BW gain\n# Marek\n\ndatamyc=cases_ls_mar[[1]]\ndataexpand=data.frame(Bodyweight_gain=rep(datamyc$Bodyweight_gain,100)+runif(length(datamyc$Bodyweight_gain)*100,-1.5,1.5)*rep(datamyc$Bodyweight_gain.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\ndataexpand$response=range01(dataexpand$Bodyweight_gain)\n\nmulti.m3=drm(Bodyweight_gain~Dose_T,Mycotoxin,data=dataexpand,fct = AR.3())\n#multi.s=drm(response~Dose_T,Mycotoxin,data=dataexpand,fct = LL.2())\n\nED(multi.m3,c(10,50), interval = \"delta\")\n\nfile.remove(\"summary_BW_gain_Marek.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_BW_gain_Marek.txt\",\n sep=\"\\n\",append = T)\n\n\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_BW_gain_Marek.txt\",\n sep=\"\\n\",append = T)\n\npng(\"images/BW_gain_Marek.png\")\n\nplot(multi.m3, \n col = TRUE, \n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"BW_gain\", \n main=\"Bodyweight_gain AF & OTA Marek chickens\\n Bootstrap=Yes Model=L.3\")\n\ndev.off()\n\n\n\n\n\n############################################################\n\ndatamyc=cases_ls_liv[[1]]\n\nmulti.m3 <- drm(Terminal_bodyweight~Dose_T,Mycotoxin,data=datamyc,fct = MM.3())\nprint(summary(multi.m3))\n\nfile.remove(\"summary_TW_gain_Liv.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_TW_gain_Liv.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_TW_gain_Liv.txt\",\n sep=\"\\n\")\n\npng(\"images/TW_gain_Liv.png\")\n\nplot(multi.m3, \n col = TRUE, \n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Terminal BW\", \n main=\"Terminal BW AF & OTA White Leghorn chickens\\n Bootstrap=Not Model=MM.3\")\ndev.off()\n\n\n\n########################################################################################à\n# Feed conversion #Marek\n\ndatamyc=cases_ls_mar[[2]]\ndataexpand=data.frame(Feed_conversion=rep(datamyc$Feed_conversion,100)+runif(length(datamyc$Feed_conversion)*100,-1.5,1.5)*rep(datamyc$Feed_conversion.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\nmulti.m3 <- drm(Feed_conversion~Dose_T,Mycotoxin,data=dataexpand,fct = AR.3())\n\nprint(summary(multi.m3))\n\nfile.remove(\"summary_Feed_conversion_mar.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_Feed_conversion_mar.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_Feed_conversion_mar.txt\",\n sep=\"\\n\")\n\npng(\"images/Feed_conversion_mar.png\")\n\nplot(multi.m3, \n col = TRUE, \n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Feed_conversion\", \n main=\"Feed_conversion AF & OTA Marek chickens\\n Bootstrap=Yes Model=AR.3\",\n legendPos = c(0.4, 2.8))\n\ndev.off()\n\n#########################################################################################\n# Feed intake #Marek\n\ndatamyc=cases_ls_mar[[3]]\nmulti.m3 <- drm(Feed_intake~Dose_T,Mycotoxin,data=datamyc,fct = AR.3())\nprint(summary(multi.m3))\n\n\npng(\"images/Feed_intake_mar_bootno.png\")\n\nplot(multi.m3, \n col = TRUE, \n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Feed_intake\",\n main=\"Feed_intake AF & OTA Marek chickens\\n Bootstrap=No Model=AR.3\")\n\ndev.off()\n\ndataexpand=data.frame(Feed_intake=rep(datamyc$Feed_intake,100)+runif(length(datamyc$Feed_intake)*100,-1.5,1.5)*rep(datamyc$Feed_intake.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\n\nmulti.m3 <- drm(Feed_intake~Dose_T,Mycotoxin,data=dataexpand,fct = AR.3())\nprint(summary(multi.m3))\n\nfile.remove(\"summary_Feed_intake_mar.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_Feed_intake_mar.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_Feed_intake_mar.txt\",\n sep=\"\\n\",append = T)\n\npng(\"images/Feed_intake_mar.png\")\n\nplot(multi.m3, \n col = TRUE, \n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Feed_intake\",\n main=\" Feed_intake AF & OTA Marek chickens\\n Bootstrap=Yes Model=AR.3\")\ndev.off()\n\n##########################################################################################\n\ndatamyc=cases_ls_liv[[3]]\nmulti.m3 <- drm(Feed_intake~Dose_T,Mycotoxin,data=datamyc,fct = L.3())\nprint(summary(multi.m3))\n\nfile.remove(\"summary_Feed_intake_liv.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_Feed_intake_liv.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_Feed_intake_mar.txt\",\n sep=\"\\n\",append = T)\n\n\npng(\"images/Feed_intake_liv_bootno.png\")\n\nplot(multi.m3,\n col = TRUE,\n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Feed_intake\",\n xlim=c(0,10),\n main=\"Feed_intake AF & OTA White Leghorn chickens\\n Bootstrap=No Model=L.3\",\n legendPos = c(9, 5400))\n\ndev.off()\n\n\n\n##########################################################################################\n# Liver_relative_weight #Marek\n\n\ndatamyc=cases_ls_mar[[4]]\n\ndataexpand=data.frame(Liver_relative_weight=rep(datamyc$Liver_relative_weight,100)+runif(length(datamyc$Liver_relative_weight)*100,-1.2,1.2)*rep(datamyc$Liver_relative_weight.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\nmulti.m3 <- drm(Liver_relative_weight~Dose_T,Mycotoxin,data=dataexpand,fct = AR.3())\nprint(summary(multi.m3))\nfile.remove(\"summary_Liver_RW_mar.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_Liver_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_Liver_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\n\npng(\"images/Liver_RW_mar.png\")\n\nplot(multi.m3, col = TRUE,\n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Liver RW\", \n main=\"Liver RW AF & OTA Marek chickens\\n Bootstrap=Yes Model=AR.3\",\n legendPos = c(0.5, 4.8))\n\ndev.off()\n\n\n\n\n##########################################################################################\n# Kidney_relative_weight#Marek\n\ndatamyc=cases_ls_mar[[5]]\n\ndataexpand=data.frame(Kidney_relative_weight=rep(datamyc$Kidney_relative_weight,100)+runif(length(datamyc$Kidney_relative_weight)*100,-1.5,1.5)*rep(datamyc$Kidney_relative_weight.sd,100),\n Mycotoxin=rep(datamyc$Mycotoxin,100),\n Dose_T=rep(datamyc$Dose_T,100))\n\nmulti.m3 <- drm(Kidney_relative_weight~Dose_T,Mycotoxin,data=dataexpand,fct = AR.3())\nprint(summary(multi.m3))\n\nfile.remove(\"summary_Kidney_RW_mar.txt\")\n\ncat(capture.output(ED(multi.m3,c(10,50), interval = \"delta\")),\n file = \"summary_Kidney_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m3)),\n file = \"summary_Kidney_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\n\npng(\"images/Kidney_RW_mar.png\")\n\nplot(multi.m3, col = TRUE,\n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Kidney RW\", \n main=\"Kidney RW AF & OTA Marek chickens\\n Bootstrap=Yes Model=AR.3\",\n legendPos = c(0.5, 0.9))\n\ndev.off()\n\n##########################################################################################\n# Spleen_relative weight\n\ndatamyc=cases_ls_mar[[6]]\nmulti.m4 <- drm(Spleen_relative_weight~Dose_T,Mycotoxin,data=datamyc[,],fct=L.3())\nprint(summary(multi.m4))\n\nfile.remove(\"summary_Spleen_RW_mar.txt\")\n\ncat(capture.output(ED(multi.m4,c(10,50), interval = \"delta\")),\n file = \"summary_Spleen_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\ncat(capture.output(summary(multi.m4)),\n file = \"summary_Spleen_RW_mar.txt\",\n sep=\"\\n\",append = T)\n\n\npng(\"images/Spleen_RW_mar.png\")\n\nplot(multi.m4, col = TRUE,\n xlab = \"Log Dose(mg/kg feed)\",\n ylab = \"Spleen RW\", \n main=\"Spleen RW AF & OTA Marek chickens\\n Bootstrap=No Model=L.3\",\n legendPos = c(0.4, 0.329))\n\ndev.off()\n", "meta": {"hexsha": "28fe081f57258d0a9840bdb7e4957622cf509008", "size": 9832, "ext": "r", "lang": "R", "max_stars_repo_path": "modeling_dose_addition/mixdrm.r", "max_stars_repo_name": "alfcrisci/michyf", "max_stars_repo_head_hexsha": "9a6a8905f272f9bc7ed9751eeaa75ad5e2418544", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-06-13T15:54:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T15:54:35.000Z", "max_issues_repo_path": "modeling_dose_addition/mixdrm.r", "max_issues_repo_name": "alfcrisci/Mychif", "max_issues_repo_head_hexsha": "9a6a8905f272f9bc7ed9751eeaa75ad5e2418544", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modeling_dose_addition/mixdrm.r", "max_forks_repo_name": "alfcrisci/Mychif", "max_forks_repo_head_hexsha": "9a6a8905f272f9bc7ed9751eeaa75ad5e2418544", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9318181818, "max_line_length": 187, "alphanum_fraction": 0.5980471928, "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.34749755709560654}} {"text": "#####################################################################\n# Fitting generalized additive models to fraction feeding data\n# See '...GAM_robustness.r' for model justifications, including\n# error family and link function and gamma wiggliness penalty\n#####################################################################\n#####################################################################\nrm(list = ls())\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nlibrary(plyr)\nlibrary(mgcv)\nlibrary(xtable) # for LaTeX export\nlibrary(ggplot2)\nsource('R/FracFeed-Functions.r') # Convenience functions\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Load saved 'fdat' w/ tWS\nload('Data/FracFeed_DataPhylo.Rdata') # load full post-ToL FracFeed database\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nnrow(fdat) # total number of surveys in database\nlength(unique(fdat$Consumer.identity)) # total number of species in database\nrange(fdat$Latitude, na.rm = TRUE)\nrange(fdat$Year, na.rm = TRUE)\n\n#####################################################################\n# Summary stats by Taxonomic Group\n##################################\nTaxonGroupLevels <-\n c(\n 'Ctenophores',\n 'Cnidarians',\n 'Annelids',\n 'Chaetognaths',\n 'Molluscs',\n 'Echinoderms',\n 'Arthropods',\n 'Fish',\n 'Reptiles',\n 'Amphibians',\n 'Birds',\n 'Mammals'\n )\nfdat$Taxon.group <- factor(fdat$Taxon.group, levels = TaxonGroupLevels)\nsfdat <-\n ddply(\n fdat,\n .(Taxon.group),\n summarise,\n 'Mean' = mean(fF),\n 'Std.dev.' = sd(fF),\n Min = min(fF),\n Max = max(fF),\n Surveys = length(fF),\n Species = length(unique(Consumer.identity)),\n minObs = min(Total.stomachs.count, na.rm = T),\n maxObs = max(Total.stomachs.count, na.rm = T)\n )\nsfdat[, 2:5] <- round(sfdat[, 2:5], 2)\n\n\nsetwd('Figures/Supp/')\nprint(\n xtable(sfdat, type = \"latex\", caption = 'Summary statistics for all taxa in the database, including those that could not be used in the analyses of the main text for lack of co-variate information. minObs and maxObs refer to the minimum and maximum number of individuals assessed in a single survey across all surveys of the group.'),\n file = \"FracFeed-Tab-SummStats.tex\",\n include.rownames = FALSE,\n table.placement = 'H'\n)\nsetwd('../../')\n\n\npdf(\n 'Figures/Supp/FracFeed-FigS-TaxonViolins.pdf',\n height = 3,\n width = 5\n)\nviol <-\n ggplot(fdat, aes(Taxon.group, Percent.feeding)) + \n geom_violin(scale = \"width\", bg = 'grey') + \n labs(x = '', y = 'Percent feeding') + \n theme_classic() + theme(axis.text.x = element_text(angle = 60, hjust = 1)) + \n stat_summary(fun.data = data_summary, color = \"black\") + \n annotate(\"text\", x = 1:nrow(sfdat), y = 106, \n label = sfdat$Species, size = 1.5) + \n annotate(\"text\", x = 1:nrow(sfdat), y = 103, \n label = paste0(\"(\", sfdat$Surveys, \")\"), size = 1.5)\nprint(viol)\ndev.off()\n\n################################################\n# General model specifications \n# (justified in GAM_robustness)\n################################################\nfam <- quasibinomial(link = 'logit')\n\n# To get actual used sample size (after dropped rows)\n# (needed for determining BIC-like gamma penalty)\nfit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TAlog + SAlog + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method='REML'\n)\ngamma <- log(nrow(fit$model)) / 2\n\n#######################\n# All primary variables\n#######################\nfit1.cont <- fit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TAlog + SAlog + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\n# Compare data lost vs. included\nnrow(fit$model)\nexcl <- fdat[fit$na.action, ]\nnrow(excl)\n\nincl <- fdat[-fit$na.action, ]\nnrow(incl)\nlength(unique(incl$Consumer.identity))\nrange(incl$Year, na.rm = TRUE)\nrange(incl$Lat, na.rm = TRUE)\n\nnrow(fdat)\nnrow(excl) + nrow(incl)\nlength(unique(fdat$Consumer.identity))\n\n# odds ratio\nexp(cbind(\"Odds ratio\" = coef(fit)[c('TAlog', 'SAlog')],\n confint.default(fit, c('TAlog', 'SAlog'), level = 0.95)))\n1 / exp(cbind(\"Odds ratio\" = coef(fit)[c('SAlog')],\n confint.default(fit, c('SAlog'), level = 0.95)))\n\n\nsave(fit, file = 'Output/GAM/GAM_fit_wTaxInf.Rdata')\n\npdf('Output/GAM/GAM_fit_wTaxInf.pdf',\n height = 8,\n width = 10)\nplot(\n fit,\n residuals = F,\n seWithMean = TRUE,\n shade = TRUE,\n rug = TRUE,\n all.terms = TRUE,\n pch = '.',\n pages = 1\n)\npar(mfrow = c(2, 2))\ngam.check(fit)\ndev.off()\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Same but with TA and SA as factors\nfit1.fact <- fit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TA + SA + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nsummary(fit)\nlogit_tr(summary(fit)$p.coeff)\n\nsave(fit, file = 'Output/GAM/GAM_fit_wTaxInf_TASAfact.Rdata')\n\npdf('Output/GAM/GAM_fit_wTaxInf_TASAfact.pdf',\n height = 8,\n width = 10)\nplot(\n fit,\n residuals = F,\n seWithMean = TRUE,\n shade = TRUE,\n rug = TRUE,\n all.terms = TRUE,\n pch = '.',\n pages = 1\n)\npar(mfrow = c(2, 2))\ngam.check(fit)\ndev.off()\n\n# Export summary tables\np.out <- summary(fit1.fact)$p.table\np.out[, 1:3] <- signif(p.out[, 1:3], 2)\np.out[, 4] <- signif(p.out[, 4], 3)\np.out[p.out[, 4] < 10 ^ -3, 4] <- '< 0.001'\np.out[p.out == 'NaN'] <- ''\n\nrownames(p.out) <- sub('TA', '', rownames(p.out))\nrownames(p.out) <- sub('SA', '', rownames(p.out))\nrownames(p.out) <- sub('Eco', '', rownames(p.out))\nrownames(p.out) <- sub('EE', '', rownames(p.out))\nrownames(p.out) <- sub('TG', '', rownames(p.out))\n\ns.out <- summary(fit1.fact)$s.table\ns.out[, 1:3] <- round(s.out[, 1:3], 2)\ns.out[, 4] <- round(s.out[, 4], 3)\ns.out[s.out[, 4] < 10 ^ -3, 4] <- '< 0.001'\n\nsetwd('Figures/Supp/')\nprint(\n xtable(\n p.out,\n type = \"latex\",\n caption = 'Estimated effects (log-odds) of the parametric terms in the primary statistical model describing variation in the observed fraction of feeding individuals. The intercept to which all effects are relative corresponds to an ectothermic marine mollusc surveyed at a spatial scale of up to 1 meter for under an hour. Birds correspond to the endotherm baseline.',\n label = 'tab:gam_main_p'\n ),\n file = \"FracFeed-Tab-GAM_main_ptable.tex\",\n table.placement = 'H'\n)\n\nprint(\n xtable(\n s.out,\n type = \"latex\",\n caption = 'Estimated effects of the smooth terms in the primary statistical model describing variation in the observed fraction of feeding individuals. $tWS$ refers to the days since the last winter solsctice, $Lat$ refers to latitude, $DRlog$ refers to $log_{10}$ of minimum diet richness, and $Year$ refers to the year of the survey.',\n label = 'tab:gam_main_s'\n ),\n file = \"FracFeed-Tab-GAM_main_stable.tex\",\n table.placement = 'H'\n)\nsetwd('../../')\n\n##############################################################\n# Same (with TA and SA as factors) but relative to terrestrial\n# (to ease language of main text)\n##############################################################\norig <- levels(fdat$Eco)\nfdat$Eco <- factor(fdat$Eco, levels = rev(orig))\nfit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TA + SA + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nsummary(fit)\ntrms <- summary(fit)$p.coeff\nsel <- grep('Eco', names(trms))\n# Log-odds\ntrms[sel]\n# Odds-ratios\nexp(trms[sel])\nexp(cbind(\"Odds ratio\" = coef(fit)[sel],\n confint.default(fit, sel, level = 0.95)))\n\n# now to compare lakes and streams\nfdat$Eco <- factor(fdat$Eco, levels = orig[c(3, 4, 5, 1, 2)])\nfit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TA + SA + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nsummary(fit)\ntrms <- summary(fit)$p.coeff\nsel <- grep('Eco', names(trms))\n# Log-odds\ntrms[sel]\n# Odds-ratios\nexp(trms[sel])\nexp(cbind(\"Odds ratio\" = coef(fit)[sel],\n confint.default(fit, sel, level = 0.95)))\n\n# Reorder to original\nfdat$Eco <- factor(fdat$Eco, levels = orig)\n\n################################################################\n# Same (with TA and SA as factors) but with DRlog as parametric linear term\n# (to enable language of main text)\n################################################################\nfit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + DRlog + s(Year) +\n TA + SA + Eco + EE + TG,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nsummary(fit)\ntrms <- summary(fit)$p.coeff\nsel <- grep('DRlog', names(trms))\n# Log-odds\ntrms[sel]\n# Odds-ratios\nexp(cbind(\"Odds ratio\" = coef(fit)[sel],\n confint.default(fit, sel, level = 0.95)))\n\n####################################################################\n# Without taxonomic information for phylogenetic tests\n# (i.e. remove Endo/Ecto, Taxon Group, Diet richness and Ecosystem)\n####################################################################\nfit.noTaxInf <- fit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(Year) + \n TAlog + SAlog,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nanova(fit)\nsummary(fit)\n\n# How many data points included (because the others didn't have info for all variables)?\nnrow(fit$model)\nexcl <- fdat[fit$na.action, ]\nnrow(excl)\n\nsave(fit, file = 'Output/GAM/GAM_fit_noTaxInf.Rdata')\n\npdf(paste0('Output/GAM/GAM_fit_noTaxInf.pdf'),\n height = 8,\n width = 10)\nplot(\n fit,\n residuals = F,\n seWithMean = TRUE,\n shade = TRUE,\n rug = TRUE,\n all.terms = TRUE,\n pch = '.',\n pages = 1\n)\npar(mfrow = c(2, 2))\ngam.check(fit)\ndev.off()\n\n########################################################################\n####################################\n# Final model plus feeding data type\n# (dismissed during robustness checks \n# but requested by reviewers)\n####################################\nfit1.fact <- fit <- gam(\n (FSc / TSc) ~ \n s(tWS, bs = 'cc') + s(Lat) + s(DRlog) + s(Year) +\n TA + SA + Eco + EE + TG + FD,\n family = fam,\n weights = TSc,\n knots = list(tWS = c(0, 365)),\n data = fdat,\n na.action = 'na.omit',\n method = 'REML',\n gamma = gamma\n)\n\nsummary(fit)\nlogit_tr(summary(fit)$p.coeff)\n\npdf(\n 'Output/GAM/GAM_fit_wTaxInf_TASAfact_wFD.pdf',\n height = 8,\n width = 10\n)\nplot(\n fit,\n residuals = F,\n seWithMean = TRUE,\n shade = TRUE,\n rug = TRUE,\n all.terms = TRUE,\n pch = '.',\n pages = 1\n)\npar(mfrow = c(2, 2))\ngam.check(fit)\ndev.off()\n\n# Export summary tables\np.out <- summary(fit1.fact)$p.table\np.out[, 1:3] <- signif(p.out[, 1:3], 2)\np.out[, 4] <- signif(p.out[, 4], 3)\np.out[p.out[, 4] < 10 ^ -3, 4] <- '< 0.001'\np.out[p.out == 'NaN'] <- ''\n\nrownames(p.out) <- sub('TA', '', rownames(p.out))\nrownames(p.out) <- sub('SA', '', rownames(p.out))\nrownames(p.out) <- sub('Eco', '', rownames(p.out))\nrownames(p.out) <- sub('EE', '', rownames(p.out))\nrownames(p.out) <- sub('TG', '', rownames(p.out))\nrownames(p.out) <- sub('FD', '', rownames(p.out))\n\ns.out <- summary(fit1.fact)$s.table\ns.out[, 1:3] <- round(s.out[, 1:3], 2)\ns.out[, 4] <- round(s.out[, 4], 3)\ns.out[s.out[, 4] < 10 ^ -3, 4] <- '< 0.001'\n\nsetwd('Figures/Supp/')\nprint(\n xtable(\n p.out,\n type = \"latex\",\n caption = 'Estimated effects (log-odds) of the parametric terms in the primary statistical model but with data type (stomach contents versus direct observation) also included.',\n label = 'tab:gam_main_p'\n ),\n file = \"FracFeed-Tab-GAM_main_wFD_ptable.tex\",\n table.placement = 'H'\n)\n\nprint(\n xtable(\n s.out,\n type = \"latex\",\n caption = 'Estimated effects of the smooth terms in the primary statistical model but with data type (stomach contents versus direct observation) also included.',\n label = 'tab:gam_main_wFD_s'\n ),\n file = \"FracFeed-Tab-GAM_main_wFD_stable.tex\",\n table.placement = 'H'\n)\nsetwd('../../')\n\n\n####################################################################\n####################################################################\n####################################################################", "meta": {"hexsha": "f56efbb4a2cee5e6b8fcfdf22e43b1b9be6d1d8e", "size": 12701, "ext": "r", "lang": "R", "max_stars_repo_path": "dev/R/FracFeed-Analyses-GAM.r", "max_stars_repo_name": "marknovak/FracFeed", "max_stars_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dev/R/FracFeed-Analyses-GAM.r", "max_issues_repo_name": "marknovak/FracFeed", "max_issues_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dev/R/FracFeed-Analyses-GAM.r", "max_forks_repo_name": "marknovak/FracFeed", "max_forks_repo_head_hexsha": "68a919d79cb38d49dbf34d7d4cff8108401d7a43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.731441048, "max_line_length": 375, "alphanum_fraction": 0.5494055586, "num_tokens": 3858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250376, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.347226515378661}} {"text": "score <- function(input) {\n var1 <- ((((((26.85177874216177) + ((subroutine0(input)) * (-0.12034962779157432))) + ((subroutine1(input)) * (1.0))) + ((subroutine2(input)) * (-1.0))) + ((subroutine3(input)) * (-1.0))) + ((subroutine4(input)) * (-1.0))) + ((subroutine5(input)) * (0.6171875007313155))\n var2 <- (subroutine6(input)) * (-1.0)\n var0 <- (((((((((((((((((((((((((var1) + (var2)) + ((subroutine7(input)) * (1.0))) + ((subroutine8(input)) * (-1.0))) + ((subroutine9(input)) * (1.0))) + ((subroutine10(input)) * (0.3164062486215933))) + ((subroutine11(input)) * (-1.0))) + ((subroutine12(input)) * (1.0))) + ((subroutine13(input)) * (-1.0))) + ((subroutine14(input)) * (1.0))) + ((subroutine15(input)) * (-1.0))) + ((subroutine16(input)) * (1.0))) + ((subroutine17(input)) * (-1.0))) + ((subroutine18(input)) * (-1.0))) + ((subroutine19(input)) * (-0.3201043650830524))) + ((subroutine20(input)) * (-1.0))) + ((subroutine21(input)) * (-1.0))) + ((subroutine22(input)) * (1.0))) + ((subroutine23(input)) * (-0.7715023625371545))) + ((subroutine24(input)) * (-1.0))) + ((subroutine25(input)) * (1.0))) + ((subroutine26(input)) * (-1.0))) + ((subroutine27(input)) * (-0.006346611962003479))) + ((subroutine28(input)) * (1.0))) + ((subroutine29(input)) * (-1.0))) + ((subroutine30(input)) * (-1.0))\n var3 <- (subroutine31(input)) * (-0.17130203879318218)\n return((((((((((((((((((((((((((var0) + (var3)) + ((subroutine32(input)) * (1.0))) + ((subroutine33(input)) * (1.0))) + ((subroutine34(input)) * (1.0))) + ((subroutine35(input)) * (-0.32034025068626093))) + ((subroutine36(input)) * (-0.9199503780639393))) + ((subroutine37(input)) * (1.0))) + ((subroutine38(input)) * (-1.0))) + ((subroutine39(input)) * (1.0))) + ((subroutine40(input)) * (-0.12010436508304956))) + ((subroutine41(input)) * (1.0))) + ((subroutine42(input)) * (1.0))) + ((subroutine43(input)) * (1.0))) + ((subroutine44(input)) * (-1.0))) + ((subroutine45(input)) * (-1.0))) + ((subroutine46(input)) * (1.0))) + ((subroutine47(input)) * (1.0))) + ((subroutine48(input)) * (0.816406250647308))) + ((subroutine49(input)) * (1.0))) + ((subroutine50(input)) * (1.0))) + ((subroutine51(input)) * (1.0))) + ((subroutine52(input)) * (-1.0))) + ((subroutine53(input)) * (1.0))) + ((subroutine54(input)) * (-1.0))) + ((subroutine55(input)) * (-1.0)))\n}\nsubroutine0 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((25.9406) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((5.304) - (input[6])) ^ (2))) + (((89.1) - (input[7])) ^ (2))) + (((1.6475) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((127.36) - (input[12])) ^ (2))) + (((26.64) - (input[13])) ^ (2)))))\n}\nsubroutine1 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((6.53876) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.631) - (input[5])) ^ (2))) + (((7.016) - (input[6])) ^ (2))) + (((97.5) - (input[7])) ^ (2))) + (((1.2024) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((392.05) - (input[12])) ^ (2))) + (((2.96) - (input[13])) ^ (2)))))\n}\nsubroutine2 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((22.5971) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.7) - (input[5])) ^ (2))) + (((5.0) - (input[6])) ^ (2))) + (((89.5) - (input[7])) ^ (2))) + (((1.5184) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((31.99) - (input[13])) ^ (2)))))\n}\nsubroutine3 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((45.7461) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((4.519) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.6582) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((88.27) - (input[12])) ^ (2))) + (((36.98) - (input[13])) ^ (2)))))\n}\nsubroutine4 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((11.8123) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.718) - (input[5])) ^ (2))) + (((6.824) - (input[6])) ^ (2))) + (((76.5) - (input[7])) ^ (2))) + (((1.794) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((48.45) - (input[12])) ^ (2))) + (((22.74) - (input[13])) ^ (2)))))\n}\nsubroutine5 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.08187) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((2.89) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.445) - (input[5])) ^ (2))) + (((7.82) - (input[6])) ^ (2))) + (((36.9) - (input[7])) ^ (2))) + (((3.4952) - (input[8])) ^ (2))) + (((2.0) - (input[9])) ^ (2))) + (((276.0) - (input[10])) ^ (2))) + (((18.0) - (input[11])) ^ (2))) + (((393.53) - (input[12])) ^ (2))) + (((3.57) - (input[13])) ^ (2)))))\n}\nsubroutine6 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((7.67202) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.747) - (input[6])) ^ (2))) + (((98.9) - (input[7])) ^ (2))) + (((1.6334) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((393.1) - (input[12])) ^ (2))) + (((19.92) - (input[13])) ^ (2)))))\n}\nsubroutine7 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((1.46336) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((19.58) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.605) - (input[5])) ^ (2))) + (((7.489) - (input[6])) ^ (2))) + (((90.8) - (input[7])) ^ (2))) + (((1.9709) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((403.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((374.43) - (input[12])) ^ (2))) + (((1.73) - (input[13])) ^ (2)))))\n}\nsubroutine8 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((20.0849) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.7) - (input[5])) ^ (2))) + (((4.368) - (input[6])) ^ (2))) + (((91.2) - (input[7])) ^ (2))) + (((1.4395) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((285.83) - (input[12])) ^ (2))) + (((30.63) - (input[13])) ^ (2)))))\n}\nsubroutine9 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((1.83377) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((19.58) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.605) - (input[5])) ^ (2))) + (((7.802) - (input[6])) ^ (2))) + (((98.2) - (input[7])) ^ (2))) + (((2.0407) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((403.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((389.61) - (input[12])) ^ (2))) + (((1.92) - (input[13])) ^ (2)))))\n}\nsubroutine10 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.5405) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.97) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.575) - (input[5])) ^ (2))) + (((7.47) - (input[6])) ^ (2))) + (((52.6) - (input[7])) ^ (2))) + (((2.872) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((264.0) - (input[10])) ^ (2))) + (((13.0) - (input[11])) ^ (2))) + (((390.3) - (input[12])) ^ (2))) + (((3.16) - (input[13])) ^ (2)))))\n}\nsubroutine11 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((73.5341) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((5.957) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.8026) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((16.45) - (input[12])) ^ (2))) + (((20.62) - (input[13])) ^ (2)))))\n}\nsubroutine12 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.33147) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((6.2) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.507) - (input[5])) ^ (2))) + (((8.247) - (input[6])) ^ (2))) + (((70.4) - (input[7])) ^ (2))) + (((3.6519) - (input[8])) ^ (2))) + (((8.0) - (input[9])) ^ (2))) + (((307.0) - (input[10])) ^ (2))) + (((17.4) - (input[11])) ^ (2))) + (((378.95) - (input[12])) ^ (2))) + (((3.95) - (input[13])) ^ (2)))))\n}\nsubroutine13 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((25.0461) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.987) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.5888) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((26.77) - (input[13])) ^ (2)))))\n}\nsubroutine14 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.57834) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.97) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.575) - (input[5])) ^ (2))) + (((8.297) - (input[6])) ^ (2))) + (((67.0) - (input[7])) ^ (2))) + (((2.4216) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((264.0) - (input[10])) ^ (2))) + (((13.0) - (input[11])) ^ (2))) + (((384.54) - (input[12])) ^ (2))) + (((7.44) - (input[13])) ^ (2)))))\n}\nsubroutine15 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((16.8118) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.7) - (input[5])) ^ (2))) + (((5.277) - (input[6])) ^ (2))) + (((98.1) - (input[7])) ^ (2))) + (((1.4261) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((30.81) - (input[13])) ^ (2)))))\n}\nsubroutine16 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.31533) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((6.2) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.504) - (input[5])) ^ (2))) + (((8.266) - (input[6])) ^ (2))) + (((78.3) - (input[7])) ^ (2))) + (((2.8944) - (input[8])) ^ (2))) + (((8.0) - (input[9])) ^ (2))) + (((307.0) - (input[10])) ^ (2))) + (((17.4) - (input[11])) ^ (2))) + (((385.05) - (input[12])) ^ (2))) + (((4.14) - (input[13])) ^ (2)))))\n}\nsubroutine17 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((67.9208) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.683) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.4254) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((384.97) - (input[12])) ^ (2))) + (((22.98) - (input[13])) ^ (2)))))\n}\nsubroutine18 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.18337) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((27.74) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.609) - (input[5])) ^ (2))) + (((5.414) - (input[6])) ^ (2))) + (((98.3) - (input[7])) ^ (2))) + (((1.7554) - (input[8])) ^ (2))) + (((4.0) - (input[9])) ^ (2))) + (((711.0) - (input[10])) ^ (2))) + (((20.1) - (input[11])) ^ (2))) + (((344.05) - (input[12])) ^ (2))) + (((23.97) - (input[13])) ^ (2)))))\n}\nsubroutine19 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((14.3337) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.7) - (input[5])) ^ (2))) + (((4.88) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.5895) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((372.92) - (input[12])) ^ (2))) + (((30.62) - (input[13])) ^ (2)))))\n}\nsubroutine20 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.20746) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((27.74) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.609) - (input[5])) ^ (2))) + (((5.093) - (input[6])) ^ (2))) + (((98.0) - (input[7])) ^ (2))) + (((1.8226) - (input[8])) ^ (2))) + (((4.0) - (input[9])) ^ (2))) + (((711.0) - (input[10])) ^ (2))) + (((20.1) - (input[11])) ^ (2))) + (((318.43) - (input[12])) ^ (2))) + (((29.68) - (input[13])) ^ (2)))))\n}\nsubroutine21 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((41.5292) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.531) - (input[6])) ^ (2))) + (((85.4) - (input[7])) ^ (2))) + (((1.6074) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((329.46) - (input[12])) ^ (2))) + (((27.38) - (input[13])) ^ (2)))))\n}\nsubroutine22 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((1.51902) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((19.58) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.605) - (input[5])) ^ (2))) + (((8.375) - (input[6])) ^ (2))) + (((93.9) - (input[7])) ^ (2))) + (((2.162) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((403.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((388.45) - (input[12])) ^ (2))) + (((3.32) - (input[13])) ^ (2)))))\n}\nsubroutine23 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((11.5779) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.7) - (input[5])) ^ (2))) + (((5.036) - (input[6])) ^ (2))) + (((97.0) - (input[7])) ^ (2))) + (((1.77) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((25.68) - (input[13])) ^ (2)))))\n}\nsubroutine24 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((14.2362) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((6.343) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.5741) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((20.32) - (input[13])) ^ (2)))))\n}\nsubroutine25 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((9.2323) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.631) - (input[5])) ^ (2))) + (((6.216) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.1691) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((366.15) - (input[12])) ^ (2))) + (((9.53) - (input[13])) ^ (2)))))\n}\nsubroutine26 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((9.91655) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.852) - (input[6])) ^ (2))) + (((77.8) - (input[7])) ^ (2))) + (((1.5004) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((338.16) - (input[12])) ^ (2))) + (((29.97) - (input[13])) ^ (2)))))\n}\nsubroutine27 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((22.0511) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.74) - (input[5])) ^ (2))) + (((5.818) - (input[6])) ^ (2))) + (((92.4) - (input[7])) ^ (2))) + (((1.8662) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((391.45) - (input[12])) ^ (2))) + (((22.11) - (input[13])) ^ (2)))))\n}\nsubroutine28 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.61154) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.97) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.647) - (input[5])) ^ (2))) + (((8.704) - (input[6])) ^ (2))) + (((86.9) - (input[7])) ^ (2))) + (((1.801) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((264.0) - (input[10])) ^ (2))) + (((13.0) - (input[11])) ^ (2))) + (((389.7) - (input[12])) ^ (2))) + (((5.12) - (input[13])) ^ (2)))))\n}\nsubroutine29 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((10.8342) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((6.782) - (input[6])) ^ (2))) + (((90.8) - (input[7])) ^ (2))) + (((1.8195) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((21.57) - (input[12])) ^ (2))) + (((25.79) - (input[13])) ^ (2)))))\n}\nsubroutine30 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((15.8603) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((5.896) - (input[6])) ^ (2))) + (((95.4) - (input[7])) ^ (2))) + (((1.9096) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((7.68) - (input[12])) ^ (2))) + (((24.39) - (input[13])) ^ (2)))))\n}\nsubroutine31 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((17.8667) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.671) - (input[5])) ^ (2))) + (((6.223) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.3861) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((393.74) - (input[12])) ^ (2))) + (((21.78) - (input[13])) ^ (2)))))\n}\nsubroutine32 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((8.26725) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.668) - (input[5])) ^ (2))) + (((5.875) - (input[6])) ^ (2))) + (((89.6) - (input[7])) ^ (2))) + (((1.1296) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((347.88) - (input[12])) ^ (2))) + (((8.88) - (input[13])) ^ (2)))))\n}\nsubroutine33 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.52693) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((6.2) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.504) - (input[5])) ^ (2))) + (((8.725) - (input[6])) ^ (2))) + (((83.0) - (input[7])) ^ (2))) + (((2.8944) - (input[8])) ^ (2))) + (((8.0) - (input[9])) ^ (2))) + (((307.0) - (input[10])) ^ (2))) + (((17.4) - (input[11])) ^ (2))) + (((382.0) - (input[12])) ^ (2))) + (((4.63) - (input[13])) ^ (2)))))\n}\nsubroutine34 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.0351) - (input[1])) ^ (2)) + (((95.0) - (input[2])) ^ (2))) + (((2.68) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.4161) - (input[5])) ^ (2))) + (((7.853) - (input[6])) ^ (2))) + (((33.2) - (input[7])) ^ (2))) + (((5.118) - (input[8])) ^ (2))) + (((4.0) - (input[9])) ^ (2))) + (((224.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((392.78) - (input[12])) ^ (2))) + (((3.81) - (input[13])) ^ (2)))))\n}\nsubroutine35 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((12.2472) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.584) - (input[5])) ^ (2))) + (((5.837) - (input[6])) ^ (2))) + (((59.7) - (input[7])) ^ (2))) + (((1.9976) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((24.65) - (input[12])) ^ (2))) + (((15.69) - (input[13])) ^ (2)))))\n}\nsubroutine36 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((14.4208) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.74) - (input[5])) ^ (2))) + (((6.461) - (input[6])) ^ (2))) + (((93.3) - (input[7])) ^ (2))) + (((2.0026) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((27.49) - (input[12])) ^ (2))) + (((18.05) - (input[13])) ^ (2)))))\n}\nsubroutine37 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.29819) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((6.2) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.504) - (input[5])) ^ (2))) + (((7.686) - (input[6])) ^ (2))) + (((17.0) - (input[7])) ^ (2))) + (((3.3751) - (input[8])) ^ (2))) + (((8.0) - (input[9])) ^ (2))) + (((307.0) - (input[10])) ^ (2))) + (((17.4) - (input[11])) ^ (2))) + (((377.51) - (input[12])) ^ (2))) + (((3.92) - (input[13])) ^ (2)))))\n}\nsubroutine38 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((38.3518) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.453) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.4896) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((30.59) - (input[13])) ^ (2)))))\n}\nsubroutine39 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.06129) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.33) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.4429) - (input[5])) ^ (2))) + (((7.645) - (input[6])) ^ (2))) + (((49.7) - (input[7])) ^ (2))) + (((5.2119) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((216.0) - (input[10])) ^ (2))) + (((14.9) - (input[11])) ^ (2))) + (((377.07) - (input[12])) ^ (2))) + (((3.01) - (input[13])) ^ (2)))))\n}\nsubroutine40 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((88.9762) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.671) - (input[5])) ^ (2))) + (((6.968) - (input[6])) ^ (2))) + (((91.9) - (input[7])) ^ (2))) + (((1.4165) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((17.21) - (input[13])) ^ (2)))))\n}\nsubroutine41 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.05602) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((2.46) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.488) - (input[5])) ^ (2))) + (((7.831) - (input[6])) ^ (2))) + (((53.6) - (input[7])) ^ (2))) + (((3.1992) - (input[8])) ^ (2))) + (((3.0) - (input[9])) ^ (2))) + (((193.0) - (input[10])) ^ (2))) + (((17.8) - (input[11])) ^ (2))) + (((392.63) - (input[12])) ^ (2))) + (((4.45) - (input[13])) ^ (2)))))\n}\nsubroutine42 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.01501) - (input[1])) ^ (2)) + (((90.0) - (input[2])) ^ (2))) + (((1.21) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.401) - (input[5])) ^ (2))) + (((7.923) - (input[6])) ^ (2))) + (((24.8) - (input[7])) ^ (2))) + (((5.885) - (input[8])) ^ (2))) + (((1.0) - (input[9])) ^ (2))) + (((198.0) - (input[10])) ^ (2))) + (((13.6) - (input[11])) ^ (2))) + (((395.52) - (input[12])) ^ (2))) + (((3.16) - (input[13])) ^ (2)))))\n}\nsubroutine43 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.02009) - (input[1])) ^ (2)) + (((95.0) - (input[2])) ^ (2))) + (((2.68) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.4161) - (input[5])) ^ (2))) + (((8.034) - (input[6])) ^ (2))) + (((31.9) - (input[7])) ^ (2))) + (((5.118) - (input[8])) ^ (2))) + (((4.0) - (input[9])) ^ (2))) + (((224.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((390.55) - (input[12])) ^ (2))) + (((2.88) - (input[13])) ^ (2)))))\n}\nsubroutine44 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((15.1772) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.74) - (input[5])) ^ (2))) + (((6.152) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.9142) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((9.32) - (input[12])) ^ (2))) + (((26.45) - (input[13])) ^ (2)))))\n}\nsubroutine45 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((18.0846) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((6.434) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.8347) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((27.25) - (input[12])) ^ (2))) + (((29.05) - (input[13])) ^ (2)))))\n}\nsubroutine46 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.01381) - (input[1])) ^ (2)) + (((80.0) - (input[2])) ^ (2))) + (((0.46) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.422) - (input[5])) ^ (2))) + (((7.875) - (input[6])) ^ (2))) + (((32.0) - (input[7])) ^ (2))) + (((5.6484) - (input[8])) ^ (2))) + (((4.0) - (input[9])) ^ (2))) + (((255.0) - (input[10])) ^ (2))) + (((14.4) - (input[11])) ^ (2))) + (((394.23) - (input[12])) ^ (2))) + (((2.97) - (input[13])) ^ (2)))))\n}\nsubroutine47 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((5.66998) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((1.0) - (input[4])) ^ (2))) + (((0.631) - (input[5])) ^ (2))) + (((6.683) - (input[6])) ^ (2))) + (((96.8) - (input[7])) ^ (2))) + (((1.3567) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((375.33) - (input[12])) ^ (2))) + (((3.73) - (input[13])) ^ (2)))))\n}\nsubroutine48 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.01538) - (input[1])) ^ (2)) + (((90.0) - (input[2])) ^ (2))) + (((3.75) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.394) - (input[5])) ^ (2))) + (((7.454) - (input[6])) ^ (2))) + (((34.2) - (input[7])) ^ (2))) + (((6.3361) - (input[8])) ^ (2))) + (((3.0) - (input[9])) ^ (2))) + (((244.0) - (input[10])) ^ (2))) + (((15.9) - (input[11])) ^ (2))) + (((386.34) - (input[12])) ^ (2))) + (((3.11) - (input[13])) ^ (2)))))\n}\nsubroutine49 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((4.89822) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.631) - (input[5])) ^ (2))) + (((4.97) - (input[6])) ^ (2))) + (((100.0) - (input[7])) ^ (2))) + (((1.3325) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((375.52) - (input[12])) ^ (2))) + (((3.26) - (input[13])) ^ (2)))))\n}\nsubroutine50 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((2.01019) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((19.58) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.605) - (input[5])) ^ (2))) + (((7.929) - (input[6])) ^ (2))) + (((96.2) - (input[7])) ^ (2))) + (((2.0459) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((403.0) - (input[10])) ^ (2))) + (((14.7) - (input[11])) ^ (2))) + (((369.3) - (input[12])) ^ (2))) + (((3.7) - (input[13])) ^ (2)))))\n}\nsubroutine51 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.52014) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.97) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.647) - (input[5])) ^ (2))) + (((8.398) - (input[6])) ^ (2))) + (((91.5) - (input[7])) ^ (2))) + (((2.2885) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((264.0) - (input[10])) ^ (2))) + (((13.0) - (input[11])) ^ (2))) + (((386.86) - (input[12])) ^ (2))) + (((5.91) - (input[13])) ^ (2)))))\n}\nsubroutine52 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((9.33889) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.679) - (input[5])) ^ (2))) + (((6.38) - (input[6])) ^ (2))) + (((95.6) - (input[7])) ^ (2))) + (((1.9682) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((60.72) - (input[12])) ^ (2))) + (((24.08) - (input[13])) ^ (2)))))\n}\nsubroutine53 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((0.03578) - (input[1])) ^ (2)) + (((20.0) - (input[2])) ^ (2))) + (((3.33) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.4429) - (input[5])) ^ (2))) + (((7.82) - (input[6])) ^ (2))) + (((64.5) - (input[7])) ^ (2))) + (((4.6947) - (input[8])) ^ (2))) + (((5.0) - (input[9])) ^ (2))) + (((216.0) - (input[10])) ^ (2))) + (((14.9) - (input[11])) ^ (2))) + (((387.31) - (input[12])) ^ (2))) + (((3.76) - (input[13])) ^ (2)))))\n}\nsubroutine54 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((24.8017) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.693) - (input[5])) ^ (2))) + (((5.349) - (input[6])) ^ (2))) + (((96.0) - (input[7])) ^ (2))) + (((1.7028) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((396.9) - (input[12])) ^ (2))) + (((19.77) - (input[13])) ^ (2)))))\n}\nsubroutine55 <- function(input) {\n var0 <- (0) - (0.07692307692307693)\n return(exp((var0) * (((((((((((((((13.6781) - (input[1])) ^ (2)) + (((0.0) - (input[2])) ^ (2))) + (((18.1) - (input[3])) ^ (2))) + (((0.0) - (input[4])) ^ (2))) + (((0.74) - (input[5])) ^ (2))) + (((5.935) - (input[6])) ^ (2))) + (((87.9) - (input[7])) ^ (2))) + (((1.8206) - (input[8])) ^ (2))) + (((24.0) - (input[9])) ^ (2))) + (((666.0) - (input[10])) ^ (2))) + (((20.2) - (input[11])) ^ (2))) + (((68.95) - (input[12])) ^ (2))) + (((34.02) - (input[13])) ^ (2)))))\n}\n", "meta": {"hexsha": "00982938b8ca63598ab66fb7f0b3887b572b169d", "size": 33210, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/regression/svm.r", "max_stars_repo_name": "yarix/m2cgen", "max_stars_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:59:21.000Z", "max_issues_repo_path": "generated_code_examples/r/regression/svm.r", "max_issues_repo_name": "yarix/m2cgen", "max_issues_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generated_code_examples/r/regression/svm.r", "max_forks_repo_name": "yarix/m2cgen", "max_forks_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 143.1465517241, "max_line_length": 965, "alphanum_fraction": 0.380277025, "num_tokens": 14673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.34689580973590656}} {"text": "## Anatomía de las funciones\n\n# En esta lección vamos a explorar las distintas partes que componen una función.\n\n# Componentes de una función\n# 1- Argumentos formales o parámetros formales (formals)\n# 2- Cuerpo de la función\n# 3- Ambiente de la función\n\n# Para comprender mejor estos componentes, empecemos por definir una función 'f'\n# bien sencilla:\n\nf <- function(a, b = 5, ...) { # a partir de dos variables 'a' y 'b'\n x <- a * b + w # se crea un objeto 'x' y\n x / 2 # la función devuelve el valor de 'x' dividido\n} # entre 2.\nw <- 24 # Vamos a definir también un valor 'w', que vamos a usar más adelante.\n\n# 1- Argumentos formales\n# Los argumentos de una función son los valores que nosotros podemos manipular\n# en la entrada al ejecutar la misma. Vamos a distinguir entre los argumentos\n# formales y los argumentos reales (actual arguments). Los primeros son los que\n# componen la función como nosotros la definimos. Indican qué valores vamos a\n# tener que definir para ejecutar la misma y muchas veces van a tener valores\n# por defecto. Veamos cuáles son estos argumentos formales en nuestra función:\n\nformals(f)\n\n# Este comando devuelve una lista de los argumentos formales de cualquier\n# función. En nuestro caso, nos dice que los argumentos formales de la función\n# f son a y b, indicando además que b tiene un valor por defecto de 5.\n# Los argumentos reales, o actuales, son los valores que le vamos a dar a los\n# argumentos formales al ejecutar la función. Intentemos correr nuestra función\n# con a = 2 y b = 4.\n\nf(2, 4)\n\n# Como dijimos antes, el argumento formal b tiene un valor por defecto por lo\n# que, si no nos interesa darle un valor particular, podemos dejarlo sin asignar\n# y la función va a utilizar ese valor.\n\nf(2)\n\n# 2- Cuerpo de la función\n# El cuerpo de una función es el conjunto de las instrucciones que se van a eje-\n# cutar al llamar a la función. En nuestra función, podemos ver el cuerpo de la\n# misma, mediante el comando 'body'.\n\nbody(f)\n\n# 3- Ambiente de la función\n# Este es el componente de las funciones que requiere más explicación, ya que es\n# el componente más abstracto de las mismas.\n# El primer componente del ambiente de una función es el marco (frame) de la\n# misma, y está compuesto por el conjunto de objetos presentes en R en el\n# momento que la función es creada. El marco del ambiente de nuestra función\n# está compuesto por los objetos presentes en el área de trabajo y los objetos\n# de los paquetes cargados. A los primeros podemos consultarlos mediante 'ls'\n# y a los segundos mediante 'search'\n\nls() # Que nos devuelve los objetos que tenemos asignados\nsearch() # Que nos devuelve '.GlobalEnv' y cada paquete actualmente cargado\n\n# '.GlobalEnv' es el ambiente correspondiente al interpretador de R, a la línea\n# de comando. La función 'environment', aplicada a una función, nos dice en qué\n# ambiente fue creada la misma.\n\nenvironment(f)\n\n# Nuestra función fue creada directamente en el nivel superior, R_GlobalEnv,\n# que corresponde a la línea de comando de R, pero veamos que ocurre con alguna\n# función, por ejemplo 'mean'.\n\nenvironment(mean)\n\n# Esta función fue creada dentro del ambiente correspondiente al paquete 'base'.\n# Los ambientes están organizados en forma jerárquica dentro de R, de modo que\n# el funcionamiento de cualquier función depende de que los objetos a los que\n# refiere se encuentren en el ambiente en que fue definida o en uno superior,\n# hasta R_GlobalEnv, que es el ambiente parental a todos. Esta pertenencia\n# jerárquica entre ambientes es lo que se denomina el enclosure, y es el segundo\n# componente del ambiente. Si una función depende de un objeto externo para su\n# funcionamiento, éste deberá estar en el ambiente en que fue definida o en\n# ambientes parentales a éste. Como ejemplo, veamos qué sucede con nuestra\n# función si eliminamos el objeto 'w' que habíamos creado al principio.\n\nrm (w)\nf(2, 4)\n\n# El objeto 'w', al que se hace referencia en el cuerpo de 'f', fue removido del\n# ambiente de ésta (del marco, concretamente), por lo que ahora no puede correr.\n# Volvamos a definirlo para seguir adelante.\n\nw <- 24\n\n# Además, cuando se corre una función se crea un ambiente dentro de la misma,\n# que es transitorio y sólo existe mientras la función esté corriendo. En este\n# ambiente se van a ejecutar las instrucciones del cuerpo de la función y no es\n# accesible desde el workspace, sino que corre en paralelo. El objetivo de esta\n# separación, es evitar siempre que sea posible que una función modifique alguna\n# variable de la propia sesión. Es decir, pase lo que pase dentro de la función,\n# no se van a afectar los objetos que se encuentran en nuestra área de trabajo.\n# Si recordamos, en el cuerpo de nuestra función una de las instrucciones crea\n# un objeto 'x'. Veamos qué sucede al correr esta función si tenemos un objeto\n# llamado 'x' en el área de trabajo.\n\nx <- 1:5\nf(3, 4)\nx\n\n# El objeto 'x' de nuestra área de trabajo no fue modificado.\n# Este territorio puede parecer confuso, por lo que sugiero que experimenten\n# hasta entenderlo bien. A modo de guía, veamos la lista de objetos visibles\n# para una función de R.\n# - objetos definidos en los argumentos\n# - objetos creados en el cuerpo de la función (hasta acá son los\n# pertenecientes al ambiente de la propia función).\n# - objetos existentes en ambientes \"parentales\" (todos los \"antepasados\").\n\n# Para entender un poco mejor esto, nótese que el objeto 'w', definido en para-\n# lelo a nuestra función 'f', no es parte de los argumentos, y no está definido\n# en el cuerpo de 'f'. El 'w' es usado dentro de la función para calcular 'x'\n# (el 'x' del cuerpo de 'f', no el que definimos en el workspace). De hecho, si\n# cambio a 'w' el resultado de evaluar 'f' será distinto.\n\nf(3, 4)\nw <- 1:5\nf(3, 4)\n\n# Esperando que esta lección complemente en buena forma lo visto en el video, la\n# próxima lección será acerca de la salida de las funciones.\n", "meta": {"hexsha": "3472a07245a6d5fc4fd046ba0e6367491db63957", "size": 5984, "ext": "r", "lang": "R", "max_stars_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.2-anatomia-de-las-funciones.r", "max_stars_repo_name": "jcombari/Data-products-Course-Project", "max_stars_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.2-anatomia-de-las-funciones.r", "max_issues_repo_name": "jcombari/Data-products-Course-Project", "max_issues_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CODIGO CHURN/CODIGOS_UTILIZADOS/lecciones/5.2-anatomia-de-las-funciones.r", "max_forks_repo_name": "jcombari/Data-products-Course-Project", "max_forks_repo_head_hexsha": "bd3bc260d2bf3def34c8fc94bf847ca0482e7549", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3333333333, "max_line_length": 81, "alphanum_fraction": 0.7456550802, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.34679039983869986}} {"text": "## File downloaded from 'http://www.sthda.com/upload/rquery_cormat.r'\n## Date: 14/11/2016\n## All Credit to Original Authors for this Script\n\n#+++++++++++++++++++++++++\n# Computing of correlation matrix\n#+++++++++++++++++++++++++\n# Required package : corrplot\n\n# x : matrix\n# type: possible values are \"lower\" (default), \"upper\", \"full\" or \"flatten\";\n #display lower or upper triangular of the matrix, full or flatten matrix.\n# graph : if TRUE, a correlogram or heatmap is plotted\n# graphType : possible values are \"correlogram\" or \"heatmap\"\n# col: colors to use for the correlogram\n# ... : Further arguments to be passed to cor or cor.test function\n\n# Result is a list including the following components :\n # r : correlation matrix, p : p-values\n # sym : Symbolic number coding of the correlation matrix\nrquery.cormat<-function(x, type=c('lower', 'upper', 'full', 'flatten'),\n graph=TRUE, graphType=c(\"correlogram\", \"heatmap\"),\n col=NULL, ...)\n{\n library(corrplot)\n # Helper functions\n #+++++++++++++++++\n # Compute the matrix of correlation p-values\n cor.pmat <- function(x, ...) {\n mat <- as.matrix(x)\n n <- ncol(mat)\n p.mat<- matrix(NA, n, n)\n diag(p.mat) <- 0\n for (i in 1:(n - 1)) {\n for (j in (i + 1):n) {\n tmp <- cor.test(mat[, i], mat[, j], ...)\n p.mat[i, j] <- p.mat[j, i] <- tmp$p.value\n }\n }\n colnames(p.mat) <- rownames(p.mat) <- colnames(mat)\n p.mat\n }\n # Get lower triangle of the matrix\n getLower.tri<-function(mat){\n upper<-mat\n upper[upper.tri(mat)]<-\"\"\n mat<-as.data.frame(upper)\n mat\n }\n # Get upper triangle of the matrix\n getUpper.tri<-function(mat){\n lt<-mat\n lt[lower.tri(mat)]<-\"\"\n mat<-as.data.frame(lt)\n mat\n }\n # Get flatten matrix\n flattenCorrMatrix <- function(cormat, pmat) {\n ut <- upper.tri(cormat)\n data.frame(\n row = rownames(cormat)[row(cormat)[ut]],\n column = rownames(cormat)[col(cormat)[ut]],\n cor =(cormat)[ut],\n p = pmat[ut]\n )\n }\n # Define color\n if (is.null(col)) {\n col <- colorRampPalette(c(\"#67001F\", \"#B2182B\", \"#D6604D\", \n \"#F4A582\", \"#FDDBC7\", \"#FFFFFF\", \"#D1E5F0\", \"#92C5DE\", \n \"#4393C3\", \"#2166AC\", \"#053061\"))(200)\n col<-rev(col)\n }\n \n # Correlation matrix\n cormat<-signif(cor(x, use = \"complete.obs\", ...),2)\n pmat<-signif(cor.pmat(x, ...),2)\n # Reorder correlation matrix\n ord<-corrMatOrder(cormat, order=\"hclust\")\n cormat<-cormat[ord, ord]\n pmat<-pmat[ord, ord]\n # Replace correlation coeff by symbols\n sym<-symnum(cormat, abbr.colnames=FALSE)\n # Correlogram\n if(graph & graphType[1]==\"correlogram\"){\n corrplot(cormat, type=ifelse(type[1]==\"flatten\", \"lower\", type[1]),\n tl.col=\"black\", tl.srt=45,col=col,...)\n }\n else if(graphType[1]==\"heatmap\")\n heatmap(cormat, col=col, symm=TRUE)\n # Get lower/upper triangle\n if(type[1]==\"lower\"){\n cormat<-getLower.tri(cormat)\n pmat<-getLower.tri(pmat)\n }\n else if(type[1]==\"upper\"){\n cormat<-getUpper.tri(cormat)\n pmat<-getUpper.tri(pmat)\n sym=t(sym)\n }\n else if(type[1]==\"flatten\"){\n cormat<-flattenCorrMatrix(cormat, pmat)\n pmat=NULL\n sym=NULL\n }\n list(r=cormat, p=pmat, sym=sym)\n}\n", "meta": {"hexsha": "7fceae8742fcd6baf258b22a1ceecee3c36f8d82", "size": 3276, "ext": "r", "lang": "R", "max_stars_repo_path": "rquery_cormat.r", "max_stars_repo_name": "uhkniazi/BRC_SkinGut_Microbiome", "max_stars_repo_head_hexsha": "94de66ca25d40faaf567cdedd0604b1d22e3db77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rquery_cormat.r", "max_issues_repo_name": "uhkniazi/BRC_SkinGut_Microbiome", "max_issues_repo_head_hexsha": "94de66ca25d40faaf567cdedd0604b1d22e3db77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rquery_cormat.r", "max_forks_repo_name": "uhkniazi/BRC_SkinGut_Microbiome", "max_forks_repo_head_hexsha": "94de66ca25d40faaf567cdedd0604b1d22e3db77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3333333333, "max_line_length": 85, "alphanum_fraction": 0.5873015873, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34660600443990675}} {"text": "# Experimental and Statistical Methods in Biological Sciences I\n# Demo 2: Descriptive statistics and plotting the data\n\n# Heini Saarimäki 25.9.2014\n\n# -----\n\n# 1. Load in data\n\nsetwd('Z:/Desktop/Demo2')\nageweight <- read.csv(\"http://becs.aalto.fi/~heikkih3/age_weight2.csv\")\n\n# Examine your data\n\nhead(ageweight)\nsummary(ageweight)\n\n# Save the original data into a new dataframe\n\nageweight.orig <- ageweight\n\n# Change MALE into a factor\n\nageweight$MALE <- factor(ageweight$MALE)\n\n# Change weird (< 0 ) WEIGHT values to NA\n\nwhich(ageweight$WEIGHT <= 0)\nageweight[which(ageweight$WEIGHT <= 0), \"WEIGHT\"] <- NA\n\nsummary(ageweight)\n\n# Attach the ageweight data\n\nattach(ageweight)\n\n# -----\n\n# 2. Basics in plotting\n\n# --\n\n# 2.1 Basic structure of plotting functions\n\n\n# Using plot function...\n\n# For a numeric variable: scatterplot\nplot(WEIGHT)\n\n# For a factor (i.e., categorical variable): bar chart\nplot(MALE)\n\n# For 2 numeric variables: scatterplot\nplot(AGE, WEIGHT)\nplot(WEIGHT~AGE)\t\t# equivalents!\n\n# For a factor and a numeric variable: box plot\nplot(MALE, WEIGHT)\n\n# For 2 factors: bar chart\nplot(MALE, SMOKE1)\n\n\n# Other plotting functions..\n\n# Histograms:\nhist(WEIGHT)\n\n# Box plots:\nboxplot(WEIGHT)\n\n# --\n\n# 2.2 Modifying your plots\n\n# Build up a nice scatterplot by adding named arguments:\n\nplot(WEIGHT~AGE, main=\"Weight by Age\",\t\t# add main title\n\txlab=\"Age (yrs)\", ylab=\"Weight (kg)\",\t# add axis labels\n\tpch=16, col=\"blue\",\t\t\t\t# modify points\n\txlim=c(0,70), ylim=c(0,140))\t\t\t# scale axes\n\nabline(lm(WEIGHT~AGE),\t\t\t\t\t# draw regression line\n\tlty=\"dashed\",\t\t\t\t\t# modify line\n\tlwd=2,\n\tcol=\"red\")\n\n# Make a nice histogram:\n\nhist(WEIGHT, main=\"Weight\", xlab=\"Weight\", ylab=\"\")\n\n# Set total area size of histogram to 1:\n\nhist(WEIGHT, main=\"Weight\", xlab=\"Weight\", ylab=\"\", freq=F)\n\n# Change the bin size\n\nhist(WEIGHT)\t\t\t# automatic binning\n\nhist(WEIGHT, breaks=15)\t\t# suggest the number of bins\n\nbins=seq(20,140,by=20)\t\t# suggest the size of a bin\nhist(WEIGHT, breaks=bins)\n\n\n# Advanced graphics:\n\n# Sometimes you want to add a normal curve approximation to the plot.\n\n# First, create the histogram object:\nh <- hist(WEIGHT, freq=F, main=\"Distribution of Weights\", \n\txlab=\"Weight (kg)\", ylab=\"\")\n\n# Second, find highest and lowest values and create a sequence of them:\nx <- min(h$breaks):max(h$breaks)\n\n# Third, create vector y from normal distribution with same mean and sd as WEIGHT:\ny <- dnorm(x, \n\tmean=mean(WEIGHT, na.rm=T), \n\tsd=sd(WEIGHT, na.rm=T))\n\n# Finally, add the normal curve: \nlines(x,y,col=\"red\", lty=\"dashed\", lwd=3)\n\n# --\n\n# 2.3 Opening several plots in the same display\n\n# E.g., put 4 plots in the same display:\n\nlayout(matrix(c(1,2,3,4),2,2))\nhist(WEIGHT, main=\"Weight\")\nhist(HEIGHT, main=\"Height\")\nplot(SMOKE1, main=\"Smoking at time point 1\")\nplot(SMOKE2, main=\"Smoking at time point 2\")\n\n# --\n\n# 2.4 Saving your plots\n\n# First, open a device, then draw your plot, then close the device:\n\npdf(file=\"hist_weight.pdf\")\nhist(WEIGHT, main=\"Weight\", xlab=\"Weight (kg)\", ylab=\"\")\ndev.off()\n\n# --\n\n# 2.5 Exercises\n\n# Question 1:\n\nhist(WEIGHT, \n\txlim=c(0,150), \t\t\t# scales x axis\n\tbreaks=6, \t\t\t\t# sets number of bins\n\tcol=\"red\", \t\t\t\t# sets bar colour\n\txlab=\"Weight (kg)\", \t\t# sets x label\n\tbg=\"grey\")\t\t\t\t# OUGHT TO set background colour?\n\n# Note: bg looks like it should set the background colour,\n# BUT it does not actually work this way (see the arguments 'hist' approves of by\n# checking ?hist.\n# If you want to do it, you should use this instead:\n\npar(bg=\"grey\")\nhist(WEIGHT, xlim=c(0,150), breaks=6, col=\"red\", xlab=\"Weight (kg)\")\n\n# Here, we define the parameter background with function 'par'\n# The background will stay grey until we change it, so run this next:\npar(bg=\"white\")\n\n# NOTE: If you want to change the 'par' arguments, the defaults are somewhat tricky\n# to restore. If you are using 'par' arguments, it is good to save the defaults first\n# in an object:\nopar <- par() # stores whatever parameters you have currently\n# Now, you can change what ever you want:\npar(bg=\"green\")\nplot(WEIGHT, AGE) # see what changed\n# And restore the default values this way:\npar(opar)\n\n\n# -\n\n# Question 2:\n\nhist(WEIGHT, \n\txlim=c(0,150), \t\t\t\n\tbreaks=6, \t\t\t\t\n\tcol=\"red\", \t\t\t\t\n\txlab=\"Weight (kg)\",\n\tmain=\"\")\t\t\t\t# sets title to none\n\n# -\n\n# Question 3:\n \t\t\n# Hmm.. Maybe weight increases with age?\n\nplot(AGE, WEIGHT)\n\n# So it seems.\n\n# -\n\n# Question 4:\n\nplot(AGE, WEIGHT,\n\tpch=10,\t\t\t\t# set plot character type\n\tcol=\"green\")\t\t\t# set plot character colour\n\nabline(lm(WEIGHT~AGE))\t\t\t# add regression line\n\n\n# -\n\n# Question 5:\n\nplot(MALE, WEIGHT)\n\n# Weight seems to depend on gender too.\n\n# -\n\n# Question 6:\n\n# In question 3 both variables are numeric, so a scatterplot is produced.\n# In question 5 there is one factor and one numeric variable, so a boxplot is produced.\n# Output of plot function depends on input!\n\n# -\n\n# Question 7:\n\n# An example plot:\nplot(AGE, WEIGHT, pch=20, \n\tmain=\"Weight by Age\", xlab=\"Age (yrs)\", ylab=\"Weight (kg)\")\n\n# Changing font size larger for main title:\n\nplot(AGE, WEIGHT, pch=20, \n\tmain=\"Weight by Age\", xlab=\"Age (yrs)\", ylab=\"Weight (kg)\",\n\tcex.main=2)\n\n# Changing font style to bold-italic for axes labels:\n\nplot(AGE, WEIGHT, pch=20, \n\tmain=\"Weight by Age\", xlab=\"Age (yrs)\", ylab=\"Weight (kg)\",\n\tfont.lab=4)\n\n# Changing font type for the whole graph:\n\nplot(AGE, WEIGHT, pch=20, \n\tmain=\"Weight by Age\", xlab=\"Age (yrs)\", ylab=\"Weight (kg)\",\n\tfamily=\"mono\")\n\n\n# -----\n\n# 3. Descriptive statistics & plotting of categorical variables\n\n# -\n\n# 3.1 Contingency tables\n\n\n# One categorical variable (same information as with summary...)\n\ntable(MALE)\n\n# Two categorical variables:\n\ntable(MALE, SMOKE1)\n\n# Or even more... \n\ntable(MALE, SMOKE1, SMOKE2)\n\n# Express frequencies as percentages:\n\nround(prop.table(table(MALE, SMOKE1), margin=1)*100, 1)\n\n# -\n\n# 3.2 Plotting\n\n# A simple bar chart:\n\nplot(MALE)\n\n# A boosted bar chart:\n\nplot(MALE, col=c(\"red\", \"blue\"), xlab=\"Gender\")\n\n# A simple bar chart for displaying two categorical variables:\n\nplot(MALE, SMOKE1)\n\n# Again then same one boosted:\n\nplot(SMOKE1, MALE, col=c(\"red\", \"blue\"),\n\txlab=\"Smoking\", ylab=\"Gender\")\n\n# -\n\n# 3.3 Exercises\n\n\n# Question 8:\n\ntable(SMOKE1, SMOKE2)\n\n# 26 people quit smoking (smoked at time 1 but not at time 2)\n\n# -\n\n# Question 9\n\nplot(SMOKE1, SMOKE2, \n\tmain=\"Smoking\",\n\txlab=\"Smoking, time 1\", ylab=\"Smoking, time 2\",\n\tcol=c(\"green\", \"red\"))\n\n# Example: how to add frequency values to the plot:\n\nsmoke.table <- table(SMOKE1,SMOKE2)\t\t# save contingency table\n\ntext(0.25,0.2,smoke.table[1,1], cex=2)\ntext(0.25,0.8,smoke.table[1,2], cex=2)\ntext(0.77,0.2,smoke.table[2,1], cex=2)\ntext(0.77,0.8,smoke.table[2,2], cex=2)\n\n\n# -----\n\n# 4. Descriptive statistics & plotting of continuous variables\n\n# --\n\n# 4.1 Descriptive statistics\n\n# Summary:\n\nsummary(ageweight)\n\n# Use describe function from 'psych' package:\n\ninstall.packages('psych')\t\t# install if necessary\nlibrary('psych')\t\t\t\t# load for the use of this session\ndescribe(ageweight)\n\n# You can also take each descriptive statistic separately:\n\nmean(WEIGHT, na.rm=T)\t\t\t# na.rm=T removes missing values\nvar(WEIGHT, na.rm=T)\n\n# Take average weight for men and women separately:\n\ntapply(WEIGHT, MALE, mean, na.rm=T)\n\n# Take average weight for female and male non-smokers and smokers separately:\n\ntapply(WEIGHT, list(MALE, SMOKE1), mean, na.rm=T)\n\n# Save your table in .csv format:\n\nmy.table <- tapply(WEIGHT, list(MALE, SMOKE1), mean, na.rm=T)\nwrite.csv(my.table, \"my_table.csv\")\n\n# --\n\n# 4.2 Plotting\n\n# Box plot of a numeric variable:\n\nboxplot(WEIGHT)\t\t# remember to modify boxplots too! (add labels etc.)\n\n# Use box plot\n\nlayout(matrix(c(1,2)))\nboxplot(ageweight$WEIGHT, main=\"Missing values removed\")\nboxplot(ageweight.orig$WEIGHT, main=\"Original data\")\n\n# Box plots can be taken for categories separately:\n\nplot(MALE, WEIGHT, main=\"Weight by Gender\", ylab=\"Weight (kg)\")\n\n# Histogram shows the shape of the distribution efficiently:\n\nhist(WEIGHT)\nhist(WEIGHT, breaks=20)\t\t# adjust e.g. number of bins\n\n\n# --\n\n# 4.3 Exercises\n\n\n# Question 10\n\nmean(HEIGHT)\nsd(HEIGHT)\n\n# \n\n# -\n\n# Question 11\n\nheight_mean <- tapply(HEIGHT, MALE, mean, na.rm=T)\t# save table of means\nheight_sd <- tapply(HEIGHT, MALE, sd, na.rm=T)\t\t# save table of sd's\n\nheight_table <- rbind(height_mean, height_sd)\t\t# combine tables\nheight_table\n\n# (a) women: mean height 1.66 (sd 0.07)\n# (b) men: mean height 1.80 (sd 0.07)\n\n# Save final table:\n\nwrite.csv(height_table, \"Height_by_gender.csv\")\n\n# -\n\n# Question 12\n\nhist(HEIGHT)\n\n# -\n\n# Question 13\n\nh <- hist(HEIGHT, freq=F)\nx <- seq(min(h$breaks),max(h$breaks), by=0.025)\ny <- dnorm(x, mean=mean(HEIGHT, na.rm=T), sd=sd(HEIGHT, na.rm=T))\nlines(x,y,col=\"red\", lty=\"dashed\", lwd=2)\n\n# -\n\n# Question 14\n\nh <- hist(HEIGHT, freq=F, \n\tylim=c(0,5), \t\t\t\t\t# change y axis\n\tmain=\"Distribution of Height\", \t\t# add main title\n\txlab=\"Height (m)\", ylab=\"\",\t\t\t# add axis labels\n\tcol=\"grey\")\t\t\t\t\t\t# change colour\t\t\t\t\t\t\nx <- seq(min(h$breaks),max(h$breaks), by=0.025)\ny <- dnorm(x, mean=mean(HEIGHT, na.rm=T), sd=sd(HEIGHT, na.rm=T))\nlines(x,y,col=\"red\", lty=\"dashed\", lwd=2)\n\n# -\n\n# Question 15\n\npdf(file=\"Height_distribution.pdf\")\nh <- hist(HEIGHT, freq=F, \n\tylim=c(0,5), \t\t\t\t\t\n\tmain=\"Distribution of Height\", \t\t\n\txlab=\"Height (m)\", ylab=\"\",\t\t\t\n\tcol=\"grey\")\t\t\t\t\t\t\t\t\t\t\t\nx <- seq(min(h$breaks),max(h$breaks), by=0.025)\ny <- dnorm(x, mean=mean(HEIGHT, na.rm=T), sd=sd(HEIGHT, na.rm=T))\nlines(x,y,col=\"red\", lty=\"dashed\", lwd=2)\ndev.off()\n\n# -\n\n# Question 16\n\nboxplot(HEIGHT)\n\n# (a) median is a bit over 1.7 m\n# (b) distribution looks quite normal, maybe a bit more higher values than lower\n\n# -\n\n# Question 17\n\nboxplot(HEIGHT~MALE, main=\"Height by Gender\", ylab=\"Height (m)\", xlab=\"Gender\")\n\n# men seem to be taller than women\n\n# -\n\n# Question 18\n\nlayout(matrix(c(1,2)))\nboxplot(WEIGHT, main=\"Box plot of Weight\", ylab=\"Weight (kg)\", col=\"grey\")\nhist(WEIGHT, main=\"Histogram of Weight\", xlab=\"Weight (kg)\", ylab=\"\", col=\"grey\")\n\n\n# -----\n\n# 5. Exercises\n\n\n# Load in naming data\n\nnaming <- read.csv(\"http://becs.aalto.fi/~heikkih3/naming_new.csv\")\n\n# Check for missing values and that factors are factors\n\nsummary(naming)\n\n# Everything looks ok!\n# We have 2 factors (word.type, sex) already coded as factors\n# ... and 3 numeric variables (iq, hrs, ms)\n# Missing values in iq already coded as NA's\n# Other values look fine too.\n\n# Detach ageweight and attach naming:\ndetach(ageweight)\nattach(naming)\n\n# -\n\n# Question 20\n\nplot(word.type,ms)\n\n# Reading times for regular words seem to be faster than for exceptional words.\n\nlayout(matrix(c(1,2)))\nplot(word.type, ms, data=naming[which(sex==\"female\"),],\n\tmain=\"Female\")\nplot(word.type, ms, data=naming[which(sex==\"male\"),],\n\tmain=\"Male\")\n\n# Effect of word type on reading types seems similar in men and women.\n# I.e., no gender effects on differences in reading times between different word types.\n\n# -\n \n# Question 21\n\n# Take a subset of the data:\n\nnaming_subset <- naming[1:1000, c(\"iq\", \"hrs\", \"sex\")]\n\n# Check this new subset:\n\nhead(naming_subset)\nsummary(naming_subset)\n\n# Detach whole data and attach just the subset:\n\ndetach(naming)\nattach(naming_subset)\n\n# - \n\n# Question 22\n\n# Create factor reading group:\n\nnaming_subset$reading.group <- 'low'\nnaming_subset$reading.group[which(hrs>3.5)] <- 'medium'\nnaming_subset$reading.group[which(hrs>4.5)] <- 'high'\nnaming_subset$reading.group <- factor(naming_subset$reading.group)\n\n# Check out the data now:\n\nhead(naming_subset)\nsummary(naming_subset)\n\n# Need to attach the data again (cause we added a variable!)\n# Previously added variables will be masked automatically\n\nattach(naming_subset)\n\n# -\n\n# Question 23\n\ntable(sex,reading.group)\t\t# contingency table\nplot(table(sex,reading.group))\t# bar charts\n\n# No differences between men and women in how many participants are in which reading group.\n\n# -\n\n# Question 24\n\n# Plot reading hours by gender:\n\nboxplot(hrs~sex, main=\"Reading hours by gender\", ylab=\"Reading hours\")\n\n# Shows similar lack of differences as question 23.\n\n# -\n\n# Question 25\n\n# Plot intelligence by gender:\n\nboxplot(iq~sex, main=\"Intelligence by gender\", ylab=\"IQ\")\n\n# No differences in intelligence between men and women.\n\n# -\n\n# Question 26\n\n# Plot histogram of intelligence with a normal curve approximation:\n\nh <- hist(iq, freq=F, main=\"Distribution of IQ\", xlab=\"IQ\", ylab=\"\", col=\"grey\")\nx <- min(h$breaks):max(h$breaks)\ny <- dnorm(x, mean=mean(iq, na.rm=T), sd=sd(iq, na.rm=T))\nlines(x,y,col=\"red\", lty=\"dashed\", lwd=2)\n\n# Other ways to check for normality (see Section 6):\nqqnorm(iq)\t\t\t\t\t# QQ-plot\nqqline(iq, col=\"red\", lwd=2)\nshapiro.test(iq)\n\n# Both histogram, qq-plot and Shapiro-Wilk test for normality suggest the same:\n# intelligence in this data set follows normal distribution.\n\n# -\n\n# Question 27\n\n# Descriptive statistics for experimental manipulation (reading times by word type):\n\nmean <- tapply(naming$ms, naming$word.type, mean, na.rm=T)\nsd <- tapply(naming$ms, naming$word.type, sd, na.rm=T)\n\nreading_times <- rbind(mean, sd)\nreading_times\n\nwrite.csv(reading_times, \"reading_times.csv\")\n\n\n# Descriptive statistics for background variables: \n\nbg_variables <- describe(naming_subset)\nbg_variables\n\nwrite.csv(bg_variables, \"background_variables.csv\")\n\n\n# -----\n\n# 6. Basic tools for testing for normality\n\n# 6.1 Histogram\n\n# Resets the seed for randomization:\n\nset.seed(111)\n\n# Take a sample of 20 from normal distribution:\n\ndata_normal <- rnorm(20)\n\n# And a sample of 20 from exponential distribution:\n\ndata_exp <- rexp(20)\n\n# Look at the histograms:\n\nlayout(matrix(c(1,2), nrow=1))\nhist(data_normal)\nhist(data_exp)\n\n# -\n\n# 6.2 Q-Q plot\n\n?qqnorm\nlayout(matrix(c(1,2), nrow=1))\nqqnorm(data_normal)\nqqline(data_normal)\nqqnorm(data_exp)\nqqline(data_exp)\n\n# data_normal is relatively normally distributed,\n# but data_exp is clearly not\n\n# -\n\n# 6.3 Statistical tests for normality\n\n# Shapiro-Wilk test:\n\nshapiro.test(data_normal)\nshapiro.test(data_exp)\n\n# Kolmogorov-Smirnov test:\nks.test(data_normal, \"pnorm\", mean=mean(data_normal), sd=sd(data_normal))\nks.test(data_exp, \"pnorm\", mean=mean(data_exp), sd=sd(data_exp))\n\n# Normality tests confirm the observation from the Q-Q plots:\n# data_normal is normally distributed, data_exp is not.\n\n# ------\n\n", "meta": {"hexsha": "9e00e8c7d088e85a32338d63bf71dbb8f5abc0b4", "size": 14144, "ext": "r", "lang": "R", "max_stars_repo_path": "files/expmethodsI_demo2_exercise-solutions.r", "max_stars_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_stars_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "files/expmethodsI_demo2_exercise-solutions.r", "max_issues_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_issues_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "files/expmethodsI_demo2_exercise-solutions.r", "max_forks_repo_name": "hpsaarimaki/hpsaarimaki.github.io", "max_forks_repo_head_hexsha": "d3b17ae732d33606b7aba30619c812950227b45e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.234620887, "max_line_length": 91, "alphanum_fraction": 0.6920248869, "num_tokens": 4224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.3458206266325807}} {"text": "# Code to generate plots for manuscript\nlibrary(rstan)\nlibrary(plyr)\nlibrary(magrittr)\nlibrary(lubridate)\nlibrary(ggplot2)\nlibrary(gridExtra)\nlibrary(patchwork)\nlibrary(reshape2)\n\n# Loading and processing mosquito and case data\ntseries <- read.csv(\"Data/Vitoria.data.csv\")\n\npost <- ddply(tseries, .(tot.week), summarise,\n qobs = sum(Mosquitoes, na.rm = T),\n yobs = sum(Cases, na.rm = T),\n tau = sum(Trap, na.rm = T),\n week = unique(Week),\n year = unique(Year),\n epiweek = 0,\n epiyear = 0)\n\n# Generating epidemic weeks/years that count from peak to peak (week 16)\npost$epiweek[16:243] <- c(1:52)\npost$epiyear <- cumsum(post$epiweek == 1)\n\n# Population size\npop <- 327801\n\n# Loading and processing the weather data\nweather <- read.csv(\"Data/Vitoria.weather.csv\") %>% \n mutate(date = ymd(BRST), year = year(date), week = week(date))\n\nweather <- subset(weather, date < date[1] + weeks(243))\nweather$control <- rep(c(1:243), each = 7)\n\ntemp <- ddply(weather, .(control), summarise, temp = mean(Mean.TemperatureC, na.rm = T),\n humid = mean(Mean.Humidity, na.rm = T))\n\npost$temp <- temp$temp\npost$rov <- 7 * exp(0.21 * temp$temp - 7.9)\n\n# Loading MCMC results\nsim <- readRDS(\"Results/chain.rds\")\n\n# Effect of control in the number of cases in the following year\nmoving <- readRDS(\"Results/moving_control.rds\")\n\n# Figure 1: Observed and estimated time series =================================\n\n# Case reports\nyhat <- rstan::extract(sim, c(\"y_meas\"), permute = T)[[1]] %>% \n reshape2::melt(varnames = c(\"rep\", \"week\"), value.name = \"yhat\") %>% \n ddply(.(week), summarise,\n ymed = median(yhat),\n ymin = quantile(yhat, 0.1), \n ymax = quantile(yhat, 0.9))\n \n# Trapped mosquitoes\nqhat <- rstan::extract(sim, c(\"q_meas\"), permute = T)[[1]] %>%\n reshape2::melt(varnames = c(\"rep\", \"week\"), value.name = \"qhat\") %>% \n ddply(.(week), summarise,\n qmed = median(qhat),\n qmin = quantile(qhat, 0.1), \n qmax = quantile(qhat, 0.9))\n\n# Mosquito mortality rate\nsystem <- rstan::extract(sim, \"state\", permute = T)[[1]]\n\ndvmu <- data.frame(rep = 1:dim(system)[1],\n dvmu = 1.47 * rstan::extract(sim, \"dvmu_c\", permute = T)[[1]])\n\ndv <- system[, 2:244, 12] %>% \n reshape2::melt(varnames = c(\"rep\", \"control\"), value.name = \"dv\") %>% \n mutate(dvnat = exp(dv)) %>% \n join(dvmu) %>% \n mutate(dvnat = dvnat * dvmu) %>% \n join(temp)\n\n# Plotting\nyhat %>% \n ggplot(aes(week, ymin = ymin, ymax = ymax)) +\n geom_ribbon(fill = \"grey70\") + \n geom_line(aes(week, ymed)) + \n geom_point(aes(tot.week, yobs), data = post, inherit.aes = FALSE, size = 0.5) +\n theme_classic() +\n scale_y_continuous(expand = c(0, 0)) + \n scale_x_continuous(expand = c(0, 1), breaks = c(1, 54, 106, 158, 210), labels = c(2008, 2009, 2010, 2011, 2012)) +\n ylab(\"case reports\") + \n xlab(\"year\") +\n ggtitle(\"A\") -> fig1a\n\nqhat %>% \n ggplot(aes(week, ymin = qmin, ymax = qmax)) +\n geom_ribbon(fill = \"grey70\") + \n geom_line(aes(week, qmed)) + \n geom_point(aes(tot.week, qobs), data = post, inherit.aes = FALSE, size = 0.5) +\n theme_classic() +\n scale_y_continuous(expand = c(0, 0)) + \n scale_x_continuous(expand = c(0, 1), breaks = c(1, 54, 106, 158, 210), labels = c(2008, 2009, 2010, 2011, 2012)) +\n ylab(\"mosquitoes trapped\") + \n xlab(\"year\") +\n ggtitle(\"B\") -> fig1b\n\npost %>% \n ggplot(aes(tot.week, 1 / rov)) + \n geom_line() + \n theme_classic() +\n scale_y_continuous(expand = c(0.05, 0)) +\n scale_x_continuous(expand = c(0, 1), breaks = c(1, 54, 106, 158, 210), labels = c(2008, 2009, 2010, 2011, 2012)) +\n ylab(\"EIP (weeks)\") +\n xlab(\"year\") +\n ggtitle(\"C\") -> fig1c\n\ndv %>% \n ggplot(aes(control, dvnat)) + \n stat_summary(fun.ymin = function(x) quantile(x, 0.05),\n fun.ymax = function(x) quantile(x, 0.95),\n geom = \"ribbon\", fill = \"gray70\") +\n stat_summary(fun.y = \"median\", geom = \"line\") +\n theme_classic() +\n scale_y_continuous(expand = c(0.05, 0)) +\n scale_x_continuous(expand = c(0, 1), breaks = c(1, 54, 106, 158, 210), labels = c(2008, 2009, 2010, 2011, 2012)) +\n ylab(\"mosquito mortality rate\") +\n xlab(\"year\") +\n ggtitle(\"D\") -> fig1d\n\npostscript(\"Manuscript/figures/fig1.eps\",\n width = 5, height = 7, paper = \"special\", horizontal = FALSE,\n family = \"ArialMT\")\n\nfig1a + fig1b + fig1c + fig1d + plot_layout(ncol = 1)\n\ndev.off()\n\n# Figure 2: Estimates of latent mosquito mortality rate ========================\n\npostscript(\"Manuscript/figures/fig2.eps\",\n width = 4, height = 3, paper = \"special\", horizontal = FALSE,\n family = \"ArialMT\")\n\ndv %>%\n ddply(.(control), summarise,\n dvnat = median(dvnat),\n temp = median(temp)) %>%\n ggplot(aes(temp, dvnat)) +\n geom_point() +\n theme_classic() +\n scale_y_continuous(expand = c(0.05, 0)) +\n scale_x_continuous(expand = c(0, 1)) +\n ylab(\"mosquito mortality rate\") +\n xlab(\"weekly mean temperature\")\n\ndev.off()\n\n# Figure 3: Effect of adult control implemented in different weeks ===================\n\n# Adding week and year to moving window control results\nmoving <- moving %>% \n dplyr::rename(\"dv0\" = \"dvmu\") %>%\n mutate(week = week(ymd(\"2008-01-01\") + weeks(control - 1)),\n year = year(ymd(\"2008-01-01\") + weeks(control - 1))) %>% \n join(dv)\n\n# Computing the overall effect of control over 2008-2010\noverall <- moving %>% \n subset(year < 2011) %>% \n ddply(.(rep, week), summarise,\n tcases = sum(tcases),\n tcases0 = sum(tcases0), \n ratio = tcases / tcases0,\n diff = tcases0 - tcases,\n dv0 = mean(dv0),\n dvmu = mean(dvmu),\n delta = mean(delta),\n phi = mean(phi))\n\noverall <- dplyr::bind_rows(overall, moving) %>% \n mutate(year = factor(year, exclude = NULL, labels = c(\"2008\",\"2009\", \"2010\", \"2011\", \"2012\", \"overall\")))\n\n# Computing the median overall best week for control\noverall %>% \n ddply(.(rep, year), summarise,\n argmin = week[which.min(ratio)]) %>% \n ddply(.(year), summarise,\n argmin = median(argmin))\n\n# Plotting\n\npostscript(\"Manuscript/figures/fig3.eps\",\n width = 4, height = 5, paper = \"special\", horizontal = FALSE,\n family = \"ArialMT\")\n\noverall %>% \n subset(year %in% c(\"2008\", \"2009\", \"2010\", \"overall\") & week < 53) %>%\n ggplot(aes(week, ratio)) +\n stat_summary(fun.ymin = function(x) quantile(x, 0.1),\n fun.ymax = function(x) quantile(x, 0.9),\n geom = \"ribbon\", fill = \"gray70\") +\n stat_summary(fun.y = \"median\", geom = \"line\") +\n facet_grid(year ~.) +\n geom_hline(yintercept = 1.0, color = \"gray50\", linetype = 2) +\n theme_classic() + \n theme(strip.background = element_blank()) + \n scale_x_continuous(expand = c(0, 0)) + \n xlab(\"week of control\") +\n ylab(\"case ratio over following year\")\n\ndev.off()\n\n# Figure 4: effect of phi on effectiveness of control ==========================\n\noverall%>% \n subset(week == 34 & year == \"overall\") %>% \n ggplot(aes(dvmu, ratio)) + \n geom_point(size = 0.5) + \n theme_classic() + \n theme(strip.background = element_blank()) + \n labs(x = \"mosquito mortality rate\", y = \"case ratio\") -> fig4a\n\noverall%>% \n subset(week == 34 & year == \"overall\") %>% \n ggplot(aes(phi, ratio)) + \n geom_point(size = 0.5) + \n theme_classic() + \n theme(strip.background = element_blank()) + \n labs(x = \"case reporting probability\", y = \"case ratio\") -> fig4b\n\npostscript(\"Manuscript/figures/fig4.eps\",\n width = 6, height = 3, paper = \"special\", horizontal = FALSE,\n family = \"ArialMT\")\n\nfig4a + fig4b\n\ndev.off()\n\n# State var and control correlations ===========================================\n\n# Cases\ncases <- system[, , 11] %>% \n aaply(1, diff) %>% \n multiply_by(pop) %>% \n reshape2::melt(varnames = c(\"rep\", \"control\"), value.name = \"cases\") \n\n# Mosquitoes\nmosq <- system[, 2:244, 9] %>% \n reshape2::melt(varnames = c(\"rep\", \"control\"), value.name = \"mosq\") \n\n# Probability of surviving EIP\ninfmosq <- system[, , 17] %>% \n aaply(1, diff) %>% \n melt(varnames = c(\"rep\", \"control\"), value.name = \"inf\")\n\ndeadmosq <- system[, , 16] %>% \n aaply(1, diff) %>% \n reshape2::melt(varnames = c(\"rep\", \"control\"), value.name = \"dead\")\n\nsurv <- join(infmosq, deadmosq) %>%\n mutate(total_exits = dead + inf,\n psurv = inf / total_exits) \n\n# Joining everything\nmoving <- join(moving, cases) %>% \n join(mosq) %>% \n join(surv)\n\npostcorr <- moving %>% \n subset(control < 191) %>% \n ddply(.(rep), summarise,\n dv = cor(ratio, dvnat),\n mosq = cor(ratio, mosq), \n cases = cor(ratio, cases), \n psurv = cor(ratio, psurv),\n temp = cor(ratio, temp))\n\ncolwise(median)(postcorr)\n\n#===============================================================================\n# Supplemental figures\n#===============================================================================\n\n# Figure S1: epsilons ==========================================================\n\neps_dv <- rstan::extract(sim, \"eps_dv\", permute = T)[[1]] %>% \n adply(2, quantile, c(0.1, 0.5, 0.9)) %>% \n mutate(week = as.numeric(X1))\nnames(eps_dv) <- c(\"X1\", \"min\", \"med\", \"max\", \"week\")\n\neps_rv <- rstan::extract(sim, \"eps_rv\", permute = T)[[1]] %>% \n adply(2, quantile, c(0.1, 0.5, 0.9)) %>% \n mutate(week = as.numeric(X1))\nnames(eps_rv) <- c(\"X1\", \"min\", \"med\", \"max\", \"week\")\n\npostscript(\"Manuscript/figures/figS1.eps\",\n width = 5.2, height = 3,\n family = \"ArialMT\")\n\nggplot(eps_dv, aes(week, med)) + \n geom_ribbon(aes(ymin = min, ymax = max), fill = \"grey70\") +\n geom_line() + \n geom_hline(yintercept = 0, linetype = 2) + \n theme_classic() + \n scale_x_continuous(expand = c(0, 1)) +\n ylab(expression(epsilon[nu])) +\n ggtitle(\"A\") -> figs1.a\n\nggplot(eps_rv, aes(week, med)) + \n geom_ribbon(aes(ymin = min, ymax = max), fill = \"grey70\") +\n geom_line() + \n theme_classic() + \n scale_x_continuous(expand = c(0, 1)) +\n ylab(expression(epsilon[r])) +\n ggtitle(\"B\") -> figs2.b\n\ngrid.arrange(figs1.a, figs2.b, nrow = 1)\n\ndev.off()\n\n# Figure S2: sigmas ============================================================\n\npostscript(\"Manuscript/figures/figS2.eps\",\n width = 6, height = 4,\n family = \"ArialMT\")\n\npar(mfrow = c(1, 2))\nrstan::extract(sim, \"sigmadv\", permute = T)[[1]] %>% hist(main = \"A\", xlab = expression(sigma[d]), freq = F)\nrstan::extract(sim, \"sigmarv\", permute = T)[[1]] %>% hist(main = \"B\", xlab = expression(sigma[r]), freq = F)\n\ndev.off()\n\n# Figure S3: epidemiological parameters ===================================================\n\nepiparams <- rstan::extract(sim, c(\"ro_c\", \"gamma_c\", \"delta_c\", \"dvmu_c\"), permute = T)\n\npostscript(\"Manuscript/figures/figS3.eps\",\n width = 6, height = 6,\n family = \"ArialMT\")\n\npar(mfrow = c(2, 2))\n\nhist(epiparams[[1]], main = \"A\", xlab = \"scaled latent period\", freq = F, breaks = 30, ylim = c(0, 1.2))\ncurve(dgamma(x, 8.3, 8.3), add = T, lwd = 2)\n\nhist(epiparams[[2]], main = \"B\", xlab = \"scaled rate of infectious decay\", freq = F, breaks = 30)\ncurve(dgamma(x, 100, 100), add = T, lwd = 2)\n\nhist(epiparams[[3]], main = \"C\", xlab = \"scaled period of cross-immunity\", freq = F, breaks = 30, ylim = c(0, 1.3))\ncurve(dgamma(x, 10, 10), add = T, lwd = 2)\n\nhist(epiparams[[4]], main = \"D\", xlab = \"scaled mosquito mortality rate\", freq = F, breaks = 30)\ncurve(dgamma(x, 100, 10), add = T, lwd = 2)\n\ndev.off()\n\n# Figure S4: initial conditions ===========================================================\n\nics <- rstan::extract(sim, c(\"S0\", \"E0\",\"I0\", \"logNv\", \"dv0\", \"rv0\"), permute = T)\n\npostscript(\"Manuscript/figures/figS4.eps\",\n width = 6, height = 5,\n family = \"ArialMT\")\n\npar(mfrow = c(2, 3))\n\nhist(ics$S0, freq = F, main = \"A\", xlab = expression(S[0]))\ncurve(dbeta(x, 4, 6), add = T, lwd = 2)\n\nhist(ics$E0, freq = F, main = \"B\", xlab = expression(E[0]), ylim = c(0, 0.015))\ncurve(dgamma(x, 10, 0.1), add = T, lwd = 2)\n\nhist(ics$I0, freq = F, main = \"C\", xlab = expression(I[0]), ylim = c(0, 0.02))\ncurve(dgamma(x, 6, 0.1), add = T, lwd = 2)\n\nhist(ics$logNv, freq = F, main = \"D\", xlab = expression(log(V[N0])))\ncurve(dnorm(x, 0.7, 0.3), add = T, lwd = 2)\n\nhist(ics$dv0, freq = F, main = \"E\", xlab = expression(nu[0]))\ncurve(dnorm(x, 0, 0.5), add = T, lwd = 2)\n\nhist(ics$rv0, freq = F, main = \"F\", xlab = expression(r[0]))\ncurve(dnorm(x, 0, 0.5), add = T, lwd = 2)\n\ndev.off()\n\n# Figure S5: Measurement parameters ============================================\n\nlibrary(truncnorm)\n\nmeas <- rstan::extract(sim, c(\"log_phi_q\", \"phi_y\", \"eta_inv_q\", \"eta_inv_y\"), permute = T)\n\npostscript(\"Manuscript/figures/figS5.eps\",\n width = 6, height = 6,\n family = \"ArialMT\")\n\npar(mfrow = c(2, 2))\n\nhist(meas$log_phi_q, freq = F, main = \"A\", xlab = expression(log(phi[q])))\ncurve(dnorm(x, -13, 0.5), add = T, lwd = 2)\n\nhist(meas$phi_y, freq = F, main = \"B\", xlab = expression(phi[y]))\ncurve(dbeta(x, 7, 77), add = T, lwd = 2)\n\nhist(meas$eta_inv_q, freq = F, main = \"C\", xlab = expression(eta[q]))\ncurve(dtruncnorm(x, a = 0, b = Inf, mean = 0, sd = 5), add = T)\n\nhist(meas$eta_inv_y, freq = F, main = \"D\", xlab = expression(eta[y]))\ncurve(dtruncnorm(x, a = 0, b = Inf, mean = 0, sd = 5), add = T)\n\ndev.off()\n\n# Model checking ===============================================================\n\nyrep <- rstan::extract(sim, \"y_meas\", permute = T)[[1]]\nqrep <- rstan::extract(sim, \"q_meas\", permute = T)[[1]]\n\n# Figure S6: ACF plots =========================================================\n\n# Calculating the observed autocorrelation function\nyacf <- acf(post$yobs, lag.max = 55, plot = F)$acf\nqacf <- acf(post$qobs, lag.max = 55, plot = F)$acf\n\n# Summarizing the posterior acf\nyacfrange <- apply(yrep, 1, function(x){acf(x, lag.max = 55, plot = F)$acf}) %>% \n apply(1, quantile, probs = c(0.1,0.5, 0.9))\n\nqacfrange <- apply(qrep, 1, function(x){acf(x, lag.max = 55, plot = F)$acf}) %>% \n apply(1, quantile, probs = c(0.1,0.5, 0.9))\n\n# Assembling data frame for ggplot\nacfdf <- data.frame(\"lag\" = c(0:55), \n \"yobs\" = yacf,\n \"qobs\" = qacf,\n \"ymed\" = yacfrange[2, ], \n \"ymin\" = yacfrange[1, ], \n \"ymax\" = yacfrange[3, ],\n \"qmed\" = qacfrange[2, ], \n \"qmin\" = qacfrange[1, ], \n \"qmax\" = qacfrange[3, ]\n )\n\n# Plots\nggplot(acfdf, aes(lag, yobs)) + \n geom_hline(yintercept = 0, color = \"gray50\") +\n geom_linerange(aes(lag, ymin = ymin, ymax = ymax)) +\n geom_point() +\n theme_classic() +\n xlab(\"lag (weeks)\") +\n ylab(\"case autocorrelation\") + \n scale_x_continuous(expand = c(0, 0.1)) + \n ggtitle(\"A\") -> figs5.a\n\nggplot(acfdf, aes(lag, qobs)) + \n geom_hline(yintercept = 0, color = \"gray50\") +\n geom_linerange(aes(lag, ymin = qmin, ymax = qmax)) +\n geom_point() +\n theme_classic() +\n xlab(\"lag (weeks)\") +\n ylab(\"mosquito autocorrelation\") + \n scale_x_continuous(expand = c(0, 0.1)) + \n ggtitle(\"B\") -> figs5.b\n\npostscript(\"Manuscript/figures/figS6.eps\",\n width = 5.2, height = 3,\n family = \"ArialMT\")\n\ngrid.arrange(figs5.a, figs5.b, nrow = 1)\n\ndev.off()\n\n# Figure S7: Totals ============================================================\n\npostscript(\"Manuscript/figures/figS7.eps\",\n width = 6, height = 4,\n family = \"ArialMT\")\n\npar(mfrow = c(1, 2))\n\nhist(rowSums(yrep), main = \"A\", xlab = \"total cases\", freq = F, breaks = 20)\nabline(v = sum(post$yobs), lwd = 2)\n\nhist(rowSums(qrep), main = \"B\", xlab = \"total captured mosquitoes\", freq = F, breaks = 20)\nabline(v = sum(post$qobs), lwd = 2)\n\ndev.off()\n\n# Figure S8: Min and max ===========================================================\n\npostscript(\"Manuscript/figures/figS8.eps\",\n width = 6, height = 6,\n family = \"ArialMT\")\n\npar(mfrow = c(2, 2))\n\nhist(apply(yrep, 1, max), main = \"A\", xlab = \"maximum weekly cases\", freq = F)\nabline(v = max(post$yobs), lwd = 2)\n\nhist(apply(qrep, 1, max), main = \"B\", xlab = \"maximum weekly trap count\", freq = F)\nabline(v = max(post$qobs), lwd = 2)\n\nhist(apply(yrep, 1, min), main = \"C\", xlab = \"minimum weekly cases\", freq = F)\nabline(v = min(post$yobs), lwd = 2)\n\nhist(apply(qrep, 1, min), main = \"D\", xlab = \"minimum weekly trap count\", freq = F)\nabline(v = min(post$qobs), lwd = 2)\n\ndev.off()\n\n# Figure S9: Probability of surviving EIP ======================================\n\npostscript(\"Manuscript/figures/figS9.eps\",\n width = 6, height = 5,\n family = \"ArialMT\")\n\nmoving %>% \n ggplot(aes(control, psurv)) + \n stat_summary(fun.ymin = function(x) quantile(x, 0.1),\n fun.ymax = function(x) quantile(x, 0.9),\n geom = \"ribbon\", fill = \"gray70\") +\n stat_summary(fun.y = \"median\", geom = \"line\") + \n theme_classic() + \n scale_x_continuous(expand = c(0, 1), breaks = c(1, 54, 106, 158, 210), labels = c(2008, 2009, 2010, 2011, 2012)) +\n xlab(\"year\") + \n ylab(\"probability of surviving EIP\") -> figS9a\n\nfig1d + ggtitle(\"\") + figS9a + plot_layout(ncol = 1)\n \ndev.off()\n\n", "meta": {"hexsha": "d3844df07a440c888802b00fda3baba0847eedf0", "size": 17058, "ext": "r", "lang": "R", "max_stars_repo_path": "Analysis/plots.r", "max_stars_repo_name": "clint-leach/mosquito-recon", "max_stars_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-11-30T08:56:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T09:40:12.000Z", "max_issues_repo_path": "Analysis/plots.r", "max_issues_repo_name": "clint-leach/mosquito-recon", "max_issues_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analysis/plots.r", "max_forks_repo_name": "clint-leach/mosquito-recon", "max_forks_repo_head_hexsha": "57506d036258a0e556f6ae9c8e5a9975c4c70e39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-03T08:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-03T08:36:04.000Z", "avg_line_length": 32.2457466919, "max_line_length": 116, "alphanum_fraction": 0.563723766, "num_tokens": 5738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.34569497312102554}} {"text": "#### continuous_rqa_parameters-DCC.r: Part of `dual-conversation-constraints.Rmd` ####\n#\n# This script explores the parameters for the continuous cross-recurrence analysis\n# that we'll run over the movement data. Because this is a lengthy process,\n# we create a series of files along the way that can be re-run in pieces if needed.\n# This allows us to keep this file commented by default.\n#\n# Written by: A. Paxton (University of California, Berkeley)\n# Date last modified: 15 May 2017\n#####################################################################################\n\n#### 1. Preliminaries ####\n\n# read in libraries and functions\nsource('./supplementary-code/libraries_and_functions-DCC.r')\n\n# prep workspace and libraries\ninvisible(lapply(c('tseriesChaos',\n 'nonlinearTseries',\n 'crqa',\n 'quantmod',\n 'beepr'), \n require, \n character.only = TRUE))\n\n# read in coords dataset\ncoords = read.table('./data/DCC-trimmed-data.csv', sep=',', header = TRUE)\n\n#### 2. Determine delay with average mutual information (AMI) ####\n\n# set maximum AMI\nami.lag.max = 100\n\n# get AMI (lag and value) for both participants in each dyad\namis = coords %>% ungroup() %>%\n group_by(dyad,conv.type) %>%\n mutate(ami.val0 = min(as.numeric(mutual(euclid0, lag.max = ami.lag.max, plot = FALSE)),na.rm=TRUE)) %>%\n mutate(ami.val1 = min(as.numeric(mutual(euclid1, lag.max = ami.lag.max, plot = FALSE)),na.rm=TRUE)) %>%\n mutate(ami.loc0 = which.min(as.numeric(mutual(euclid0, lag.max = ami.lag.max, plot = FALSE)))-1) %>%\n mutate(ami.loc1 = which.min(as.numeric(mutual(euclid1, lag.max = ami.lag.max, plot = FALSE)))-1) %>%\n group_by(dyad,conv.num,conv.type,ami.val0,ami.val1,ami.loc0,ami.loc1) %>%\n distinct() %>%\n mutate(ami.selected = min(ami.loc1,ami.loc0))\n\n# write AMI information to file\nwrite.table(amis,'./data/crqa_parameters/ami_calculations-DCC.csv', sep=',',row.names=FALSE,col.names=TRUE)\n\n# if we've already run it, load it in\namis = read.table('./data/crqa_parameters/ami_calculations-DCC.csv', sep=',',header=TRUE)\n\n# join the AMI information to our whole dataframe\ncoords = join(coords,amis,by=c(\"dyad\",'conv.type','conv.num'))\n\n#### 3. Determing embedding dimension with FNN ####\n\n# set maximum percentage of false nearest neighbors\nfnnpercent = 10\n\n# create empty dataframe\nfnns = data.frame(dyad = numeric(),\n partic = numeric(),\n conv.type = numeric(),\n head.embed = numeric(),\n tail.embed = numeric())\n\n# cycle through both conversations for each dyad\nconvo.dfs = split(coords,list(coords$dyad,coords$conv.type))\nfor (conv.code in names(convo.dfs)){\n \n # cycle through participants\n for (partic in 0:1){\n \n # print update\n print(paste(\"Beginning FNN calculations for P\",partic,\" of Conversation \",conv.code,sep=\"\"))\n \n # grab next participant's data\n p.data = select(convo.dfs[[conv.code]],matches(paste(\"euclid\",partic,sep=\"\")))[,1]\n p.ami = unique(convo.dfs[[conv.code]]$ami.selected)\n \n # only proceed if we have the dyad's data\n if (length(p.data) > 0) {\n \n # calculate false nearest neighbors\n fnn = false.nearest(p.data,\n m = fnnpercent,\n d = p.ami,\n t = 0,\n rt = 10,\n eps = sd(p.data)/10)\n fnn = fnn[1,][complete.cases(fnn[1,])]\n threshold = fnn[1]/fnnpercent\n \n # identify the largest dimension after a large drop\n embed.dim.index = as.numeric(which(diff(fnn) < -threshold)) + 1\n head.embed = head(embed.dim.index,1)\n tail.embed = tail(embed.dim.index,1)\n if (length(embed.dim.index) == 0){\n head.embed = 1\n tail.embed = 1\n }\n \n # identify conversation type and dyad number from information\n conv.info = unlist(strsplit(conv.code,'[.]'))\n dyad = as.integer(conv.info[1])\n conv.type = as.integer(conv.info[2])\n \n # bind everything to data frame\n fnns = rbind.data.frame(fnns,\n cbind.data.frame(dyad, \n partic, \n conv.type, \n head.embed, \n tail.embed))\n \n }}}\n\n# change table configuration so that we get participants' embedding dimensions as columns, not rows\nfnn.partic = split(fnns,fnns$partic)\nfnn.partic.0 = plyr::rename(as.data.frame(fnn.partic[[\"0\"]]),c('head.embed' = 'embed.0')) %>%\n select(dyad,conv.type,embed.0)\nfnn.partic.1 = plyr::rename(as.data.frame(fnn.partic[[\"1\"]]),c('head.embed' = 'embed.1')) %>%\n select(dyad,conv.type,embed.1)\nfnn.merged = join(fnn.partic.0,fnn.partic.1,by=c(\"dyad\",\"conv.type\"))\n\n# choose the largest embedding dimension\nfnn.merged = fnn.merged %>% ungroup() %>%\n group_by(dyad,conv.type) %>%\n mutate(embed.selected = max(c(embed.0,embed.1)))\n\n# save false nearest neighbor calculations to file\nwrite.table(fnn.merged,'./data/crqa_parameters/fnn_calculations-DCC.csv', sep=',',row.names=FALSE,col.names=TRUE)\n\n# if we've already run it, load it in\nfnn.merged = read.table('./data/crqa_parameters/fnn_calculations-DCC.csv', sep=',',header=TRUE)\n\n# merge with coords dataset\ncoords = join(coords, fnn.merged, by = c(\"dyad\",\"conv.type\"))\n\n#### 4. Determine optimal radius ####\n\n# rescale by mean distance\ncoords_crqa = coords %>% ungroup() %>%\n dplyr::select(dyad,conv.num,conv.type,euclid0,euclid1,conv.num,ami.selected,embed.selected) %>%\n group_by(dyad,conv.num) %>%\n mutate(rescale.euclid0 = euclid0/mean(euclid0)) %>%\n mutate(rescale.euclid1 = euclid1/mean(euclid1))\n\n# create an empty dataframe to hold the parameter information\nradius_selection = data.frame(dyad = numeric(),\n conv.num = numeric(),\n chosen.delay = numeric(),\n chosen.embed = numeric(),\n chosen.radius = numeric(),\n rr = numeric())\n\n# identify radius for calculations\nradius.list = seq(.04,.26,by=.02)\n\n# cycle through all conversations of all dyads\ncrqa.data = split(coords_crqa,\n list(coords$dyad,\n coords$conv.type))\nfor (next.conv in crqa.data){\n \n # make sure we only proceed if we have data for the conversation\n if (dim(next.conv)[1] != 0){\n \n # reset `target` variables for new radius (above what RR can be)\n from.target = 101\n last.from.target = 102\n \n # cycle through radii\n for (chosen.radius in radius.list){\n \n # if we're still improving, keep going\n if (from.target < last.from.target){\n \n # keep the previous iteration's performance\n last.from.target = from.target\n \n # print update\n print(paste(\"Dyad \", unique(next.conv$dyad),\n \", conversation \",unique(next.conv$conv.num),\n \": radius \",chosen.radius,sep=\"\"))\n \n # identify parameters\n chosen.delay = unique(next.conv$ami.selected)\n chosen.embed = unique(next.conv$embed.selected)\n \n # run CRQA and grab recurrence rate (RR)\n rec_analysis = crqa(next.conv$rescale.euclid0, \n next.conv$rescale.euclid1,\n delay = chosen.delay, \n embed = chosen.embed, \n r = chosen.radius,\n normalize = 0, \n rescale = 0, \n mindiagline = 2,\n minvertline = 2, \n tw = 0, \n whiteline = FALSE,\n recpt=FALSE)\n rr = rec_analysis$RR\n \n # clear it so we don't take up too much memory (optional)\n rm(rec_analysis)\n \n # identify how far off the RR is from our target (5%)\n from.target = abs(rr - 5)\n \n # save individual radius calculations\n dyad = unique(next.conv$dyad)\n conv.num = unique(next.conv$conv.num)\n write.table(cbind.data.frame(dyad,\n conv.num,\n chosen.delay,\n chosen.embed,\n chosen.radius,\n rr,\n from.target),\n paste('./data/crqa_parameters/radius_calculations-mean_scaled-r',chosen.radius,'-',dyad,'_',conv.num,'-DCC.csv', sep=''), \n sep=',',row.names=FALSE,col.names=TRUE)\n \n # append to dataframe\n radius_selection = rbind.data.frame(radius_selection,\n cbind.data.frame(dyad,\n conv.num,\n chosen.delay,\n chosen.embed,\n chosen.radius,\n rr,\n from.target))\n } else {\n \n # if we're no longer improving, break\n break\n \n }}}}\n\n# save the radius explorations to file\nwrite.table(radius_selection,'./data/crqa_parameters/radius_calculations-mean_scaled-DCC.csv', sep=',',row.names=FALSE,col.names=TRUE)\n\n# let us know when it's finished\nbeepr::beep(\"fanfare\")\n\n# if we've already run it, load it in\nradius_selection = read.table('./data/crqa_parameters/radius_calculations-mean_scaled-DCC.csv', sep=',',header=TRUE)\n\n#### 5. Expand radius where necessary ####\n\n# load back in the data\nradius_selection = read.table('./data/crqa_parameters/radius_calculations-mean_scaled-DCC.csv', sep=',',header=TRUE)\nradius_stats = radius_selection %>% ungroup() %>%\n group_by(dyad,conv.num) %>%\n dplyr::filter(from.target==min(from.target)) %>%\n dplyr::arrange(dyad,conv.num)\n\n# check whether some conversations are further than 1% from our target recurrence rate\nrecheck_radii = radius_stats %>% ungroup() %>%\n dplyr::filter(from.target > 1) %>%\n dplyr::select(dyad,conv.num)\n\n# link conversation numbers to types\nchecking_numbers = coords_crqa %>%\n ungroup() %>%\n dplyr::select(dyad,conv.type,conv.num) %>%\n distinct()\nrecheck_radii = recheck_radii %>%\n dplyr::left_join(x=.,\n y=checking_numbers, \n by=c(\"dyad\"=\"dyad\",\"conv.num\"=\"conv.num\")) %>%\n mutate(recheck.conv = paste(dyad,conv.type,sep='.'))\n\n# create an empty dataframe to hold the parameter information\nrecheck_radius_selection = data.frame(dyad = numeric(),\n conv.num = numeric(),\n chosen.delay = numeric(),\n chosen.embed = numeric(),\n chosen.radius = numeric(),\n rr = numeric())\n\n# cycle through the conversations\nrecheck_radii = crqa.data[recheck_radii$recheck.conv]\nrecheck_radius_list = seq(.28,1.4,by=.02)\nfor (next.conv in recheck_radii){\n \n # make sure we only proceed if we have data for the conversation\n if (dim(next.conv)[1] != 0){\n \n # reset `target` variables for new radius (above what RR can be)\n from.target = 101\n last.from.target = 102\n \n # cycle through radii\n for (chosen.radius in recheck_radius_list){\n \n # if we're still improving, keep going\n if (from.target < last.from.target){\n \n # keep the previous iteration's performance\n last.from.target = from.target\n \n # print update\n print(paste(\"Dyad \", unique(next.conv$dyad),\n \", conversation \",unique(next.conv$conv.num),\n \": radius \",chosen.radius,sep=\"\"))\n \n # identify parameters\n chosen.delay = unique(next.conv$ami.selected)\n chosen.embed = unique(next.conv$embed.selected)\n \n # run CRQA and grab recurrence rate (RR)\n rec_analysis = crqa(next.conv$rescale.euclid0, \n next.conv$rescale.euclid1,\n delay = chosen.delay, \n embed = chosen.embed, \n r = chosen.radius,\n normalize = 0, \n rescale = 0, \n mindiagline = 2,\n minvertline = 2, \n tw = 0, \n whiteline = FALSE,\n recpt=FALSE)\n rr = rec_analysis$RR\n \n # clear it so we don't take up too much memory (optional)\n rm(rec_analysis)\n \n # identify how far off the RR is from our target (5%)\n from.target = abs(rr - 5)\n \n # save individual radius calculations\n dyad = unique(next.conv$dyad)\n conv.num = unique(next.conv$conv.num)\n write.table(cbind.data.frame(dyad,\n conv.num,\n chosen.delay,\n chosen.embed,\n chosen.radius,\n rr,\n from.target),\n paste('./data/crqa_parameters/radius_calculations-mean_scaled-r',chosen.radius,'-',dyad,'_',conv.num,'-DCC.csv', sep=''), \n sep=',',row.names=FALSE,col.names=TRUE)\n \n # append to dataframe\n recheck_radius_selection = rbind.data.frame(recheck_radius_selection,\n cbind.data.frame(dyad,\n conv.num,\n chosen.delay,\n chosen.embed,\n chosen.radius,\n rr,\n from.target))\n } else {\n \n # if we're no longer improving, break\n break\n \n }}}}\n\n# save the radius explorations to file\nwrite.table(recheck_radius_selection,'./data/crqa_parameters/radius_recheck_calculations-mean_scaled-DCC.csv', sep=',',row.names=FALSE,col.names=TRUE)\n\n# let us know when it's finished\nbeepr::beep(\"fanfare\")\n\n# if we've already run it, load it in\nrecheck_radius_selection = read.table('./data/crqa_parameters/radius_recheck_calculations-mean_scaled-DCC.csv', sep=',',header=TRUE)\n\n#### 6. Export chosen radii for all conversations ####\n\n# load in files\nradius_files = list.files('./data/crqa_parameters', \n pattern='radius_calculations-mean_scaled*',\n full.names = TRUE)\n\n# identify the target radii\nradius_stats = rbind.data.frame(rbindlist(lapply(radius_files, fread, sep=\",\"))) %>%\n ungroup() %>%\n group_by(dyad,conv.num) %>%\n dplyr::filter(from.target==min(from.target)) %>%\n dplyr::arrange(dyad,conv.num) %>%\n ungroup() %>%\n distinct()\n\n# rename our rescaled variables here\ncoords_crqa = coords_crqa %>% ungroup() %>%\n select(dyad,conv.num,rescale.euclid0,rescale.euclid1)\n\n# join the dataframes\ncoords_crqa = plyr::join(x=coords_crqa,\n y=radius_stats, by=c(\"dyad\"=\"dyad\",\"conv.num\"=\"conv.num\"))\n\n# save to file\nwrite.table(coords_crqa,'./data/crqa_data_and_parameters-DCC.csv', sep=',',row.names=FALSE,col.names=TRUE)", "meta": {"hexsha": "f585a7db878a6ebfd6a7d7e4db7d880d3095740c", "size": 15922, "ext": "r", "lang": "R", "max_stars_repo_path": "supplementary-code/continuous_rqa_parameters-DCC.r", "max_stars_repo_name": "a-paxton/dual-conversation-constraints", "max_stars_repo_head_hexsha": "a167f004c71d9637ec30082de13a1ba6283846bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-10-11T23:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-31T18:52:49.000Z", "max_issues_repo_path": "supplementary-code/continuous_rqa_parameters-DCC.r", "max_issues_repo_name": "a-paxton/dual-conversation-constraints", "max_issues_repo_head_hexsha": "a167f004c71d9637ec30082de13a1ba6283846bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "supplementary-code/continuous_rqa_parameters-DCC.r", "max_forks_repo_name": "a-paxton/dual-conversation-constraints", "max_forks_repo_head_hexsha": "a167f004c71d9637ec30082de13a1ba6283846bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2070707071, "max_line_length": 150, "alphanum_fraction": 0.539065444, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.34548181972574316}} {"text": "#' Predict probability from DMBC model\n#'\n#' @description\n#' Based on a set of optimized features from training set, this function predicts the posterior probability for two class labels.\n#'\n#' @param data Validation dataset with rows are samples, columns are features. The first column should be the sample ID, second column group variable (Disease type, the label you want to classify on).\n#' @param testset Lable unknown testset without sample IDs.\n#' @param auc_out Output object of Cal_AUC() from a validation set.\n#' @param col_start An index indicating at which column is the beginning of bacteria (features) data in the validation set. The default is the 3rd column.\n#' @param type_col An index indicating at which column is group/type variable in the validation set. The default is the 2nd column.\n#' @param Prior1 Prevalence of label1 according to literature or experience. Default is 0.5.\n#' @param Prior2 Prevalence of label2 according to literature or experience. Default is 0.5.\n#'\n#' @return\n#'\n#' @examples\n#' #load the DMBC library\n#' library(DMBC)\n#'\n#' #load training dataset\n#' data(training)\n#'\n#' #load test dataset\n#' data(test)\n#'\n#'## calculate AUC based on training set using 10-fold cv ##\n#' auc_out <- Cal_AUC(tfcv(training))\n#'\n#'## calculate AUC based on training set using leave-one-out cv ##\n#' auc_out <- Cal_AUC(loocv(training))\n#'\n#' #predict unknown test set using training set and auc results.\n#' dmbc_predict(data=training,testset=test,auc_out=auc_out)\n#' @export\n\n\n\ndmbc_predict <- function(data=data,testset = testset,auc_out=auc_out,col_start =3,type_col=2,Prior1=0.5,Prior2=1-Prior1){\n namelist <- auc_out$Features[which.max(auc_out$AUC_Area)]\n NameList <- as.vector(unlist(strsplit(as.character(namelist),\";\")))\n\n Disease <- levels(data[,type_col])\n\n NewDF <- as.data.frame(data[,colnames(data) %in% NameList])\n colnames(NewDF) <- colnames(data)[colnames(data) %in% NameList]\n\n NewDF2 <- data[,!colnames(data)%in% NameList]\n\n col_end2 = dim(NewDF2)[2]\n NewDF2$Others = rowSums(NewDF2[, col_start:col_end2])\n NewDFTotal = data.frame(NewDF2[, 1:(col_start-1)],NewDF, NewDF2$Others)\n\n rep2_Type1 = NewDFTotal[NewDFTotal[,type_col] == Disease[1],]\n rep2_Type2 = NewDFTotal[NewDFTotal[,type_col] == Disease[2],]\n\n for (taxa in NameList){\n if(nrow(rep2_Type1) == sum(rep2_Type1[,taxa]<1)) {\n rep2_Type1[,taxa][1] =1\n }\n if(nrow(rep2_Type2) == sum(rep2_Type2[,taxa]<1)) {\n rep2_Type2[,taxa][1] =1\n }\n }\n\n\n ####fit3 <- dirmult(rep2_Type1[,-(1:(col_start-1))],epsilon=10^(-4),trace=FALSE)\n ####fit4 <- dirmult(rep2_Type2[,-(1:(col_start-1))],epsilon=10^(-4),trace=FALSE)\n ####alpha_Type1 = fit3$gamma\n ####alpha_Type2 = fit4$gamma\n tol=0.0001\n max.iter=1000\n\n Xc = as.matrix(rep(1, dim(rep2_Type1)[1]))\n Xa = Xc\n Xb = Xc\n c0 = as.matrix(rep(1, dim(rep2_Type1)[2]-1))\n alpha0 = c0\n beta0 = c0\n p_Type1 <- ZIGDM_prob(rep2_Type1[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n\n Xc = as.matrix(rep(1, dim(rep2_Type1)[1]))\n Xa = Xc\n Xb = Xc\n c0 = as.matrix(rep(1, dim(rep2_Type1)[2]-1))\n alpha0 = c0\n beta0 = c0\n p_Type2 <- ZIGDM_prob(rep2_Type2[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n ###### predict test set #####\n\n for (t in NameList){\n if (! (t %in% colnames(testset)) ){\n testset <- data.frame(testset,rep(0,nrow(testset)))\n colnames(testset)[ncol(testset)] <- t\n }\n }\n\n NewTestSignature = testset[, colnames(testset)%in% NameList]\n NewTestNonSignature = testset[, !colnames(testset)%in% NameList]\n NewTestNonSignature$Others = rowSums(NewTestNonSignature)\n NewTestTotal = data.frame(NewTestSignature, NewTestNonSignature$Others)\n\n test_res <- list()\n for (r in 1:nrow(testset)){\n ##### Calculate log of Dirichlet multinomial probability mass function P(x|Type1)\n #pdfln_Type1 <- ddirmn(NewTestTotal[r,], t(as.matrix(alpha_Type1)))\n #lh_Type1=exp(pdfln_Type1)\n #lhP_Type1 = lh_Type1*Prior1\n\n probability_Type1 = apply(NewTestTotal[r,],1,dmultinom, prob = p_Type1)\n lhP_Type1 = probability_Type1*Prior1\n\n ##### Calculate log of Dirichlet multinomial probability mass function P(x|Type2)\n #pdfln_Type2 <- ddirmn(NewTestTotal[r,], t(as.matrix(alpha_Type2)))\n #lh_Type2=exp(pdfln_Type2)\n #lhP_Type2 = lh_Type2*Prior2\n probability_Type2 = apply(NewTestTotal[r,],1,dmultinom, prob = p_Type2)\n lhP_Type12 = probability_Type2*Prior2\n\n #Pos_Type1 = lh_Type1/(lh_Type1+lh_Type2)\n #Pos_Type2 = lh_Type2/(lh_Type1+lh_Type2)\n\n PosP_Type1 = lhP_Type1/(lhP_Type1+lhP_Type2)\n PosP_Type2 = lhP_Type2/(lhP_Type1+lhP_Type2)\n\n test_res[[r]] <- as.matrix(t(c(rownames(testset)[r],Disease[1], PosP_Type1, Disease[2], PosP_Type2,paste(NameList,collapse=\";\"))))\n\n }\n\n out <- data.frame(t(sapply(test_res,function(x) x)))\n colnames(out) <- c(\"test_idx\",\"Group1\",\"Group1_prb\",\"Group2\",\"Group2_prb\",\"Features\")\n\n return(out)\n}\n", "meta": {"hexsha": "e519836e1a593aa7b1cc52e1f4c0b25672c5cfac", "size": 4943, "ext": "r", "lang": "R", "max_stars_repo_path": "R/dmbc_predict.r", "max_stars_repo_name": "qunfengdong/BioMarkerClassifier", "max_stars_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_stars_repo_licenses": ["MIT"], "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/dmbc_predict.r", "max_issues_repo_name": "qunfengdong/BioMarkerClassifier", "max_issues_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_issues_repo_licenses": ["MIT"], "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/dmbc_predict.r", "max_forks_repo_name": "qunfengdong/BioMarkerClassifier", "max_forks_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_forks_repo_licenses": ["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.8880597015, "max_line_length": 200, "alphanum_fraction": 0.6965405624, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34529197632961595}} {"text": "##############################################################################\n# dci_calc_fx.r\n\n# Edited by: G Oldford\n # Last modified: August, 2020\n # Inputs: \n # sum_table \n # lengths\n # all_sections (t/f)\n #\n # Output:\n # DCI\n #\n # Output example: \n # DCIp DCId\n # 30.03119 44.29823\n #\n # Notes:\n # \n #\n # to-do: \n \n #\n # Notes from previous coding work: \n\ndci_calc_fx<-function(sum_table,\n lengths,\n all_sections=F){\n\n # Old Notes\n #sum.table is a variable that is used in the dci.calc.r function, \n #where we describe sum.table as sum.table.all or sum.table.nat\n #where: sum.table.nat<-read.csv(\"summary table natural.csv\") and \n #sum.table.all<-read.csv(\"summary table all.csv\") - from the \n #graph.and.data.setup.for.DCI.r function\n\n #WHAT THIS FUNCTION DOES: it calculates the DCIp and DCId \n #values for the riverscape (includes both natural and \n #artificial barriers)\n\n #this contains the length of each section\n\n #use this number for the DCIp calculation - i\n # interested in movements in all directions from all segments\n p_nrows<-dim(sum_table)[1]\n \n d_nrows<-subset(sum_table, \n start==\"sink\")\n #for diadromous fish we are only interested in the movement \n # from the segment which is closest to the ocean\n d_sum_table<-d_nrows\n\n DCIp<-0\n DCId<-0\n\n #DCIp calculation\n for (k in 1:p_nrows){\n # Old notes: \n #to get the riverscape connectivity index for potadromous fish, \n #use the given formula: DCIp= Cij*(li/L)*(lj/L)\n #Cij = passability for pathway (product of all barrier passabilities \n #in the pathway), li & lj = length of start and finish sections, \n #L = total length of all sections\n\n lj<-sum_table$start_section_length[k]/sum(lengths$Shape_Length)\n lk<-sum_table$finish_section_length[k]/sum(lengths$Shape_Length)\n pass<-sum_table$pathway_pass[k]\n DCIp<-DCIp+lj*lk*pass*100\n \n #add DCIp at the beginning to keep a running total of DCIp values\n }\n\n #DCId calculation\n for (a in 1:dim(d_nrows)[1]){\n # Old notes:\n #to get the DCI for diadromous fish, use the following formula: \n # DCId= li/L*Cj (where j= the product of the passability in the pathway)\n \n la<-d_sum_table$finish_section_length[a]/sum(lengths$Shape_Length)\n pass_d<-d_sum_table$pathway_pass[a]\n DCId<-DCId+la*pass_d*100\n }\n\n DCI<-t(c(DCIp,DCId))\n DCI<-as.data.frame(DCI)\t\n\n names(DCI)<-c(\"DCIp\",\"DCId\")\n \n # Old notes\n ######### ALL SECTION ANLAYSIS ######\n ## if desired, one can calculate the DCI_d starting with every sections. This\n ## gives a \"section-level\" DCI score for each section in the watershed\n if(all_sections==T){\n sections<-as.vector(unique(sum_table$start))\n # store the all section results in DCI.as\n DCI_as<-NULL\n \n for(s in 1:length(sections)){\n DCI_s<-0\n # Old notes:\n # select out only the data that corresponds to pathways from one sectino \n # to all other sections\n d_nrows<-subset(sum_table, start==sections[s])\n d_sum_table<-d_nrows\n \n for (a in 1:dim(d_nrows)[1]){\n # Old note:\n #to get the DCI for diadromous fish, use the following formula: \n # DCId= li/L*Cj (where j= the product of the passability in the pathway)\n la<-d_sum_table$finish_section_length[a]/sum(lengths$Shape_Length)\n pass_d<-d_sum_table$pathway_pass[a]\n DCI_s<-round(DCI_s+la*pass_d*100, digits=2)\n } # end loop over sections for dci calc\n \n DCI_as[s]<-DCI_s\n } # end loop over \"first\" sections\t\n\n # STORE RESULTS IN .CSV file\n res<-data.frame(sections,DCI_as)\n write.table(x=res,\n file=\"DCI_all_sections.csv\",\n sep=\",\",\n row.names=F)\n\n } # end if statement over all.sections\n\n print(DCI)\n\n #write.table(DCI,\"DCI.csv\", row.names=F, sep=\",\")\n\n return(DCI)\n # Old note:\n #returns the results (but you can't do anything after this, so \"return\" \n # must always be at the end of a function)\n\n}", "meta": {"hexsha": "a9bda9a5dd1a8683611bed8273fb13cda98bd508", "size": 4389, "ext": "r", "lang": "R", "max_stars_repo_path": "2021 Debug/dci_calc_fx.r", "max_stars_repo_name": "aligharouni/DCI-R-Code-2020", "max_stars_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021 Debug/dci_calc_fx.r", "max_issues_repo_name": "aligharouni/DCI-R-Code-2020", "max_issues_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021 Debug/dci_calc_fx.r", "max_forks_repo_name": "aligharouni/DCI-R-Code-2020", "max_forks_repo_head_hexsha": "1784dcf0907832ff9a6798948f1aa23ba55613c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-17T17:27:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:27:40.000Z", "avg_line_length": 32.2720588235, "max_line_length": 88, "alphanum_fraction": 0.5848712691, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.3444155417354649}} {"text": "#' Draw meanfield model attractor\n#'\n#' @param model\n#' @param times\n#' @param parms\n#' @param method\n#' @param rho\n#' @param colors\n#'\n#' @import foreach\n#'\n#' @return\n#' @export\n#' @examples\n#'\n#' p <- set_parms(livestock$parms, set = list(b = 0.1, f = 0.5, p = 0.9, L = 1.5))\n#' par(mfrow = c(1,2))\n#' plot_pairapproximation(livestock, parms = p) -> out\n#' plot_pairapproximation(out, parms = p, side = \"plain\")\n\nplot_pairapproximation <- function(\n model,\n parms = model$parms,\n side = \"rho\",\n rho_1_ini = seq(0,1, length = 11),\n rho_11_ini = seq(0,1, length = 11),\n times = c(0,1000),\n method = \"ode45\",\n rho = seq(0,1,length = 100),\n colors = c(\"#000000\",\"#009933\"),\n #fog = TRUE,\n new = TRUE,\n ...\n) {\n\n #par(mfrow = c(1,3))\n # open new base plot if none exists\n if(dev.cur() == 1 | new == TRUE) plot_base(ylim = switch(side, plain = c(0,1), c(0,0.25) ),\n ylab = switch(side, plain = \"local cover\", \"plant mortality/growth\" ),\n xlab = switch(side, q = \"local cover\",\"vegetation cover\"), ...)\n\n # draw trajectories of mortality and growth\n if(class(model) == \"attractor\") {\n trajectories <- model$trajectories\n } else {\n trajectories <- sim_trajectories(model = model, parms = parms, rho_1_ini = rho_1_ini, times = times, method = method)\n }\n\n # visualize trajectories to the attractor\n sapply(trajectories, function(x){\n rho <- ini_rho(x$rho_1, x$rho_11)\n mort <- limit(mortality(rho, parms))\n grow <- limit(growth(rho, parms))\n q_11_vec <- q_11(rho)\n #fog_m <- highlight(q_11_vec, colrange = c(paste0(colors[1],\"88\"),colors[1]))\n #fog_g <- highlight(q_11_vec, colrange = c(paste0(colors[2],\"88\"),colors[2]))\n\n\n switch(side,\n rho = {\n lines(rho$rho_1, mort)\n #arrows(tail(rho$rho_1,2)[1],tail(mort,2)[1],tail(rho$rho_1,1),tail(mort,1), length = 0.1 )\n lines(rho$rho_1, grow, col = \"#009933\")\n #arrows(tail(rho$rho_1,2)[1],tail(grow,2)[1],tail(rho$rho_1,1),tail(grow,1), length = 0.1 , col = \"#009933\")\n\n },\n q = {\n lines(q_11_vec, mort)\n #arrows(tail(q_11_vec,2)[1],tail(mort,2)[1],tail(q_11_vec,1),tail(mort,1), length = 0.1 )\n lines(q_11_vec, grow, col = \"#009933\")\n #arrows(tail(q_11_vec,2)[1],tail(grow,2)[1],tail(q_11_vec,1),tail(grow,1), length = 0.1 , col = \"#009933\")\n\n },\n plain = {\n lines(rho$rho_1, q_11_vec)\n #arrows(tail(rho$rho_1,2)[1],tail(q_11_vec,2)[1],tail(rho$rho_1,1),tail(q_11_vec,1), length = 0.1 )\n lines(rho$rho_1+0.002, q_11_vec+0.002, col = \"#009933\")\n #arrows(tail(rho$rho_1,2)[1],tail(q_11_vec,2)[1],tail(rho$rho_1,1),tail(q_11_vec,1), length = 0.1 , col = \"#009933\")\n\n }\n\n )\n\n\n }\n )\n\n\n if(class(model) == \"attractor\") {\n eq <- model$eq\n } else {\n eq <- get_equilibria(y = model$template, func = model$pair, parms = parms, method = method, t_max = 130)\n }\n\n rho_steady <- ini_rho(c(eq$lo[1],eq$hi[1]),c(eq$lo[2],eq$hi[2]))\n q_steady <- q_11(rho_steady)\n switch(side,\n rho = {\n points(rho_steady$rho_1, mortality(rho_steady, parms = parms), xpd = TRUE, pch = 20, cex = 2)\n\n },\n q = {\n points(q_steady, mortality(rho_steady, parms = parms), xpd = TRUE, pch = 20, cex = 2)\n\n },\n plain = {\n points(rho_steady$rho_1, q_steady, xpd = TRUE, pch = 20, cex = 2)\n\n }\n\n )\n\n\n output <- list(trajectories = trajectories,\n eq = eq\n )\n class(output) <- \"attractor\"\n return(output)\n\n}\n\n\n\n\n\n", "meta": {"hexsha": "253488614f4eb9cb909c744296825fa6e3fd24e4", "size": 3633, "ext": "r", "lang": "R", "max_stars_repo_path": "R/plot_pairapproximation.r", "max_stars_repo_name": "fdschneider/livestock", "max_stars_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-01T02:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:59:02.000Z", "max_issues_repo_path": "R/plot_pairapproximation.r", "max_issues_repo_name": "fdschneider/livestock", "max_issues_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/plot_pairapproximation.r", "max_forks_repo_name": "fdschneider/livestock", "max_forks_repo_head_hexsha": "d7f8767f1bfd447f6f885bcce527ca2fcc723be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8333333333, "max_line_length": 126, "alphanum_fraction": 0.5598678778, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.34394860923816123}} {"text": "### tripsAndDip uses read counts for biallelic SNPS to determine if a sample is diploid or triploid\n### Input\n### counts is either a matrix or a dataframe with each row corresponding to a different sample\n### the columns correspond to the read counts for each locus, in a two column per locus format\n### So, column 1 is the read counts for locus1Allele1, column two is the read counts for locus1Allele2, locus2Allele1, locus2Allele2, ...\n### the rownames of the matrix or dataframe should be the sample names\n### h is a list of h values for each locus in the same order that the loci are ordered in counts\n### eps is a list of epsilon (error rate per read) values for each locus in the same order that the loci are ordered in counts\n### min_reads is the minimum number of reads needed to use a locus in the algorithm\n### min_loci is the minimum number of loci needed to attempt to calculate an LLR\n### Output\n### a dataframe with column 1 containing sample names, column 2 containing calculated LLRs (larger means more likely triploid)\n### and column 3 containing the number of loci used to calculate the LLR\n######\n### note that constant values for h and epsilon can be easily implemented usign the rep() function in R, for example\n###### constant_h <- rep(1, (ncol(allele_counts))/2)\n###### constant_eps <- rep(.01, (ncol(allele_counts))/2)\n###### results <- tripsAndDip(allele_counts, constant_h, constant_eps)\n\ntripsAndDip <- function(counts, h, eps, min_reads = 30, min_loci = 15, binom_p_value = .05){\n\t### input error checking\n\tif(!is.matrix(counts) && !is.data.frame(counts)){\n\t\tcat(\"\\nError. Counts must be either a matrix or a dataframe.\\n\")\n\t\treturn()\n\t}\n\tif((ncol(counts)/2) != length(h)){\n\t\tcat(\"\\nError. The number of columns of counts is not equal to twice the length of h.\\n\")\n\t\treturn()\n\t}\n\tif(length(eps) != length(h)){\n\t\tcat(\"\\nError. The length of h is not equal to the length of eps.\\n\")\n\t\treturn()\n\t}\n\tif(min_reads < 1){\n\t\tcat(\"\\nError. min_reads must be 1 or greater.\\n\")\n\t\treturn()\n\t}\n\tif(min_loci < 1){\n\t\tcat(\"\\nError. min_loci must be 1 or greater.\\n\")\n\t\treturn()\n\t}\n\tif(binom_p_value < 0 || binom_p_value > 1){\n\t\tcat(\"\\nError. binom_p_value must be between 0 and 1.\\n\")\n\t\treturn()\n\t}\n\t\n\t### calculate llr for each sample\n\tnum_counts <- ncol(counts)\n\tllr <- apply(counts, 1, function(x){\n\t\t#separate allele1 and allele2\n\t\tcount1 <- x[seq(1, (num_counts - 1), 2)]\n\t\tcount2 <- x[seq(2, num_counts, 2)]\n\t\t#caluculate total read count and which is larger\n\t\tn <- count1 + count2\n\t\t#determine whether to include loci based on read count\n\t\tcount1 <- count1[n >= min_reads]\n\t\tcount2 <- count2[n >= min_reads]\n\t\th_corr <- h[n >= min_reads]\n\t\teps_corr <- eps[n >= min_reads]\n\t\tn <- n[n >= min_reads]\n\t\t# determine if enough loci\n\t\tif (length(n) < min_loci){\n\t\t\treturn(c(NA, length(n)))\n\t\t}\n\t\t\n\t\tk <- mapply(max, count1, count2)\n\t\t#flip h as necessary\n\t\th_corr[count2 > count1] <- 1/h_corr[count2 > count1]\n\t\t\n\t\t#calculate probabilities\n\t\t#based on model with error and allelic bias from Gerard et al. 2018\n\t\tp_temp <- (0.6666667*(1 - eps_corr) + (0.3333333)*eps_corr)\n\t\tprob_trip <- p_temp / (h_corr*(1 - p_temp) + p_temp)\n\t\tp_temp <- 0.5 # (0.5*(1 - eps_corr) + (0.5)*eps_corr) simplifies to 0.5\n\t\tprob_dip <- p_temp / (h_corr*(1 - p_temp) + p_temp)\n\t\t\n\t\t#determine which loci to include using binomial test\n\t\tbinom_results <- mapply(function(x,y,z){\n\t\t\t\treturn(binom.test(x, y, z, \"greater\")$p.value)\n\t\t\t}, k, n, prob_trip)\n\t\tbinom_results <- binom_results > binom_p_value\n\t\t\n\t\th_corr <- h_corr[binom_results]\n\t\teps_corr <- eps_corr[binom_results]\n\t\tn <- n[binom_results]\n\t\tk <- k[binom_results]\n\t\tprob_trip <- prob_trip[binom_results]\n\t\tprob_dip <- prob_dip[binom_results]\n\t\t# determine if enough loci\n\t\tif (length(n) < min_loci){\n\t\t\treturn(c(NA, length(n)))\n\t\t}\n\t\t\n\t\t#calculate log likelihoods\n\t\ttrip <- (k*log(prob_trip)) + ((n-k)*log(1-prob_trip))\n\t\tdip <- (k*log(prob_dip)) + ((n-k)*log(1-prob_dip))\n\t\t#sum accros loci\n\t\ttrip <- sum(trip)\n\t\tdip <- sum(dip)\n\t\n\t\treturn(c(trip - dip, length(n)))\n\t\t\t\n\t})\n\t# associate llr's with sample names and return\n\treturn(data.frame(sample_name = rownames(counts),\n\t\t\t LLR = llr[1,], loci_used=llr[2,], stringsAsFactors = F, row.names = NULL))\n}\n", "meta": {"hexsha": "6df204265a0e85516bce546c665cd7222332e1c2", "size": 4208, "ext": "r", "lang": "R", "max_stars_repo_path": "tripsAndDip.r", "max_stars_repo_name": "delomast/tripsAndDip", "max_stars_repo_head_hexsha": "9ca40bea33b1afde1b8c84526d62f03605234cfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tripsAndDip.r", "max_issues_repo_name": "delomast/tripsAndDip", "max_issues_repo_head_hexsha": "9ca40bea33b1afde1b8c84526d62f03605234cfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tripsAndDip.r", "max_forks_repo_name": "delomast/tripsAndDip", "max_forks_repo_head_hexsha": "9ca40bea33b1afde1b8c84526d62f03605234cfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.962962963, "max_line_length": 137, "alphanum_fraction": 0.6839353612, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3438830474919201}} {"text": "#setwd(\"D:/Dropbox/Data analyze/Rdocuments/datas\")\nlibrary(xlsx)\n library(RColorBrewer)\n\n\n\n fv<-5:3500 #电压频率\n\nq<-c(2.5e-14, 4.5e-13, 9e-13, 3e-12) #不同的流量下\n\nk<-c(0.5,0.6,0.7,0.8) #不同占空比下无电场时间比例,即1-k_i\n\nv<-4.66e-13 #泰勒锥的体积总量\n\nmycolors<-c(\"red\", \"blue\", \"darkgreen\", \"yellow3\")\n\npchall<-c(21,22,23,24)\n\n######\npar(fig=c(0,1,0,1), mar = c(3,3,1,1), oma = c(1,1,1,1),new=FALSE)\nplot(fv, (k[1]*q[1]/fv+v), mgp = c(1, 0, 0),tck=0.01,col=mycolors[1], log=\"x\", type=\"b\", xlab = expression(italic(f[\"v\"])(Hz)),\n ylab = expression(italic(V[\"ne\"]+V[\"m\"](m^3))), main=\"\", lwd=2, pch=pchall[1], lty=2,cex.lab=1,cex.axis=1, ylim=c(4.4e-13, 8e-13))\n\n#画出占空比为0.5,流量为1.5nl/min时的弯月面体积,说明最小值是什么\n\n###流量为1.5nl/min时####\nfor (i in 1:3){\nlines(fv, (k[i+1]*q[1]/fv+v), lwd=1.5, type=\"b\",col=\"red\", pch=pchall[i+1],lty=2,cex=0.6)\n}\n#画出,流量为最小,占空比从大到小,体积从小到大变化的曲线,其中:颜色均为red,pch的改变代表着占空比的改变\n\n###流量为27nl/min时####\npar(fig=c(0,1,0,1))\nfor (i in 1:4){\nlines(fv, (k[i]*q[2]/fv+v), lwd=1.5, type=\"b\", col=\"blue\", pch=pchall[i] ,lty=2,cex=0.6)\n}\n\n###流量为54nl/min时####\nfor (i in 1:4){\nlines(fv, (k[i]*q[3]/fv+v), lwd=1.5, type=\"b\", col=\"darkgreen\", pch=pchall[i] ,lty=2,cex=0.6)\n}\n\n###流量为180nl/min时####\nfor (i in 1:4){\nlines(fv, (k[i]*q[4]/fv+v), lwd=1.5, type=\"b\", col=\"yellow3\", pch=pchall[i] ,lty=2,cex=0.6)\n}\n\nda<-c(\"kv0.5-Q1.5nlmin\", \"kv0.4-Q1.5nlmin\", \"kv0.3-Q1.5nlmin\", \"kv0.2-Q1.5nlmin\", \"kv0.5-Q27nlmin\", \"kv0.4-Q27nlmin\", \"kv0.3-Q27nlmin\", \"kv0.2-Q27nlmin\",\"kv0.5-54nlmin\", \"kv0.4-Q54nlmin\", \"kv0.3-Q54nlmin\", \"kv0.2-Q54nlmin\",\"kv0.5-Q180nlmin\", \"kv0.4-Q180nlmin\", \"kv0.3-Q180nlmin\", \"kv0.2-Q180nlmin\")\n\nmycolorsss<-c(\"red\",\"red\",\"red\",\"red\",\"blue\",\"blue\",\"blue\",\"blue\",\"darkgreen\",\"darkgreen\",\"darkgreen\",\"darkgreen\",\"yellow3\",\"yellow3\",\"yellow3\",\"yellow3\")\n\npchss<-c(21,22,23,24,21,22,23,24,21,22,23,24,21,22,23,24)\n\nlegend(\"topright\", da, inset=0, col=mycolorsss, pch=pchss,lwd=1.5, lty=2, cex=0.8, bty=\"n\")\n\nabline(v=20, col=\"red\", lwd=2,lty=3)\nabline(v=45, col=\"blue\", lwd=2,lty=3)\n#abline(v=125, col=\"darkgreen\", lwd=2,lty=3)\n\n#################################################\npar(fig=c(0.4, 0.98,0.20,0.98), new=TRUE)\n\nplot(fv, (k[1]*q[1]/fv+v),bty=\"n\", col=mycolors[1], mgp = c(1, 0, 0),tck=0.01,log=\"x\", type=\"l\", xlab = \"125Hz ~ 1KHz\", ylab =\"\", lwd=2, lty=2, xlim=c(125,1000), ylim=c(4.66e-13, 5e-13))\n\n\n#画出占空比为0.5,流量为1.5nl/min时的弯月面体积,说明最小值是什么\n\n###流量为1.5nl/min时####\nfor (i in 1:3){\nlines(fv, (k[i+1]*q[1]/fv+v), lwd=2, col=\"red\", lty=1)\n}\n#画出,流量为最小,占空比从大到小,体积从小到大变化的曲线,其中:颜色均为red,pch的改变代表着占空比的改变\n\n###流量为27nl/min时####\nfor (i in 1:4){\nlines(fv, (k[i]*q[2]/fv+v), lwd=2, col=\"blue\", lty=1)\n}\n\n###流量为54nl/min时####\nfor (i in 1:4){\nlines(fv, (k[i]*q[3]/fv+v), lwd=2,col=\"darkgreen\", lty=1)\n}\n\n###流量为180nl/min时####\nfor (i in 1:4){\nlines(fv, (k[i]*q[4]/fv+v), lwd=2,col=\"yellow3\", lty=1)\n}\n\nabline(h=5.126e-13, col=\"red\", lwd=1.5, lty=4)\nabline(h=5.592e-13, col=\"blue\", lwd=1.5, lty=4)\n", "meta": {"hexsha": "3c181cee0aa624bb53e7f10400e41d34176c827e", "size": 2873, "ext": "r", "lang": "R", "max_stars_repo_path": "thesis/chap4/fig4-2.r", "max_stars_repo_name": "shuaimeng/r", "max_stars_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thesis/chap4/fig4-2.r", "max_issues_repo_name": "shuaimeng/r", "max_issues_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thesis/chap4/fig4-2.r", "max_forks_repo_name": "shuaimeng/r", "max_forks_repo_head_hexsha": "94fa0cce89c89a847b95000f07e64a0feac1eabe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5714285714, "max_line_length": 298, "alphanum_fraction": 0.5938043857, "num_tokens": 1573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3428032392466955}} {"text": "## ============================================================================================\n##\n## predictDiagnosis\n##\n## ============================================================================================\n\ncomputePredResMat <- function(predRes, predRes0, followUpTime, followUpTime0) {\n selPeriodStrs <- c(\"Year 1\", \"Year 1-2\", \"Year 3-4\", \"Year 5-6\")\n selPeriodInterval <- matrix(NA, nrow=4, ncol=2)\n selPeriodInterval[1,] <- c(1,365)\n selPeriodInterval[2,] <- c(1,2*365)\n selPeriodInterval[3,] <- c(2*365+1,4*365)\n selPeriodInterval[4,] <- c(4*365+1,6*365)\n \n resMat <- matrix(NA, nrow=5, ncol=5)\n rownames(resMat) <- c(\"All years\", selPeriodStrs)\n colnames(resMat) <- c(\"FN\", \"TP\", \"FP\", \"TN\", \"P-value\")\n \n for (i in 0:length(selPeriodStrs)) {\n fn <- sum(!predRes>0)\n tp <- sum(predRes>0)\n fp <- sum(!predRes0<0)\n tn <- sum(predRes0<0)\n if (i>0) {\n sel <- followUpTime>selPeriodInterval[i,1] & followUpTime<=selPeriodInterval[i,2]\n sel0 <- followUpTime0>selPeriodInterval[i,1] & followUpTime0<=selPeriodInterval[i,2]\n fn <- sum(!predRes[sel]>0)\n tp <- sum(predRes[sel]>0)\n fp <- sum(!predRes0[sel0]<0)\n tn <- sum(predRes0[sel0]<0)\n }\n \n resMat[i+1,] <-\n c(fn, tp, fp, tn,\n fisher.test(matrix(c(tp, fn, fp, tn), ncol=2, byrow=F),\n alternative=\"g\")$p.value)\n }\n\n resMat\n}\n\n\npredictDiagnosis <- function(dataList, n, nofGenes, strFollowUpTime, strPlotFracCorr, strResMat,\n m, m2, selPeriodStr, selPeriodInterval, selPeriodFromWith,\n hasInsitu=FALSE) {\n\n ## Predict diagnosis using a leave-one-out approach, n=periodLength\n caseStr <- \"Weight\"\n caseN <- \"N1\"\n \n curDataList <- selectDataset(dataList, caseN, dataList$withSpread)\n data <- curDataList$data\n followUpTime <- curDataList$followUpTime\n weights <- curDataList$weights\n curDataList0 <- selectDataset(dataList, caseN, dataList$withoutSpread)\n data0 <- curDataList0$data\n followUpTime0 <- curDataList0$followUpTime\n weights0 <- curDataList0$weights\n if (hasInsitu) {\n curDataListInsitu <- selectDataset(dataList, caseN, dataList$insitu)\n dataInsitu <- curDataListInsitu$data\n followUpTimeInsitu <- curDataListInsitu$followUpTime\n weightsInsitu <- curDataListInsitu$weights\n }\n selFollowUpTime <- followUpTime0\n notSelFollowUpTime <- followUpTime\n if (selPeriodFromWith) {\n selFollowUpTime <- followUpTime\n notSelFollowUpTime <- followUpTime0\n }\n nofPeriods <- length(selFollowUpTime)-n+1\n \n ## Select genes for predictor\n ## Find sorting of genes from analyses for \"Weights\" in predictor\n ## Weights with sign for genes selected for predictor: Number of genes selected?\n \n predRes <- matrix(NA, ncol=length(nofGenes), nrow=ncol(data))\n predRes0 <- matrix(NA, ncol=length(nofGenes), nrow=ncol(data0))\n rownames(predRes) <- colnames(data)\n rownames(predRes0) <- colnames(data0)\n colnames(predRes) <- colnames(predRes0) <- nofGenes\n if (hasInsitu) {\n predResInsitu <- matrix(NA, ncol=length(nofGenes), nrow=ncol(dataInsitu))\n colnames(predResInsitu) <- nofGenes\n }\n \n for (p in 1:nofPeriods)\n print(c(selFollowUpTime[p+n-1]-selFollowUpTime[p],\n sum(notSelFollowUpTime %in% selFollowUpTime[p]:selFollowUpTime[p+n-1])))\n \n meanTimeForPeriod <- rep(NA, nofPeriods)\n for (p in 1:nofPeriods)\n meanTimeForPeriod[p] <- (selFollowUpTime[p+n-1]+selFollowUpTime[p])/2\n \n bestPeriod <- rep(NA, length(followUpTime))\n bestPeriod0 <- rep(NA, length(followUpTime0))\n bestPeriod[followUpTime < mean(meanTimeForPeriod[1:2])] <- 1\n bestPeriod0[followUpTime0 < mean(meanTimeForPeriod[1:2])] <- 1\n bestPeriod[followUpTime > mean(meanTimeForPeriod[(length(meanTimeForPeriod)-1):\n (length(meanTimeForPeriod))])] <- nofPeriods\n bestPeriod0[followUpTime0 > mean(meanTimeForPeriod[(length(meanTimeForPeriod)-1):\n (length(meanTimeForPeriod))])] <- nofPeriods\n if (hasInsitu) {\n bestPeriodInsitu <- rep(NA, length(followUpTimeInsitu))\n bestPeriodInsitu[followUpTimeInsitu < mean(meanTimeForPeriod[1:2])] <- 1\n bestPeriodInsitu[followUpTimeInsitu >\n mean(meanTimeForPeriod[(length(meanTimeForPeriod)-1):\n (length(meanTimeForPeriod))])] <- nofPeriods\n } else {\n bestPeriodInsitu <- c()\n }\n\n for (p in 2:(nofPeriods-1)) {\n bestPeriod[followUpTime >= mean(meanTimeForPeriod[(p-1):p]) &\n followUpTime <= mean(meanTimeForPeriod[(p):(p+1)])] <- p\n bestPeriod0[followUpTime0 >= mean(meanTimeForPeriod[(p-1):p]) &\n followUpTime0 <= mean(meanTimeForPeriod[(p):(p+1)])] <- p\n if (hasInsitu) {\n bestPeriodInsitu[followUpTimeInsitu >= mean(meanTimeForPeriod[(p-1):p]) &\n followUpTimeInsitu <= mean(meanTimeForPeriod[(p):(p+1)])] <- p\n }\n }\n \n for (p in unique(sort(c(bestPeriod, bestPeriod0, bestPeriodInsitu)))) {\n selInd <- (1:length(followUpTime))[followUpTime>=selFollowUpTime[p] &\n followUpTime<=selFollowUpTime[p+n-1]]\n selInd0 <- (1:length(followUpTime0))[followUpTime0>=selFollowUpTime[p] &\n followUpTime0<=selFollowUpTime[p+n-1]]\n \n leaveOut <- which(bestPeriod==p)\n leaveOut0 <- which(bestPeriod0==p)\n if (hasInsitu) {\n leaveOutInsitu <- which(bestPeriodInsitu==p)\n }\n \n ## Predict for group1\n if (length(leaveOut)>0)\n for (i in leaveOut) { \n curData <- data[, selInd[selInd!=i]]\n curWeights <- weights[, selInd[selInd!=i]]\n curFollowUpTime <- followUpTime[selInd[selInd!=i]]\n curData0 <- data0[, selInd0]\n curWeights0 <- weights0[, selInd0]\n curFollowUpTime0 <- followUpTime0[selInd0]\n \n mu1 <- computeMean(curData, curWeights)\n mu0 <- computeMean(curData0, curWeights0)\n var1 <- computeVar(curData, curWeights)\n var0 <- computeVar(curData0, curWeights0)\n \n weight <- as.numeric((mu1-mu0)/sqrt(var1 + var0))\n sortList <- sort.list(abs(weight), decreasing=TRUE)\n \n for (j in 1:length(nofGenes)) {\n selGenes <- sortList[1:nofGenes[j]]\n predRes[i, j] <- sum(weight[selGenes]*data[selGenes,i])\n }\n }\n \n ## Predict for group0\n if (length(leaveOut0)>0)\n for (i in leaveOut0) { \n curData <- data[, selInd] \n curWeights <- weights[, selInd] \n curFollowUpTime <- followUpTime[selInd]\n curData0 <- data0[, selInd0[selInd0!=i]]\n curWeights0 <- weights0[, selInd0[selInd0!=i]]\n curFollowUpTime0 <- followUpTime0[selInd0[selInd0!=i]]\n \n mu1 <- computeMean(curData, curWeights)\n mu0 <- computeMean(curData0, curWeights0)\n var1 <- computeVar(curData, curWeights)\n var0 <- computeVar(curData0, curWeights0)\n \n weight <- as.numeric((mu1-mu0)/sqrt(var1+var0))\n sortList <- sort.list(abs(weight), decreasing=TRUE)\n for (j in 1:length(nofGenes)) {\n selGenes <- sortList[1:nofGenes[j]]\n predRes0[i, j] <- sum(weight[selGenes]*data0[selGenes,i])\n }\n }\n \n ## Predict for groupInsitu\n if (hasInsitu) {\n if (length(leaveOutInsitu)>0) {\n curData <- data[, selInd] \n curWeights <- weights[, selInd] \n curFollowUpTime <- followUpTime[selInd]\n curData0 <- data0[, selInd0]\n curWeights0 <- weights0[, selInd0]\n curFollowUpTime0 <- followUpTime0[selInd0]\n \n mu1 <- computeMean(curData, curWeights)\n mu0 <- computeMean(curData0, curWeights0)\n var1 <- computeVar(curData, curWeights)\n var0 <- computeVar(curData0, curWeights0)\n \n weight <- as.numeric((mu1-mu0)/sqrt(var1+var0))\n sortList <- sort.list(abs(weight), decreasing=TRUE)\n \n for (i in leaveOutInsitu) { \n for (j in 1:length(nofGenes)) {\n selGenes <- sortList[1:nofGenes[j]]\n predResInsitu[i, j] <- sum(weight[selGenes]*dataInsitu[selGenes,i])\n }\n }\n }\n }\n }\n\n for (nGenes in nofGenes) {\n\n resMat <- computePredResMat(predRes[,paste(nGenes)], predRes0[,paste(nGenes)],\n followUpTime, followUpTime0)\n write.table(resMat, paste(strResMat, nGenes, \".txt\", sep=\"\"), sep=\"\\t\")\n \n ## === Print correctly and wrongly classified and p-value ===\n print(paste(\"Number of genes selected:\", nGenes))\n ##\n fn <- sum(!predRes[,paste(nGenes)]>0)\n tp <- sum(predRes[,paste(nGenes)]>0)\n fp <- sum(!predRes0[,paste(nGenes)]<0)\n tn <- sum(predRes0[,paste(nGenes)]<0)\n print(\"FN TP FP TN:\")\n print(c(fn, tp, fp, tn))\n print(\"p-value in Fisher test, all years:\")\n print(fisher.test(matrix(c(tp, fn, fp, tn), ncol=2, byrow=F), alternative=\"g\")$p.value)\n ## \n sel <- followUpTime>selPeriodInterval[1] & followUpTime<=selPeriodInterval[2]\n sel0 <- followUpTime0>selPeriodInterval[1] & followUpTime0<=selPeriodInterval[2]\n fn <- sum(!predRes[,paste(nGenes)][sel]>0)\n tp <- sum(predRes[,paste(nGenes)][sel]>0)\n fp <- sum(!predRes0[,paste(nGenes)][sel0]<0)\n tn <- sum(predRes0[,paste(nGenes)][sel0]<0)\n print(\"FN TP FP TN:\")\n print(c(fn, tp, fp, tn))\n print(paste(\"p-value in Fisher test, \", selPeriodStr, \":\", sep=\"\")) \n print(fisher.test(matrix(c(tp, fn, fp, tn), ncol=2, byrow=F), alternative=\"g\")$p.value)\n ##\n print(\"\")\n \n ## === Plot correctly and wrongly classified ===\n plotDataList <- dataList\n plotCorrectPredWithS <- predRes[,paste(nGenes)]>0\n plotCorrectPredWithoutS <- predRes0[,paste(nGenes)]<=0\n ##save(plotDataList, plotCorrectPredWithS, plotCorrectPredWithoutS,\n ## file=paste(strFollowUpTime, nGenes, \".pdf.R\", sep=\"\"))\n plotFollowUpTimesWithPredRes(dataList, predRes[,paste(nGenes)]>0,\n predRes0[,paste(nGenes)]<=0, \n paste(strFollowUpTime, nGenes, \".pdf\", sep=\"\"))\n \n ## === Plot fraction of correctly classified ===\n \n pdf(paste(strPlotFracCorr, nGenes, \".pdf\", sep=\"\"), height=7, width=15)\n \n tVecStart <- min(followUpTime):(max(followUpTime)-m2)\n tVecStop <- tVecStart+m2\n tVecMean <- tVecStart+m\n isCorr <- predRes[,paste(nGenes)]>0\n fracCorr <- rep(NA, length(tVecStart))\n for (i in 1:length(tVecStart))\n fracCorr[i] <- mean(isCorr[followUpTime>=tVecStart[i] & followUpTime<=tVecStop[i]])\n keep <- !is.na(fracCorr)\n ##\n plotX <- tVecMean[keep]\n plotY <- runmed(fracCorr[keep],m2)\n plotXlim <- rev(range(dataList$followUpTime))\n ##save(plotX, plotY, plotXlim, file=paste(strPlotFracCorr, nGenes, \".pdf.red.R\", sep=\"\"))\n ##\n plot(tVecMean[keep], runmed(fracCorr[keep],m2), xlim=rev(range(dataList$followUpTime)),\n type=\"l\", ylim =c(0,1), xlab=\"Follow up time (days)\", ylab=\"Fraction correctly classified\",\n cex=1.4, cex.axis=1.4, cex.lab=1.4, col=2)\n \n tVecStart <- min(followUpTime0):(max(followUpTime0)-m2)\n tVecStop <- tVecStart+m2\n tVecMean <- tVecStart+m\n isCorr <- predRes0[,paste(nGenes)]<=0\n fracCorr <- rep(NA, length(tVecStart))\n for (i in 1:length(tVecStart))\n fracCorr[i] <- mean(isCorr[followUpTime0>=tVecStart[i] & followUpTime0<=tVecStop[i]])\n keep <- !is.na(fracCorr)\n ##\n plotX <- tVecMean[keep]\n plotY <- runmed(fracCorr[keep],m2)\n ##save(plotX, plotY, plotXlim, file=paste(strPlotFracCorr, nGenes, \".pdf.black.R\", sep=\"\"))\n ##\n lines(tVecMean[keep], runmed(fracCorr[keep], m2), cex=1.4, cex.axis=1.4, cex.lab=1.4, col=1)\n \n abline(h=0.5, lty=2)\n for (i in 0:7)\n abline(v=365*i)\n \n dev.off()\n }\n}\n\n", "meta": {"hexsha": "d4a1e9947538c51532ae4fa0b672f6f9a3b7c862", "size": 11857, "ext": "r", "lang": "R", "max_stars_repo_path": "predictDiagnosis.r", "max_stars_repo_name": "theresenoest/Local_in_time_statistics", "max_stars_repo_head_hexsha": "88e0437b2f480ed26de1ddde3e1a08b667ff9070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-12-07T11:16:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T19:17:48.000Z", "max_issues_repo_path": "predictDiagnosis.r", "max_issues_repo_name": "theresenoest/Local_in_time_statistics", "max_issues_repo_head_hexsha": "88e0437b2f480ed26de1ddde3e1a08b667ff9070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "predictDiagnosis.r", "max_forks_repo_name": "theresenoest/Local_in_time_statistics", "max_forks_repo_head_hexsha": "88e0437b2f480ed26de1ddde3e1a08b667ff9070", "max_forks_repo_licenses": ["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.9225589226, "max_line_length": 100, "alphanum_fraction": 0.6060554946, "num_tokens": 3647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3420619233238505}} {"text": "#!/usr/bin/env Rscript\r\n#----------------------------------------------------------------------------------------------------------------#\r\n# Filename:\r\n# ppa_sibgc_v1.r\r\n# Description:\r\n# R implementation of the Perfect Plasticity Approximation (PPA) with simply biogeochemistry (PPA-SiBGC).\r\n# Version:\r\n# 1.0\r\n# Authors:\r\n# Adam Erickson, Washington State University\r\n# Nikolay Strigul, Washington State University\r\n# Modified:\r\n# June 30, 2018\r\n# Procedure:\r\n# (1) Generate constant growth, mortality, and regeneration coefficients from plot data\r\n# (2) Generate above- and below-ground stoichiometric coefficients from databases\r\n# (3) Run the Sortie-PPA model:\r\n# (*) Generate cohorts from tree inventory data\r\n# (*) Initialize values for allometry, biomass, C, and N from species, type, DBH\r\n# (a) Soil respiration\r\n# (b) Regeneratation\r\n# (c) Sort by height descending\r\n# (d) Calculate cumulative crown area (CCA)\r\n# (e) Calculate Z* height and nearest cohort\r\n# (f) Mortality\r\n# (g) Growth\r\n# (h) Allometry\r\n# (i) Biomass fractions\r\n# (j) Carbon fractions\r\n# (k) Nitrogen fractions\r\n# (l) Save yearly results to CSV\r\n# (m) Save final results to CSV\r\n# (4) Compare model results against empirical data\r\n# Notes:\r\n# Sortie-PPA is based on the assumption that tree canopies are perfectly plastic. This reduces\r\n# the variance in canopy join heights to zero, creating a single canopy join height known as z*.\r\n# The approximation allows for model simplification and mathematical tractability. The spatial\r\n# location of trees is discarded. Growth and mortality are modeled by their mean values for each\r\n# species and type (adults = above z*; saplings = below z*). Coefficients are used to modify\r\n# growth rates per the fraction of light received by trees above and below the z* threshold.\r\n# Aboveground biomass is modeled using equations from Chojnacky, Heath, and Jenkins (2014).\r\n# Belowground biomass as well as C,N dynamics are modeled using allometry and stoichiometry.\r\n# Examples:\r\n# Rscript --vanilla ppa_v50.r\r\n# Rscript --vanilla ppa_v50.r --wd /Users/null/test --verbose\r\n#----------------------------------------------------------------------------------------------------------------#\r\nVersion <- \"5.0\"\r\n\r\n# Debugging\r\noptions(error=quote({dump.frames(to.file=TRUE); q()}))\r\n\r\n# Print banner and pause\r\nBanner <- readLines(\"sortie_ppa_ansi_shadow.txt\")\r\ncat(Banner, sep=\"\\n\")\r\n\r\n# Print version\r\nmessage(\"\")\r\nmessage(\"Authors: Adam Erickson, Nikolay Strigul\")\r\nmessage(paste(\"Version:\", Version, \"\\n\"))\r\nSys.sleep(0)\r\n\r\n# Remove existing outputs\r\noutputs_files <- dir(\"outputs\", recursive=FALSE, full.names=TRUE)\r\noutputs_deleted <- file.remove(outputs_files)\r\n\r\n# Fetch trailing command line arguments\r\nargs <- commandArgs(trailingOnly=TRUE)\r\n\r\n# Default verbosity setting\r\nVerbose <- FALSE\r\n\r\n# Set working directory\r\nif (length(args) == 0) {\r\n message(paste0(\"Working directory: \", getwd()))\r\n} else if (length(args) == 1) {\r\n Verbose <- args[1] %in% c(\"--v\", \"--verbose\")\r\n stopifnot(Verbose)\r\n} else if (length(args) == 2) {\r\n flag <- args[1]\r\n stopifnot(flag %in% c(\"--wd\", \"--dir\"))\r\n folder <- args[2]\r\n if (flag==\"--wd\" || flag==\"--dir\") {\r\n setwd(folder)\r\n message(paste(\"Working directory:\", getwd()))\r\n } else {\r\n message(\"Flag not recognized.\")\r\n }\r\n} else if (length(args) == 3) {\r\n flag <- args[1]\r\n stopifnot(flag %in% c(\"--wd\", \"--dir\"))\r\n folder <- args[2]\r\n setwd(folder)\r\n message(paste(\"Working directory:\", getwd()))\r\n Verbose <- args[3] %in% c(\"--v\", \"--verbose\")\r\n stopifnot(Verbose)\r\n} else {\r\n stop(\"Error: Only 0 or 2 arguments may be passed.\", call.=FALSE)\r\n}\r\n\r\n# Libraries #\r\n\r\n# Functions #\r\n\r\n# Round to the nearest integer by step\r\nround_int <- function(x, step) { \r\n return(step * round(x / step))\r\n}\r\n\r\n# Bin trees into cohorts by rounding DBH to the nearest cm; check n-trees\r\n# Expects CSV file with species, type, dbh, age (optional)\r\nGenerateCohorts <- function(Trees, interval=1) {\r\n n_trees <- nrow(Trees)\r\n Trees$dbh <- round_int(Trees$dbh, interval)\r\n if(\"age\" %in% tolower(colnames(Trees))) {\r\n age <- aggregate(Trees$age, by=list(Trees$species, Trees$type, Trees$dbh), FUN=mean)\r\n colnames(age) <- c(\"species\",\"type\",\"dbh\",\"age\")\r\n Trees <- subset(Trees, select= -c(age))\r\n Trees <- merge(Trees, age, by=c(\"species\",\"type\",\"dbh\"))\r\n }\r\n cohorts <- data.frame(table(Trees$species, Trees$type, Trees$dbh))\r\n colnames(cohorts) <- c(\"species\",\"type\",\"dbh\",\"n_trees\")\r\n cohorts$n_trees <- cohorts$n_trees + 1\r\n Trees <- merge(Trees, cohorts, by=c(\"species\",\"type\",\"dbh\"))\r\n Trees <- Trees[!duplicated(Trees[,c(\"species\",\"type\",\"dbh\")]), ]\r\n Trees <- Trees[Trees$dbh > 0 & !is.na(Trees$n_trees), ]\r\n Trees$id <- 1:nrow(Trees)\r\n if (\"age\" %in% tolower(colnames(Trees))) {\r\n Trees <- Trees[, c(\"id\",\"species\",\"type\",\"age\",\"dbh\",\"n_trees\")]\r\n } else {\r\n Trees <- Trees[, c(\"id\",\"species\",\"type\",\"dbh\",\"n_trees\")]\r\n }\r\n message(paste(n_trees, \"trees merged to\", nrow(Trees), \"cohorts containing\",\r\n sum(Trees$n_trees), \"trees\"))\r\n return(Trees)\r\n}\r\n\r\n# Create biomass, C, and N compartments\r\nInitialize <- function(Trees, ...) {\r\n # Create columns\r\n Trees$height <- NA\r\n Trees$crown_l <- NA\r\n Trees$crown_r <- NA\r\n Trees$crown_a <- NA\r\n Trees$ba <- NA\r\n Trees$crown_a_cumsum <- NA\r\n Trees$biomass_ag <- NA\r\n Trees$biomass_stem <- NA\r\n Trees$biomass_branch <- NA\r\n Trees$biomass_leaf <- NA\r\n Trees$biomass_root_coarse <- NA\r\n Trees$biomass_root_fine <- NA\r\n Trees$biomass_soil <- NA\r\n Trees$biomass_bg <- NA\r\n Trees$biomass_total <- NA\r\n Trees$c_ag <- NA\r\n Trees$c_bg <- NA\r\n Trees$c_total <- NA\r\n Trees$anpp <- NA\r\n Trees$n_ag <- NA\r\n Trees$n_bg <- NA\r\n Trees$n_total <- NA\r\n Trees$annp <- NA\r\n # Update each species and type; vectorized\r\n for (species in unique(Trees$species)) {\r\n if (!species %in% AllometryLUT$species) { stop(\"Species not found in allometry table\") }\r\n s <- Trees$species==species\r\n for (type in unique(Trees[s,]$type)) {\r\n st <- Trees$species==species & Trees$type==type\r\n index <- AllometryLUT$species==species & AllometryLUT$type==type\r\n allometry <- AllometryLUT[index,]\r\n Trees[st,]$height <- 1.35 + (30-1.35) * (1-exp(-(allometry$h_coeff * Trees[st,]$dbh)))\r\n Trees[st,]$height <- ifelse(Trees[st,]$height > 30, 30, Trees[st,]$height) # limit height to 30m\r\n Trees[st,]$type <- ifelse(Trees[st,]$dbh > 10, \"adult\", \"sapling\")\r\n Trees[st,]$crown_l <- allometry$cd * Trees[st,]$dbh\r\n Trees[st,]$crown_r <- allometry$cr1 * Trees[st,]$dbh^allometry$cr2\r\n Trees[st,]$crown_a <- Trees[st,]$crown_r^2 * pi\r\n Trees[st,]$ba <- Trees[st,]$dbh^2 * 0.00007854 # forester's constant for DBH (cm); m2\r\n }\r\n # Biomass allocation or partitioning\r\n if (!species %in% BiomassLUT$species) { stop(\"Species not found in biomass table\") }\r\n index <- BiomassLUT$species==species\r\n biomass <- BiomassLUT[index,]\r\n if (CohortMode) {\r\n Trees[s,]$biomass_ag <- exp(biomass$b0 + biomass$b1 * log(Trees[s,]$dbh)) * Trees[s,]$n_trees\r\n } else {\r\n Trees[s,]$biomass_ag <- exp(biomass$b0 + biomass$b1 * log(Trees[s,]$dbh))\r\n }\r\n Trees[s,]$biomass_stem <- Trees[s,]$biomass_ag * biomass$fraction_stem\r\n Trees[s,]$biomass_branch <- Trees[s,]$biomass_ag * biomass$fraction_branch\r\n Trees[s,]$biomass_leaf <- Trees[s,]$biomass_ag * biomass$fraction_leaf\r\n Trees[s,]$biomass_root_coarse <- Trees[s,]$biomass_ag * exp(-1.4485 - 0.03476 * log(Trees[s,]$dbh))\r\n Trees[s,]$biomass_root_fine <- Trees[s,]$biomass_ag * exp(-1.8629 - 0.77534 * log(Trees[s,]$dbh))\r\n Trees[s,]$biomass_soil <- Trees[s,]$biomass_ag * biomass$fraction_soil\r\n Trees[s,]$biomass_bg <- Trees[s,]$biomass_root_coarse + Trees[s,]$biomass_root_fine +\r\n Trees[s,]$biomass_soil\r\n Trees[s,]$biomass_total <- Trees[s,]$biomass_ag + Trees[s,]$biomass_bg\r\n # C fraction\r\n #index <- CarbonLUT$species==species\r\n carbon <- CarbonLUT #[index,]\r\n Trees[s,]$c_ag <- Trees[s,]$biomass_ag *\r\n ((biomass$fraction_stem * carbon$fraction_stem) +\r\n (biomass$fraction_branch * carbon$fraction_branch) +\r\n (biomass$fraction_leaf * carbon$fraction_leaf))\r\n Trees[s,]$c_bg <- Trees[s,]$biomass_ag *\r\n ((biomass$fraction_root * carbon$fraction_root) +\r\n (biomass$fraction_soil * carbon$fraction_soil))\r\n Trees[s,]$c_total <- Trees[s,]$c_ag + Trees[s,]$c_bg\r\n Trees[s,]$anpp <- NA\r\n # C:N stoichiometry\r\n if (!species %in% StoichiometryLUT$species) { stop(\"Species not found in stoichiometry table\") }\r\n index <- StoichiometryLUT$species==species\r\n stoichiometry <- StoichiometryLUT[index,]\r\n Trees[s,]$n_ag <- Trees[s,]$c_ag /\r\n ((biomass$fraction_stem * stoichiometry$cn_stem) +\r\n (biomass$fraction_branch * stoichiometry$cn_branch) +\r\n (biomass$fraction_leaf * stoichiometry$cn_leaf))\r\n Trees[s,]$n_bg <- Trees[s,]$c_bg /\r\n ((biomass$fraction_root * stoichiometry$cn_root) +\r\n (biomass$fraction_soil * stoichiometry$cn_soil))\r\n Trees[s,]$n_total <- Trees[s,]$n_ag + Trees[s,]$n_bg\r\n Trees[s,]$annp <- NA\r\n }\r\n return(Trees)\r\n}\r\n\r\n# Ensure column names and tree type are lower case\r\nensure_lowercase <- function(Trees) {\r\n colnames(Trees) <- tolower(colnames(Trees))\r\n Trees$type <- tolower(Trees$type)\r\n return(Trees)\r\n}\r\n\r\n# Check if year is a leap year (366 days instead of 365)\r\nleap_year <- function(year) {\r\n return(ifelse((year %%4 == 0 & year %%100 != 0) | year %%400 == 0, TRUE, FALSE))\r\n}\r\n\r\n# Soil respiration, monthly mean; heterotrophic + autotrophic\r\n# g C m-2 day-1; kg C m-2 day-1\r\n# Parameters:\r\n# Ta = monthly mean temperature (°C)\r\n# P = monthly mean precipitation (cm)\r\n# Raich, Potter, Bhagawati, 2002, Interannual variability in global soil respiration, 1980-94, Global Change Biology, 8, pp. 800-12.\r\n# https://onlinelibrary.wiley.com/doi/abs/10.1046/j.1365-2486.2002.00511.x\r\nrespiration_soil <- function(Ta, P) {\r\n if (Ta < -13.3) {\r\n Rs <- 0\r\n } else {\r\n if (Ta > 33.5) { Ta <- 33.5 } # bound the temperature response\r\n e <- exp(1) # Euler's constant\r\n Q <- 0.05452 # soil respiration rate change wrt temperature (°C-1)\r\n F <- 1.250 # soil respiration rate at 0°C (g C m-2 day-1)\r\n K <- 4.259 # hyperbolic respiration-rainfall curve half-saturation constant (mm month-1)\r\n Rs <- F * e^(Q * Ta) * (P / (K + P))\r\n }\r\n return(Rs / 1000)\r\n}\r\n\r\n# Simple SOC model\r\n# Mg C ha-1 cm-1; kg C m-2; midpoint of profile depth; Approximates integral in 1 cm steps\r\n# Domke et al. (2017) Toward inventory-based estimates of soil organic carbon in forests of the United States, Ecological Applications, 27(4), pp. 1223–1235.\r\n# https://www.fs.fed.us/nrs/pubs/jrnl/2017/nrs_2017_domke_001.pdf\r\nsoc_depth = function(order, depth_cm=100) {\r\n soc_table = data.frame(\r\n order = c(\"All\",\"Alfisols\",\"Andisols\",\"Aridisols\",\"Entisols\",\"Histosols\",\"Inceptisols\",\r\n \"Mollisols\",\"Spodosols\",\"Ultisols\",\"Vertisols\"),\r\n intercept = c(1.1795,1.1122,1.3837,0.2065,0.9300,1.6227,1.1631,1.0163,1.4262,1.1576,0.5145),\r\n slope = c(-0.8228,-0.8330,-0.8425,-0.1300,-0.7207,-1.0109,-0.7331,-0.6214,-0.9801,-0.8867,-0.2427)\r\n )\r\n coeffs = as.numeric(soc_table[soc_table$order==order,][,c(\"intercept\",\"slope\")])\r\n soc = sapply(seq(1, depth_cm, 1), function(x) 10^(coeffs[1] + coeffs[2] * log10(x)))\r\n soc = sum(soc) / 10 # convert to kg m-2 integrated over depth\r\n return(soc)\r\n}\r\n\r\n# Time #\r\nstart_time <- proc.time()\r\nloop_times <- c()\r\n\r\n# Data #\r\n\r\n# Load lookup tables (LUTs) into memory; expects CSV files in lut folder\r\nConfiguration <- read.csv(\"configuration.csv\", stringsAsFactors=FALSE, nrows=1)\r\nTrees <- read.csv(\"trees.csv\", stringsAsFactors=FALSE)\r\nClimate <- read.csv(\"climate.csv\", stringsAsFactors=FALSE)\r\nGrowthLUT <- read.csv(\"lut/growth.csv\", stringsAsFactors=FALSE)\r\nMortalityLUT <- read.csv(\"lut/mortality.csv\", stringsAsFactors=FALSE)\r\nRegenerationLUT <- read.csv(\"lut/regeneration.csv\", stringsAsFactors=FALSE)\r\nAllometryLUT <- read.csv(\"lut/allometry.csv\", stringsAsFactors=FALSE)\r\nBiomassLUT <- read.csv(\"lut/biomass.csv\", stringsAsFactors=FALSE)\r\nStoichiometryLUT <- read.csv(\"lut/stoichiometry.csv\", stringsAsFactors=FALSE)\r\nCarbonLUT <- read.csv(\"lut/carbon.csv\", stringsAsFactors=FALSE, nrows=1)\r\n\r\n# Model #\r\n\r\n# Optional: process in parallel\r\n#nCores <- as.integer(Configuration$n_cores)\r\n#if (nCores > 1) {\r\n# library(doParallel)\r\n# cl <- parallel::makeCluster(nCores)\r\n# doParallel::registerDoParallel(cl)\r\n#}\r\n\r\n# Optional: Generate cohorts from initial tree list\r\nCohortMode <- as.logical(Configuration$cohort_mode)\r\nif (CohortMode == TRUE) {\r\n message(\"Generating cohorts...\")\r\n Trees <- GenerateCohorts(Trees)\r\n}\r\n\r\n# Initialize tree biomass\r\nmessage(\"Initializing...\")\r\nTrees <- Initialize(Trees)\r\n\r\n# Ensure column names and tree type are lower case\r\nTrees <- ensure_lowercase(Trees)\r\n\r\n# Number of years to run model; e.g., 2000-2049 (50 years)\r\nStartYear <- as.numeric(Configuration$start_year) \r\nEndYear <- as.numeric(Configuration$end_year)\r\nYears <- StartYear:EndYear # 200 years\r\n\r\n# Amount of light suppressed cohorts receive\r\nUnderstoryAdult <- as.numeric(Configuration$understory_adult) # 0.1\r\nUnderstorySapling <- as.numeric(Configuration$understory_sapling) # 0.7\r\n\r\n# id placeholder\r\nid_holder <- nrow(Trees)\r\n\r\n# Run the simulation\r\nmessage(\"Starting simulation...\")\r\nmessage(\"=========================================================================\")\r\nfor (year in Years) {\r\n \r\n loop_start_time <- proc.time()\r\n \r\n if (Verbose) {\r\n message(\"=========================================================================\")\r\n message(paste(\"Year:\", year))\r\n message(paste(\"n-Trees:\", nrow(Trees)))\r\n message(\"=========================================================================\")\r\n }\r\n\r\n # Append or update year; vectorized\r\n Trees$year <- year\r\n\r\n # Increment tree age; vectorized; regeneration yields age 0\r\n Trees$age <- Trees$age + 1\r\n\r\n # Calculate soil respiration\r\n if (Verbose) {\r\n message(\"Computing soil respiration...\")\r\n }\r\n climate <- Climate[Climate$year==year,]\r\n n_days <- list(\r\n \"1\" = 31,\r\n \"2\" = ifelse(leap_year(year), 29, 28),\r\n \"3\" = 31,\r\n \"4\" = 30,\r\n \"5\" = 31,\r\n \"6\" = 30,\r\n \"7\" = 31,\r\n \"8\" = 31,\r\n \"9\" = 30,\r\n \"10\" = 31,\r\n \"11\" = 30,\r\n \"12\" = 31\r\n )\r\n Rs_month <- c()\r\n for (month in climate$month) {\r\n month_days <- as.numeric(n_days[as.character(month)])\r\n month_i <- climate[climate$month==month,]\r\n Rs <- respiration_soil(Ta=month_i$temperature, P=month_i$precipitation)\r\n Rs <- Rs * month_days\r\n Rs_month <- c(Rs_month, Rs)\r\n }\r\n Rs_year <- sum(Rs_month) # * Configuration$field_area\r\n respiration_df <- data.frame(year=year, r_soil=Rs_year)\r\n\r\n # Calculate soil organic C and N\r\n c_so <- soc_depth(order=Configuration$soil_order, depth_cm=100)\r\n n_so <- c_so / mean(StoichiometryLUT$cn_soil, na.rm=TRUE)\r\n som_df <- data.frame(year=year, c_so=c_so, n_so=n_so)\r\n\r\n # Sort trees by descending height; vectorized\r\n if (Verbose) {\r\n message(\"Sorting...\")\r\n }\r\n Trees <- Trees[order(Trees$height, decreasing=TRUE), ]\r\n\r\n # Calculate cumulative crown area; vectorized\r\n if (Verbose) {\r\n message(\"Calculating culumative crown area...\")\r\n }\r\n if (CohortMode) {\r\n Trees$crown_a_cumsum <- cumsum(Trees$crown_a * Trees$n_trees)\r\n } else {\r\n Trees$crown_a_cumsum <- cumsum(Trees$crown_a)\r\n }\r\n\r\n # Calculate z* and closest cohort; vectorized\r\n if (Verbose) {\r\n message(\"Calculating Z*...\")\r\n }\r\n index <- which.min(abs(Trees$crown_a_cumsum - Configuration$field_area))\r\n zstar_df <- Trees[index,]\r\n if (Verbose) {\r\n message(paste(\"Z* height:\", zstar_df$height))\r\n }\r\n\r\n # Dataframe placeholders\r\n mortality_df <- data.frame(matrix(ncol=nrow(Trees), nrow=0))\r\n colnames(mortality_df) <- colnames(Trees)\r\n regeneration_df <- data.frame(matrix(ncol=nrow(Trees), nrow=0))\r\n colnames(regeneration_df) <- colnames(Trees)\r\n\r\n # Loop over each species\r\n for (species in unique(Trees$species)) {\r\n\r\n # Skip species not found in lookup tables\r\n if (!species %in% GrowthLUT$species) {\r\n next\r\n }\r\n\r\n # Species index\r\n s <- Trees$species==species\r\n \r\n # Regeneration; species\r\n if (Verbose) {\r\n message(\"Applying regeneration...\")\r\n }\r\n n_replicates <- length(which(s))\r\n index <- RegenerationLUT$species==species\r\n n_saplings <- RegenerationLUT[index,]$mean\r\n # new sapling used in regeneration\r\n new_sapling <- data.frame(species=species, type=\"sapling\", age=0, dbh=1,\r\n height=2, crown_r=0.1, crown_l=0.845, crown_a=0.0314, ba=0.00008,\r\n crown_a_cumsum=NA, biomass_ag=NA, biomass_stem=NA, biomass_branch=NA,\r\n biomass_leaf=NA, biomass_root_coarse=NA, biomass_root_fine=NA,\r\n biomass_soil=NA, biomass_bg=NA, biomass_total=NA, c_ag=NA, c_bg=NA,\r\n c_total=NA, anpp=NA, n_ag=NA, n_bg=NA, n_total=NA, annp=NA, year=year)\r\n if (CohortMode & n_replicates > 0) {\r\n new_sapling$id <- id_holder\r\n new_sapling$n_trees <- n_saplings\r\n Trees <- rbind(Trees, new_sapling)\r\n regeneration_df <- rbind(regeneration_df, new_sapling)\r\n id_holder <- id_holder + 1 #+ n_replicates\r\n } else if (n_replicates > 0){\r\n n_trees <- nrow(trees)\r\n new_saplings <- do.call(rbind, replicate(n_replicates * n_saplings, new_sapling, simplify=FALSE))\r\n new_saplings$id <- id_holder:(id_holder + (n_replicates * n_saplings) - 1)\r\n Trees <- rbind(Trees, new_saplings)\r\n regeneration_df <- rbind(regeneration_df, new_saplings)\r\n id_holder <- id_holder + (n_replicates * n_saplings)\r\n }\r\n\r\n # Recalculate species index after regeneration\r\n s <- Trees$species==species\r\n\r\n # Loop over each type within each species\r\n for (type in unique(Trees[s,]$type)) {\r\n\r\n # Species and type index\r\n st <- Trees$species==species & Trees$type==type\r\n\r\n # Mortality; species & type\r\n if (Verbose) {\r\n message(\"Applying mortality...\")\r\n }\r\n index <- MortalityLUT$species==species & MortalityLUT$type==type\r\n mortality <- MortalityLUT[index,]\r\n random_uniform <- runif(1, min=0, max=1)\r\n if (random_uniform < mortality$probability) {\r\n kill_fraction <- runif(1, min=0, max=1) # random uniform\r\n if (CohortMode) {\r\n kill_n <- round(nrow(Trees[st,]) * kill_fraction)\r\n if (kill_n > 0) {\r\n # Kill fraction of cohorts\r\n kill_index <- sample(which(st), kill_n, replace=FALSE)\r\n mortality_df <- rbind(mortality_df, Trees[kill_index,])\r\n Trees <- Trees[-kill_index,] # kill trees\r\n # Optional: kill fraction within cohorts and then remove dead cohorts\r\n #Trees[st,]$n_trees <- Trees[st,]$n_trees - kill_n # kill trees\r\n #mortality_df <- cbind(data.frame(year=year), Trees[st,])\r\n #mortality_df$n_trees <- round(mortality_df$n_trees * kill_fraction)\r\n }\r\n #dead_cohorts <- Trees$n_trees < 1 | is.na(Trees$n_trees) | is.na(Trees$dbh)\r\n #if(any(dead_cohorts)) {\r\n # Trees <- Trees[-which(dead_cohorts),] # remove dead trees/cohorts\r\n # message(\"Removal\")\r\n # stopifnot(!anyNA(Trees[st,]$dbh) | !anyNA(Trees[st,]$n_trees)) # \"PIAB\" \"sapling\"\r\n #}\r\n } else {\r\n kill_n <- round(nrow(Trees[st,]) * kill_fraction)\r\n if (kill_n > 0) {\r\n kill_index <- sample(which(st), kill_n, replace=FALSE)\r\n mortality_df <- rbind(mortality_df, Trees[kill_index,])\r\n Trees <- Trees[-kill_index,] # kill trees\r\n }\r\n }\r\n }\r\n\r\n # Recalculate species and type index after mortality\r\n st <- Trees$species==species & Trees$type==type\r\n\r\n # Skip ahead if species or type is all dead\r\n if (nrow(Trees[st,]) < 1) {\r\n next\r\n }\r\n\r\n # Growth; species & type\r\n index <- GrowthLUT$species==species & GrowthLUT$type==type\r\n growth <- GrowthLUT[index,]\r\n if (type==\"adult\") {\r\n Trees[st,]$dbh <- ifelse(Trees[st,]$crown_a_cumsum < Configuration$field_area,\r\n Trees[st,]$dbh + growth$mean,\r\n Trees[st,]$dbh + growth$mean * UnderstoryAdult)\r\n } else if (type==\"sapling\") {\r\n Trees[st,]$dbh <- Trees[st,]$dbh + growth$mean * UnderstorySapling\r\n } else {\r\n message(\"Error: Type not recognized\")\r\n }\r\n\r\n # Allometry; species & type\r\n if (Verbose) {\r\n message(\"Calculating allometry...\")\r\n }\r\n index <- AllometryLUT$species==species & AllometryLUT$type==type\r\n allometry <- AllometryLUT[index,]\r\n Trees[st,]$height <- 1.35 + (30-1.35) * (1-exp(-(allometry$h_coeff * Trees[st,]$dbh)))\r\n Trees[st,]$height <- ifelse(Trees[st,]$height > 30, 30, Trees[st,]$height) # limit height to 30m\r\n Trees[st,]$type <- ifelse(Trees[st,]$dbh > 10, \"adult\", \"sapling\")\r\n Trees[st,]$crown_l <- allometry$cd * Trees[st,]$dbh\r\n Trees[st,]$crown_r <- allometry$cr1 * Trees[st,]$dbh^allometry$cr2\r\n Trees[st,]$crown_a <- Trees[st,]$crown_r^2 * pi\r\n Trees[st,]$ba <- Trees[st,]$dbh^2 * 0.00007854 # forester's constant for DBH (cm); m2\r\n } # end type loop\r\n\r\n # Calculate species index after regeneration and mortality\r\n s <- Trees$species==species\r\n\r\n # Skip ahead if species is all dead\r\n if (nrow(Trees[s,]) < 1) {\r\n next\r\n }\r\n\r\n # Biomass expansion factors and allocation or partitioning; species\r\n # DBH to AGB and AGB to BGB (Chojnacky, Heath, Jenkins, 2014)\r\n # To add...? BGB to leaf and steam (Enquist and Niklas, 2002)\r\n if (Verbose) {\r\n message(\"Calculating biomass...\")\r\n }\r\n index <- BiomassLUT$species==species\r\n biomass <- BiomassLUT[index,]\r\n if (CohortMode) {\r\n Trees[s,]$biomass_ag <- exp(biomass$b0 + biomass$b1 * log(Trees[s,]$dbh)) * Trees[s,]$n_trees\r\n } else {\r\n Trees[s,]$biomass_ag <- exp(biomass$b0 + biomass$b1 * log(Trees[s,]$dbh))\r\n }\r\n Trees[s,]$biomass_stem <- Trees[s,]$biomass_ag * biomass$fraction_stem\r\n Trees[s,]$biomass_branch <- Trees[s,]$biomass_ag * biomass$fraction_branch\r\n Trees[s,]$biomass_leaf <- Trees[s,]$biomass_ag * biomass$fraction_leaf\r\n Trees[s,]$biomass_root_coarse <- Trees[s,]$biomass_ag * exp(-1.4485 - 0.03476 * log(Trees[s,]$dbh))\r\n Trees[s,]$biomass_root_fine <- Trees[s,]$biomass_ag * exp(-1.8629 - 0.77534 * log(Trees[s,]$dbh))\r\n Trees[s,]$biomass_soil <- Trees[s,]$biomass_ag * biomass$fraction_soil\r\n Trees[s,]$biomass_bg <- Trees[s,]$biomass_root_coarse + Trees[s,]$biomass_root_fine +\r\n Trees[s,]$biomass_soil\r\n Trees[s,]$biomass_total <- Trees[s,]$biomass_ag + Trees[s,]$biomass_bg\r\n\r\n # Year naught total C and N for ANPP and ANNP calculations\r\n c_total_previous <- Trees[s,]$c_total\r\n n_total_previous <- Trees[s,]$n_total\r\n\r\n # C fraction; species\r\n if (Verbose) {\r\n message(\"Calculating C fraction...\")\r\n }\r\n #index <- CarbonLUT$species==species\r\n carbon <- CarbonLUT #[index,]\r\n Trees[s,]$c_ag <- Trees[s,]$biomass_ag * \r\n (biomass$fraction_stem * carbon$fraction_stem) +\r\n (biomass$fraction_branch * carbon$fraction_branch) +\r\n (biomass$fraction_leaf * carbon$fraction_leaf)\r\n Trees[s,]$c_bg <- Trees[s,]$biomass_ag *\r\n (biomass$fraction_root * carbon$fraction_root) +\r\n (biomass$fraction_soil * carbon$fraction_soil)\r\n Trees[s,]$c_total <- Trees[s,]$c_ag + Trees[s,]$c_bg\r\n if (year > min(Years)) {\r\n Trees[s,]$anpp <- Trees[s,]$c_total - c_total_previous\r\n }\r\n # C:N stoichiometry; species\r\n if (Verbose) {\r\n message(\"Calculating N fraction...\")\r\n }\r\n index <- StoichiometryLUT$species==species\r\n stoichiometry <- StoichiometryLUT[index,]\r\n Trees[s,]$n_ag <- Trees[s,]$c_ag /\r\n (biomass$fraction_stem * stoichiometry$cn_stem) +\r\n (biomass$fraction_branch * stoichiometry$cn_branch) +\r\n (biomass$fraction_leaf * stoichiometry$cn_leaf)\r\n Trees[s,]$n_bg <- Trees[s,]$c_bg /\r\n (biomass$fraction_root * stoichiometry$cn_root) +\r\n (biomass$fraction_soil * stoichiometry$cn_soil)\r\n Trees[s,]$n_total <- Trees[s,]$n_ag + Trees[s,]$n_bg\r\n if (year > min(Years)) {\r\n Trees[s,]$annp <- Trees[s,]$n_total - n_total_previous\r\n }\r\n } # end species loop\r\n\r\n # Fix order of regeneration_df columns\r\n regeneration_df <- regeneration_df[,colnames(Trees)]\r\n\r\n # Calculate NEE and add to fluxes; NEE calculation based on Equation 1 in:\r\n # Clark et al. (2001) Measuring Net Primary Production in Forests: Concepts and Field Methods,\r\n # Ecological Applications, 11(2), pp. 356-370.\r\n # and\r\n # Reichstein et al. (2005) On the separation of net ecosystem exchange into assimilation and\r\n # ecosystem respiration: review and improved algorithm, Global Change Biology, 11, pp. 1424–1439.\r\n # Convert C to CO2 in ANPP\r\n fluxes_df <- data.frame(\r\n year = year,\r\n nee = (respiration_df$r_soil * Configuration$field_area) - sum(Trees$anpp, na.rm=TRUE),\r\n r_soil = (respiration_df$r_soil * Configuration$field_area)\r\n )\r\n\r\n # Save annual tree/cohort results\r\n write.csv(Trees, file=paste0(\"outputs/trees_\", year, \".csv\"), row.names=FALSE,\r\n fileEncoding=\"UTF-8\")\r\n\r\n # Append results to CSV\r\n header_boolean <- year == Years[1]\r\n\r\n suppressWarnings(write.table(som_df, file=\"outputs/som.csv\",\r\n append=TRUE, col.names=header_boolean, row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\"))\r\n suppressWarnings(write.table(fluxes_df, file=\"outputs/fluxes.csv\",\r\n append=TRUE, col.names=header_boolean, row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\"))\r\n suppressWarnings(write.table(zstar_df, file=\"outputs/zstar.csv\",\r\n append=TRUE, col.names=header_boolean, row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\"))\r\n suppressWarnings(write.table(regeneration_df, file=\"outputs/regeneration.csv\",\r\n append=TRUE, col.names=header_boolean, row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\"))\r\n # Mortality is non-deterministic\r\n if (nrow(mortality_df) > 0 | header_boolean) {\r\n suppressWarnings(write.table(mortality_df, file=\"outputs/mortality.csv\",\r\n append=TRUE, col.names=header_boolean, row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\"))\r\n }\r\n\r\n # Calculate loop time\r\n loop_time <- proc.time() - loop_start_time\r\n loop_time <- as.numeric(loop_time[\"elapsed\"])\r\n message(paste(paste0(\"Year: \", year, \",\"), \"Duration (sec):\", round(loop_time, 2)))\r\n loop_times <- c(loop_times, loop_time)\r\n} # end year loop\r\n\r\n# Calculate total time\r\ntotal_time <- proc.time() - start_time\r\ntotal_time <- as.numeric(total_time[\"elapsed\"])\r\nmessage(\"=========================================================================\")\r\nmessage(\"Simulation complete\")\r\nmessage(paste(\"Years:\", length(Years)))\r\nmessage(paste(\"Duration (sec):\", round(total_time, 2)))\r\nmessage(\"=========================================================================\")\r\n\r\n# Export loop times to CSV\r\nloop_times_df <- data.frame(year=Years, time=loop_times)\r\nwrite.table(loop_times_df, file=\"outputs/loop_times.csv\", col.names=TRUE,\r\n row.names=FALSE, sep=\",\", fileEncoding=\"UTF-8\")\r\n\r\n# End #\r\n", "meta": {"hexsha": "e16b2be27b96000284a9f43460eeee579b88d320", "size": 27944, "ext": "r", "lang": "R", "max_stars_repo_path": "models/ppa_sibgc/jerc_rd/ppa_sibgc_v1.r", "max_stars_repo_name": "adam-erickson/ecosystem-model-comparison", "max_stars_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-02T13:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T11:36:59.000Z", "max_issues_repo_path": "models/ppa_sibgc/jerc_rd/ppa_sibgc_v1.r", "max_issues_repo_name": "adam-erickson/ecosystem-model-comparison", "max_issues_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/ppa_sibgc/jerc_rd/ppa_sibgc_v1.r", "max_forks_repo_name": "adam-erickson/ecosystem-model-comparison", "max_forks_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7698056801, "max_line_length": 158, "alphanum_fraction": 0.6168408245, "num_tokens": 8083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.34201891972181364}} {"text": "#' Calculate percentage change between two years using Bayesian output\n#' \n#' Using the data returned from occDetModel/occDetFunc this function models a \n#' trend between two years for each iteration of the models. Several options are\n#' available for the method used to calculate the trend. This distribution of the results is used to\n#' calculate the mean estimate and the 95% credibale intervals. \n#'\n#' @param bayesOut occDet object as returned from occDetModel or occDetFunc. \n#' @param firstYear numeric, the first year over which the change is to be estimated. Defaults to the final year in the dataset\n#' @param lastYear numeric, the last year over which the change is to be estimated. Defaults to the first year in the dataset\n#' @param change A character string that specifies the type of change to be calculated, the default\n#' is annual growth rate. See details for options.\n#' @param region A character string specifying the region name if change is to be determined regional estimates of occupancy.\n#' Region names must match those in the model output.\n#' \n#' \n#' @details \\code{change} is used to specify which change measure to be calculated.\n#' There are four options to choose from: difference, percentdif, growthrate and\n#' lineargrowth.\n#' \n#' \\code{difference} calculates the simple difference between the first and last year.\n#' \n#' \\code{percentdif} calculates the percentage difference between the first and last year.\n#' \n#' \\code{growthrate} calculates the annual growth rate across years.\n#' \n#' \\code{lineargrowth} calculates the linear growth rate from a linear model.\n#' \n#' @return A list giving the mean, median, credible intervals and raw data from the\n#' estimations.\n#' @examples\n#' \\dontrun{\n#' \n#' #' # Create data\n#' n <- 15000 #size of dataset\n#' nyr <- 20 # number of years in data\n#' nSamples <- 100 # set number of dates\n#' nSites <- 50 # set number of sites\n#' \n#' # Create somes dates\n#' first <- as.Date(strptime(\"1980/01/01\", \"%Y/%m/%d\")) \n#' last <- as.Date(strptime(paste(1980+(nyr-1),\"/12/31\", sep=''), \"%Y/%m/%d\")) \n#' dt <- last-first \n#' rDates <- first + (runif(nSamples)*dt)\n#' \n#' # taxa are set as random letters\n#' taxa <- sample(letters, size = n, TRUE)\n#' \n#' # three sites are visited randomly\n#' site <- sample(paste('A', 1:nSites, sep=''), size = n, TRUE)\n#' \n#' # the date of visit is selected at random from those created earlier\n#' survey <- sample(rDates, size = n, TRUE)\n#'\n#' # run the model with these data for one species\n#' results <- occDetModel(taxa = taxa,\n#' site = site,\n#' survey = survey,\n#' species_list = c('a','m','g'),\n#' write_results = FALSE,\n#' n_iterations = 1000,\n#' burnin = 10,\n#' thinning = 2)\n#'\n#' # estimate the change for one species \n#' change <- occurrenceChange(firstYear = 1990,\n#' lastYear = 1999,\n#' bayesOut = results$a) \n#' } \n#' @export\n\noccurrenceChange <- function(bayesOut, firstYear=NULL, lastYear=NULL, change = 'growthrate', region = NULL){\n\n # error checks for years (or set to defaults)\n if(is.null(firstYear)) \n firstYear <- bayesOut$min_year\n else\n if(!firstYear %in% bayesOut$min_year:bayesOut$max_year) stop('firstYear must be in the year range of the data')\n \n if(is.null(lastYear)) \n lastYear <- bayesOut$max_year\n else \n if(!lastYear %in% bayesOut$min_year:bayesOut$max_year) stop('lastYear must be in the year range of the data')\n \n # error checks for change\n if(!class(change) == 'character') stop('Change must be a character string identifying the change metric. Either: difference, percentdif, growthrate or lineargrowth')\n if(!change %in% c('difference', 'percentdif', 'growthrate', 'lineargrowth')) stop('The change metric must be one of the following: difference, percentdif, growthrate or lineargrowth')\n \n # error check for region\n if(!is.null(region)){\n if(!class(region) == 'character') stop('region must be a character string identifying the regional estimates that change is to be calculated for.')\n if(!region %in% bayesOut$regions) stop('region must match that used in the model output file, check spelling.')\n }\n \n \n # extract the sims list, if there is a region code, use the psi.fs for that region\n if(!is.null(region)){\n reg_code <- paste(\"psi.fs.r_\", region, sep = \"\")\n\n occ_it <- bayesOut$BUGSoutput$sims.list\n occ_it <- occ_it[[grep(reg_code, names(occ_it))]]\n\n }else{\n occ_it <- bayesOut$BUGSoutput$sims.list$psi.fs\n \n }\n \n \n colnames(occ_it) <- bayesOut$min_year:bayesOut$max_year\n years <- firstYear:lastYear\n \n ## edit values that are 0 or 1 to prevent estimates of inf later on\n #occ_it[occ_it == 0] <- 0.0001\n #occ_it[occ_it == 1] <- 0.9999\n \n \n ### loops depend on which change metric has been specified\n \n if(change == 'lineargrowth'){\n prediction <- function(years, series){\n\n # cut data\n data_table <- data.frame(occ = series[as.character(years)], year = (years - min(years) + 1))\n \n # run model\n model <- glm(occ ~ year, data = data_table, family = 'quasibinomial')\n \n # create predicted values\n predicted <- plogis(predict(model))\n names(predicted) <- years\n \n # build results\n results <- data.frame(predicted[1], predicted[length(predicted)], row.names = NULL)\n colnames(results) <- as.character(c(min(years), max(years)))\n results$change = (results[,2] - results[,1]) / results[,1]\n \n return(results)\n \n }\n\n res_tab <- do.call(rbind, apply(X = occ_it, MARGIN = 1, years = years, FUN = prediction))\n \n } # end of loop for linear growth rate\n \n \n if(change == 'difference'){\n first <- years[1]\n last <- years[length(years)]\n res_tab <- data.frame(occ_it[, colnames(occ_it) == first],\n occ_it[, colnames(occ_it) == last],\n row.names = NULL)\n colnames(res_tab) <- as.character(c(min(years), max(years)))\n res_tab$change = res_tab[,2] - res_tab[,1]\n } # end of loop for simple difference\n \n \n if(change == 'percentdif'){\n first <- years[1]\n last <- years[length(years)]\n res_tab <- data.frame(occ_it[, colnames(occ_it) == first],\n occ_it[, colnames(occ_it) == last],\n row.names = NULL)\n\n ## edit 0 in the first year with some small value to prevent Infinite trends\n res_tab[,1][res_tab[,1] == 0] <- 0.0000001\n \n colnames(res_tab) <- as.character(c(min(years), max(years)))\n res_tab$change = ((res_tab[,2] - res_tab[,1])/res_tab[,1])*100\n } # end of loop for percentage difference\n \n \n if(change == 'growthrate'){\n nyr <- length(years)\n first <- years[1]\n last <- years[length(years)]\n res_tab <- data.frame(occ_it[, colnames(occ_it) == first],\n occ_it[, colnames(occ_it) == last],\n row.names = NULL)\n\n ## edit 0 in the first year with some small value to prevent Infinite trends\n res_tab[,1][res_tab[,1] == 0] <- 0.0000001\n \n colnames(res_tab) <- as.character(c(min(years), max(years)))\n res_tab$change = (((res_tab[,2]/res_tab[,1])^(1/nyr))-1)*100\n } # end of loop for growth rate\n\n # return the mean, quantiles, and the data\n return(list(mean = mean(res_tab$change),\n median = median(res_tab$change),\n CIs = quantile(res_tab$change, probs = c(0.025, 0.975)),\n data = res_tab))\n\n}\n", "meta": {"hexsha": "fe50502785ea1014258e0848cab48c07db43ea46", "size": 7614, "ext": "r", "lang": "R", "max_stars_repo_path": "R/occurrenceChange.r", "max_stars_repo_name": "03rcooke/sparta", "max_stars_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_stars_repo_licenses": ["MIT"], "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/occurrenceChange.r", "max_issues_repo_name": "03rcooke/sparta", "max_issues_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-05-28T13:47:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T09:06:41.000Z", "max_forks_repo_path": "R/occurrenceChange.r", "max_forks_repo_name": "AugustT/sparta", "max_forks_repo_head_hexsha": "84594eeaaca02954ac05d058e5cc6eedb2fb3918", "max_forks_repo_licenses": ["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.2474226804, "max_line_length": 185, "alphanum_fraction": 0.6334384029, "num_tokens": 1978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3414180135742385}} {"text": "mcmcMH <- function(target, init.theta, proposal.sd = NULL,\n n.iterations, covmat = NULL,\n limits=list(lower = NULL, upper = NULL),\n adapt.size.start = NULL, adapt.size.cooling = 0.99,\n adapt.shape.start = NULL, adapt.shape.stop = NULL,\n print.info.every = n.iterations/100,\n verbose = FALSE, max.scaling.sd = 50) {\n \n # initialise theta\n theta.current <- init.theta\n theta.propose <- init.theta\n \n # extract theta of gaussian proposal\n covmat.proposal <- covmat\n lower.proposal <- limits$lower\n upper.proposal <- limits$upper\n \n # reorder vector and matrix by names, set to default if necessary\n theta.names <- names(init.theta)\n if (!is.null(proposal.sd) && is.null(names(proposal.sd))) {\n names(proposal.sd) <- theta.names\n }\n \n if (is.null(covmat.proposal)) {\n if (is.null(proposal.sd)) {\n proposal.sd <- init.theta/10\n }\n covmat.proposal <-\n matrix(diag(proposal.sd[theta.names]^2, nrow = length(theta.names)),\n nrow = length(theta.names),\n dimnames = list(theta.names, theta.names))\n } else {\n covmat.proposal <- covmat.proposal[theta.names,theta.names]\n }\n \n if (is.null(lower.proposal)) {\n lower.proposal <- init.theta\n lower.proposal[] <- -Inf\n } else {\n lower.proposal <- lower.proposal[theta.names]\n }\n \n if (is.null(upper.proposal)) {\n upper.proposal <- init.theta\n upper.proposal[] <- Inf\n } else {\n upper.proposal <- upper.proposal[theta.names]\n }\n \n # covmat init\n covmat.proposal.init <- covmat.proposal\n \n adapting.size <- FALSE # will be set to TRUE once we start\n # adapting the size\n \n adapting.shape <- 0 # will be set to the iteration at which\n # adaptation starts\n \n # find estimated theta\n theta.estimated.names <- names(which(diag(covmat.proposal) > 0))\n \n # evaluate target at theta init\n target.theta.current <- target(theta.current)\n \n if (!is.null(print.info.every)) {\n message(Sys.time(), \", Init: \", printNamedVector(theta.current[theta.estimated.names]),\n \", target: \", target.theta.current)\n }\n \n # trace\n trace <- matrix(ncol=length(theta.current)+1, nrow=n.iterations, 0)\n colnames(trace) <- c(theta.estimated.names, \"log.density\")\n \n # acceptance rate\n acceptance.rate <- 0\n \n # scaling factor for covmat size\n scaling.sd <- 1\n \n # scaling multiplier\n scaling.multiplier <- 1\n \n # empirical covariance matrix (0 everywhere initially)\n covmat.empirical <- covmat.proposal\n covmat.empirical[,] <- 0\n \n # empirical mean vector\n theta.mean <- theta.current\n \n # if print.info.every is null never print info\n if (is.null(print.info.every)) {\n print.info.every <- n.iterations + 1\n }\n \n start_iteration_time <- Sys.time()\n \n for (i.iteration in seq_len(n.iterations)) {\n \n # adaptive step\n if (!is.null(adapt.size.start) && i.iteration >= adapt.size.start &&\n (is.null(adapt.shape.start) || acceptance.rate*i.iteration < adapt.shape.start)) {\n if (!adapting.size) {\n message(\"\\n---> Start adapting size of covariance matrix\")\n adapting.size <- TRUE\n }\n # adapt size of covmat until we get enough accepted jumps\n scaling.multiplier <- exp(adapt.size.cooling^(i.iteration-adapt.size.start) * (acceptance.rate - 0.234))\n scaling.sd <- scaling.sd * scaling.multiplier\n scaling.sd <- min(c(scaling.sd,max.scaling.sd))\n # only scale if it doesn't reduce the covariance matrix to 0\n covmat.proposal.new <- scaling.sd^2*covmat.proposal.init\n if (!(any(diag(covmat.proposal.new)[theta.estimated.names] <\n .Machine$double.eps))) {\n covmat.proposal <- covmat.proposal.new\n }\n \n } else if (!is.null(adapt.shape.start) &&\n acceptance.rate*i.iteration >= adapt.shape.start &&\n (adapting.shape == 0 || is.null(adapt.shape.stop) ||\n i.iteration < adapting.shape + adapt.shape.stop)) {\n if (!adapting.shape) {\n message(\"\\n---> Start adapting shape of covariance matrix\")\n # flush.console()\n adapting.shape <- i.iteration\n }\n \n ## adapt shape of covmat using optimal scaling factor for multivariate target distributions\n scaling.sd <- 2.38/sqrt(length(theta.estimated.names))\n \n covmat.proposal <- scaling.sd^2 * covmat.empirical\n } else if (adapting.shape > 0) {\n message(\"\\n---> Stop adapting shape of covariance matrix\")\n adapting.shape <- -1\n }\n \n # print info\n if (i.iteration %% ceiling(print.info.every) == 0) {\n message(Sys.time(), \", Iteration: \",i.iteration,\"/\", n.iterations,\n \", acceptance rate: \",\n sprintf(\"%.3f\",acceptance.rate), appendLF=FALSE)\n if (!is.null(adapt.size.start) || !is.null(adapt.shape.start)) {\n message(\", scaling.sd: \", sprintf(\"%.3f\", scaling.sd),\n \", scaling.multiplier: \", sprintf(\"%.3f\", scaling.multiplier),\n appendLF=FALSE)\n }\n message(\", state: \",(printNamedVector(theta.current)))\n message(\", logdensity: \", target.theta.current)\n }\n \n # propose another parameter set\n if (any(diag(covmat.proposal)[theta.estimated.names] <\n .Machine$double.eps)) {\n print(covmat.proposal[theta.estimated.names,theta.estimated.names])\n stop(\"non-positive definite covmat\",call.=FALSE)\n }\n if (length(theta.estimated.names) > 0) {\n theta.propose[theta.estimated.names] <-\n as.vector(rtmvnorm(1,\n mean =\n theta.current[theta.estimated.names],\n sigma =\n covmat.proposal[theta.estimated.names,theta.estimated.names],\n lower =\n lower.proposal[theta.estimated.names],\n upper = upper.proposal[theta.estimated.names]))\n }\n \n # evaluate posterior of proposed parameter\n target.theta.propose <- target(theta.propose)\n # if return value is a vector, set log.density and trace\n \n if (!any(is.finite(target.theta.propose))) { # GK: changed to include \"any\" as getting error with list\n # if posterior is 0 then do not compute anything else and don't accept\n log.acceptance <- -Inf\n \n }else{\n \n # compute Metropolis-Hastings ratio (acceptance probability)\n log.acceptance <- target.theta.propose - target.theta.current\n log.acceptance <- log.acceptance +\n dtmvnorm(x = theta.current[theta.estimated.names],\n mean =\n theta.propose[theta.estimated.names],\n sigma =\n covmat.proposal[theta.estimated.names,\n theta.estimated.names],\n lower =\n lower.proposal[theta.estimated.names],\n upper =\n upper.proposal[theta.estimated.names],\n log = TRUE)\n log.acceptance <- log.acceptance -\n dtmvnorm(x = theta.propose[theta.estimated.names],\n mean = theta.current[theta.estimated.names],\n sigma =\n covmat.proposal[theta.estimated.names,\n theta.estimated.names],\n lower =\n lower.proposal[theta.estimated.names],\n upper =\n upper.proposal[theta.estimated.names],\n log = TRUE)\n \n }\n \n if (verbose) {\n message(\"Propose: \", theta.propose[theta.estimated.names],\n \", target: \", target.theta.propose,\n \", acc prob: \", exp(log.acceptance), \", \",\n appendLF = FALSE)\n }\n \n if (is.accepted <- (log(runif (1)) < log.acceptance)) {\n # accept proposed parameter set\n theta.current <- theta.propose\n target.theta.current <- target.theta.propose\n if (verbose) {\n message(\"accepted\")\n }\n } else if (verbose) {\n message(\"rejected\")\n }\n trace[i.iteration, ] <- c(theta.current, target.theta.current)\n \n # update acceptance rate\n if (i.iteration == 1) {\n acceptance.rate <- is.accepted\n } else {\n acceptance.rate <- acceptance.rate +\n (is.accepted - acceptance.rate) / i.iteration\n }\n \n # update empirical covariance matrix\n if (adapting.shape >= 0) {\n tmp <- updateCovmat(covmat.empirical, theta.mean,\n theta.current, i.iteration)\n covmat.empirical <- tmp$covmat\n theta.mean <- tmp$theta.mean\n }\n \n }\n \n return(list(trace = trace,\n acceptance.rate = acceptance.rate,\n covmat.empirical = covmat.empirical))\n}\n\n\n#'Print named vector\n#'\n#'Print named vector with format specified by \\code{fmt} (2 decimal places by default).\n#' @param x named vector\n#' @inheritParams base::sprintf\n#' @inheritParams base::paste\n#' @export\n#' @seealso \\code{\\link[base]{sprintf}}\n#' @keywords internal\nprintNamedVector <- function(x, fmt=\"%.2f\", sep=\" | \") {\n \n paste(paste(names(x),sprintf(fmt,x),sep=\" = \"),collapse=sep)\n \n}\n\n#' Simulate forward a stochastic model\n#'\n#' This function uses the function \\code{\\link[adaptivetau]{ssa.adaptivetau}} to simulate the model and returns the trajectories in a valid format for the class \\code{\\link{fitmodel}}.\n#' @param theta named vector of model parameters.\n#' @param init.state named vector of initial state of the model.\n#' @param times time sequence for which state of the model is wanted; the first value of times must be the initial time.\n#' @inheritParams adaptivetau::ssa.adaptivetau\n#' @export\n#' @import adaptivetau\n#' @return a data.frame of dimension \\code{length(times)x(length(init.state)+1)} with column names equal to \\code{c(\"time\",names(init.state))}.\nsimulateModelStochastic <- function(theta,init.state,times,transitions,rateFunc) {\n \n \n stoch <- as.data.frame(ssa.adaptivetau(init.state,transitions,rateFunc,theta,tf=diff(range(times))))\n \n # rescale time as absolute value\n stoch$time <- stoch$time + min(times)\n \n # interpolate\n traj <- cbind(time=times,apply(stoch[,-1],2,function(col){approx(x=stoch[,1],y=col,xout=times,method=\"constant\")$y}))\n \n return(as.data.frame(traj))\n \n}\n\n\n\n#'Simulate several replicate of the model\n#'\n#'Simulate several replicate of a fitmodel using its function simulate\n#' @param times vector of times at which you want to observe the states of the model.\n#' @param n number of replicated simulations.\n#' @param observation logical, if \\code{TRUE} simulated observation are generated by \\code{rTrajObs}.\n#' @inheritParams testFitmodel\n#' @export\n#' @import plyr\n#' @return a data.frame of dimension \\code{[nxlength(times)]x[length(init.state)+2]} with column names equal to \\code{c(\"replicate\",\"time\",names(init.state))}.\nsimulateModelReplicates <- function(fitmodel,theta, init.state, times, n, observation=FALSE) {\n \n stopifnot(inherits(fitmodel,\"fitmodel\"),n>0)\n \n if(observation && is.null(fitmodel$dPointObs)){\n stop(\"Can't generate observation as \",sQuote(\"fitmodel\"),\" doesn't have a \",sQuote(\"dPointObs\"),\" function.\")\n }\n \n rep <- as.list(1:n)\n names(rep) <- rep\n \n if (n > 1) {\n progress = \"text\"\n } else {\n progress = \"none\"\n }\n \n traj.rep <- ldply(rep,function(x) {\n \n if(observation){\n traj <- rTrajObs(fitmodel, theta, init.state, times)\n } else {\n traj <- fitmodel$simulate(theta,init.state,times)\n }\n \n return(traj)\n \n },.progress=progress,.id=\"replicate\")\n \n return(traj.rep)\n}\n\n\n#'Simulate model until extinction\n#'\n#'Return final state at extinction\n#' @param extinct character vetor. Simulations stop when all these state are extinct.\n#' @param time.init numeric. Start time of simulation.\n#' @param time.step numeric. Time step at which extinction is checked\n#' @inheritParams testFitmodel\n#' @inheritParams simulateModelReplicates\n#' @inheritParams particleFilter\n#' @export\n#' @import plyr parallel doParallel\nsimulateFinalStateAtExtinction <- function(fitmodel, theta, init.state, extinct=NULL ,time.init=0, time.step=100, n=100, observation=FALSE, n.cores = 1) {\n \n stopifnot(inherits(fitmodel,\"fitmodel\"),n>0)\n \n if(observation && is.null(fitmodel$dPointObs)){\n stop(\"Can't generate observation as \",sQuote(\"fitmodel\"),\" doesn't have a \",sQuote(\"dPointObs\"),\" function.\")\n }\n \n if(is.null(n.cores)){\n n.cores <- detectCores()\n }\n \n if(n.cores > 1){\n registerDoParallel(cores=n.cores)\n }\n \n rep <- as.list(1:n)\n names(rep) <- rep\n \n if (n > 1 && n.cores==1) {\n progress = \"text\"\n } else {\n progress = \"none\"\n }\n \n times <- c(time.init, time.step)\n \n final.state.rep <- ldply(rep,function(x) {\n \n if(observation){\n traj <- rTrajObs(fitmodel, theta, init.state, times)\n } else {\n traj <- fitmodel$simulate(theta,init.state,times)\n }\n \n current.state <- unlist(traj[nrow(traj),fitmodel$state.names])\n current.time <- last(traj$time)\n \n while(any(current.state[extinct]>=0.5)){\n \n times <- times + current.time\n \n if(observation){\n traj <- rTrajObs(fitmodel, theta, current.state, times)\n } else {\n traj <- fitmodel$simulate(theta, current.state,times)\n }\n \n current.state <- unlist(traj[nrow(traj),fitmodel$state.names])\n current.time <- last(traj$time)\n }\n \n return(data.frame(t(c(time=current.time,current.state))))\n \n },.progress=progress,.id=\"replicate\",.parallel=(n.cores > 1),.paropts=list(.inorder=FALSE))\n \n return(final.state.rep)\n}\n\n\n#'Update covariance matrix\n#'\n#'Update covariance matrix using a stable one-pass algorithm. This is much more efficient than using \\code{\\link{cov}} on the full data.\n#' @param covmat covariance matrix at iteration \\code{i-1}. Must be numeric, symmetrical and named.\n#' @param theta.mean mean vector at iteration \\code{i-1}. Must be numeric and named.\n#' @param theta vector of new value at iteration \\code{i}. Must be numeric and named.\n#' @param i current iteration.\n#' @references \\url{http://en.wikipedia.org/wiki/Algorithms\\%5Ffor\\%5Fcalculating\\%5Fvariance#Covariance}\n#' @export\n#' @keywords internal\n#' @return A list of two elements\n#' \\itemize{\n#' \\item \\code{covmat} update covariance matrix\n#' \\item \\code{theta.mean} updated mean vector\n#' }\nupdateCovmat <- function(covmat,theta.mean,theta,i) {\n \n if(is.null(names(theta))){\n stop(\"Argument \",sQuote(\"theta\"),\" must be named.\",.call=FALSE)\n }\n if(is.null(names(theta.mean))){\n stop(\"Argument \",sQuote(\"theta.mean\"),\" must be named.\",.call=FALSE)\n }\n if(is.null(rownames(covmat))){\n stop(\"Argument \",sQuote(\"covmat\"),\" must have named rows.\",.call=FALSE)\n }\n if(is.null(colnames(covmat))){\n stop(\"Argument \",sQuote(\"covmat\"),\" must have named columns.\",.call=FALSE)\n }\n \n covmat <- covmat[names(theta),names(theta)]\n theta.mean <- theta.mean[names(theta)]\n \n residual <- as.vector(theta-theta.mean)\n covmat <- (covmat*(i-1)+(i-1)/i*residual%*%t(residual))/i\n theta.mean <- theta.mean + residual/i\n \n return(list(covmat=covmat,theta.mean=theta.mean))\n}\n\n\n\n#'Burn and thin MCMC chain\n#'\n#'Return a burned and thined trace of the chain.\n#' @param trace either a \\code{data.frame} or a \\code{list} of \\code{data.frame} with all variables in column, as outputed by \\code{\\link{mcmcMH}}. Accept also an \\code{mcmc} or \\code{mcmc.list} object.\n#' @param burn proportion of the chain to burn.\n#' @param thin number of samples to discard per sample that is being kept\n#' @export\n#' @import coda\n#' @return an object with the same format as \\code{trace} (\\code{data.frame} or \\code{list} of \\code{data.frame} or \\code{mcmc} object or \\code{mcmc.list} object)\nburnAndThin <- function(trace, burn = 0, thin = 0) {\n \n convert_to_mcmc <- FALSE\n \n if(class(trace)==\"mcmc\"){\n convert_to_mcmc <- TRUE\n trace <- as.data.frame(trace)\n } else if(class(trace)==\"mcmc.list\"){\n convert_to_mcmc <- TRUE\n trace <- as.list(trace)\n }\n \n if(is.data.frame(trace) || is.matrix(trace)){\n \n # remove burn\n if (burn > 0) {\n trace <- trace[-(1:burn), ]\n }\n # thin\n trace <- trace[seq(1, nrow(trace), thin + 1), ]\n \n if(convert_to_mcmc){\n trace <- mcmc(trace)\n }\n \n } else {\n \n trace <- lapply(trace, function(x) {\n \n # remove burn\n if (burn > 0) {\n x <- x[-(1:burn), ]\n }\n # thin\n x <- x[seq(1, nrow(x), thin + 1), ]\n \n if(convert_to_mcmc){\n x <- mcmc(x)\n }\n \n return(x)\n }) \n \n if(convert_to_mcmc){\n trace <- mcmc.list(trace) \n }\n }\n \n return(trace)\n}\n\n\n#'Distance weighted by number of oscillations\n#'\n#'This positive distance is the mean squared differences between \\code{x} and the \\code{y}, divided by the square of the number of times the \\code{x} oscillates around the \\code{y} (see note below for illustration).\n#' @param x,y numeric vectors of the same length.\n#' @note To illustrate this distance, suppose we observed a time series \\code{y = c(1,3,5,7,5,3,1)} and we have two simulated time series \\code{x1 = (3,5,7,9,7,5,3)} and \\code{x2 = (3,5,3,5,7,5,3)}; \\code{x1} is consistently above \\code{y} and \\code{x2} oscillates around \\code{y}. While the squared differences are the same, we obtain \\eqn{d(y, x1) = 4} and \\eqn{d(y, x2) = 1.3}.\n#' @export\ndistanceOscillation <- function(x, y) {\n \n # check x and y have same length\n if(length(x)!=length(y)){\n stop(sQuote(\"x\"),\" and \",sQuote(\"y\"),\" must be vector of the same length\")\n }\n \n # 1 + number of times x oscillates around y\n n.oscillations <- 1+length(which(diff((x-y)>0)!=0))\n \n dist <- sum((x-y)^2)/(length(x)*n.oscillations)\n \n return(dist)\n}\n\n\n#'Export trace in Tracer format\n#'\n#'Print \\code{trace} in a \\code{file} that can be read by the software Tracer.\n#' @param trace a \\code{data.frame} with one column per estimated parameter, as returned by \\code{\\link{burnAndThin}}\n#' @inheritParams utils::write.table\n#' @note Tracer is a program for analysing the trace files generated by Bayesian MCMC runs. It can be dowloaded at \\url{http://tree.bio.ed.ac.uk/software/tracer}.\n#' @export\n#' @seealso burnAndThin\n#' @keywords internal\nexport2Tracer <- function(trace, file) {\n \n if(is.mcmc(trace)){\n trace <- as.data.frame(trace)\n }\n \n if(!\"iteration\"%in%names(trace)){\n trace$iteration <- (1:nrow(trace) - 1)\n }\n \n trace <- trace[c(\"iteration\",setdiff(names(trace),c(\"iteration\",\"weight\")))]\n write.table(trace,file=file,quote=FALSE,row.names=FALSE,sep=\"\\t\")\n \n}", "meta": {"hexsha": "8a7a26ccd0e582d2b68c18680cedb19cdc129981", "size": 18628, "ext": "r", "lang": "R", "max_stars_repo_path": "code/mcmcmh.r", "max_stars_repo_name": "gwenknight/piglet_transfer_rates", "max_stars_repo_head_hexsha": "25b015ee67538419f77c15e915867533d867e024", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/mcmcmh.r", "max_issues_repo_name": "gwenknight/piglet_transfer_rates", "max_issues_repo_head_hexsha": "25b015ee67538419f77c15e915867533d867e024", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/mcmcmh.r", "max_forks_repo_name": "gwenknight/piglet_transfer_rates", "max_forks_repo_head_hexsha": "25b015ee67538419f77c15e915867533d867e024", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7463768116, "max_line_length": 380, "alphanum_fraction": 0.6257783981, "num_tokens": 4824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33971054342622387}} {"text": "#' Function that corrects chronologies for sudden jumps in time\n#' \n#' Some occurrences in the model results can lead the CumDY function\n#' to detect extra year transitions, resulting in sudden jumps in\n#' the shell chronology or a start of the chronology at an age\n#' beyond 1 year. This function removes these sharp transitions\n#' and late onset by adding or subtracting whole years to the age\n#' result.\n#' @param resultarray Array containing the full results of\n#' the optimized growth model\n#' @param T_per The period length of one year (in days)\n#' @param agecorrection Correct for jumps in age (/code{TRUE}) or\n#' only for starting time (/code{FALSE})\n#' @param plot Should the results be plotted? (/code{TRUE/FALSE})\n#' @return An updated and corrected version of \\code{resultarray}\n#' @references package dependencies: ggplot2 3.2.1\n#' @examples\n#' testarray <- array(NA, dim = c(20, 16, 9)) # Create empty array\n#' # with correct third dimension\n#' windowfill <- seq(10, 100, 10) # Create dummy simulation data \n#' # (ages) to copy through the array\n#' for(i in 6:length(testarray[1, , 1])){\n#' testarray[, i, 3] <- c(windowfill,\n#' rep(NA, length(testarray[, 1, 3]) - length(windowfill)))\n#' windowfill <- c(NA, windowfill + 31)\n#' }\n#' testarray2 <- age_corr(testarray, 365, FALSE, FALSE) # Apply function on \n#' array\n#' @export\nage_corr <- function(resultarray,\n T_per = 365,\n plot = TRUE,\n agecorrection = TRUE\n ){\n Age <- Age_corr <- NULL # Predefine variables to circumvent global variable binding error\n # Check on glitches where consecutive windows are placed (almost) 1 year apart.\n # These are repaired by adding one T_per to the cumulative Day values of those windows in\n # resultarray[, , 3]\n mean_window_age <- data.frame(\n 1:(length(resultarray[1,,1]) - 5),\n unname(colMeans(resultarray[, 6:length(resultarray[1, , 1]), 3], na.rm = TRUE)))\n colnames(mean_window_age) <- c(\"window\", \"Age\")\n\n # Plot mean window ages\n dev.new() # Plot Window age to check for strange jumps in age\n ageplot <- ggplot2::ggplot(mean_window_age, ggplot2::aes(window, Age)) +\n ggplot2::geom_line() +\n ggplot2::geom_point() +\n ggplot2::ggtitle(\"Plot of average ages of modelling windows\") +\n ggplot2::xlab(\"Window #\") +\n ggplot2::scale_y_continuous(\"Age (days)\", seq(0, 365 * ceiling(max(unname(colMeans(\n resultarray[, 6:length(resultarray[1,,1]),3], na.rm = TRUE)),\n na.rm = TRUE) / 365), 365))\n plot(ageplot)\n\n if(agecorrection == TRUE){\n agecorr <- rep(0, length(mean_window_age[, 2])) # Create vector to store corrections\n # (in days) to the mean ages of modelling windows\n for(i in 1:(length(mean_window_age[,2]) - 1)){ # Loop through all windows\n if(mean_window_age[i + 1, 2] - mean_window_age[i, 2] > T_per / 2){ # If there is a\n # large (> half a year) positive step between consecutive windows...\n # ...subtract one year from the subsequent windows\n agecorr[(i + 1):length(agecorr)] <- agecorr[(i + 1):length(agecorr)] - T_per\n }else if(mean_window_age[i + 1, 2] - mean_window_age[i, 2] < T_per / -2){ # If there is\n # a large (> half a year) negative drop between consecutive windows, add one year\n # from the subsequent windows\n agecorr[(i + 1):length(agecorr)] <- agecorr[(i + 1):length(agecorr)] + T_per \n }\n }\n\n if(min(mean_window_age$Age + agecorr) > T_per){\n agecorr <- agecorr - 365 # Subtract whole number of years from correction if the\n # smallest value is more than one year old\n }\n\n mean_window_age$Age_corr <- mean_window_age$Age + agecorr\n mean_window_age$correction <- agecorr\n\n if(plot == TRUE){ # Plot updated result\n ageplot <- ggplot2::ggplot(mean_window_age, ggplot2::aes(window, Age)) + # Plot Window\n # age to check for strange jumps in age\n ggplot2::geom_line() +\n ggplot2::geom_point() +\n ggplot2::ggtitle(\"Plot of average ages of modelling windows\") +\n ggplot2::xlab(\"Window #\") +\n ggplot2::scale_y_continuous(\"Age (days)\", seq(0, 365 * ceiling(max(unname(colMeans(\n resultarray[, 6:length(resultarray[1,,1]),3], na.rm = TRUE)),\n na.rm = TRUE) / 365), 365)) +\n ggplot2::geom_line(ggplot2::aes(window, Age_corr), col = \"red\") # Add corrected window\n # age to plot\n plot(ageplot)\n }\n \n resultarray[, 6:length(resultarray[1, , 1]), 3] <- resultarray[, 6:length(\n resultarray[1, , 1]), 3] + matrix(agecorr, nrow = length(resultarray[, 1, 1]),\n ncol = length(agecorr), byrow = TRUE) # Apply correction on the results of\n # age modelling\n }else{\n resultarray[, 6:length(resultarray[1, , 1]), 3] <- resultarray[, 6:length(\n resultarray[1, , 1]), 3] - floor(min(mean_window_age$Age) / 365) * 365 # Correct age if\n # all windows occur past year one\n }\n return(resultarray)\n}", "meta": {"hexsha": "ad88aed87be6334fdaee3d818c6d55c8d14490f7", "size": 5169, "ext": "r", "lang": "R", "max_stars_repo_path": "R/age_corr.r", "max_stars_repo_name": "nhoeche/ShellChron.jl", "max_stars_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/age_corr.r", "max_issues_repo_name": "nhoeche/ShellChron.jl", "max_issues_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/age_corr.r", "max_forks_repo_name": "nhoeche/ShellChron.jl", "max_forks_repo_head_hexsha": "935bcde7e015581a18eee324b7a5ff2ab7f1970f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7019230769, "max_line_length": 99, "alphanum_fraction": 0.6225575547, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.33862061780087627}} {"text": "stanfit_one <- function(gdat, dz, nnfits, which.spax,\n prep_data = prep_data_mod,\n init_opt = init_opt_mod,\n init_sampler = init_sampler_mod,\n stan_model=NULL,\n stan_file=\"spm_dust_mod_simpl.stan\", stan_filedir=\"~/spmcode/\",\n iter_opt=5000, \n jv=1.e-4,\n iter=1000, warmup=250, thin=1, chains=4, \n OP=FALSE, ...) {\n \n require(rstan)\n if (is.null(stan_model)) {\n stan_model <- rstan::stan_model(file=file.path(stan_filedir, stan_file))\n }\n \n spm_data <- prep_data(gdat, dz, nnfits, which.spax)\n inits <- init_opt(spm_data, nnfits, which.spax, jv)\n spm_opt <- optimizing(stan_model, data=spm_data, init=inits, as_vector=FALSE, verbose=TRUE, iter=iter_opt)\n \n init_pars <- lapply(X=1:chains, init_sampler, stan_opt=spm_opt$par, jv=jv)\n \n stanfit <- sampling(stan_model, data=spm_data,\n chains=chains, iter=iter, warmup=warmup, thin=thin,\n cores=min(chains, getOption(\"mc.cores\")),\n init=init_pars, open_progress=OP, ...)\n \n list(spm_data=spm_data, stanfit=stanfit, \n norm_g=spm_data$norm_g, norm_st=spm_data$norm_st, norm_em=spm_data$norm_em, in_em=spm_data$in_em)\n}\n\n\n \nstanfit_batch <- function(gdat, dz, nnfits,\n init_tracked = init_tracked_mod,\n update_tracked = update_tracked_mod,\n return_tracked = return_tracked_mod,\n prep_data = prep_data_mod,\n init_opt = init_opt_mod,\n init_sampler = init_sampler_mod,\n stan_file=\"spm_dust_mod_simpl.stan\", stan_filedir=\"~/spmcode/\",\n iter_opt=5000, \n jv=1.e-4,\n iter=1000, warmup=250, chains=4,\n OP=FALSE,\n start=NULL, end=NULL, fpart=\"bfits.rda\", ...) {\n dims <- dim(gdat$flux)\n dz <- dz$dz\n nsim <- (iter-warmup)*chains\n nt <- length(ages)\n nr <- dims[1]\n n_st <- ncol(lib.ssp)-1\n n_em <- length(emlines)\n nl <- length(gdat$lambda)\n smodel <- rstan::stan_model(file.path(stan_filedir, stan_file))\n if (is.null(start) || !file.exists(fpart)) {\n init_tracked(nsim, n_st, n_em, nr)\n start <- 1\n } else {\n load(fpart)\n }\n if (is.null(end)) {\n end <- nr\n }\n for (i in start:end) {\n if (is.na(dz[i]) || is.na(nnfits$Mstar[i])) next\n sfit <- stanfit_one(gdat, dz, nnfits, which.spax=i,\n prep_data,\n init_opt,\n init_sampler,\n stan_model=smodel,\n iter_opt=iter_opt, jv=jv,\n iter = iter, warmup = warmup, chains = chains, \n OP=OP, ...)\n plot(plotpp(sfit)+ggtitle(paste(\"fiber =\", i)))\n update_tracked(i, sfit, fpart)\n rm(sfit)\n }\n return_tracked()\n}\n\n## star formation history, mass growth history, etc.\n\nget_sfh <- function(..., z, fibersinbin=1, density=TRUE, tsf=0.1) {\n ins <- list(...)\n if (is.list(ins[[1]])) {\n ins <- ins[[1]]\n post <- rstan::extract(ins$stanfit)\n b_st <- post$b_st\n norm_st <- ins$norm_st\n if (exists(\"norm_g\", ins)) {\n b_st <- b_st*ins$norm_g\n norm_st <- 1/norm_st\n }\n } else {\n b_st <- ins$b_st\n norm_st <- ins$norm_st\n }\n nsim <- nrow(b_st)\n nt <- length(ages)\n nz <- ncol(b_st)/nt\n T.gyr <- 10^(ages-9)\n isf <- which.min(abs(tsf-T.gyr))\n if (density) {\n binarea <- log10(pi*fibersinbin*cosmo::ascale(z)^2)\n } else {\n binarea <- 0\n }\n b_st <- t(t(b_st)*norm_st)*cosmo::lum.sol(1, z)\n rmass <- t(t(b_st) * mstar)\n sfh_post <- matrix(0, nsim, nt)\n mgh_post <- matrix(0, nsim, nt)\n for (i in 1:nz) {\n sfh_post <- sfh_post + b_st[,((i-1)*nt+1):(i*nt)]\n mgh_post <- mgh_post + rmass[,((i-1)*nt+1):(i*nt)]\n }\n totalmg_post <- cbind(rowSums(mgh_post), rowSums(mgh_post) - t(apply(mgh_post, 1, cumsum)))\n mgh_post <- cbind(rep(1, nsim), 1 - (t(apply(mgh_post, 1, cumsum))/rowSums(mgh_post)))\n sfr <- log10(rowSums(sfh_post[,1:isf])/T.gyr[isf])-9.\n relsfr <- sfr - log10(rowSums(sfh_post)/(cosmo::dcos(Inf)$dT-cosmo::dcos(z)$dT)) + 6\n sigma_sfr <- sfr - binarea\n sigma_mstar <- log10(b_st %*% mstar) - binarea\n ssfr <- sigma_sfr - sigma_mstar\n list(sfh_post=sfh_post, mgh_post=mgh_post, totalmg_post=totalmg_post,\n sigma_mstar=sigma_mstar, sigma_sfr=sigma_sfr, ssfr=ssfr, relsfr=relsfr)\n}\n\nbatch_sfh <- function(gdat, sfits, tsf=0.1) {\n b_st <- sfits$b_st\n norm_st <- sfits$norm_st\n dims <- dim(b_st)\n nsim <- dims[1]\n nt <- length(ages)\n nz <- dims[2]/nt\n nf <- dims[3]\n if (exists(\"norm_g\", sfits)) {\n norm_g <- sfits$norm_g\n norm_st <- 1/norm_st\n } else {\n norm_g <- rep(1, nf)\n }\n z <- gdat$meta$z\n if (!exists(\"fibersinbin\", gdat)) {\n fibersinbin <- rep(1, nf)\n } else {\n fibersinbin <- gdat$fibersinbin\n }\n \n sfh_post <- array(NA, dim=c(nsim, nt, nf))\n mgh_post <- array(0, dim=c(nsim, nt+1, nf))\n totalmg_post <- matrix(0, nsim, nt+1)\n sigma_mstar <- matrix(NA, nsim, nf)\n sigma_sfr <- matrix(NA, nsim, nf)\n ssfr <- matrix(NA, nsim, nf)\n relsfr <- matrix(NA, nsim, nf)\n \n for (i in 1:nf) {\n if (is.na(b_st[1, 1, i])) next\n sfi <- get_sfh(b_st=b_st[,,i]*norm_g[i], norm_st=norm_st[,i], z=z, fibersinbin=fibersinbin[i])\n sfh_post[,,i] <- sfi$sfh_post\n mgh_post[,,i] <- sfi$mgh_post\n totalmg_post <- totalmg_post + sfi$totalmg_post\n sigma_mstar[, i] <- sfi$sigma_mstar\n sigma_sfr[, i] <- sfi$sigma_sfr\n ssfr[, i] <- sfi$ssfr\n relsfr[,i] <- sfi$relsfr\n }\n list(sfh_post=sfh_post, mgh_post=mgh_post, totalmg_post=totalmg_post,\n sigma_mstar=sigma_mstar, sigma_sfr=sigma_sfr, ssfr=ssfr, relsfr=relsfr)\n}\n \n \n## some sorta useful summary measures\n\nget_proxies <- function(...) {\n ins <- list(...)\n if (is.list(ins[[1]])) {\n ins <- ins[[1]]\n post <- rstan::extract(ins$stanfit)\n b_st <- post$b_st\n norm_st <- ins$norm_st\n if (exists(\"a\", post)) {\n b_st <- b_st*ins$norm_g\n norm_st <- 1/norm_st\n }\n } else {\n b_st <- ins$b_st\n norm_st <- ins$norm_st\n }\n b_st <- t(t(b_st)*norm_st)\n nz <- length(Z)\n nt <- length(ages)\n T.gyr <- 10^(ages-9)\n tbar <- log10((b_st %*% rep(T.gyr, nz))/rowSums(b_st)) + 9\n tbar_lum <- log10((b_st %*% (rep(T.gyr, nz) * gri.ssp[\"r\",]))/\n ((b_st %*% gri.ssp[\"r\",]))) + 9\n g_i <- 2.5*log10(b_st %*% gri.ssp[\"i\",]) - 2.5*log10(b_st %*% gri.ssp[\"g\",])\n data.frame(tbar=tbar, tbar_lum=tbar_lum, g_i=g_i)\n}\n\n## emission line fluxes, luminosity density, equivalent width\n\nget_em <- function(..., z, fibersinbin=1, ew_width=15) {\n ins <- list(...)\n if (is.list(ins[[1]])) {\n ins <- ins[[1]]\n post <- rstan::extract(ins$stanfit)\n b_st <- post$b_st\n b_em <- post$b_em\n norm_st <- ins$norm_st\n norm_em <- ins$norm_em\n if (exists(\"norm_g\", ins)) {\n b_st <- b_st*ins$norm_g\n b_em <- b_em*ins$norm_g\n norm_st <- 1/norm_st\n }\n } else {\n b_st <- ins$b_st\n b_em <- ins$b_em\n norm_st <- ins$norm_st\n norm_em <- ins$norm_em\n }\n emlines <- emlines[ins$in.em]\n b_st <- t(t(b_st)*norm_st)\n ne <- ncol(b_em)\n nsim <- nrow(b_em)\n binarea <- log10(pi*fibersinbin*cosmo::ascale(z)^2)\n em.mult <- emlines*log(10)/10000\n\n flux_em <- matrix(NA, nsim, ne)\n sigma_logl_em <- matrix(NA, nsim, ne)\n ew_em <- matrix(NA, nsim, ne)\n \n flux_em <- t(t(b_em)*em.mult)*norm_em\n sigma_logl_em <- cosmo::loglum.ergs(flux_em, z) - binarea\n \n mu_st <- tcrossprod(b_st, as.matrix(lib.ssp[, -1]))\n il_em <- findInterval(emlines, lib.ssp$lambda)\n for (i in 1:ne) {\n intvl <- (il_em[i]-ew_width):(il_em[i]+ew_width)\n fc <- rowMeans(mu_st[, intvl])\n ew_em[, i] <- flux_em[, i]/fc\n }\n colnames(flux_em) <- names(emlines)\n colnames(sigma_logl_em) <- names(emlines)\n colnames(ew_em) <- names(emlines)\n list(flux_em=flux_em, sigma_logl_em=sigma_logl_em, ew_em=ew_em)\n}\n\nbatch_em <- function(gdat, sfits, ew_width=15) {\n nsim <- dim(sfits$b_em)[1]\n ne <- length(emlines)\n nf <- length(gdat$xpos)\n norm_st <- sfits$norm_st\n if (exists(\"norm_g\", sfits)) {\n norm_g <- sfits$norm_g\n norm_st <- 1/sfits$norm_st\n } else {\n norm_g <- rep(1, nf)\n }\n \n flux_em <- array(NA, dim=c(nsim, ne, nf))\n sigma_logl_em <- array(NA, dim=c(nsim, ne, nf))\n ew_em <- array(NA, dim=c(nsim, ne, nf))\n \n for (i in 1:nf) {\n if (is.na(sfits$b_st[1, 1, i])) next\n in.em <- sfits$in_em[!is.na(sfits$in_em[,i]), i]\n if(is.null(dim(norm_st))) {\n nst <- norm_st[i]\n } else {\n nst <- norm_st[,i]\n }\n emi <- get_em(b_em=sfits$b_em[,in.em,i]*norm_g[i], b_st=sfits$b_st[,,i]*norm_g[i], \n norm_em=sfits$norm_em[i], norm_st=nst, \n in.em=in.em, z=gdat$meta$z,\n fibersinbin=gdat$fibersinbin[i], ew_width=ew_width)\n flux_em[,in.em,i] <- emi$flux_em\n sigma_logl_em[,in.em,i] <- emi$sigma_logl_em\n ew_em[,in.em,i] <- emi$ew_em\n }\n dimnames(flux_em)[[2]] <- names(emlines)\n dimnames(sigma_logl_em)[[2]] <- names(emlines)\n dimnames(ew_em)[[2]] <- names(emlines)\n list(flux_em=flux_em, sigma_logl_em=sigma_logl_em, ew_em=ew_em)\n}\n\n## bpt class from [N II]/Halpha\n\nbatch_bptclass <- function(flux_em, snthresh=3) {\n nb <- dim(flux_em)[3]\n bpt <- as.factor(rep(\"NO EM\", nb))\n levels(bpt) <- c(\"NO EM\", \"EL\", \"SF\", \"COMP\", \"LINER\", \"AGN\")\n f_m <- apply(flux_em, c(2, 3), mean)\n f_sd <- apply(flux_em, c(2, 3), sd)\n for (i in 1:nb) {\n if (all(is.na(f_m[, i]))) {\n bpt[i] <- NA\n next\n }\n if(any(f_m[, i]/f_sd[, i] > snthresh, na.rm=TRUE)) bpt[i] <- \"EL\"\n if (any(is.na(f_m[c(\"h_beta\", \"oiii_5007\", \"h_alpha\", \"nii_6584\"), i]))) next\n if (f_m[\"h_beta\", i]/f_sd[\"h_beta\", i] > snthresh &&\n f_m[\"oiii_5007\", i]/f_sd[\"oiii_5007\", i] > snthresh &&\n f_m[\"h_alpha\", i]/f_sd[\"h_alpha\", i] > snthresh &&\n f_m[\"nii_6584\", i]/f_sd[\"nii_6584\", i] > snthresh) {\n o3hbeta <- log10(f_m[\"oiii_5007\", i]/f_m[\"h_beta\", i])\n n2halpha <- log10(f_m[\"nii_6584\", i]/f_m[\"h_alpha\", i])\n if ((o3hbeta <= 0.61/(n2halpha-0.05)+1.3) &&\n (n2halpha <= 0.05)) {\n bpt[i] <- \"SF\"\n next\n }\n if ((o3hbeta > 0.61/(n2halpha-0.05)+1.3 || n2halpha > 0.05) &&\n (o3hbeta <= 0.61/(n2halpha-0.47)+1.19)) {\n bpt[i] <- \"COMP\"\n next\n }\n if ((o3hbeta > 0.61/(n2halpha-0.47)+1.19 || n2halpha > 0.47) &&\n (o3hbeta > 1.05*n2halpha+0.45)) {\n bpt[i] <- \"AGN\"\n } else {\n bpt[i] <- \"LINER\"\n }\n }\n }\n bpt\n}\n\n\n## emission line ratios and various \"strong line\" metallicity calibrations\n \nget_lineratios <- function(flux_em, tauv, delta=0, tauv_mult=1, alaw=calzetti_mod) {\n o3hbeta <- log10(flux_em[,\"oiii_5007\"]/flux_em[,\"h_beta\"])\n o1halpha <- log10(flux_em[,\"oi_6300\"]/flux_em[,\"h_alpha\"])\n n2halpha <- log10(flux_em[,\"nii_6584\"]/flux_em[,\"h_alpha\"])\n s2halpha <- log10((flux_em[,\"sii_6717\"]+flux_em[,\"sii_6730\"])/flux_em[,\"h_alpha\"])\n \n \n o2 <- (flux_em[,\"oii_3727\"]+flux_em[,\"oii_3729\"])*alaw(3728., -tauv*tauv_mult, delta)\n o3 <- (flux_em[,\"oiii_4959\"]+flux_em[,\"oiii_5007\"])*alaw(4980., -tauv*tauv_mult, delta)\n hb <- flux_em[,\"h_beta\"]*alaw(4863., -tauv*tauv_mult, delta)\n \n r23 <- log10((o2+o3)/hb)\n o3n2 <- o3hbeta-n2halpha\n\n ## log(O/H) estimates from Pettini & Pagel 2004, Tremonti et al. 2004, or Dopita et al. 2016\n \n oh_n2 <- 9.37+2.03*n2halpha+1.26*n2halpha^2+0.32*n2halpha^3\n oh_o3n2 <- 8.73-0.32*o3n2\n oh_r23 <- 9.185-0.313*r23-0.264*r23^2-0.321*r23^3\n oh_n2s2ha <- 8.77+n2halpha-s2halpha+0.264*n2halpha\n \n data.frame(o3hbeta=o3hbeta, o1halpha=o1halpha, n2halpha=n2halpha, s2halpha=s2halpha,\n r23=r23, o3n2=o3n2, \n oh_n2=oh_n2, oh_o3n2=oh_o3n2, oh_r23=oh_r23, oh_n2s2ha=oh_n2s2ha)\n}\n\n \nsum_batchfits <- function(gdat, nnfits, sfits, drpcat, alaw=calzetti_mod, intr_bd=2.86, clim=0.95) {\n \n tauv.bd <- function(flux_em, intr_bd, delta=0, alaw) {\n bd <- flux_em[,'h_alpha']/flux_em[,'h_beta']\n bd[!is.finite(bd)] <- NA\n tauv <- log(bd/intr_bd)/(log(alaw(6562.8,1, delta))-log(alaw(4861.3,1, delta)))\n tauv[tauv<0] <- 0\n tauv\n }\n \n logl.ha.cor <- function(logl.halpha, tauv, delta=0, alaw) {\n att <- alaw(lambda=6562.8, tauv, delta)\n logl.halpha - log10(att)\n }\n \n nf <- length(gdat$xpos)\n fibersinbin <- rep(1, nf)\n if (exists(\"bin.fiber\", gdat)) {\n if (!exists(\"fibersinbin\", gdat)) {\n bin.fiber <- gdat$bin.fiber\n bin.no <- unique(bin.fiber[!is.na(bin.fiber)])\n for (i in seq_along(bin.no)) {\n fibersinbin[i] <- length(which(bin.fiber == bin.no[i]))\n }\n } else {\n fibersinbin <- gdat$fibersinbin\n }\n }\n \n nsim <- nrow(sfits$b_st)\n nt <- length(ages)\n fiberarea <- pi*cosmo::ascale(gdat$meta$z)^2\n plateifu <- rep(gdat$meta$plateifu, nf)\n \n ## projected distance in kpc and relative to effective radius\n \n d_kpc <- cosmo::ascale(gdat$meta$z)*sqrt(gdat$xpos^2+gdat$ypos^2)\n d_re <- sqrt(gdat$xpos^2+gdat$ypos^2)/\n drpcat$nsa_petro_th50[match(gdat$meta$plateifu,drpcat$plateifu)]\n \n \n ## stuff taken from nnfits\n \n d4000_n <- nnfits$d4000_n\n d4000_n_err <- nnfits$d4000_n_err\n lick_hd_a <- nnfits$lick[,'HdeltaA']\n lick_hd_a_err <- nnfits$lick.err[,'HdeltaA_err']\n mgfe <- sqrt(nnfits$lick[,'Mg_b']*(0.72*nnfits$lick[,'Fe5270']+0.28*nnfits$lick[,'Fe5335']))\n mgfe[is.nan(mgfe)] <- NA\n \n ## tauv from batch fits\n \n tauv_m <- colMeans(sfits$tauv)\n tauv_std <- apply(sfits$tauv, 2, sd)\n \n if (exists(\"delta\", sfits)) {\n delta <- sfits$delta\n } else {\n delta <- matrix(0, nsim, nf)\n }\n delta_m <- colMeans(delta)\n delta_std <- apply(delta, 2, sd)\n \n if (exists(\"ll\", sfits)) {\n ll_m <- colMeans(sfits$ll)\n } else {\n ll_m <- rep(NA, nf)\n }\n \n mgh_post <- array(NA, dim=c(nsim, nt+1, nf))\n sfh_post <- array(NA, dim=c(nsim, nt, nf))\n totalmg_post <- matrix(0, nsim, nt+1)\n \n varnames <- c(\"sigma_mstar\", \"sigma_sfr\", \"ssfr\", \"relsfr\",\n \"tbar\", \"tbar_lum\", \"g_i\",\n \"tauv_bd\", \"sigma_logl_ha\", \"sigma_logl_ha_ctauv\", \"sigma_logl_ha_ctauv_bd\",\n \"eqw_ha\", \"o3hbeta\", \"o1halpha\", \"n2halpha\", \"s2halpha\",\n \"r23\", \"o3n2\", \"oh_n2\", \"oh_o3n2\", \"oh_r23\", \"oh_n2s2ha\")\n suffixes <- c(\"m\", \"std\", \"lo\", \"hi\")\n \n for (i in seq_along(varnames)) {\n for (j in seq_along(suffixes)) {\n assign(paste(varnames[i], suffixes[j], sep=\"_\"), numeric(nf))\n }\n }\n \n sfh_all <- batch_sfh(gdat, sfits)\n \n for (i in 1:4) {\n assign(paste(varnames[i], suffixes[1], sep=\"_\"), colMeans(sfh_all[[varnames[i]]]))\n assign(paste(varnames[i], suffixes[2], sep=\"_\"), apply(sfh_all[[varnames[i]]], 2, sd))\n }\n \n \n em_all <- batch_em(gdat, sfits)\n bpt <- batch_bptclass(em_all$flux_em)\n \n \n for (i in 1:nf) {\n \n ## star formation history, etc.\n \n quants <- hdiofmcmc(sfh_all$sigma_mstar[,i])\n sigma_mstar_lo[i] <- quants[1]\n sigma_mstar_hi[i] <- quants[2]\n \n quants <- hdiofmcmc(sfh_all$sigma_sfr[,i])\n sigma_sfr_lo[i] <- quants[1]\n sigma_sfr_hi[i] <- quants[2]\n \n quants <- hdiofmcmc(sfh_all$ssfr[,i])\n ssfr_lo[i] <- quants[1]\n ssfr_hi[i] <- quants[2]\n \n quants <- hdiofmcmc(sfh_all$relsfr[,i])\n relsfr_lo[i] <- quants[1]\n relsfr_hi[i] <- quants[2]\n \n if (is.null(dim(sfits$norm_st))) {\n norm_st <- sfits$norm_st[i]\n } else {\n norm_st <- 1/sfits$norm_st[,i]\n }\n proxi <- get_proxies(b_st=sfits$b_st[,,i], norm_st=norm_st)\n \n tbar_m[i] <- mean(proxi$tbar)\n tbar_std[i] <- sd(proxi$tbar)\n quants <- hdiofmcmc(proxi$tbar, credmass=clim)\n tbar_lo[i] <- quants[1]\n tbar_hi[i] <- quants[2]\n \n tbar_lum_m[i] <- mean(proxi$tbar_lum)\n tbar_lum_std[i] <- sd(proxi$tbar_lum)\n quants <- hdiofmcmc(proxi$tbar_lum, credmass=clim)\n tbar_lum_lo[i] <- quants[1]\n tbar_lum_hi[i] <- quants[2]\n \n g_i_m[i] <- mean(proxi$g_i)\n g_i_std[i] <- sd(proxi$g_i)\n quants <- hdiofmcmc(proxi$g_i, credmass=clim)\n g_i_lo[i] <- quants[1]\n g_i_hi[i] <- quants[2]\n \n linesi <- get_lineratios(em_all$flux_em[,,i], sfits$tauv[,i], delta[,i], alaw=alaw)\n \n tauv_bd <- tauv.bd(em_all$flux_em[,,i], intr_bd=intr_bd, delta[,i], alaw=alaw)\n \n tauv_bd_m[i] <- mean(tauv_bd)\n tauv_bd_std[i] <- sd(tauv_bd)\n quants <- hdiofmcmc(tauv_bd, credmass=clim)\n tauv_bd_lo[i] <- quants[1]\n tauv_bd_hi[i] <- quants[2]\n \n ## uncorrected Halpha luminosity from stan fits\n \n sigma_logl_ha_m[i] <- mean(em_all$sigma_logl_em[,\"h_alpha\", i])\n sigma_logl_ha_std[i] <- sd(em_all$sigma_logl_em[,\"h_alpha\", i])\n quants <- hdiofmcmc(em_all$sigma_logl_em[,\"h_alpha\", i], credmass=clim)\n sigma_logl_ha_lo[i] <- quants[1]\n sigma_logl_ha_hi[i] <- quants[2]\n \n ## correct from stan fit estimate of tauv\n \n logl_ha_c <- logl.ha.cor(em_all$sigma_logl_em[, \"h_alpha\", i], sfits$tauv[,i], delta[,i], alaw=alaw)\n \n sigma_logl_ha_ctauv_m[i] <- mean(logl_ha_c)\n sigma_logl_ha_ctauv_std[i] <- sd(logl_ha_c)\n quants <- hdiofmcmc(logl_ha_c, credmass=clim)\n sigma_logl_ha_ctauv_lo[i] <- quants[1]\n sigma_logl_ha_ctauv_hi[i] <- quants[2]\n \n \n ## correct from balmer decrement\n \n logl_ha_c <- logl.ha.cor(em_all$sigma_logl_em[, \"h_alpha\", i], tauv_bd, delta[,i], alaw=alaw)\n \n sigma_logl_ha_ctauv_bd_m[i] <- mean(logl_ha_c)\n sigma_logl_ha_ctauv_bd_std[i] <- sd(logl_ha_c)\n quants <- hdiofmcmc(logl_ha_c, credmass=clim)\n sigma_logl_ha_ctauv_bd_lo[i] <- quants[1]\n sigma_logl_ha_ctauv_bd_hi[i] <- quants[2]\n \n eqw_ha_m[i] <- mean(em_all$ew_em[,\"h_alpha\", i])\n eqw_ha_std[i] <- sd(em_all$ew_em[,\"h_alpha\", i])\n quants <- hdiofmcmc(em_all$ew_em[,\"h_alpha\", i], credmass=clim)\n eqw_ha_lo[i] <- quants[1]\n eqw_ha_hi[i] <- quants[2]\n \n ## some emission line ratios\n \n o3hbeta_m[i] <- mean(linesi$o3hbeta)\n o3hbeta_std[i] <- sd(linesi$o3hbeta)\n quants <- hdiofmcmc(linesi$o3hbeta, credmass=clim)\n o3hbeta_lo[i] <- quants[1]\n o3hbeta_hi[i] <- quants[2]\n \n o1halpha_m[i] <- mean(linesi$o1halpha)\n o1halpha_std[i] <- sd(linesi$o1halpha)\n quants <- hdiofmcmc(linesi$o1halpha, credmass=clim)\n o1halpha_lo[i] <- quants[1]\n o1halpha_hi[i] <- quants[2]\n \n n2halpha_m[i] <- mean(linesi$n2halpha)\n n2halpha_std[i] <- sd(linesi$n2halpha)\n quants <- hdiofmcmc(linesi$n2halpha, credmass=clim)\n n2halpha_lo[i] <- quants[1]\n n2halpha_hi[i] <- quants[2]\n \n s2halpha_m[i] <- mean(linesi$s2halpha)\n s2halpha_std[i] <- sd(linesi$s2halpha)\n quants <- hdiofmcmc(linesi$s2halpha, credmass=clim)\n s2halpha_lo[i] <- quants[1]\n s2halpha_hi[i] <- quants[2]\n \n r23_m[i] <- mean(linesi$r23)\n r23_std[i] <- sd(linesi$r23)\n quants <- hdiofmcmc(linesi$r23, credmass=clim)\n r23_lo[i] <- quants[1]\n r23_hi[i] <- quants[2]\n \n o3n2_m[i] <- mean(linesi$o3n2)\n o3n2_std[i] <- sd(linesi$o3n2)\n quants <- hdiofmcmc(linesi$o3n2, credmass=clim)\n o3n2_lo[i] <- quants[1]\n o3n2_hi[i] <- quants[2]\n\n oh_n2_m[i] <- mean(linesi$oh_n2)\n oh_n2_std[i] <- sd(linesi$oh_n2)\n quants <- hdiofmcmc(linesi$oh_n2, credmass=clim)\n oh_n2_lo[i] <- quants[1]\n oh_n2_hi[i] <- quants[2]\n \n oh_o3n2_m[i] <- mean(linesi$oh_o3n2)\n oh_o3n2_std[i] <- sd(linesi$oh_o3n2)\n quants <- hdiofmcmc(linesi$oh_o3n2, credmass=clim)\n oh_o3n2_lo[i] <- quants[1]\n oh_o3n2_hi[i] <- quants[2]\n \n oh_r23_m[i] <- mean(linesi$oh_r23)\n oh_r23_std[i] <- sd(linesi$oh_r23)\n quants <- hdiofmcmc(linesi$oh_r23, credmass=clim)\n oh_r23_lo[i] <- quants[1]\n oh_r23_hi[i] <- quants[2]\n \n oh_n2s2ha_m[i] <- mean(linesi$oh_n2s2ha)\n oh_n2s2ha_std[i] <- sd(linesi$oh_n2s2ha)\n quants <- hdiofmcmc(linesi$oh_n2s2ha, credmass=clim)\n oh_n2s2ha_lo[i] <- quants[1]\n oh_n2s2ha_hi[i] <- quants[2]\n }\n \n data.frame(plateifu, d4000_n, d4000_n_err,\n lick_hd_a, lick_hd_a_err, mgfe,\n d_kpc, d_re,\n tauv_m, tauv_std, \n delta_m, delta_std, ll_m=ll_m,\n sigma_mstar_m , sigma_mstar_std , sigma_mstar_lo , sigma_mstar_hi , \n sigma_sfr_m , sigma_sfr_std , sigma_sfr_lo , sigma_sfr_hi , \n ssfr_m , ssfr_std , ssfr_lo , ssfr_hi , \n relsfr_m , relsfr_std , relsfr_lo , relsfr_hi , \n tbar_m , tbar_std , tbar_lo , tbar_hi , \n tbar_lum_m , tbar_lum_std , tbar_lum_lo , tbar_lum_hi , \n g_i_m , g_i_std , g_i_lo , g_i_hi , \n tauv_bd_m , tauv_bd_std , tauv_bd_lo , tauv_bd_hi , \n sigma_logl_ha_m , sigma_logl_ha_std , sigma_logl_ha_lo , sigma_logl_ha_hi , \n sigma_logl_ha_ctauv_m , sigma_logl_ha_ctauv_std , sigma_logl_ha_ctauv_lo , sigma_logl_ha_ctauv_hi , \n sigma_logl_ha_ctauv_bd_m , sigma_logl_ha_ctauv_bd_std , sigma_logl_ha_ctauv_bd_lo , sigma_logl_ha_ctauv_bd_hi ,\n eqw_ha_m, eqw_ha_std, eqw_ha_lo, eqw_ha_hi,\n o3hbeta_m , o3hbeta_std , o3hbeta_lo , o3hbeta_hi , \n o1halpha_m , o1halpha_std , o1halpha_lo , o1halpha_hi , \n n2halpha_m , n2halpha_std , n2halpha_lo , n2halpha_hi , \n s2halpha_m , s2halpha_std , s2halpha_lo , s2halpha_hi , \n r23_m , r23_std , r23_lo , r23_hi , \n o3n2_m , o3n2_std , o3n2_lo , o3n2_hi , \n oh_n2_m , oh_n2_std , oh_n2_lo , oh_n2_hi , \n oh_o3n2_m , oh_o3n2_std , oh_o3n2_lo , oh_o3n2_hi , \n oh_r23_m , oh_r23_std , oh_r23_lo , oh_r23_hi , \n oh_n2s2ha_m , oh_n2s2ha_std , oh_n2s2ha_lo , oh_n2s2ha_hi , \n bpt=bpt)\n}\n\n## estimated mean mass fraction in broad ages bins\n\nsum_binnedmass <- function(mgh_post, ages, ages.bins = c(0.1, 2.5, 5)) {\n T.gyr <- 10^(ages-9)\n ind.bins <- findInterval(ages.bins, T.gyr)\n dims <- dim(mgh_post)\n nsim <- dims[1]\n nfib <- dims[3]\n nt <- length(ages.bins)+2\n mgh.binned <- mgh_post[, c(1, ind.bins, dims[2]), ]\n mdiff <- mgh.binned[, 1:(nt-1),] - mgh.binned[, 2:nt, ]\n mb_m <- apply(mdiff, c(2, 3), mean)\n mb_sd <- apply(mdiff, c(2, 3), sd)\n df <- data.frame(cbind(t(mb_m), t(mb_sd)))\n df[df==0] <- NA\n T.ind <- c(0, T.gyr[ind.bins], T.gyr[length(T.gyr)])\n nt <- length(T.ind)\n bnames <- paste(formatC(T.ind[1:(nt-1)], format=\"f\", digits=1), \" < T < \",\n formatC(T.ind[2:nt], format=\"f\", digits=1), sep=\"\")\n names(df) <- c(paste(bnames, \"_m\", sep=\"\"), paste(bnames, \"_sd\", sep=\"\"))\n df\n}\n \n\n## computes highest density interval from a sample of representative values,\n## estimated as shortest credible interval.\n## arguments:\n## samplevec\n## is a vector of representative values from a probability distribution.\n## credmass\n## is a scalar between 0 and 1, indicating the mass within the credible\n## interval that is to be estimated.\n## value:\n## hdilim is a vector containing the limits of the hdi\n\n\nhdiofmcmc <- function(samplevec , credmass=0.95) {\n sortedpts <- sort(samplevec)\n ciidxinc <- floor(credmass * length(sortedpts))\n ncis <- length(sortedpts) - ciidxinc\n ciwidth <- rep(0 , ncis)\n for (i in 1:ncis) {\n ciwidth[i] <- sortedpts[i + ciidxinc] - sortedpts[i]\n }\n hdimin <- sortedpts[which.min(ciwidth)]\n hdimax <- sortedpts[which.min(ciwidth) + ciidxinc]\n hdilim <- c(hdimin , hdimax)\n return(hdilim)\n}\n\n", "meta": {"hexsha": "76f3939831bc16029f27e551987c1b180a3bdb49", "size": 24155, "ext": "r", "lang": "R", "max_stars_repo_path": "spmutils/R/spm_stan.r", "max_stars_repo_name": "mlpeck/spmutils", "max_stars_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spmutils/R/spm_stan.r", "max_issues_repo_name": "mlpeck/spmutils", "max_issues_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spmutils/R/spm_stan.r", "max_forks_repo_name": "mlpeck/spmutils", "max_forks_repo_head_hexsha": "ebd2a6a634f1f34c4bb0399136f8164092fa5e67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9565846599, "max_line_length": 126, "alphanum_fraction": 0.5786793625, "num_tokens": 8681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.33636278819118204}} {"text": "#' Calculate mass based on MT3D Model Run\n#'\n#' This function reads in a btn file, hds file, and ucn file to calculate\n#' the total mass (in units of lbs) in the model at each times step.\n#'\n#' @param BTN This is the name of the .btn file (without the file extension)\n#' @param HDS This is the name of the .hds file (without the file extension)\n#' @param UCN This is the name of the .ucn file (without the file extension)\n#' @export\n#' @examples\n#' masscalc(BTN = \"T04\", HDS = \"F95\", UCN = \"T041\")\n#' \n#' # A tibble: 32,325,120 x 7\n#' YEARS LAY ROW COL THICK CONC MASS\n#' \n#' 1 1 1 1 1 0 0 0\n#' 2 1 1 1 2 0 0 0\n#' 3 1 1 1 3 0 0 0\n#' 4 1 1 1 4 0 0 0\n#' 5 1 1 1 5 0 0 0\n#' 6 1 1 1 6 0 0 0\n#' 7 1 1 1 7 0 0 0\n#' 8 1 1 1 8 0 0 0\n#' 9 1 1 1 9 0 0 0\n#' 10 1 1 1 10 0 0 0\n#' # ... with 32,325,110 more rows\n#' \n#' # Determine the total mass in the top layer of model for each timestep:\n#' m <- masscalc(BTN = \"T04\", HDS = \"F95\", UCN = \"T041\")\n#' m %>% filter(LAY == 1) %>%\n#' group_by(YEARS) %>%\n#' summarise(TOT = sum(MASS))\n#' # A tibble: 16 x 2\n#' YEARS TOT\n#' \n#' 1 1 4866.663\n#' 2 2 4896.831\n#' 3 3 4926.615\n#' 4 4 4954.909\n#' 5 5 4981.363\n#' 6 6 5005.803\n#' 7 7 5028.133\n#' 8 8 5048.347\n#' 9 9 5066.414\n#' 10 10 5082.366\n#' 11 11 5096.217\n#' 12 12 5107.996\n#' 13 13 5117.772\n#' 14 14 5125.564\n#' 15 15 5101.810\n#' 16 100 1442.831\n#' \n#' # Note: the total mass is in units of lbs\n\nmasscalc <- function(BTN, HDS, UCN){\n b <- readbtn(BTN)\n NLAY <- b$NLAY\n NCOL <- b$NCOL\n NROW <- b$NROW\n NSP <- b$NPER\n NPRS <- b$NPRS\n POR <- b$TRANS$PRSITY\n THICK <- b$TRANS$dZ\n dX <- b$dX\n dY <- b$dY\n dZ <- b$TRANS %>% select(LAY, ROW, COL, dZ) \n TOP <- b$TOP$TOP\n BOTL1 <- b$TOP$TOP - dZ[dZ$LAY == 1, ]$dZ\n rm(TOP)\n gc()\n if(toupper(b$LUNIT) == \"FT\"){\n from_L <- 1000. / 2.54^3 / 12^3\n } else if(toupper(b$LUNIT) == \"FEET\"){\n from_L <- 1000. / 2.54^3 / 12^3\n } else if(toupper(b$LUNIT) == \"FOOT\"){\n from_L <- 1000. / 2.54^3 / 12^3\n } else if(toupper(b$LUNIT) == \"M\"){\n from_L_ <- 1000. / 100^3\n } else if(toupper(b$LUNIT) == \"METER\"){\n from_L_ <- 1000. / 100^3\n } else if(toupper(b$LUNIT) == \"METERS\"){\n from_L_ <- 1000. / 100^3\n } else if(toupper(b$LUNIT) == \"CM\"){\n from_L_ <- 1000.\n } else{\n print(\"LENGTH UNITS CAN BE ft, m, cm\")\n stop(\"LENGTH UNITS DON'T MATCH\\n CHECK THE BTN FILE\")\n }\n \n if(toupper(b$MUNIT) == \"MG\"){\n to_lbs <- 1. / 1000 * 2.2046226218\n } else if(toupper(b$MUNIT) == \"LB\"){\n to_lbs <- 1.\n } else if(toupper(b$MUNIT) == \"LBS\"){\n to_lbs <- 1.\n } else{\n to_lbs <- 1. / 10^6 / 1000. * 2.2046226218\n print(\"MASS UNITS ARE ASSUMED TO BE micrograms\")\n print(\"IF THIS IS NOT THE CASE, MAKE THE CORRECTION\")\n print(\"IN THE MASS DATA FRAME\")\n }\n \n if(toupper(b$TUNIT) == \"D\"){\n to_yrs <- 1. / 365\n } else if(toupper(b$TUNIT) == \"DAYS\"){\n to_yrs <- 1. / 365\n } else if(toupper(b$TUNIT) == \"DAY\"){\n to_yrs <- 1. / 365\n } else if(toupper(b$TUNIT) == \"H\"){\n to_yrs <- 1. / 24 / 365\n } else if(toupper(b$TUNIT) == \"HOUR\"){\n to_yrs <- 1. / 24 / 365\n } else if(toupper(b$MUNIT) == \"HOURS\"){\n to_yrs <- 1. / 24 / 365\n } else if(toupper(b$TUNIT) == \"S\"){\n to_yrs <- 1. / 60 / 24 / 365\n } else if(toupper(b$TUNIT) == \"SEC\"){\n to_yrs <- 1. / 60 / 24 / 365\n } else if(toupper(b$MUNIT) == \"SECS\"){\n to_yrs <- 1. / 60 / 24 / 365\n } else if(toupper(b$TUNIT) == \"Y\"){\n to_yrs <- 1.\n } else if(toupper(b$TUNIT) == \"YRS\"){\n to_yrs <- 1.\n } else if(toupper(b$MUNIT) == \"YEAR\"){\n to_yrs <- 1.\n } else{\n stop(\"TIME UNITS DON'T MATCH\\n CHECK THE BTN FILE\")\n }\n \n TIMPRS_YEARS <- b$TIMPRS * to_yrs\n rm(b) \n gc()\n h <- MFtools::readhds(HDS, NLAY, NSP) %>%\n dplyr::mutate(YEARS = TIME * to_yrs) \n \n h$GWE[h$GWE == 999] <- -10^6 # Index and filter this way to improve speed\n \n h %<>% dplyr::mutate(THICK = ifelse(LAY == 1, GWE - BOTL1, dZ$dZ)) %>% \n dplyr::mutate(THICK = ifelse(THICK < 0, 0, THICK))\n \n FLWYRS <- h %>% dplyr::group_by(YEARS) %>% dplyr::summarise(TIME = mean(YEARS)) %>% dplyr::select(YEARS)\n h %<>% dplyr::select(STP, LAY, ROW, COL, THICK) %>% dplyr::rename(PER = STP)\n \n TRANSYRS <- TIMPRS_YEARS %>% tibble::data_frame(YEARS = .)\n NTTS <- dplyr::full_join(FLWYRS, TRANSYRS, by = \"YEARS\") %>% nrow() %>% as.integer()\n dX <- dX %>% rep(NROW) %>% rep(NLAY) %>% rep(NTTS)\n dY <- dY %>% rep(each = NCOL) %>% rep(NLAY) %>% rep(NTTS)\n POR <- POR %>% rep(NTTS)\n \n MASS <- MFtools::readucn(UCN, NLAY, NTTS) %>%\n dplyr::mutate(YEARS = TIME * to_yrs) %>% \n dplyr::left_join(h, by = c(\"PER\", \"LAY\", \"ROW\", \"COL\")) %>%\n dplyr::mutate(dX = dX) %>%\n dplyr::mutate(dY = dY) %>%\n dplyr::mutate(POR = POR) %>%\n dplyr::mutate(CONC = ifelse(CONC < 0 , 0, CONC)) %>%\n dplyr::mutate(MASS = dX * dY * POR * THICK * CONC / from_L * to_lbs) %>%\n dplyr::select(YEARS, LAY, ROW, COL, THICK, CONC, MASS) \n \n rm(h)\n rm(dX) \n rm(dY)\n rm(POR) \n rm(BOTL1)\n rm(THICK)\n gc() \n return(MASS)\n }\n \n \n", "meta": {"hexsha": "576a0ae8cda19aaab8b69cad5546b6c9eb1fd61f", "size": 5827, "ext": "r", "lang": "R", "max_stars_repo_path": "R/masscalc.r", "max_stars_repo_name": "dpphat/MFtools", "max_stars_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2016-12-23T21:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T14:52:25.000Z", "max_issues_repo_path": "R/masscalc.r", "max_issues_repo_name": "dpphat/MFtools", "max_issues_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/masscalc.r", "max_forks_repo_name": "dpphat/MFtools", "max_forks_repo_head_hexsha": "fe87cb57f24e3b132a013111d9444e51cd1386aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-10-21T18:07:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-21T18:07:26.000Z", "avg_line_length": 33.8779069767, "max_line_length": 108, "alphanum_fraction": 0.477604256, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33613228959443797}} {"text": "#' Fit a local model via the local adaptive group lasso\n#' \n#' This function augments the covariates with local interactions, drops\n#' observations with zero weight, runs the adaptive grouped lasso, computes the\n#' residuals, and returns the necessary values for tuning or reporting.\n#' \n#' @param x matrix of observed covariates\n#' @param y vector of observed responses\n#' @param loc location at which to fit a model\n#' @param family exponential family distribution of the response\n#' @param varselect.method criterion to minimize in the regularization step of\n#' fitting local models - options are \\code{AIC}, \\code{AICc}, \\code{BIC},\n#' \\code{GCV}\n#' @param tuning logical indicating whether this model will be used to tune the\n#' bandwidth, in which case only the tuning criteria are returned\n#' @param kernel.weights vector of observation weights from the kernel\n#' @param prior.weights vector of prior observation weights provided by the user\n#' @param longlat \\code{TRUE} indicates that the coordinates are specified in\n#' longitude/latitude, \\code{FALSE} indicates Cartesian coordinates. Default\n#' is \\code{FALSE}.\n#' \n#' @return list of coefficients, nonzero coefficient identities, and tuning data\n#' @useDynLib lagr \n#'\nlagr.fit.inner = function(x, y, group.id, coords, loc, family, varselect.method, oracle, tuning, predict, simulation, n.lambda, lambda.min.ratio, lagr.convergence.tol, lagr.max.iter, verbose, kernel.weights=NULL, prior.weights=NULL, longlat=FALSE) {\n #Find which observations were made at the model location \n colocated = which(apply(coords, 1, function(cc) all(round(cc,5) == round(as.numeric(loc),5))))\n\n #Bail now if only one observation has weight:\n if (sum(kernel.weights)==length(colocated)) {\n return(list('tunelist'=list('df-local'=1, 'ssr-loc'=list('pearson'=Inf, 'deviance'=Inf))))\n }\n \n #Use oracular variable selection if specified\n orig.names = colnames(x)\n if (!is.null(oracle)) {\n x = matrix(x[,oracle], nrow=nrow(x), ncol=length(oracle))\n colnames(x) = oracle\n }\n\n #Establish groups for the group lasso and if there's an intercept, mark it as unpenalized\n if (0 %in% group.id)\n unpen = 0\n raw.vargroup = group.id\n \n #This is the naming system for the covariate-by-location interaction variables.\n raw.names = colnames(x)\n interact.names = vector()\n for (l in 1:length(raw.names)) {\n for (m in 1:ncol(coords)) {\n interact.names = c(interact.names, paste(raw.names[l], \":\", colnames(coords)[m], sep=\"\"))\n }\n }\n\n #Compute the covariate-by-location interactions\n q = ncol(coords)\n interacted = matrix(0, ncol=q*ncol(x), nrow=nrow(x))\n for (k in 1:ncol(x)) {\n for (ll in 1:q) {\n interacted[,q*(k-1)+ll] = x[,k, drop=FALSE]*(coords[,ll]-loc[[ll]])\n group.id = c(group.id, group.id[k])\n }\n }\n x.interacted = cbind(x, interacted)\n colnames(x.interacted) = c(raw.names, interact.names)\n\n #Combine prior weights and kernel weights\n w <- prior.weights * kernel.weights\n weighted = which(w>0)\n n.weighted = length(weighted)\n\n #Limit our attention to the observations with nonzero weight\n xxx = as.matrix(x.interacted[weighted,, drop=FALSE])\n yyy = as.matrix(y[weighted])\n colocated = which(kernel.weights[weighted]==1)\n w = w[weighted]\n sumw = sum(w)\n \n #Instantiate objects to store our output\n tunelist = list()\n\n if (is.null(oracle)) {\n #Use the adaptive group lasso to produce a local model:\n model = grouplasso(data=list(x=xxx, y=yyy), weights=w, index=group.id, family=family, maxit=lagr.max.iter, delta=2, nlam=n.lambda, min.frac=lambda.min.ratio, thresh=lagr.convergence.tol, unpenalized=unpen)\n\n vars = apply(as.matrix(model$beta), 2, function(x) {which(x!=0)})\n df = model$results$df + 1 #Add one because we must estimate the scale parameter.\n } else {\n model = glm(yyy~xxx-1, weights=w, family=family)\n vars = list(1:ncol(xxx))\n varset = vars[[1]]\n df = ncol(xxx) + 1 #Add one for the scale parameter\n \n fitted = model$fitted\n localfit = fitted[colocated]\n dispersion = summary(model)$dispersion\n k = 1\n\n #Estimating scale in penalty formula:\n loss = sumw * log(sum(w * model$residuals**2)) - log(sumw) + 1\n }\n\n if (sumw > ncol(x)) {\n if (is.null(oracle)) {\n #Extract the fitted values for each lambda:\n dispersion = model$results$dispersion\n\n #Using the grouplasso's criteria:\n loss = model$results[[varselect.method]]\n \n #Pick the lambda that minimizes the loss:\n k = which.min(loss)\n localfit = model$results$fitted[colocated,]\n df = df[k]\n if (k > 1) {\n varset = vars[[k]]\n } else {\n varset = NULL\n }\n } \n \n #Prepare some outputs for the bandwidth-finding scheme:\n tunelist[['localfit']] = localfit\n tunelist[['criterion']] = model$results[[varselect.method]]\n tunelist[['dispersion']] = dispersion\n tunelist[['n']] = sumw\n tunelist[['df']] = df\n tunelist[['df-local']] = length(colocated) * df / sumw\n \n } else {\n fitted = rep(meany, nrow(xxx))\n dispersion = 0\n loss = Inf\n loss.local = c(Inf) \n localfit = meany\n }\n \n #Get the coefficients:\n if (is.null(oracle)) {\n coefs = drop(model$beta)\n rownames(coefs) = colnames(xxx)\n\n #Use AIC weights, or not:\n if (varselect.method %in% c('wAIC','wAICc')) {\n #Big average based on a selection criterion:\n w = -model$results[[varselect.method]]\n w = matrix(w / sum(w))\n #coefs = (model$beta %*% w)[1:length(orig.names)]\n #conf.zero = drop((model$beta==0) %*% w)[1:length(orig.names)]\n coefs = drop(model$beta %*% w)\n conf.zero = drop((model$beta==0) %*% w)\n } else {\n #coefs = model$beta[1:length(orig.names),k]\n coefs = model$beta[,k]\n conf.zero = as.numeric(coefs==0)\n names(conf.zero) = names(coefs)\n }\n\n #list the covariates that weren't shrunk to zero, but don't bother listing the intercept.\n nonzero = raw.names[which(raw.vargroup %in% unique(group.id[which(conf.zero!=1)]))]\n nonzero = nonzero[nonzero != \"(Intercept)\"]\n\n #names(coefs) = raw.names\n #names(conf.zero) = colnames(raw.names) \n #names(coefs) = colnames(xxx)\n #names(conf.zero) = colnames(xxx) \n } else {\n #coefs = rep(0, length(orig.names))\n #names(coefs) = orig.names\n coefs = rep(0, ncol(xxx))\n names(coefs) = colnames(xxx)\n coefs[raw.names] = coef(model)[1:length(oracle)]\n nonzero = raw.names\n conf.zero = rep(0, length(orig.names))\n names(conf.zero) = colnames(raw.names)\n }\n \n \n if (tuning) {\n return(list(tunelist=tunelist, model=model, s=k, dispersion=dispersion, nonzero=nonzero, weightsum=sumw, loss=loss))\n } else if (predict) {\n return(list(tunelist=tunelist, coef=coefs, weightsum=sumw, s=k, dispersion=dispersion, nonzero=nonzero, conf.zero=conf.zero))\n } else if (simulation) {\n return(list(tunelist=tunelist, coef=coefs, s=k, dispersion=dispersion, fitted=localfit, nonzero=nonzero, conf.zero=conf.zero, actual=yyy[colocated], weightsum=sumw, loss=loss))\n } else {\n return(list(model=model, loss=loss, coef=coefs, nonzero=nonzero, conf.zero=conf.zero, s=k, loc=loc, df=df, loss.local=loss, dispersion=dispersion, fitted=localfit, weightsum=sumw, tunelist=tunelist))\n }\n}\n", "meta": {"hexsha": "10c4f0480ef26fdf470ac6f1776d24a97d131d2e", "size": 7827, "ext": "r", "lang": "R", "max_stars_repo_path": "R/lagr.fit.inner.r", "max_stars_repo_name": "wrbrooks/lagr", "max_stars_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "max_stars_repo_licenses": ["MIT"], "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/lagr.fit.inner.r", "max_issues_repo_name": "wrbrooks/lagr", "max_issues_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "max_issues_repo_licenses": ["MIT"], "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/lagr.fit.inner.r", "max_forks_repo_name": "wrbrooks/lagr", "max_forks_repo_head_hexsha": "7ac867f0bf091e8835917205cab44ea806d3c65e", "max_forks_repo_licenses": ["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.4126984127, "max_line_length": 249, "alphanum_fraction": 0.6174779609, "num_tokens": 2074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.33512050718409186}} {"text": "#' ---\n#' title: \"Script 3 of pipeline: read in workspace from script1, run beta diversity analysis\"\n#' author: \"Francesco Vitali\"\n#' output: html_document\n#' ---\n\n#' ```{r setup library load, include=FALSE}\n\n\nlibrary(phyloseq)\nlibrary(tidyverse)\nlibrary(data.table)\nlibrary(ggsci)\nlibrary(ggpubr)\nlibrary(microbiome)\nlibrary(patchwork)\nlibrary(metagenomeSeq)\nlibrary(vegan)\nlibrary(reshape2)\nlibrary(psych)\nlibrary(corrplot)\nlibrary(rstatix)\nlibrary(pairwiseAdonis)\n\n# red in workspace from script 1\n\nload (\"./WP3WP4_workspace\")\n\npalette_custom <- c(\"#1F78B4\", \"#E31A1C\", \"#FF7F00\", \"#33A02C\") \n\n#' knitr::opts_chunk$set(fig.width=unit(15,\"cm\"), fig.height=unit(11,\"cm\"))\n\n#' ```\n\n#' ```\n\n#' *BACTERIA*\n\n#############\n\n#' **WP3 BACTERIA**\n\n#############\n#' ```{r betadiv bact WP3, include=TRUE, echo = FALSE}\n\n# how to transform data for beta diversity analysis? \n\n\n# calculate the variation in read obtained per sample\nsdt = data.table(as(sample_data(WP3_initial_bact), \"data.frame\"),\n TotalReads = sample_sums(WP3_initial_bact), keep.rownames = TRUE)\nsummary(sdt$TotalReads)\nmax(sdt$TotalReads)/min(sdt$TotalReads)\n# variation in read depth is 7X \n\n# plot reads to find outliers\n\nsdt %>%\n filter(AnimalID != \"E149-40\") %>%\n ggboxplot(.,y = \"TotalReads\")\n\nsdt %>%\n filter(AnimalID != \"E149-40\") %>%\n summary()\n\n\n# NORMALIZATION: open problematic of which to choose\n\n# see https://microbiomejournal.biomedcentral.com/articles/10.1186/s40168-017-0237-y\n# see https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003531\n# see https://www.nature.com/articles/s41522-020-00160-w\n\n# new kid on the block! : avgdist() supported by Schloss \n# (see https://www.youtube.com/watch?v=xyufizOpc5I) also (https://www.youtube.com/watch?v=ht3AX5uZTTQ) also (https://www.youtube.com/watch?v=t5qXPIS-ECU)\n# So, the whole thing is about rarefaction or not. He support rarefaction as is the only method that is removing some relation between BC distance and \n# depth of sampling (n reads). To note, however, is that he is not doing the \"classical\" rarefaction (i.e. as in script2.r for alpha-div) using subsampling \n# and replacement, as it is not that good, as it really all depends on the seed and on which sequences get subsampled.\n# Instead, in the videos above, he use a nice combination of rarefaction and vegdist: he use rarefaction analysis followed by BC calculation multiple time, \n# so that the final distance matrix is an average od the distance matrices obtained over the different replicates and the relation with n° seqs disappear, but \n# without the risk of normal (single) rarefaction of loosing OTUs only by chance of the random procedure.\n# So, he is using un-rarefied and un-transformed counts, but rather performs this normalization step at the level of distance calculation. \n# From the video, and also conceptually, seems very convincing.\n\n# CSS remain one of the most interesting and supported, but rarefaction is still an option. \n# Evaluate both Bray and Jaccard eventually, in one case to evaluate changes in abundance, in the other\n# changes as presence/absence\n\n# Data driven evaluation: transform with rarefaction and with CSS, calculate bray and jaccard, compare with Mantel\n\n# generate a 10% prevalece filter dataset (see https://www.nature.com/articles/s41467-022-28034-z)\n\n# calculate prevalence for each ASV\nWP3.bact.ASVprev <- prevalence(subset_samples(WP3_initial_bact, AnimalID != \"E149-40\"), detection=0, sort=TRUE, count=F)\nsummary(names(WP3.bact.ASVprev[WP3.bact.ASVprev > 0.1]))\nsummary(names(WP3.bact.ASVprev[WP3.bact.ASVprev < 0.1]))\n# create an object with only the ASV in more than 10% of samples\nWP3_initial_bact_prevalence <- prune_taxa(names(WP3.bact.ASVprev[WP3.bact.ASVprev > 0.1]), subset_samples(WP3_initial_bact, AnimalID != \"E149-40\")) \n#check\nmin(prevalence(WP3_initial_bact_prevalence, detection=0, sort=TRUE, count=F))\n\n# rarefaction on the full dataset\nWP3_raref_bact<- rarefy_even_depth(subset_samples(WP3_initial_bact, AnimalID != \"E149-40\"),\n rngseed=1234,\n sample.size=round(0.99*min(sample_sums(subset_samples(WP3_initial_bact, AnimalID != \"E149-40\")))),\n replace=F)\n\n# rarefaction on the prevalence dataset\nWP3_raref_bact.prevalence<- rarefy_even_depth(subset_samples(WP3_initial_bact_prevalence, AnimalID != \"E149-40\"),\n rngseed=1234,\n sample.size=round(0.99*min(sample_sums(subset_samples(WP3_initial_bact_prevalence, AnimalID != \"E149-40\")))),\n replace=F)\n\n# CSS scaling (not removing singletons) on the full dataset\ndata.metagenomeSeq = phyloseq_to_metagenomeSeq(subset_samples(WP3_initial_bact, AnimalID != \"E149-40\"))\np = cumNormStat(data.metagenomeSeq) #default is 0.5\ndata.cumnorm = cumNorm(data.metagenomeSeq, p=p)\n#data.cumnorm\ndata.CSS = MRcounts(data.cumnorm, norm=TRUE, log=TRUE)\nWP3_CSS_bact <- subset_samples(WP3_initial_bact, AnimalID != \"E149-40\")\notu_table(WP3_CSS_bact) <- otu_table(data.CSS, taxa_are_rows = T)\n\n# CSS scaling (not removing singletons) on the prevalence dataset\ndata.metagenomeSeq = phyloseq_to_metagenomeSeq(subset_samples(WP3_initial_bact_prevalence, AnimalID != \"E149-40\"))\np = cumNormStat(data.metagenomeSeq) #default is 0.5\ndata.cumnorm = cumNorm(data.metagenomeSeq, p=p)\n#data.cumnorm\ndata.CSS = MRcounts(data.cumnorm, norm=TRUE, log=TRUE)\nWP3_CSS_bact.prevalence <- subset_samples(WP3_initial_bact_prevalence, AnimalID != \"E149-40\")\notu_table(WP3_CSS_bact.prevalence) <- otu_table(data.CSS, taxa_are_rows = T)\n\n\n# calculate distance matrices\nbray_WP3_raref <- phyloseq::distance(WP3_raref_bact, \"bray\")\nbray_WP3_CSS <- phyloseq::distance(WP3_CSS_bact, \"bray\")\n\nbray_WP3_raref.prevalence <- phyloseq::distance(WP3_raref_bact.prevalence, \"bray\")\nbray_WP3_CSS.prevalence <- phyloseq::distance(WP3_CSS_bact.prevalence, \"bray\")\n\n# check if order of the matrix is the same\nsummary(melt(as.matrix(bray_WP3_raref))[1] == melt(as.matrix(bray_WP3_CSS))[1])\n\n# perform mantel test\nset.seed(35264)\nmantel(xdis = bray_WP3_CSS, ydis = bray_WP3_raref, permutations = 999, method = \"pearson\")\n\nset.seed(35264)\nmantel(xdis = bray_WP3_CSS, ydis = bray_WP3_CSS.prevalence, permutations = 999, method = \"pearson\")\n\nset.seed(35264)\nmantel(xdis = bray_WP3_raref, ydis = bray_WP3_raref.prevalence, permutations = 999, method = \"pearson\")\n\nmds.css <- monoMDS(bray_WP3_CSS)\nmds.raref <- monoMDS(bray_WP3_raref)\nWP3.bact.proc <- procrustes(mds.raref, mds.css)\nsummary(WP3.bact.proc)\nplot(WP3.bact.proc)\n\n# see if biological interpretation is the same or not\ndf <- as(sample_data(WP3_CSS_bact), \"data.frame\")\nperm <- how(nperm = 999)\nsetBlocks(perm) <- with(df, AnimalID)\n\nset.seed(12387)\nadonis2(bray_WP3_CSS ~ Time * Diet * Sacrif_dfference, data = df, permutations = perm)\nset.seed(12387)\nadonis2(bray_WP3_CSS.prevalence ~ Time * Diet * Sacrif_dfference, data = df, permutations = perm)\n\nset.seed(12387)\nadonis2(bray_WP3_raref ~ Time * Diet * Sacrif_dfference, data = df, permutations = perm)\nset.seed(12387)\nadonis2(bray_WP3_raref.prevalence ~ Time * Diet * Sacrif_dfference, data = df, permutations = perm)\n\n# significance and R2 only show minor changes, but the Mantel correl between the two dist matrices is not high\n# overall, higher R2 in all factors (time diet and sacrifice difference) with CSS.prevalence dataset\n\n# This set the basis of choosing the CSS transformation on the prevalence (10%) filtered dataset as this seems\n# to show higher power to discriminate over the exp factors\n\n# Perform ordination now\n\n# NMDS\nset.seed(34624)\nWP3_bact_ord <- ordinate(WP3_CSS_bact.prevalence, \"NMDS\", distance = \"bray\")\np.WP3_bact_ord <- plot_ordination(physeq = WP3_CSS_bact.prevalence, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8, aes(fill = Diet, shape = Time)) #+ geom_text(mapping = aes(label = Gender), size = 3, nudge_x = 0.015, nudge_y = -0.015)\np.WP3_bact_ord <- p.WP3_bact_ord + theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(21,22,23,24))+\n xlab(\"Dim1\") + ylab(\"Dim2\") + labs( fill = \"Diet\") + theme(legend.position=\"right\")\n\np.WP3_bact_ord\n\ndf <- as(sample_data(WP3_CSS_bact.prevalence), \"data.frame\")\nperm <- how(nperm = 999)\nsetBlocks(perm) <- with(df, AnimalID)\n\nbray_WP3_CSS.prevalence <- phyloseq::distance(WP3_CSS_bact.prevalence, \"bray\")\n\nset.seed(12387)\nadonis2(bray_WP3_CSS.prevalence ~ Time + Diet + Sacrif_dfference, data = df, permutations = perm)\n\n# NMDS with Schloss approach\n\n# starting data is the untransformed DF, will still remove the lower outlier and remove low prevalence OTUs\nphylo_schloss <- subset_samples(WP3_initial_bact_prevalence, AnimalID != \"E149-40\")\notu_table_schloss <- otu_table(phylo_schloss)@.Data\n\notu_table_schloss %>%\n t() %>%\n as.data.frame() -> otu_table_schloss\n\n# adding some metadata\nrow.names(otu_table_schloss) == row.names(sample_data(phylo_schloss))\notu_table_schloss <- cbind(sample_data(phylo_schloss)[,3:4], otu_table_schloss)\n\n# calculate depth\nnSeqs <- min(sample_sums(phylo_schloss))\n\n# calculate rarefaction of BC distance and plot MDS\nset.seed(43655826)\nraref_BC <- avgdist(x = otu_table_schloss[,-c(1,2)], sample = nSeqs, dmethod = \"bray\", iterations = 100)\nset.seed(62853)\nschloss_MDS <- metaMDS(raref_BC)\n\nscores(schloss_MDS) %>%\n as_tibble(rownames = \"Group\") %>%\n ggplot(aes(x = NMDS1, y = NMDS2)) +\n geom_point(size = 5, stroke = 0.8, aes(fill = otu_table_schloss$Diet, shape = otu_table_schloss$Time))+\n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(21,22,23,24))+\n xlab(\"Dim1\") + ylab(\"Dim2\") + labs( fill = \"Diet\") + theme(legend.position=\"right\")\n\n# PCOA\n\nWP3_CSS_bact.prevalenceT3 <- subset_samples(WP3_CSS_bact.prevalence, Time == \"T3\")\n\nWP3_bact_ord <- ordinate(WP3_CSS_bact.prevalenceT3, \"PCoA\", distance = \"bray\")\np.WP3_bact_ord <- plot_ordination(physeq = WP3_CSS_bact.prevalenceT3, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + \n geom_point(size = 3, stroke = 0.8, aes(fill = Diet), shape = 22) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n xlab(\"PCoA1 (17.4%)\") + \n ylab(\"PCoA2 (11.6%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord_1\n\np.WP3_bact_ord -> p.WP3_bact_ord_final\n\n# pairwise adonis\ndf <- as(sample_data(WP3_CSS_bact.prevalenceT3), \"data.frame\")\nd.bacteria = phyloseq::distance(WP3_CSS_bact.prevalenceT3, \"bray\")\nset.seed(12387)\npw_ad_bactT3 <- pairwise.adonis(d.bacteria, factors = df$Diet, p.adjust.m = \"BH\", perm = 999)\n\npw_ad_bactT3$R2\n\n# PCoA using the Schloss avgdist method\nWP3_bact_ord <- ordinate(phylo_schloss, \"PCoA\",distance = raref_BC)\np.WP3_bact_ord <- plot_ordination(physeq = phylo_schloss, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8, aes(fill = Diet, shape = Time)) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(21,22,23,24))+\n xlab(\"PCoA1 (21.2%)\") + \n ylab(\"PCoA2 (8.6%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord_1\n\n\n\n# plot on distance from sacrifice\np.WP3_bact_ord <- plot_ordination(physeq = WP3_CSS_bact.prevalence, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8, aes(fill = Sacrif_dfference, shape = Time)) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_viridis_c(option = \"C\") +\n scale_shape_manual(values = c(21,22,23,24))+\n xlab(\"PCoA1 (17.3%)\") + \n ylab(\"PCoA2 (11.5%)\") + \n labs(fill = \"Days from \\nfirst sacrif.\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord_2\n\np.WP3_bact_ord_1 / p.WP3_bact_ord_2 -> p_suppl_ordi\n\nggsave('./Supplementary figure 2.png', p_suppl_ordi)\n\n# Which component capture best experimental factors?\n\nplot_scree(WP3_bact_ord, title = NULL)\n\n# extract coordinates on the first 20 axis, mount a df with exp factors\ndf <- as(sample_data(WP3_CSS_bact.prevalence), \"data.frame\")\nordi.coordinates <- as.data.frame(WP3_bact_ord$vectors[,1:10])\nrow.names(df) == row.names(ordi.coordinates) # row name is in same order\nordi.coordinates <- cbind(ordi.coordinates, df[,c(3,4,9:14)]) # attach some variables\n\n# BEST AXIS FOR TIME\nordi.coordinates %>%\n wilcox_effsize(Axis.1 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.2 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.3 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.4 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.5 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.6 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.7 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.8 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.9 ~ Time)\nordi.coordinates %>%\n wilcox_effsize(Axis.10 ~ Time)\n\n\nordi.coordinates %>%\n wilcox_test(Axis.1 ~ Time)\nordi.coordinates %>%\n wilcox_test(Axis.2 ~ Time)\n\n# BEST AXIS FOR Diet\nordi.coordinates %>%\n wilcox_effsize(Axis.1 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.2 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.3 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.4 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.5 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.6 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.7 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.8 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.9 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.10 ~ Diet)\n\n\n## Other numeric variables with correlation\n\nordi.coordinates %>%\n select(-c(Diet, start_body_weight, Time)) %>%\n corr.test(scale(.),method = \"spearman\", adjust = \"none\") -> cor_test_mat # Apply corr.test function\n\ncorrplot(as.matrix(cor_test_mat$r), order=\"original\", method = \"number\",tl.cex = 0.8,number.cex = 1, type = \"lower\",\n p.mat = as.matrix(cor_test_mat$p), sig.level = 0.05)\n\n\n\n# Maybe it has more sense to see beta diversity at T3, where the diet should have had an effect\n\nWP3_CSS_bact.prevalence.T3 <- subset_samples(WP3_CSS_bact.prevalence, Time == \"T3\") %>% prune_taxa(taxa_sums(.) > 0, .)\n\n# PCOA\nWP3_bact_ord <- ordinate(WP3_CSS_bact.prevalence.T3, \"PCoA\", distance = \"bray\")\np.WP3_bact_ord <- plot_ordination(physeq = WP3_CSS_bact.prevalence.T3, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8, shape = 21, aes(fill = Diet)) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n xlab(\"PCoA1 (17.4%)\") + \n ylab(\"PCoA2 (11.6%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord.T3\n\np.WP3_bact_ord\n\n## With Schloss\n# starting data is the untransformed DF, will still remove the lower outlier and remove low prevalence OTUs\nphylo_schloss <- subset_samples(subset_samples(WP3_initial_bact_prevalence, Time == \"T3\"), AnimalID != \"E149-40\")\notu_table_schloss <- otu_table(phylo_schloss)@.Data\n\notu_table_schloss %>%\n t() %>%\n as.data.frame() -> otu_table_schloss\n\n# adding some metadata\nrow.names(otu_table_schloss) == row.names(sample_data(phylo_schloss))\notu_table_schloss <- cbind(sample_data(phylo_schloss)[,3:4], otu_table_schloss)\n\n# calculate depth\nnSeqs <- min(sample_sums(phylo_schloss))\n\n# calculate rarefaction of BC distance and plot MDS\nset.seed(43655826)\nraref_BC <- avgdist(x = otu_table_schloss[,-c(1,2)], sample = nSeqs, dmethod = \"bray\", iterations = 100)\n\n# PCoA using the Schloss avgdist method\nWP3_bact_ord <- ordinate(phylo_schloss, \"PCoA\",distance = raref_BC)\n p.WP3_bact_ord <- plot_ordination(physeq = phylo_schloss, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8, aes(fill = Diet, shape = Time)) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(21,22,23,24))+\n xlab(\"PCoA1 (24.1%)\") + \n ylab(\"PCoA2 (12.3%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord_1\n\n\n# see if biological interpretation is the same or not\nbray_WP3_CSS.prevalence.T3 <- phyloseq::distance(WP3_CSS_bact.prevalence.T3, \"bray\")\ndf <- as(sample_data(WP3_CSS_bact.prevalence.T3), \"data.frame\")\nset.seed(12387)\nadonis2(bray_WP3_CSS.prevalence.T3 ~ Diet + Sacrif_dfference + end_body_weight, data = df, permutations = 999)\n\n\n# plot on distance from sacrifice\np.WP3_bact_ord <- plot_ordination(physeq = WP3_CSS_bact.prevalence.T3, WP3_bact_ord, axes = c(1,2))\np.WP3_bact_ord <- p.WP3_bact_ord + geom_point(size = 5, stroke = 0.8,shape = 21, aes(fill = Sacrif_dfference)) \np.WP3_bact_ord <- p.WP3_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_viridis_c(option = \"C\") +\n xlab(\"PCoA1 (17.3%)\") + \n ylab(\"PCoA2 (11.5%)\") + \n labs(fill = \"Days from \\nfirst sacrif.\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP3_bact_ord.T3\n\n# Which component capture best experimental factors?\n\nplot_scree(WP3_bact_ord, title = NULL)\n\n# extract coordinates on the first 20 axis, mount a df with exp factors\ndf <- as(sample_data(WP3_CSS_bact.prevalence.T3), \"data.frame\")\nordi.coordinates <- as.data.frame(WP3_bact_ord$vectors[,1:10])\nrow.names(df) == row.names(ordi.coordinates) # row name is in same order\nordi.coordinates <- cbind(ordi.coordinates, df[,c(4,9:14)]) # attach some variables\n\n# for sacrifice difference and other numeric var, I could do a scatterplot matrix\n\nordi.coordinates %>%\n select(-c(Diet, start_body_weight)) %>%\n corr.test(scale(.),method = \"spearman\", adjust = \"none\") -> cor_test_mat # Apply corr.test function\n\ncorrplot(as.matrix(cor_test_mat$r), order=\"original\", method = \"number\",tl.cex = 0.8,number.cex = 1,\n p.mat = as.matrix(cor_test_mat$p), sig.level = 0.05)\n\n# sacrifice difference strongly correlate with axis.2 \n\n# BEST AXIS FOR Diet\n\n\nordi.coordinates %>%\n wilcox_test(Axis.1 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.2 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.3 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.4 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.5 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.6 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.7 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.8 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.9 ~ Diet)\nordi.coordinates %>%\n wilcox_test(Axis.10 ~ Diet)\n\n# axis 1:5 have a significant anova respect to diet, should calculate which has the higher effect size\n\nordi.coordinates %>%\n wilcox_effsize(Axis.1 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.2 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.3 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.4 ~ Diet)\nordi.coordinates %>%\n wilcox_effsize(Axis.5 ~ Diet)\n\n\n#############\n\n#' **WP4 BACTERIA**\n\n###########\n\n#' ```{r betadiv bact WP4, include=TRUE, echo = FALSE}\n\n# Optimization of transformation and of methods was performed only for WP3, here take the same \n\n# calculate the variation in read obtained per sample\nsdt = data.table(as(sample_data(WP4_initial_bact), \"data.frame\"),\n TotalReads = sample_sums(WP4_initial_bact), keep.rownames = TRUE)\nsummary(sdt$TotalReads)\nmax(sdt$TotalReads)/min(sdt$TotalReads)\n\n# plot reads to find outliers\n\nsdt %>%\n filter(AnimalID != \"WP4-928\") %>%\n ggboxplot(.,y = \"TotalReads\")\n\nsdt %>%\n filter(AnimalID != \"WP4-928\") %>%\n summary()\n\n\n# generate a 10% prevalece filter dataset (see https://www.nature.com/articles/s41467-022-28034-z)\n\n# calculate prevalence for each ASV\nWP4.bact.ASVprev <- prevalence(subset_samples(WP4_initial_bact, AnimalID != \"WP4-928\"), detection=0, sort=TRUE, count=F)\nsummary(names(WP4.bact.ASVprev[WP4.bact.ASVprev > 0.1]))\nsummary(names(WP4.bact.ASVprev[WP4.bact.ASVprev < 0.1]))\n# create an object with only the ASV in more than 10% of samples\nWP4_initial_bact_prevalence <- prune_taxa(names(WP4.bact.ASVprev[WP4.bact.ASVprev > 0.1]), subset_samples(WP4_initial_bact, AnimalID != \"WP4-928\")) \n#check\nmin(prevalence(WP4_initial_bact_prevalence, detection=0, sort=TRUE, count=F))\n\n# CSS scaling (not removing singletons) on the prevalence dataset\ndata.metagenomeSeq = phyloseq_to_metagenomeSeq(subset_samples(WP4_initial_bact_prevalence, AnimalID != \"WP4-928\"))\np = cumNormStat(data.metagenomeSeq) #default is 0.5\ndata.cumnorm = cumNorm(data.metagenomeSeq, p=p)\n#data.cumnorm\ndata.CSS = MRcounts(data.cumnorm, norm=TRUE, log=TRUE)\nWP4_CSS_bact.prevalence <- subset_samples(WP4_initial_bact_prevalence, AnimalID != \"WP4-928\")\notu_table(WP4_CSS_bact.prevalence) <- otu_table(data.CSS, taxa_are_rows = T)\n\n# Perform ordination now\n# PCOA\n\nWP4_bact_ord <- ordinate(WP4_CSS_bact.prevalence, \"PCoA\", distance = \"bray\")\np.WP4_bact_ord <- plot_ordination(physeq = WP4_CSS_bact.prevalence, WP4_bact_ord, axes = c(1,2))\np.WP4_bact_ord <- p.WP4_bact_ord + geom_point(size = 3, stroke = 0.8, aes(fill = Inoculum_diet, shape = Time)) \np.WP4_bact_ord <- p.WP4_bact_ord + \n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(24,21,22,23))+\n xlab(\"PCoA1 (24%)\") + \n ylab(\"PCoA2 (14.5%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) -> p.WP4_bact_ord_1\n\n## Plot with WP3\nfigure2 <- p.WP3_bact_ord_final / p.WP4_bact_ord + plot_layout(guides = \"collect\") & theme(legend.position = 'left') \n\n#ggsave('./Figure 2.png', figure2)\n\n# pairwise adonis\ndf <- as(sample_data(subset_samples(WP4_CSS_bact.prevalence, Time == \"T3\" & Type != \"Inoculum\")), \"data.frame\")\nd.bacteria = phyloseq::distance(subset_samples(WP4_CSS_bact.prevalence, Time == \"T3\" & Type != \"Inoculum\"), \"bray\")\nset.seed(12387)\npw_ad_bactWP4 <- pairwise.adonis(d.bacteria, factors = df$Diets, p.adjust.m = \"BH\", perm = 999)\n\nmat1 <- data.frame(matrix(nrow=4,ncol=4,byrow=TRUE))\n\nmat1[1,1] <- 0\nmat1[1,2] <- pw_ad_bactT3$R2[1]\nmat1[1,3] <-pw_ad_bactT3$R2[2]\nmat1[1,4] <-pw_ad_bactT3$R2[4]\nmat1[2,1] <- pw_ad_bactT3$R2[1]\nmat1[2,2] <- 0\nmat1[2,3] <-pw_ad_bactT3$R2[4]\nmat1[2,4] <-pw_ad_bactT3$R2[5]\nmat1[3,1] <-pw_ad_bactT3$R2[2] \nmat1[3,2] <- pw_ad_bactT3$R2[4]\nmat1[3,3] <- 0\nmat1[3,4] <-pw_ad_bactT3$R2[6]\nmat1[4,1] <- pw_ad_bactT3$R2[3]\nmat1[4,2] <- pw_ad_bactT3$R2[5]\nmat1[4,3] <-pw_ad_bactT3$R2[6]\nmat1[4,4] <- 0\n\ncolnames(mat1) <- c(\"MBDT\", \"PVD\", \"MBD\", \"CTR\")\nrow.names(mat1) <- c(\"MBDT\", \"PVD\", \"MBD\", \"CTR\")\n\ncorrplot(as.matrix(mat1), type = \"lower\", diag = F, method = 'number', col = \"black\")\n\n###########\n\n#' **WP3 WP4 BACTERIA**\n\n###########\n\n# here analysis of WP3 at T3 and WP4 all timepoint, to highlight the \"passage\" in the FTM\n# optionally, one could select only the ID that actually were used for the pool\n\nWP3WP4_initial_bact <- subset_samples(phyloseq_obj_initial_bact, \n AnimalID != \"E149-40\" & AnimalID != \"WP4-928\") %>% prune_taxa(taxa_sums(.) > 0, .)\n\n\n\n# select sample subset of interest (i.e. only T3 of WP3)\n\nWP3WP4_initial_bact <- subset_samples(WP3WP4_initial_bact, WP != \"WP3\" | Time != \"T0\")\n\n# obtain rarefied object for alpha diversity\n\nWP3WP4_raref_bact<- rarefy_even_depth(WP3WP4_initial_bact,\n rngseed=1234,\n sample.size=round(0.99*min(sample_sums(WP3WP4_initial_bact))),\n replace=F)\n\n# calculate the variation in read obtained per sample\nsdt = data.table(as(sample_data(WP3WP4_initial_bact), \"data.frame\"),\n TotalReads = sample_sums(WP3WP4_initial_bact), keep.rownames = TRUE)\nsummary(sdt$TotalReads)\nmax(sdt$TotalReads)/min(sdt$TotalReads)\n\n# plot reads to find outliers\n\nsdt %>%\n ggboxplot(.,y = \"TotalReads\")\n\nsdt %>%\n summary()\n\n# generate a 10% prevalece filter dataset (see https://www.nature.com/articles/s41467-022-28034-z)\n\n# calculate prevalence for each ASV\nWP34.bact.ASVprev <- prevalence(WP3WP4_initial_bact, detection=0, sort=TRUE, count=F)\nsummary(names(WP34.bact.ASVprev[WP34.bact.ASVprev > 0.1]))\nsummary(names(WP34.bact.ASVprev[WP34.bact.ASVprev < 0.1]))\n# create an object with only the ASV in more than 10% of samples\nWP34_initial_bact_prevalence <- prune_taxa(names(WP34.bact.ASVprev[WP34.bact.ASVprev > 0.1]), WP3WP4_initial_bact) \n#check\nmin(prevalence(WP34_initial_bact_prevalence, detection=0, sort=TRUE, count=F))\n\n# CSS scaling (not removing singletons) on the prevalence dataset\ndata.metagenomeSeq = phyloseq_to_metagenomeSeq(WP34_initial_bact_prevalence)\np = cumNormStat(data.metagenomeSeq) #default is 0.5\ndata.cumnorm = cumNorm(data.metagenomeSeq, p=p)\n#data.cumnorm\ndata.CSS = MRcounts(data.cumnorm, norm=TRUE, log=TRUE)\nWP34_CSS_bact.prevalence <- WP34_initial_bact_prevalence\notu_table(WP34_CSS_bact.prevalence) <- otu_table(data.CSS, taxa_are_rows = T)\n\nsample_data(WP34_CSS_bact.prevalence)$Time\n\nWP34_bact_ord <- ordinate(WP34_CSS_bact.prevalence, \"PCoA\", distance = \"bray\")\np.WP34_bact_ord <- plot_ordination(physeq = WP34_CSS_bact.prevalence, WP34_bact_ord, axes = c(1,2))\np.WP34_bact_ord <- p.WP34_bact_ord + \n geom_point(size = 3, stroke = 0.8, aes(fill = Diets, shape = Time))+\n #geom_line(aes(group = AnimalID)) + \n geom_vline(xintercept= 0, linetype=\"dotted\") +\n geom_hline(yintercept= 0, linetype=\"dotted\") +\n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(24,21,22,25))+\n xlab(\"PCoA1 (24.1%)\") + \n ylab(\"PCoA2 (11.9%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) + \n theme(legend.position=\"none\")\n\np.WP34_bact_ord\n\n# Calculate alpha-div\n# richness\nalphadiv_WP34_bact <- microbiome::richness(WP3WP4_raref_bact)\ndf <- as(sample_data(WP3WP4_raref_bact), \"data.frame\")\ndf <- cbind(df, alphadiv_WP34_bact)\n\nrow.names(alphadiv_WP34_bact$vectors) == row.names(df)\n\ndf <- cbind(df, WP34_bact_ord$vectors[,1:2])\n\nggscatter(data = df, x = \"Axis.1\", y = \"observed\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA1\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggscatter(data = df, x = \"Axis.2\", y = \"observed\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA2\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggboxplot(data = df, x = \"WP\", y = \"observed\", add = \"jitter\", \n fill = \"WP\", palette =\"grey\", rotate = F, dot.size = 4) + theme_bw() + \n stat_compare_means(label.y = 100) +\n #ggtitle(label = \"Bacteria\", subtitle = \"Richness (n° of ASVs)\") +\n xlab(\"\") + \n ylab(\"Richness (n° of observed ASVs)\") + \n coord_flip() + \n theme(legend.position=\"none\") -> sottoplot_b_ord\n\n\n# evenness\nalphadiv_WP34_bact <- microbiome::evenness(WP3WP4_raref_bact)\ndf <- as(sample_data(WP3WP4_raref_bact), \"data.frame\")\ndf <- cbind(df, alphadiv_WP34_bact)\n\nrow.names(alphadiv_WP34_bact$vectors) == row.names(df)\n\ndf <- cbind(df, WP34_bact_ord$vectors[,1:2])\n\nggscatter(data = df, x = \"Axis.1\", y = \"pielou\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA1\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggscatter(data = df, x = \"Axis.2\", y = \"pielou\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA2\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggboxplot(data = df, x = \"WP\", y = \"pielou\", add = \"jitter\", \n fill = \"WP\", palette =\"grey\", rotate = F, dot.size = 4) + theme_bw() + \n stat_compare_means(label.y = .3, label.x = 2) +\n #ggtitle(label = \"Bacteria\", subtitle = \"Richness (n° of ASVs)\") +\n xlab(\"\") + \n ylab(\"Pielou's Evenness\") + \n coord_flip() + \n theme(legend.position=\"none\") -> sottoplot_b_ord_eve\n\n\n## Plot with other single \n\nfigure2 <- p.WP34_bact_ord + p.WP3_bact_ord_final/p.WP4_bact_ord + plot_layout(guides = \"collect\") & theme(legend.position = 'bottom')\n\n#ggsave('./Figure 2.png', figure2)\n\nlayout <- \"\nA\nA\nA\nB\nC\n\"\n\np.WP34_bact_ord / sottoplot_b_ord / sottoplot_b_ord_eve+ \n plot_layout(design = layout) -> panel_ord_bact\n\n#####\n\n#' *FUNGI*\n\n#' **WP3 FUNGI**\n\n#' ```{r betadiv fungi WP3, include=TRUE, echo = FALSE}\n\n\n#' **WP4 FUNGI**\n\n#' ```{r betadiv fungi WP4, include=TRUE, echo = FALSE}\n\n# how to transform data for alpha diversity analysis? \n\n#########################\n#' **WP3 WP4 FUNGI**\n######################\n\n# here analysis of WP3 at T3 and WP4 all timepoint, to highlight the \"passage\" in the FTM\n# optionally, one could select only the ID that actually were used for the pool\n\nWP3WP4_initial_fung <- subset_samples(phyloseq_obj_initial_fungi, \n AnimalID != \"E149-40\" & AnimalID != \"WP4-928\") %>% prune_taxa(taxa_sums(.) > 0, .)\n\n# select sample subset of interest (i.e. only T3 of WP3)\n\nWP3WP4_initial_fung <- subset_samples(WP3WP4_initial_fung, WP != \"WP3\" | Time != \"T0\")\n\n# obtain rarefied object for alpha diversity\n\nWP3WP4_raref_fung<- rarefy_even_depth(WP3WP4_initial_fung,\n rngseed=1234,\n sample.size=round(0.99*min(sample_sums(WP3WP4_initial_fung))),\n replace=F)\n\n\n# calculate the variation in read obtained per sample\nsdt = data.table(as(sample_data(WP3WP4_initial_fung), \"data.frame\"),\n TotalReads = sample_sums(WP3WP4_initial_fung), keep.rownames = TRUE)\nsummary(sdt$TotalReads)\nmax(sdt$TotalReads)/min(sdt$TotalReads)\n\n# plot reads to find outliers\n\nsdt %>%\n ggboxplot(.,y = \"TotalReads\")\n\nsdt %>%\n summary()\n\n# generate a 10% prevalece filter dataset (see https://www.nature.com/articles/s41467-022-28034-z)\n\n# calculate prevalence for each ASV\nWP34.fung.ASVprev <- prevalence(WP3WP4_initial_fung, detection=0, sort=TRUE, count=F)\nsummary(names(WP34.fung.ASVprev[WP34.fung.ASVprev > 0.01]))\nsummary(names(WP34.fung.ASVprev[WP34.fung.ASVprev < 0.01]))\n# create an object with only the ASV in more than 10% of samples\nWP34_initial_fung_prevalence <- prune_taxa(names(WP34.fung.ASVprev[WP34.fung.ASVprev > 0.1]), WP3WP4_initial_fung) \n#check\nmin(prevalence(WP34_initial_fung_prevalence, detection=0, sort=TRUE, count=F))\n\n# CSS scaling (not removing singletons) on the prevalence dataset\ndata.metagenomeSeq = phyloseq_to_metagenomeSeq(WP34_initial_fung_prevalence)\np = cumNormStat(data.metagenomeSeq) #default is 0.5\ndata.cumnorm = cumNorm(data.metagenomeSeq, p=p)\n#data.cumnorm\ndata.CSS = MRcounts(data.cumnorm, norm=TRUE, log=TRUE)\nWP34_CSS_fung.prevalence <- WP34_initial_fung_prevalence\notu_table(WP34_CSS_fung.prevalence) <- otu_table(data.CSS, taxa_are_rows = T)\n\nsample_data(WP34_CSS_fung.prevalence)$Time\n\n \n# Ordination and plot\n \nWP34_fung_ord <- ordinate(WP34_CSS_fung.prevalence, \"PCoA\", distance = \"bray\")\np.WP34_fung_ord <- plot_ordination(physeq = WP34_CSS_fung.prevalence, WP34_fung_ord, axes = c(1,2))\np.WP34_fung_ord <- p.WP34_fung_ord + \n geom_point(size = 3, stroke = 0.8, aes(fill = Diets, shape = Time))+\n #geom_line(aes(group = AnimalID)) + \n geom_vline(xintercept= 0, linetype=\"dotted\") +\n geom_hline(yintercept= 0, linetype=\"dotted\") +\n theme_bw() + \n theme( panel.grid.major = element_blank(),\n panel.grid.minor = element_blank()) + \n scale_fill_manual(values = palette_custom) +\n scale_shape_manual(values = c(24,21,22,25))+\n xlab(\"PCoA1 (40.9%)\") + \n ylab(\"PCoA2 (5.4%)\") + \n labs(fill = \"Diet\", shape = \"Time\") + \n theme(legend.position=\"right\") +\n guides(fill = guide_legend(override.aes = list(shape = 23))) + \n theme(legend.position=\"none\")\n\np.WP34_fung_ord\n\n\n# Calculate alpha-div\nalphadiv_WP34_fung <- microbiome::richness(WP3WP4_raref_fung)\ndf <- as(sample_data(WP3WP4_raref_fung), \"data.frame\")\ndf <- cbind(df, alphadiv_WP34_fung)\n\nrow.names(WP34_fung_ord$vectors) == row.names(df)\n\ndf <- cbind(df, WP34_fung_ord$vectors[,1:2])\n\nggscatter(data = df, x = \"Axis.1\", y = \"observed\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA1\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggscatter(data = df, x = \"Axis.2\", y = \"observed\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA2\") + \n ylab(\"Richness (n° of observed ASVs)\")\n\nggboxplot(data = df, x = \"WP\", y = \"observed\", add = \"jitter\", \n fill = \"WP\", palette =\"grey\", rotate = F, dot.size = 4) + theme_bw() + \n stat_compare_means(label.y = 90) +\n #ggtitle(label = \"Fungi\", subtitle = \"Richness (n° of ASVs)\") +\n xlab(\"\") + \n ylab(\"Richness (n° of observed ASVs)\") + \n coord_flip() + \n theme(legend.position=\"none\") -> sottoplot_f_ord\n\n\n# evenness\nalphadiv_WP34_fung <- microbiome::evenness(WP3WP4_raref_fung)\ndf <- as(sample_data(WP3WP4_raref_fung), \"data.frame\")\ndf <- cbind(df, alphadiv_WP34_fung)\n\nrow.names(alphadiv_WP34_fung$vectors) == row.names(df)\n\ndf <- cbind(df, WP34_fung_ord$vectors[,1:2])\n\nggscatter(data = df, x = \"Axis.1\", y = \"pielou\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA1\") + \n ylab(\"Pielou's Evenness\")\n\nggscatter(data = df, x = \"Axis.2\", y = \"pielou\", add = \"reg.line\", add.params = list(linetype = \"dotted\")) + \n stat_cor(method = \"pearson\") + \n xlab(\"PCoA2\") + \n ylab(\"Pielou's Evenness\")\n\nggboxplot(data = df, x = \"WP\", y = \"pielou\", add = \"jitter\", \n fill = \"WP\", palette =\"grey\", rotate = F, dot.size = 4) + theme_bw() + \n stat_compare_means(label.y = .2, label.x = 2) +\n #ggtitle(label = \"Bacteria\", subtitle = \"Richness (n° of ASVs)\") +\n xlab(\"\") + \n ylab(\"Pielou's Evenness\") + \n coord_flip() + \n theme(legend.position=\"none\") -> sottoplot_f_ord_eve\n\n\n \nlayout <- \"\nA\nA\nA\nB\nC\n\"\n\np.WP34_fung_ord / sottoplot_f_ord / sottoplot_f_ord_eve+ \n plot_layout(design = layout) -> panel_ord_fung\n\n\nggarrange(panel_ord_bact, panel_ord_fung, \n labels = c(\"A\", \"B\"),\n ncol = 2) -> figure2\n\n\nggsave('./Figure 2.png', figure2)\n\n#' ```\n\n#' ```{r write images, include=FALSE}\n#' knitr::opts_chunk$set(echo = TRUE)\n\n# use ggsave for images\n\n#' ```\n\n", "meta": {"hexsha": "5d7592c4a85fcdf9ff75792f93f37487d1565313", "size": 35478, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Script3.r", "max_stars_repo_name": "FrancescoVit/TargetMeta_pipeline", "max_stars_repo_head_hexsha": "96f97e967f76de96e4845fa00acd7c6f792571e6", "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": "R/Script3.r", "max_issues_repo_name": "FrancescoVit/TargetMeta_pipeline", "max_issues_repo_head_hexsha": "96f97e967f76de96e4845fa00acd7c6f792571e6", "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": "R/Script3.r", "max_forks_repo_name": "FrancescoVit/TargetMeta_pipeline", "max_forks_repo_head_hexsha": "96f97e967f76de96e4845fa00acd7c6f792571e6", "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": 37.0721003135, "max_line_length": 190, "alphanum_fraction": 0.7015897176, "num_tokens": 11584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3345838170744818}} {"text": "[[[[[\n FUNDAMENTAL DECOMPOSITION\n We prove here that \n H(y|x) <= H_C(x,y) - H(x) + c\n]]]]]\n\ndefine (all-together x*)\n\nlet c debug 100 [constant to satisfy Kraft (see lemma)]\n\nlet x debug run-utm-on debug x*\n\nlet H-of-x debug length x*\n\n[programs we've discovered that calculate pairs \n starting with x]\nlet programs nil\n\nlet (stage n)\n [generate requirements for all new programs we've\n discovered that produce (x y) pairs]\n let programs \n (add-to-set debug (halts? nil debug n) programs) \n (stage + n 1)\n\n[at stage n = 0, 1, 2, 3, ...]\n[look at all programs with <=n bits that halt within time n]\n[returns list of all of them that produce pairs (x y)]\nlet (halts? p bits-left)\n let v try n C p [C is eval read-exp if C = U]\n if = success car v (look-at cadr v)\n if = 0 bits-left nil\n append (halts? append p cons 0 nil - bits-left 1)\n (halts? append p cons 1 nil - bits-left 1)\n\n[returns (p) if C(p) = (x y), otherwise ()]\nlet (look-at v)\n if (and (is-pair v) \n = x car v ) cons p nil\n nil\n\n[logical \"and\"]\nlet (and p q)\n if p q false\n\n[is x a pair?]\nlet (is-pair? x)\n if atom x false\n if atom cdr x false\n if atom cdr cdr x true\n false\n\n[is an element in a set?]\nlet (is-in-set? element set)\n if atom set false\n if = element car set true\n (is-in-set? element cdr set)\n\n[forms set union avoiding duplicates, \n and makes requirement for each new find]\nlet (add-to-set new old)\n if atom new old \n let first-new car new\n let rest-new cdr new\n if (is-in-set? first-new old) (add-to-set rest-new old)\n (do (make-requirement first-new)\n cons first-new (add-to-set rest-new old)\n )\n \n[first argument discarded, done for side-effect only!]\nlet (do x y) y\n\n[given new p such that C(p) = (x y), \n we produce the requirement for C_x\n that there be a program for y that is |p|-H(x)+c bits long]\nlet (make-requirement p)\n display cons cadr cadr try no-time-limit C p \n cons - + c length p H-of-x\n nil\n\nlet C ' [here eval read-exp gives U]\n[test case special-purpose computer C here in place of U:] \n[C(00100001) with x-1 and y-1 0's gives pair (x xy)]\n[loop function gives number of bits up to next 1 bit]\n let (loop n)\n if = 1 read-bit n\n (loop + n 1)\n let x (loop 1)\n let y (loop 1)\n cons x cons * x y nil\n\n[HERE GOES!]\n(stage 0)\n\ndefine all-together\nvalue (lambda (x*) ((' (lambda (c) ((' (lambda (x) ((' (\n lambda (H-of-x) ((' (lambda (programs) ((' (lambda\n (stage) ((' (lambda (halts?) ((' (lambda (look-at\n ) ((' (lambda (and) ((' (lambda (is-pair?) ((' (la\n mbda (is-in-set?) ((' (lambda (add-to-set) ((' (la\n mbda (do) ((' (lambda (make-requirement) ((' (lamb\n da (C) (stage 0))) (' ((' (lambda (loop) ((' (lamb\n da (x) ((' (lambda (y) (cons x (cons (* x y) nil))\n )) (loop 1)))) (loop 1)))) (' (lambda (n) (if (= 1\n (read-bit)) n (loop (+ n 1)))))))))) (' (lambda (\n p) (display (cons (car (cdr (car (cdr (try no-time\n -limit C p))))) (cons (- (+ c (length p)) H-of-x) \n nil)))))))) (' (lambda (x y) y))))) (' (lambda (ne\n w old) (if (atom new) old ((' (lambda (first-new) \n ((' (lambda (rest-new) (if (is-in-set? first-new o\n ld) (add-to-set rest-new old) (do (make-requiremen\n t first-new) (cons first-new (add-to-set rest-new \n old)))))) (cdr new)))) (car new)))))))) (' (lambda\n (element set) (if (atom set) false (if (= element\n (car set)) true (is-in-set? element (cdr set)))))\n )))) (' (lambda (x) (if (atom x) false (if (atom (\n cdr x)) false (if (atom (cdr (cdr x))) true false)\n ))))))) (' (lambda (p q) (if p q false)))))) (' (l\n ambda (v) (if (and (is-pair v) (= x (car v))) (con\n s p nil) nil)))))) (' (lambda (p bits-left) ((' (l\n ambda (v) (if (= success (car v)) (look-at (car (c\n dr v))) (if (= 0 bits-left) nil (append (halts? (a\n ppend p (cons 0 nil)) (- bits-left 1)) (halts? (ap\n pend p (cons 1 nil)) (- bits-left 1))))))) (try n \n C p))))))) (' (lambda (n) ((' (lambda (programs) (\n stage (+ n 1)))) (add-to-set (debug (halts? nil (d\n ebug n))) programs))))))) nil))) (debug (length x*\n ))))) (debug (car (cdr (try no-time-limit (' (eval\n (read-exp))) (debug x*)))))))) (debug 100)))\n\ndefine x* 3\n\ndefine x*\nvalue 3\n\nlength bits x* \n\nexpression (length (bits x*))\nvalue 16\n\n[give all-together x*]\ntry 60 cons cons \"'\n cons all-together \n nil \n cons cons \"' \n cons bits x* \n nil \n nil \n nil\n\nexpression (try 60 (cons (cons ' (cons all-together nil)) (co\n ns (cons ' (cons (bits x*) nil)) nil)) nil)\ndebug 100\ndebug (0 0 1 1 0 0 1 1 0 0 0 0 1 0 1 0)\ndebug 3\ndebug 16\ndebug 0\ndebug ()\ndebug 1\ndebug ()\ndebug 2\ndebug ()\ndebug 3\ndebug ()\ndebug 4\ndebug ((0 0 1 1))\ndebug 5\ndebug ((0 0 1 0 1) (0 0 1 1))\ndebug 6\ndebug ((0 0 1 0 0 1) (0 0 1 0 1) (0 0 1 1))\ndebug 7\ndebug ((0 0 1 0 0 0 1) (0 0 1 0 0 1) (0 0 1 0 1) (0 0 1 \n 1))\ndebug 8\ndebug ((0 0 1 0 0 0 0 1) (0 0 1 0 0 0 1) (0 0 1 0 0 1) (\n 0 0 1 0 1) (0 0 1 1))\ndebug 9\nvalue (failure out-of-time ((3 88) (6 89) (9 90) (12 91)\n (15 92)))\n\ndefine x* 4\n\ndefine x*\nvalue 4\n\nlength bits x* \n\nexpression (length (bits x*))\nvalue 16\n\n[give all-together x*]\ntry 60 cons cons \"'\n cons all-together \n nil \n cons cons \"' \n cons bits x* \n nil \n nil \n nil\n\nexpression (try 60 (cons (cons ' (cons all-together nil)) (co\n ns (cons ' (cons (bits x*) nil)) nil)) nil)\ndebug 100\ndebug (0 0 1 1 0 1 0 0 0 0 0 0 1 0 1 0)\ndebug 4\ndebug 16\ndebug 0\ndebug ()\ndebug 1\ndebug ()\ndebug 2\ndebug ()\ndebug 3\ndebug ()\ndebug 4\ndebug ()\ndebug 5\ndebug ((0 0 0 1 1))\ndebug 6\ndebug ((0 0 0 1 0 1) (0 0 0 1 1))\ndebug 7\ndebug ((0 0 0 1 0 0 1) (0 0 0 1 0 1) (0 0 0 1 1))\ndebug 8\ndebug ((0 0 0 1 0 0 0 1) (0 0 0 1 0 0 1) (0 0 0 1 0 1) (\n 0 0 0 1 1))\ndebug 9\nvalue (failure out-of-time ((4 89) (8 90) (12 91) (16 92\n )))\n", "meta": {"hexsha": "d6a92dabce20b591051c7c510253e902fa466867", "size": 6679, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/decomp.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/decomp.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/decomp.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 29.1659388646, "max_line_length": 62, "alphanum_fraction": 0.4979787393, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.33400770541375235}} {"text": "library(deSolve) \r\nlibrary(ggplot2)\r\nlibrary(rstan)\r\n\r\n# ALL files should be in the same working directory. The user should set this directory under the 'path' varialbe\r\noptions(max.print=999999)\r\npath <- \"\" ###### USER INPUT HERE #####\r\nsetwd(path)\r\nload(\"results.RData\")\r\nstan_fit <- extract(fit)\r\n\r\n# !!!!!!!!! In exposure concentration, the last value will not be taken into account by the model, so it better be zero !!!!!!!!!!!!!!!!!!!\r\n##########################################\r\n# Function for creating parameter vector #\r\n##########################################\r\n\r\ncreate.params <- function(input, stan_fit, stochastic = TRUE){\r\n with( as.list(input),{\r\n \r\n # List with names of all possible compartments\r\n comps <- list(\"Lungs\" = \"Lungs\" ,\"Liver\"=\"Liver\", \"Spleen\"=\"Spleen\", \"Kidneys\"=\"Kidneys\", \"Heart\"=\"Heart\", \"Brain\"=\"Brain\",\r\n \"Uterus\"=\"Uterus\", \"Skeleton\"=\"Skeleton\", \"Skin\"=\"Skin\", \"Soft\"=\"Soft\") # List with names of all possible compartments\r\n \r\n \r\n \r\n ### Density of tissues/organs\r\n d_tissue <- 1 #g/ml\r\n d_skeleton <- 1.92 #g/ml\r\n d_adipose <- 0.940 #g/ml\r\n \r\n Q_total <- (1.54*weight^0.75)*60 # Total Cardiac Output (ml/h)\r\n \r\n Total_Blood <- 0.06*weight+0.77 # Total blood volume (ml)\r\n \r\n #Arterial blood volume\r\n Vart <- 0.15*Total_Blood #(ml)\r\n \r\n #Veins blood volume\r\n Vven <-0.64*Total_Blood #(ml)\r\n \r\n #Tissue weight fraction \r\n Tissue_fractions <- c(0.5, 3.66, 0.2, 0.73, 0.33, 0.57, 0.011, 10, 19.03, NA)/100 # % of BW. Na values refers to the volume of the rest organs(RoB)\r\n \r\n #Regional blood flow fraction\r\n Regional_flow_fractions <- c(100, 17.4, 1.22, 14.1, 4.9, 2, 1.1, 12.2, 5.8, NA)/100 # % of total cardiac output\r\n \r\n #Capillary volume fractions (fractions of tissue volume)\r\n Capillary_fractions <- c(0.36, 0.21, 0.22, 0.16, 0.26, 0.03, 0.04, 0.04, 0.02, 0.04) # fraction of tissue volume\r\n # Where NA, it is the same value as Rest of Body due to luck od data for uterus and adipose\r\n \r\n #Macrophage content (g per gram of tissue)\r\n Macrophage_fraction <- c(0.04, 0.1, 0.3, 0.02, 0.02, 0.04, 0.04, 0.04, 0.02, 0.02) \r\n Macrophage_fraction_blood <- 0.01\r\n \r\n CLE_ua <- 0\r\n CLE_muc <- 0.01181567\r\n k_ua_br <- 0\r\n CLE_hep <- 1.52e-03\r\n CLE_muc_cor <- 1\r\n k_ab0 <- 1.45\r\n k_de <- 6.7e-19\r\n k_ab0_spl <- 0.5\r\n \r\n W_tis <- rep(0,length(comps))\r\n V_tis <- rep(0,length(comps))\r\n V_cap <- rep(0,length(comps))\r\n W_macro <- rep(0,length(comps)) \r\n Q <- rep(0,length(comps))\r\n \r\n for (i in 1:(length(comps)-1)) {\r\n control <- comps[i]\r\n \r\n Tissue_fractions[i] <- ifelse(is.na(control), NA, Tissue_fractions[i])\r\n Regional_flow_fractions[i] <- ifelse(is.na(control), NA, Regional_flow_fractions[i])\r\n Capillary_fractions[i] <- ifelse(is.na(control), NA, Capillary_fractions[i])\r\n Macrophage_fraction[i] <- ifelse(is.na(control), NA, Macrophage_fraction[i])\r\n \r\n ### Calculation of tissue weights \r\n W_tis[i] <- weight*Tissue_fractions[i]\r\n W_macro[i] <- W_tis[i]*Macrophage_fraction[i]\r\n \r\n ###Calculation of tissue volumes\r\n \r\n if (i==9){\r\n V_tis[i] <- W_tis[i]/d_skeleton\r\n } else{\r\n V_tis[i] <- W_tis[i]/d_tissue \r\n }\r\n \r\n ###Calculation of capillary volumes\r\n V_cap[i] <- V_tis[i]*Capillary_fractions[i]\r\n \r\n \r\n ###Calculation of regional blood flows\r\n Q[i] <- Q_total*Regional_flow_fractions[i]\r\n }\r\n \r\n ### Calculations for \"Rest of Body\" compartment\r\n W_tis[10] <- weight - sum(W_tis[1:(length(W_tis)-1)], na.rm = TRUE)\r\n V_tis[10] <- W_tis[10]/d_adipose #(considering that the density of the rest tissues is 1 g/ml)\r\n Q[10] <- Q_total - sum(Q[2:(length(Q)-1)],na.rm = TRUE)\r\n V_cap[10] <- V_tis[10]*Capillary_fractions[10]\r\n # V_cap[9] <- Total_Blood - Vven - Vart - sum(V_cap[1:(length(V_cap)-1)], na.rm = TRUE) #this is problematic because it produces negative number\r\n W_macro[10] <- W_tis[10]*Macrophage_fraction[10]\r\n #Capillary_fractions[1] <- V_cap[1]/V_tis[1]\r\n \r\n Macro_blood <- Macrophage_fraction_blood*Total_Blood\r\n Wm_al <- W_macro[1]\r\n \r\n if(stochastic == TRUE){\r\n x_fast <- exp(rnorm(1,mean(stan_fit$theta_tr[,1]), sd(stan_fit$theta_tr[,1])))\r\n CLE_ur<- exp(rnorm(1,mean(stan_fit$theta_tr[,2]), sd(stan_fit$theta_tr[,2])))\r\n uptake <- exp(rnorm(1,mean(stan_fit$theta_tr[,3]), sd(stan_fit$theta_tr[,3])))\r\n k_alpc_tb <- exp(rnorm(1,mean(stan_fit$theta_tr[,4]), sd(stan_fit$theta_tr[,4])))\r\n k_lu_al <- exp(rnorm(1,mean(stan_fit$theta_tr[,5]), sd(stan_fit$theta_tr[,5])))\r\n k_al_lu <- exp(rnorm(1,mean(stan_fit$theta_tr[,6]), sd(stan_fit$theta_tr[,6])))\r\n uptake_al <- exp(rnorm(1,mean(stan_fit$theta_tr[,7]), sd(stan_fit$theta_tr[,7])))\r\n uptake_skel <- exp(rnorm(1,mean(stan_fit$theta_tr[,8]), sd(stan_fit$theta_tr[,8])))\r\n P_lu <- exp(rnorm(1,mean(stan_fit$theta_tr[,9]), sd(stan_fit$theta_tr[,9])))\r\n P_ki <- exp(rnorm(1,mean(stan_fit$theta_tr[,10]), sd(stan_fit$theta_tr[,10])))\r\n P_br <- exp(rnorm(1,mean(stan_fit$theta_tr[,11]), sd(stan_fit$theta_tr[,11])))\r\n P_ut <- exp(rnorm(1,mean(stan_fit$theta_tr[,12]), sd(stan_fit$theta_tr[,12])))\r\n P_skin <- exp(rnorm(1,mean(stan_fit$theta_tr[,13]), sd(stan_fit$theta_tr[,13])))\r\n P_soft_skel_ht <- exp(rnorm(1,mean(stan_fit$theta_tr[,14]), sd(stan_fit$theta_tr[,14])))\r\n P_li_spl <- exp(rnorm(1,mean(stan_fit$theta_tr[,15]), sd(stan_fit$theta_tr[,15])))\r\n \r\n }else{\r\n x_fast <- exp(mean(stan_fit$theta_tr[,1]))\r\n CLE_ur<- exp(mean(stan_fit$theta_tr[,2]))\r\n uptake <- exp(mean(stan_fit$theta_tr[,3]))\r\n k_alpc_tb <- exp(mean(stan_fit$theta_tr[,4]))\r\n k_lu_al <- exp(mean(stan_fit$theta_tr[,5]))\r\n k_al_lu <- exp(mean(stan_fit$theta_tr[,6]))\r\n uptake_al <- exp(mean(stan_fit$theta_tr[,7]))\r\n uptake_skel <- exp(mean(stan_fit$theta_tr[,8]))\r\n P_lu <- exp(mean(stan_fit$theta_tr[,9]))\r\n P_ki <- exp(mean(stan_fit$theta_tr[,10]))\r\n P_br <- exp(mean(stan_fit$theta_tr[,11]))\r\n P_ut <- exp(mean(stan_fit$theta_tr[,12]))\r\n P_skin <- exp(mean(stan_fit$theta_tr[,13]))\r\n P_soft_skel_ht <- exp(mean(stan_fit$theta_tr[,14]))\r\n P_li_spl <- exp(mean(stan_fit$theta_tr[,15]))\r\n \r\n }\r\n\r\n \r\n e1 <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = mean(stan_fit$sigma[,1]) , sd = sd(stan_fit$sigma[,1]))\r\n e2 <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = mean(stan_fit$sigma[,2]) , sd = sd(stan_fit$sigma[,2]))\r\n e3 <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = mean(stan_fit$sigma[,3]) , sd = sd(stan_fit$sigma[,3]))\r\n \r\n uptake_spl <- uptake\r\n P_li <- P_li_spl\r\n P_spl <- P_li_spl\r\n P_ht <- P_soft_skel_ht\r\n P_soft <- P_soft_skel_ht\r\n P_skel <- P_soft_skel_ht\r\n \r\n x_lu <- x_fast\r\n x_li <- x_fast\r\n x_spl <- x_fast\r\n x_ki <- x_fast\r\n x_ht <- x_fast\r\n x_br <- x_fast\r\n x_ut <- x_fast\r\n x_skel <- x_fast\r\n x_skin <- x_fast\r\n x_soft <- x_fast\r\n \r\n return(list(\"Vlu_tis\"= V_tis[1], \"Vli_tis\"= V_tis[2], \"Vspl_tis\"= V_tis[3], \"Vki_tis\"= V_tis[4],\"Vht_tis\"= V_tis[5],\r\n \"Vbr_tis\"= V_tis[6], \"Vut_tis\"= V_tis[7], \"Vskel_tis\"= V_tis[8], \"Vskin_tis\"= V_tis[9], \"Vsoft_tis\"= V_tis[10],\r\n \"Vven\"=Vven, \"Vart\"=Vart, \"V_blood\"=Total_Blood,\r\n \r\n \"Vlu_cap\"= V_cap[1], \"Vli_cap\"= V_cap[2], \"Vspl_cap\"= V_cap[3], \"Vki_cap\"= V_cap[4], \"Vht_cap\"= V_cap[5],\r\n \"Vbr_cap\"= V_cap[6], \"Vut_cap\"= V_cap[7], \"Vskel_cap\"= V_cap[8], \"Vskin_cap\"= V_cap[9], \"Vsoft_cap\"= V_cap[10],\r\n \r\n \"Q_lu\"= Q[1], \"Q_li\"= Q[2], \"Q_spl\"= Q[3], \"Q_ki\"= Q[4], \"Q_ht\"= Q[5], \"Q_br\"= Q[6], \"Q_ut\"= Q[7], \"Q_skel\"= Q[8],\r\n \"Q_skin\"= Q[9], \"Q_soft\"= Q[10], \"Q_total\"=Q_total, \r\n \r\n \"Wm_blood\" = Macro_blood, \"Wm_lu\"= W_macro[1], \"Wm_li\"= W_macro[2], \"Wm_spl\"= W_macro[3], \"Wm_ki\"= W_macro[4], \r\n \"Wm_ht\"= W_macro[5], \"Wm_br\"= W_macro[6], \"Wm_ut\"= W_macro[7], \"Wm_skel\"= W_macro[8], \"Wm_skin\"= W_macro[9],\r\n \"Wm_soft\"= W_macro[10],\r\n \r\n \"Inhaled.vol.rate\" = Inhaled.vol.rate, \"dep.ua\" = dep.ua, \"dep.tb\" = dep.tb, \"dep.al\" = dep.al, \r\n \"exposure.concentration\" = exposure.concentration, \"exposure.time\" = exposure.time,\r\n \r\n \"CLE_ua\" = CLE_ua, \"CLE_muc\" = CLE_muc,\r\n \"x_fast\" = x_fast , \"CLE_ur\" = CLE_ur, \"CLE_hep\" = CLE_hep, \r\n \"CLE_muc_cor\" = CLE_muc_cor, \"k_ab0\" = k_ab0, \"k_de\" = k_de,\r\n \"k_ab0_spl\" = k_ab0_spl, \"uptake\" = uptake,\r\n \"Wm_al\" = Wm_al, \"k_ua_br\" = k_ua_br, \"k_alpc_tb\" = k_alpc_tb, \"k_lu_al\" = k_lu_al,\r\n \"k_al_lu\" = k_al_lu, \"uptake_al\" =uptake_al, \r\n \"uptake_skel\" = uptake_skel, \"uptake_spl\" = uptake_spl,\r\n \r\n \"P_lu\"= P_lu, \"x_lu\" = x_lu, \"P_li\" = P_li, \"x_li\" = x_li, \"P_spl\" =P_spl, \r\n \"x_spl\" = x_spl, \"P_ki\" = P_ki, \"x_ki\" = x_ki, \"P_ht\" = P_ht, \"x_ht\" = x_ht,\r\n \"P_br\" = P_br, \"x_br\" = x_br, \"P_ut\" = P_ut, x_ut = x_ut,\r\n \"P_skel\" = P_skel, \"x_skel\" = x_skel, \"P_skin\" = P_skin, \"x_skin\" = x_skin,\r\n \"P_soft\" = P_soft, \"x_soft\" = x_soft,\r\n \r\n \"error1\" = e1, \"error2\" = e2, \"error3\" = e3\r\n ))\r\n \r\n }) \r\n}\r\n\r\n\r\n### store them once\r\n\r\n\r\n#################################################\r\n# Function for creating initial values for ODEs #\r\n#################################################\r\n\r\ncreate.inits <- function(parameters){\r\n with( as.list(parameters),{\r\n Mua<- 0; Mtb <- 0;Mal <- 0; Mal_pc <- 0; Mlu_cap <- 0;\r\n Mlu_tis <- 0; Mlu_pc <- 0; Mli_cap <- 0; Mli_tis <- 0;\r\n Mli_pc <- 0; Mspl_cap <- 0; Mspl_tis <- 0; Mspl_pc <- 0;\r\n Mki_cap <- 0; Mki_tis <- 0; Mki_pc <- 0; Mht_cap <- 0;\r\n Mht_tis <- 0; Mht_pc <- 0; Mbr_cap <- 0; Mbr_tis <- 0;\r\n Mbr_pc <- 0; Mut_cap <- 0; Mut_tis <- 0; Mut_pc <- 0;\r\n Mskel_cap <- 0; Mskel_tis <- 0; Mskel_pc <- 0; Mskin_cap <- 0;\r\n Mskin_tis <- 0; Mskin_pc <- 0; Msoft_cap <- 0; Msoft_tis <- 0;\r\n Msoft_pc <- 0; Art_blood <- 0; Ven_blood <- 0; Mblood_pc <- 0;\r\n Mfeces <- 0; Murine <- 0;\r\n \r\n return(c(\"Mua\" = Mua, \"Mtb\" = Mtb, \"Mal\" = Mal,\"Mal_pc\" = Mal_pc,\r\n \"Mlu_cap\" = Mlu_cap, \"Mlu_tis\" = Mlu_tis, \"Mlu_pc\" = Mlu_pc, \"Mli_cap\" = Mli_cap, \r\n \"Mli_tis\" = Mli_tis, \"Mli_pc\" = Mli_pc, \"Mspl_cap\" = Mspl_cap, \"Mspl_tis\" = Mspl_tis,\r\n \"Mspl_pc\" = Mspl_pc, \"Mki_cap\" = Mki_cap, \"Mki_tis\" = Mki_tis, \"Mki_pc\" = Mki_pc,\r\n \"Mht_cap\" = Mht_cap, \"Mht_tis\" = Mht_tis, \"Mht_pc\" = Mht_pc, \"Mbr_cap\" = Mbr_cap,\r\n \"Mbr_tis\" = Mbr_tis, \"Mbr_pc\" = Mbr_pc, \"Mut_cap\" = Mut_cap, \"Mut_tis\" = Mut_tis,\r\n \"Mut_pc\" = Mut_pc, \"Mskel_cap\" = Mskel_cap, \"Mskel_tis\" = Mskel_tis, \"Mskel_pc\" = Mskel_pc, \r\n \"Mskin_cap\" = Mskin_cap, \"Mskin_tis\" = Mskin_tis, \"Mskin_pc\" = Mskin_pc, \"Msoft_cap\" = Msoft_cap,\r\n \"Msoft_tis\" = Msoft_tis, \"Msoft_pc\" = Msoft_pc, \"Art_blood\" = Art_blood, \"Ven_blood\" = Ven_blood,\r\n \"Mblood_pc\" = Mblood_pc, \"Mfeces\" = Mfeces, \"Murine\" =Murine))\r\n }) \r\n}\r\n\r\n#################################################\r\n# Function for creating events #\r\n#################################################\r\ncreate.events<- function(parameters){\r\n with( as.list(parameters),{\r\n \r\n exposure.time <- seq(from=0, to=exposure.time , by=exposure.time /100) #inhalation time in hours (When was this applies)\r\n exposure.concentration <- rep(exposure.concentration,length(exposure.time)) # in mg/m^3\r\n \r\n \r\n lexposure <- length(exposure.concentration)\r\n ltimes <- length(exposure.time)\r\n \r\n add.tb <- rep(0,lexposure-1)\r\n add.al <- rep(0,lexposure-1)\r\n cur.time <- exposure.time[1]\r\n \r\n for (i in 1:(ltimes-1)){\r\n # Calculate the interval of exposure\r\n interval <- exposure.time[i+1] - cur.time\r\n add.tb[i] = interval * exposure.concentration[i] * (Inhaled.vol.rate/1000) * dep.tb * 1000 # deposited mass in microgram in trancheobronchial region\r\n add.al[i] = interval * exposure.concentration[i] * (Inhaled.vol.rate/1000) * dep.al * 1000 # deposited mass in microgram in alveolar region\r\n cur.time <- exposure.time[i+1]\r\n }\r\n \r\n if (lexposure == ltimes){\r\n events <- list(data = rbind(data.frame(var = \"Mtb\", time = exposure.time[2:ltimes], \r\n value = add.tb, method = c(\"add\")),\r\n data.frame(var = \"Mal\", time = exposure.time[2:ltimes], \r\n value = add.al, method = c(\"add\"))\r\n \r\n \r\n ))\r\n }else{\r\n stop(\"The user must provide t\")\r\n }\r\n \r\n \r\n return(events)\r\n }) \r\n}\r\n\r\n\r\n###################\r\n# Custom function #\r\n###################\r\n\r\ncustom.func <- function(){\r\n return()\r\n}\r\n\r\n#################\r\n# ODEs system #\r\n#################\r\n\r\n\r\node.func <- function(time, Initial.values, Parameters, custom.func){\r\n with( as.list(c(Initial.values, Parameters)),{\r\n \r\n # concentrations in tissues\r\n #C_lu <- Lu_tissue/W_lu\r\n Clu_tis <- Mlu_tis/Vlu_tis\r\n Clu_cap <- Mlu_cap/Vlu_cap\r\n Cli_tis <- Mli_tis/Vli_tis\r\n Cli_cap <- Mli_cap/Vli_cap\r\n Cspl_tis <- Mspl_tis/Vspl_tis\r\n Cspl_cap <- Mspl_cap/Vspl_cap\r\n Cki_tis <- Mki_tis/Vki_tis\r\n Cki_cap <- Mki_cap/Vki_cap\r\n Cht_tis <- Mht_tis/Vht_tis\r\n Cht_cap <- Mht_cap/Vht_cap\r\n Cbr_tis <- Mbr_tis/Vbr_tis\r\n Cbr_cap <- Mbr_cap/Vbr_cap\r\n Cut_tis <- Mut_tis/Vut_tis\r\n Cut_cap <- Mut_cap/Vut_cap\r\n Cskel_tis <- Mskel_tis/Vskel_tis\r\n Cskel_cap <- Mskel_cap/Vskel_cap\r\n Cskin_tis <- Mskin_tis/Vskin_tis\r\n Cskin_cap <- Mskin_cap/Vskin_cap\r\n Csoft_tis <- Msoft_tis/Vsoft_tis\r\n Csoft_cap <- Msoft_cap/Vsoft_cap\r\n \r\n Cart <- Art_blood/(0.19*V_blood)\r\n Cven <- Ven_blood/(0.81*V_blood)\r\n \r\n # Uptake rates by phagocytizing cells\r\n kluab <- k_ab0*(1-(Mlu_pc/(Wm_lu*uptake)))\r\n kliab <- k_ab0*(1-(Mli_pc/(Wm_li*uptake)))\r\n ksplab <- k_ab0_spl*(1-(Mspl_pc/(Wm_spl*uptake_spl)))\r\n kkiab <- k_ab0*(1-(Mki_pc/(Wm_ki*uptake)))\r\n khtab <- k_ab0*(1-(Mht_pc/(Wm_ht*uptake)))\r\n kbrab <- k_ab0*(1-(Mbr_pc/(Wm_br*uptake)))\r\n kutab <- k_ab0*(1-(Mut_pc/(Wm_ut*uptake)))\r\n kskelab <- k_ab0*(1-(Mskel_pc/(Wm_skel*uptake_skel)))\r\n kskinab <- k_ab0*(1-(Mskin_pc/(Wm_skin*uptake)))\r\n ksoftab <- k_ab0*(1-(Msoft_pc/(Wm_soft*uptake)))\r\n kbloodab <- k_ab0*(1-(Mblood_pc/(Wm_blood*uptake)))\r\n kalab <- k_ab0*(1-(Mal_pc/(Wm_al*uptake_al)))\r\n \r\n #Upper airways\r\n dMua = -(k_ua_br*Mua) - (CLE_ua * Mua) \r\n \r\n #Trancheobronchial region\r\n dMtb = (k_alpc_tb * Mal_pc) - (CLE_muc * CLE_muc_cor* Mtb) \r\n \r\n #Alveolar region\r\n dMal = (k_lu_al * Mlu_tis) - (k_al_lu * Mal) - (Mal*kalab - Mal_pc*k_de)\r\n dMal_pc = (Mal*kalab - Mal_pc*k_de) - (k_alpc_tb * Mal_pc)\r\n \r\n #Lungs\r\n dMlu_cap = (Cven*Q_lu)- (Clu_cap*Q_lu) + (x_lu*Q_lu)*Clu_tis/P_lu - (x_lu*Q_lu)*Clu_cap ; \r\n dMlu_tis = - (x_lu*Q_lu)*Clu_tis/P_lu + (x_lu*Q_lu)*Clu_cap - (Vlu_tis*Clu_tis*kluab - Mlu_pc*k_de) -\r\n (k_lu_al * Mlu_tis) + (k_al_lu * Mal) ; #Lung interstitium\r\n dMlu_pc = (Vlu_tis*Clu_tis*kluab - Mlu_pc*k_de); \r\n \r\n \r\n #Liver\r\n dMli_cap = (Cart*Q_li) + (Cspl_cap*Q_spl) - (Cli_cap*(Q_li+Q_spl)) + (x_li*Q_li)*Cli_tis/P_li - (x_li*Q_li)*Cli_cap; #capillary\r\n dMli_tis = - (x_li*Q_li)*Cli_tis/P_li + (x_li*Q_li)*Cli_cap -(Vli_tis*Cli_tis*kliab - Mli_pc*k_de) - (CLE_hep*Mli_tis) ; #tissue\r\n dMli_pc = (Vli_tis*Cli_tis*kliab - Mli_pc*k_de) ; #Phagocytized\r\n \r\n \r\n #Spleen\r\n dMspl_cap = (Cart*Q_spl) - (Cspl_cap*Q_spl) + (x_spl*Q_spl)*Cspl_tis/P_spl - (x_spl*Q_spl)*Cspl_cap ; #capillary\r\n dMspl_tis = - (x_spl*Q_spl)*Cspl_tis/P_spl + (x_spl*Q_spl)*Cspl_cap - (Vspl_tis*Cspl_tis*ksplab - Mspl_pc*k_de) ; #tissue\r\n dMspl_pc = (Vspl_tis*Cspl_tis*ksplab - Mspl_pc*k_de) ; #seq\r\n \r\n \r\n #Kidneys\r\n dMki_cap = (Cart*Q_ki) - (Cki_cap*Q_ki) + (x_ki*Q_ki)*Cki_tis/P_ki - (x_ki*Q_ki)*Cki_cap- (CLE_ur*Mki_cap) ; #capillary\r\n dMki_tis = - (x_ki*Q_ki)*Cki_tis/P_ki + (x_ki*Q_ki)*Cki_cap - (Vki_tis*Cki_tis*kkiab - Mki_pc*k_de) ; #tissue\r\n dMki_pc = (Vki_tis*Cki_tis*kkiab - Mki_pc*k_de) ; #seq\r\n \r\n #Heart\r\n dMht_cap = (Cart*Q_ht) - (Cht_cap*Q_ht) + (x_ht*Q_ht)*Cht_tis/P_ht - (x_ht*Q_ht)*Cht_cap ; #capillary\r\n dMht_tis = - (x_ht*Q_ht)*Cht_tis/P_ht + (x_ht*Q_ht)*Cht_cap - (Vht_tis*Cht_tis*khtab - Mht_pc*k_de) ; #tissue\r\n dMht_pc = (Vht_tis*Cht_tis*khtab - Mht_pc*k_de) ; #seq\r\n \r\n \r\n #Brain\r\n dMbr_cap = (Cart*Q_br) - (Cbr_cap*Q_br) + (x_br*Q_br)*Cbr_tis/P_br - (x_br*Q_br)*Cbr_cap ; #capillary\r\n dMbr_tis = - (x_br*Q_br)*Cbr_tis/P_br + (x_br*Q_br)*Cbr_cap - (Vbr_tis*Cbr_tis*kbrab - Mbr_pc*k_de) + (k_ua_br*Mua) ; #tissue\r\n dMbr_pc = (Vbr_tis*Cbr_tis*kbrab - Mbr_pc*k_de) ; #seq\r\n \r\n \r\n #Uterus\r\n dMut_cap = (Cart*Q_ut) - (Cut_cap*Q_ut) + (x_ut*Q_ut)*Cut_tis/P_ut - (x_ut*Q_ut)*Cut_cap ; #capillary\r\n dMut_tis = - (x_ut*Q_ut)*Cut_tis/P_ut + (x_ut*Q_ut)*Cut_cap - (Vut_tis*Cut_tis*kutab - Mut_pc*k_de) ; #tissue\r\n dMut_pc = (Vut_tis*Cut_tis*kutab - Mut_pc*k_de) ; #seq\r\n \r\n \r\n #Skeleton\r\n dMskel_cap = (Cart*Q_skel) - (Cskel_cap*Q_skel) + (x_skel*Q_skel)*Cskel_tis/P_skel - (x_skel*Q_skel)*Cskel_cap ; #capillary\r\n dMskel_tis = - (x_skel*Q_skel)*Cskel_tis/P_skel + (x_skel*Q_skel)*Cskel_cap - (Vskel_tis*Cskel_tis*kskelab - Mskel_pc*k_de) ; #tissue\r\n dMskel_pc = (Vskel_tis*Cskel_tis*kskelab - Mskel_pc*k_de) ; #seq\r\n \r\n #Skin\r\n dMskin_cap = (Cart*Q_skin) - (Cskin_cap*Q_skin) + (x_skin*Q_skin)*Cskin_tis/P_skin - (x_skin*Q_skin)*Cskin_cap ; #capillary\r\n dMskin_tis = - (x_skin*Q_skin)*Cskin_tis/P_skin + (x_skin*Q_skin)*Cskin_cap - (Vskin_tis*Cskin_tis*kskinab - Mskin_pc*k_de) ; #tissue\r\n dMskin_pc = (Vskin_tis*Cskin_tis*kskinab - Mskin_pc*k_de) ; #seq\r\n \r\n #Soft\r\n dMsoft_cap = (Cart*Q_soft) - (Csoft_cap*Q_soft) + (x_soft*Q_soft)*Csoft_tis/P_soft - (x_soft*Q_soft)*Csoft_cap ; #capillary\r\n dMsoft_tis = - (x_soft*Q_soft)*Csoft_tis/P_soft + (x_soft*Q_soft)*Csoft_cap - (Vsoft_tis*Csoft_tis*ksoftab - Msoft_pc*k_de) ; #tissue\r\n dMsoft_pc = (Vsoft_tis*Csoft_tis*ksoftab - Msoft_pc*k_de) ; #seq\r\n \r\n \r\n #Blood\r\n dArt_blood = (Clu_cap*Q_lu) - Cart* (Q_li + Q_spl+ Q_ki + Q_ht + Q_br + Q_ut + Q_skel + Q_skin + Q_soft) - \r\n (0.19*V_blood*Cart*kbloodab - 0.19* Mblood_pc*k_de); \r\n dVen_blood = (Cli_cap*(Q_li+Q_spl)) + (Cki_cap*Q_ki) + (Cht_cap*Q_ht) + (Cbr_cap*Q_br) + (Cut_cap*Q_ut) + (Cskel_cap*Q_skel) +\r\n (Cskin_cap*Q_skin) + (Csoft_cap*Q_soft) - (Cven*Q_lu) - (0.81*V_blood*Cven*kbloodab - 0.81* Mblood_pc*k_de)\r\n dMblood_pc <- ((0.19*V_blood*Cart + 0.81*V_blood*Cven)*kbloodab - Mblood_pc*k_de) \r\n \r\n #Feces\r\n dMfeces = (CLE_hep*Mli_tis) + (CLE_ua * Mua) + (CLE_muc* CLE_muc_cor * Mtb) ;\r\n \r\n #Urine\r\n dMurine = (CLE_ur*Mki_cap) ;\r\n \r\n Total_lungs <- Mal + Mal_pc + Mlu_cap + Mlu_tis + Mlu_pc + Mtb \r\n \r\n \r\n \r\n list(c(dMua = dMua, dMtb = dMtb, dMal = dMal,dMal_pc = dMal_pc,\r\n dMlu_cap = dMlu_cap, dMlu_tis = dMlu_tis, dMlu_pc = dMlu_pc, dMli_cap = dMli_cap, \r\n dMli_tis = dMli_tis, dMli_pc = dMli_pc, dMspl_cap = dMspl_cap, dMspl_tis = dMspl_tis,\r\n dMspl_pc = dMspl_pc, dMki_cap = dMki_cap, dMki_tis = dMki_tis, dMki_pc = dMki_pc,\r\n dMht_cap = dMht_cap, dMht_tis = dMht_tis, dMht_pc = dMht_pc, dMbr_cap = dMbr_cap,\r\n dMbr_tis = dMbr_tis, dMbr_pc = dMbr_pc, dMut_cap = dMut_cap, dMut_tis = dMut_tis,\r\n dMut_pc = dMut_pc, dMskel_cap = dMskel_cap, dMskel_tis = dMskel_tis, dMskel_pc = dMskel_pc, \r\n dMskin_cap = dMskin_cap, dMskin_tis = dMskin_tis, dMskin_pc = dMskin_pc, dMsoft_cap = dMsoft_cap,\r\n dMsoft_tis = dMsoft_tis, dMsoft_pc = dMsoft_pc, dArt_blood = dArt_blood, dVen_blood = dVen_blood,\r\n dMblood_pc = dMblood_pc, dMfeces = dMfeces, dMurine = dMurine), Total_lungs = Total_lungs)\r\n })\r\n}\r\n\r\n##############################################\r\n\r\n# User must provide a string declaring the path where the vpc_data file is stored\r\npath <- \"\"\r\ninput.data <- openxlsx::read.xlsx(paste(path,\"biodist_data.xlsx\", sep = \"\"), \r\n sheet=3,colNames = TRUE, rowNames = TRUE)\r\n\r\n# the following numbers derive from normalisation of the MPPD numbers 0.12 and 0.52\r\ntb.depo = 0.1875 \r\nal.depo = 0.8125\r\nua.depo = 0\r\n# use average input data to represent all rats\r\ninput <-list(\"exposure.concentration\" = rowMeans(input.data[3,]), \"exposure.time\" = 2,\r\n \"weight\" = 277, \"dep.ua\" = 0, \"dep.tb\" = tb.depo*rowMeans(input.data[2,]), \r\n \"dep.al\" = al.depo*rowMeans(input.data[2,]), \r\n \"Inhaled.vol.rate\" = rowMeans(input.data[10,]))\r\n\r\n# Produce one solution with mean values\r\nparams_determ <- create.params(input,stan_fit, stochastic = FALSE)\r\ninits <- create.inits(params_determ)\r\nevents <- create.events(params_determ)\r\n\r\n# Here we create a first solution to get the dimensions because the total instances will be \r\n# equal to the dimension of sample_time plus the extra events which occured at times\r\n# not provided in the sample time vector\r\nsample_time <- c(1e-08, 1e-04, 1e-03, 1e-02, 1e-01, 0.5, 1, 2, 6, 12, 26, 48, 72, 144, 256, 300, \r\n 400, 500, 600 , 700)\r\nsolution <- ode(times = sample_time, func = ode.func, y = inits, parms = params_determ, \r\n custom.func = custom.func, method=\"lsodes\", events = events)\r\nsolution <- as.data.frame(solution[solution[,1] %in% sample_time,1:40])\r\ndeterministic.df <- matrix(rep(NA, 17*dim(solution)[1]), ncol = 17)\r\ndeterministic.df[,1] <- solution[,1]\r\ndeterministic.df[,2] <- solution[,3] \r\ndeterministic.df[,3] <- solution[,4] \r\ndeterministic.df[,4] <- solution[,5] \r\ndeterministic.df[,5] <- (solution[,7] + solution[,8]) \r\ndeterministic.df[,6] <- (solution[,10] + solution[,11]) \r\ndeterministic.df[,7] <- (solution[,13] + solution[,14])\r\ndeterministic.df[,8] <- (solution[,16] + solution[,17])\r\ndeterministic.df[,9] <- (solution[,19] + solution[,20])\r\ndeterministic.df[,10] <- (solution[,22] + solution[,23])\r\ndeterministic.df[,11] <- (solution[,25] + solution[,26])\r\ndeterministic.df[,12] <- (solution[,28] + solution[,29]) \r\ndeterministic.df[,13] <- (solution[,31] + solution[,32]) \r\ndeterministic.df[,14] <- (solution[,34] + solution[,35]) \r\ndeterministic.df[,15] <- (solution[,36] + solution[,37]+ solution[,38])\r\ndeterministic.df[,16] <- solution[,39]\r\ndeterministic.df[,17] <- solution[,40]\r\n\r\ncolnames(deterministic.df) <- c( \"Time\", \"Trachea\", \"BALF\", \"BALC\", \"Lavaged lungs\", \"Liver\", \"Spleen\",\r\n \"Kidneys\", \"Heart\", \"Brain\", \"Uterus\", \"Skeleton\", \"Skin\", \"Soft tissues\",\r\n \"Blood\", \"Feces\", \"Urine\")\r\n\r\n\r\nNsim = 1000 # number of simulations\r\nNrat = 20 # number of virtual rats\r\nltime <- dim(solution)[1] # number of solution instances\r\ndata_time <- solution[,\"time\"]\r\nNcomp <- dim(solution)[2] # Number of compartments to plot\r\npred_con_tra <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_balf <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_balc <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_lav <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_li <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_spl <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_ki <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_ht <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_br <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_ut <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_skel <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_skin <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_soft <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_blood <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_feces <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\npred_con_urine <-array(rep(NA,Nrat*ltime*Nsim),dim=c(Nrat,ltime,Nsim))\r\n\r\nfailed = list()\r\n\r\nfor (sim in 1:Nsim){\r\n for (rat in 1:Nrat){\r\n print(paste(\"rat \",rat, \"Nsim \",sim))\r\n\r\n pred <- matrix(rep(NA, Ncomp*ltime), nrow = ltime)\r\n # parameter to inform about failed attempts\r\n failed_attempt <- 0\r\n # if params result in odes not solving, resample and resolve\r\n while( (dim(pred)[1] != ltime) | sum(is.na(pred)) ) {\r\n \r\n #params are selected stochastically because create.params samples from stan estimates\r\n params <- create.params(input,stan_fit)\r\n events <- create.events(params)\r\n sol <- ode(times = sample_time, func = ode.func, y = inits, parms = params, \r\n custom.func = custom.func, method=\"lsodes\", events = events, \r\n maxsteps = 50000) \r\n pred <- sol[sol[,1] %in% sample_time,]\r\n pred\r\n }\r\n \r\n \r\n for(t in 1:ltime){\r\n ###Total amount of NPs in each organ\r\n # Amount in trachea\r\n pred_con_tra[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = pred[t,3] , sd = params$error1)\r\n # Amount in Balf\r\n pred_con_balf[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = pred[t,4] , sd = params$error1/2)\r\n \r\n # Amount in Balc\r\n pred_con_balc[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = pred[t,5] , sd = params$error1/2) \r\n \r\n # Amount in lavaged lungs\r\n pred_con_lav[rat,t,sim]<- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,7] + pred[t,8]) , sd = params$error1)\r\n \r\n # Amount in liver\r\n pred_con_li[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,10] + pred[t,11]) , sd = params$error2) \r\n \r\n # Amount in spleen\r\n pred_con_spl[rat,t,sim]<- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,13] + pred[t,14]) , sd = params$error3) \r\n \r\n # Amount in kidneys\r\n pred_con_ki[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,16] + pred[t,17]) , sd = params$error2) \r\n \r\n # Amount in heart\r\n pred_con_ht[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,19] + pred[t,20]) , sd = params$error3) \r\n \r\n # Amount in brain\r\n pred_con_br[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,22] + pred[t,23]) , sd = params$error3) \r\n \r\n # Amount in uterus\r\n pred_con_ut[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,25] + pred[t,26]) , sd = params$error3) \r\n \r\n # Amount in skeleton\r\n pred_con_skel[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,28] + pred[t,29]) , sd = params$error2) \r\n \r\n # Amount in skin\r\n pred_con_skin[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,31] + pred[t,32]) , sd = params$error2) \r\n \r\n # Amount in soft tissues\r\n pred_con_soft[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,34] + pred[t,35]) , sd = params$error2) \r\n \r\n # Amount in blood\r\n pred_con_blood[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = (pred[t,36] + pred[t,37]+ pred[t,38]), sd = params$error2) \r\n \r\n # Amount in feces\r\n pred_con_feces[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = pred[t,39], sd = params$error1) \r\n \r\n # Amount in urine\r\n pred_con_urine[rat,t,sim] <- truncnorm::rtruncnorm(1, a=0, b=Inf, mean = pred[t,40], sd = params$error1) \r\n }\r\n }\r\n}\r\n\r\n\r\nbag_of_data <- list( pred_con_tra, pred_con_balf, pred_con_balc, pred_con_lav, pred_con_li, \r\n pred_con_spl, pred_con_ki, pred_con_ht, pred_con_br, pred_con_ut, pred_con_skel,\r\n pred_con_skin, pred_con_soft, pred_con_blood, pred_con_feces, pred_con_urine)\r\nnames(bag_of_data) <- c( \"Trachea\", \"BALF\", \"BALC\", \"Lavaged lungs\", \"Liver\", \"Spleen\",\r\n \"Kidneys\", \"Heart\", \"Brain\", \"Uterus\", \"Skeleton\", \"Skin\", \"Soft tissues\",\r\n \"Blood\", \"Feces\", \"Urine\")\r\ncomp_names <- names(bag_of_data) \r\n\r\n# File where data are stored\r\npath <- \"\"\r\n### load data\r\nbiodist_data <- openxlsx::read.xlsx(paste(path,\"biodist_data.xlsx\", sep = \"\"),\r\n sheet=1,colNames = TRUE,rowNames = TRUE)\r\nsd_data <- openxlsx::read.xlsx(paste(path,\"biodist_data.xlsx\", sep = \"\"),\r\n sheet=2,colNames = TRUE,rowNames = TRUE)\r\n\r\nfeces <- openxlsx::read.xlsx(paste(path,\"feces.xlsx\", sep = \"\"),\r\n sheet=2,colNames = TRUE)[,2]*input.data[1,5]\r\nurine<- openxlsx::read.xlsx(paste(path,\"urine.xlsx\", sep = \"\")\r\n , sheet=2,colNames = TRUE)[,2]*input.data[7,5]\r\n\r\nexcreta_time <- c(3.5, 7, 10.5, 14, 17.5, 21, 24.5, 27)*24\r\nbiodist_time <- c(2, 6, 26, (7*24+2), (28*24+2))\r\n\r\nexcreta.df <- as.data.frame(cbind(excreta_time, feces, urine))\r\ncolnames(excreta.df) <- c(\"Time\", \"Feces\", \"Urine\")\r\n\r\ndata.df <- data.frame(cbind(biodist_time, biodist_data))\r\ncolnames(data.df) <- c(\"Time\", colnames(biodist_data))\r\n\r\nsd.data.df <- data.frame(cbind(biodist_time, sd_data))\r\ncolnames(data.df) <- c(\"Time\", colnames(sd_data))\r\n\r\n# Set the path where the plots will be stored\r\nsetwd(path)\r\n\r\ncounter <-1\r\nfor (dat in bag_of_data) {\r\n # Get the compartment name to be plotted\r\n comp_name <- comp_names[counter]\r\n # Define the save name\r\n save_name <- paste0(comp_name, \"_vpc.png\", sep=\"\")\r\n pred_con <- dat\r\n \r\n \r\n \r\n \r\n ##########################\r\n # Calculation of 95 % CI of the 50th quantile\r\n con<-matrix(rep(NA,ltime*Nsim), nrow = ltime)\r\n ymin<- rep(NA,ltime)\r\n ymax<- rep(NA,ltime)\r\n \r\n for (i in 1:ltime){\r\n for (j in 1:Nsim){\r\n con[i,j]<-quantile(pred_con[,i,j],probs=0.5)\r\n }\r\n }\r\n \r\n for (i in 1:ltime){\r\n con[i,]<-sort(con[i,])\r\n ymin[i]<-quantile(con[i,],probs=0.025)\r\n ymax[i]<-quantile(con[i,],probs=0.975)\r\n }\r\n \r\n q50<-data.frame(time=data_time,lo=ymin,hi=ymax)\r\n ############################ \r\n # Calculation of 95 % CI of the 5th quantile\r\n \r\n con<-matrix(rep(NA,ltime*Nsim), nrow = ltime)\r\n ymin<- rep(NA,ltime)\r\n ymax<- rep(NA,ltime)\r\n \r\n for (i in 1:ltime){\r\n for (j in 1:Nsim){\r\n con[i,j]<-quantile(pred_con[,i,j],probs=0.05)\r\n }\r\n }\r\n \r\n for (i in 1:ltime){\r\n con[i,]<-sort(con[i,])\r\n ymin[i]<-quantile(con[i,],probs=0.025)\r\n ymax[i]<-quantile(con[i,],probs=0.975)\r\n }\r\n \r\n q05<-data.frame(time=data_time,lo=ymin,hi=ymax)\r\n ################################# \r\n # Calculation of 95 % CI of the 95th quantile\r\n con<-matrix(rep(NA,ltime*Nsim), nrow = ltime)\r\n ymin<- rep(NA,ltime)\r\n ymax<- rep(NA,ltime)\r\n \r\n for (i in 1:ltime){\r\n for (j in 1:Nsim){\r\n con[i,j]<-quantile(pred_con[,i,j],probs=0.95)\r\n }\r\n }\r\n \r\n for (i in 1:ltime){\r\n con[i,]<-sort(con[i,])\r\n ymin[i]<-quantile(con[i,],probs=0.025)\r\n ymax[i]<-quantile(con[i,],probs=0.975)\r\n }\r\n \r\n q95<-data.frame(time=data_time,lo=ymin,hi=ymax)\r\n ############################\r\n # Mean values of predictions from deterministic.df model\r\n use_comp <- colnames(deterministic.df)[counter+1]\r\n mean_pred = data.frame(deterministic.df[,c(\"Time\", use_comp)])\r\n colnames(mean_pred) = c(\"time\", \"value\")\r\n \r\n if(!(comp_name %in% c(\"Feces\", \"Urine\"))){\r\n use_comp <- colnames(data.df)[counter+1]\r\n df1 <- as.data.frame(cbind(data.df[,c(\"Time\",use_comp)], sd.data.df[,use_comp]))\r\n colnames(df1) <- c(\"Time\", \"Mean\", \"Sd\")\r\n my_plot <- ggplot() + \r\n geom_line(data=mean_pred, aes(x=time, y=value, linetype = \" Prediction mean\"),\r\n size=1.2)+\r\n geom_ribbon(data=q50,aes(x=time, ymin = lo, ymax = hi, fill = \"50th percentile\"),\r\n inherit.aes=FALSE, alpha = 0.2) + \r\n geom_ribbon(data=q05,aes(x=time, ymin = lo, ymax = hi, fill = \"5th percentile\"),\r\n inherit.aes=FALSE, alpha = 0.2) + \r\n geom_ribbon(data=q95,aes(x=time, ymin = lo, ymax = hi, fill=\"95th percentile\"),\r\n inherit.aes=FALSE,alpha = 0.2) + \r\n geom_point(data = df1, aes(x = Time, y=Mean),size=5)+\r\n geom_errorbar(data = df1, aes(x = Time, ymin=ifelse((Mean-Sd)>0,Mean-Sd,0), ymax=Mean+Sd),size=1)+\r\n labs(title = rlang::expr(!!comp_name), y = \"TiO2 (ug)\", x = \"Time (in hours)\") +\r\n scale_fill_manual(\"Prediction Ribbons\", values = c( \"50th percentile\" = 1, \r\n \"5th percentile\" = 2,\"95th percentile\" = 3)) + \r\n scale_linetype_manual(\"Line\", values = c(\" Prediction mean\" = 1))+\r\n scale_colour_manual(\"Point\", values = c(\"Biodistribtion data\" = 1))+\r\n theme(plot.title =element_text(hjust = 0.5, size=30, face=\"bold\"),\r\n axis.title.y =element_text(hjust = 0.5, size=20, face=\"bold\"),\r\n axis.text.y=element_text(size=18),\r\n axis.title.x =element_text(hjust = 0.5, size=20, face=\"bold\"),\r\n axis.text.x=element_text(size=18),\r\n legend.title=element_text(hjust = 0.01, size=20), \r\n legend.text=element_text(size=18))\r\n png(rlang::expr(!!save_name), width = 15, height = 10, units = 'in', res = 500)\r\n print(my_plot)\r\n } else{\r\n observed <- excreta.df[,c(\"Time\",colnames(excreta.df)[counter-13])]\r\n colnames(observed) <- c(\"Time\", \"mean\")\r\n my_plot <- ggplot(observed, aes(x=Time, y=mean, colour=\"Biodistribtion data\"))+\r\n geom_point(shape=19, size=4) + \r\n #geom_bar(aes(ymin=ifelse((mean-sd)>0,mean-sd,0), ymax=mean+sd), width=.1) +\r\n geom_line(data=mean_pred, aes(x=time, y=value, linetype = \" Prediction mean\"), \r\n size=1.2)+\r\n geom_ribbon(data=q50,aes(x=time, ymin = lo, ymax = hi, fill = \"50th percentile\"),\r\n inherit.aes=FALSE, alpha = 0.2) + \r\n geom_ribbon(data=q05,aes(x=time, ymin = lo, ymax = hi, fill = \"5th percentile\"),\r\n inherit.aes=FALSE, alpha = 0.2) + \r\n geom_ribbon(data=q95,aes(x=time, ymin = lo, ymax = hi, fill=\"95th percentile\"),\r\n inherit.aes=FALSE,alpha = 0.2) + \r\n labs(title = rlang::expr(!!comp_name), y = \"TiO2 (ug)\", x = \"Time (in hours)\") +\r\n scale_fill_manual(\"Prediction Ribbons\", values = c( \"50th percentile\" = 1, \r\n \"5th percentile\" = 2,\"95th percentile\" = 3)) +\r\n scale_linetype_manual(\"Line\", values = c(\" Prediction mean\" = 1))+\r\n scale_colour_manual(\"Point\", values = c(\"Biodistribtion data\" = 1))+\r\n theme(plot.title =element_text(hjust = 0.5, size=30, face=\"bold\"),\r\n axis.title.y =element_text(hjust = 0.5, size=20, face=\"bold\"),\r\n axis.text.y=element_text(size=18),\r\n axis.title.x =element_text(hjust = 0.5, size=20, face=\"bold\"),\r\n axis.text.x=element_text(size=18),\r\n legend.title=element_text(hjust = 0.01, size=20), \r\n legend.text=element_text(size=18))\r\n png(rlang::expr(!!save_name), width = 15, height = 10, units = 'in', res = 500)\r\n print(my_plot)\r\n \r\n }\r\n dev.off()\r\n counter <- counter +1\r\n}\r\n \r\n", "meta": {"hexsha": "0c02186207ac7e529be1b5970eb5079b16c11b6b", "size": 36149, "ext": "r", "lang": "R", "max_stars_repo_path": "VPC_plots.r", "max_stars_repo_name": "ntua-unit-of-control-and-informatics/TiO2_inhalation", "max_stars_repo_head_hexsha": "ea5a3f0ede86648571e99340492a676dc2e2c31b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VPC_plots.r", "max_issues_repo_name": "ntua-unit-of-control-and-informatics/TiO2_inhalation", "max_issues_repo_head_hexsha": "ea5a3f0ede86648571e99340492a676dc2e2c31b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VPC_plots.r", "max_forks_repo_name": "ntua-unit-of-control-and-informatics/TiO2_inhalation", "max_forks_repo_head_hexsha": "ea5a3f0ede86648571e99340492a676dc2e2c31b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.377457405, "max_line_length": 155, "alphanum_fraction": 0.5756175828, "num_tokens": 12518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3326017341963572}} {"text": "\nrunTime <- function(combs, maxDoseT, missp, Rscale, doseType = \"random\", Ne = 1.5*10^5){\n\n\n mutinf <- return_mutinf()\n druginf <- return_druginf()\n \n hours <- list()\n hours[[combs[1]]] <- 0\n hours[[combs[2]]] <- 0\n hours[[combs[3]]] <- 0\n\n #There are three dose missing types:\n #These patterns are NOT explored in this MS, but I will include them anyway\n\n #1) Totally random, with dose taking probability p\n if(doseType == \"random\"){\n missedDoses <- runif(maxDoseT, 0, 1) < missp\n\n\t#Each year, they have a missp probability of a week long treatment interruption (i.e., 336 time periods)\n\tmissedYears <- runif(10, 0, 1) < missp\n\t#Each year is 48 * 7 * 4 * 12 = 16128 time periods\n\tfor(i in 1:10){\n\t if(i == TRUE){\n\t \t #choose a time within the year\n\t\t missedDoseStart <- 16128 * (i - 1) + sample(1:16128, 1)\n\t\t missedDoses[missedDoseStart:(missedDoseStart + 336 * 2)] <- 0\n\t }\n\t}\n\t\n for(i in 2:maxDoseT){\n if(missedDoses[i] == TRUE){\n for(D in combs){ \n hours[[D]] <- append(hours[[D]], tail(hours[[D]], n = 1) + 0.5)\n }\n }else{\n for(D in combs){\n di <- druginf[[which(names(druginf) == D)]]\n dosing <- di[which(names(di) == \"dosing\")]\n hour <- tail(hours[[D]], n = 1)\n if(i %% (24/dosing) == 0){\n hour = 0\n }else{\n hour = hour + 0.5\n }\n hours[[D]] <- append(hours[[D]], hour)\n }\n }\n }\n\n }\n\n #Weekends off, weekdays on (Five on, Two off)\n if(doseType == \"FOTO\"){\n\n #Weekday index?\n #240 half hour chunks in 5 days\n #96 half hour chunks in a weekend\n missedDoses <- rep(c(rep(FALSE, 240), rep(TRUE, 96)),\n ceiling(maxDoseT/(240+96)))[1:maxDoseT]\n\n for(i in 2:maxDoseT){\n if(missedDoses[i] == TRUE){\n for(D in combs){ \n hours[[D]] <- append(hours[[D]], tail(hours[[D]], n = 1) + 0.5)\n }\n }else{\n for(D in combs){\n di <- druginf[[which(names(druginf) == D)]]\n dosing <- di[which(names(di) == \"dosing\")]\n hour <- tail(hours[[D]], n = 1)\n if(i %% (24/dosing) == 0){\n hour = 0\n }else{\n hour = hour + 0.5\n }\n hours[[D]] <- append(hours[[D]], hour)\n }\n }\n }\n\n }\n\n #The dosing approach that maximizes the time at which resistant strains have higher R than\n # sensitive strains\n if(doseType == \"resistantAdvantage\"){\n\n dosingPeriods <- foreach(D = combs, .combine = \"rbind\")%do%{\n\n di <- druginf[[which(names(druginf) == D)]]\n mi <- mutinf[[which(names(druginf) == D)]]\n\n IC_50 <- di[which(names(di) == \"IC_50\")]\n hl <- di[which(names(di) == \"hl\")]\n m <- di[which(names(di) == \"slope\")]\n C_max <- di[which(names(di) == \"c_max\")]\n dosing <- di[which(names(di) == \"dosing\")]\n\n s <- as.numeric(mi[which(names(mi) == \"s\")])\n mu <- as.numeric(mi[which(names(mi) == \"mu\")])\n rho <- as.numeric(mi[which(names(mi) == \"rho\")])\n sigma <- as.numeric((mi[which(names(mi) == \"sigma\")]))\n\n mut <- 1\n checkPeriod <- 1000\n\n #clunky\n relHours <- bind_rows(bind_cols(t = 1:checkPeriod, nhours = seq(0.5, checkPeriod/2, by = 0.5),\n mut = rep(1, checkPeriod)),\n bind_cols(t = 1:checkPeriod, nhours = seq(0.5, checkPeriod/2, by = 0.5),\n mut = rep(0, checkPeriod))) %>% \n mutate(drug = D) %>%\n mutate( R = (1 - mut * s)/(1 + (decay_instant(nhours, hl, C_max )/(IC_50 * (1 - mut*(1 - rho))))^(m * (1 + mut * (sigma)))))\n\n\n worstT <- (relHours %>% spread(mut, R) %>%\n filter(`1` <= `0`) %>% slice(n = 1))$t\n\n missedDoses <- rep(c(rep(TRUE, worstT - 1), rep(FALSE, 1)),\n ceiling(maxDoseT/worstT))[1:maxDoseT]\n\n\n for(i in 2:maxDoseT){\n\n if(missedDoses[i] == TRUE){\n hours[[D]] <- append(hours[[D]], tail(hours[[D]], n = 1) + 0.5)\n\n }else{\n hour = 0\n hours[[D]] <- append(hours[[D]], hour)\n \n }\n }\n }\n }\n\n\n Rinf <- foreach(D = combs, .combine = \"rbind\")%do%{\n\n di <- druginf[[which(names(druginf) == D)]]\n mi <- mutinf[[which(names(druginf) == D)]]\n\n IC_50 <- di[which(names(di) == \"IC_50\")]\n hl <- di[which(names(di) == \"hl\")]\n m <- di[which(names(di) == \"slope\")]\n C_max <- di[which(names(di) == \"c_max\")]\n dosing <- di[which(names(di) == \"dosing\")]\n\n s <- as.numeric(mi[which(names(mi) == \"s\")])\n mu <- as.numeric(mi[which(names(mi) == \"mu\")])\n rho <- as.numeric(mi[which(names(mi) == \"rho\")])\n sigma <- as.numeric((mi[which(names(mi) == \"sigma\")]))\n \n\n mut <- 1\n #clunky\n bind_rows(bind_cols(t = 1:maxDoseT, nhours = hours[[D]], mut = rep(1, maxDoseT)),\n bind_cols(t = 1:maxDoseT, nhours = hours[[D]], mut = rep(0, maxDoseT))) %>% \n mutate(drug = D) %>%\n mutate( R = (1 - mut * s)/(1 + (decay_instant(nhours, hl, C_max )/(IC_50 * (1 - mut*(1 - rho))))^(m * (1 + mut * (sigma)))))\n\n }\n\n toTrack <- tbl_df(expand.grid(A = c(1, 0), B = c(1, 0), C = c(1, 0)))\n names(toTrack) = combs\n druginds <- toTrack %>% mutate(ind = 1:n()) %>% gather(drug, mut, -ind)\n\n #Now, we go through and compute R at each of these timepoints for each of the resistance profiles\n allRs <- left_join(druginds, Rinf, by = c(\"drug\", \"mut\")) %>%\n group_by(ind, t) %>% summarize(R = Rscale * prod(R), .groups = 'drop')\n\n arsplit <- allRs %>% group_split(t)\n\n N <- Ne\n A_i <- 3000 #3000\n lambda <- Ne * 1 * 10/(10 - 1)\n dy <- 1\n dt <- .02\n mu <- .00001\n\n mutinf <- foreach(D = combs, .combine = 'rbind')%do%{\n\n mi <- mutinf[[which(names(mutinf) == D)]]\n s <- mi[which(names(mi) == \"s\")]\n mu <- mi[which(names(mi) == \"mu\")]\n rho <- mi[which(names(mi) == \"rho\")]\n sigma <- mi[which(names(mi) == \"sigma\")]\n\n return(c(D, mu, s, sigma, rho))\n }\n\n colnames(mutinf) <- c(\"drug\", \"mu\", \"s\", \"sigma\", \"rho\")\n mutinf <- tbl_df(mutinf)\n\n init.n <- left_join(druginds, mutinf, by = \"drug\") %>%\n mutate(mu_over_s = as.numeric(mu)/as.numeric(s) ) %>%\n group_by(ind) %>% mutate(mu_over_s = ifelse(mut == 1, mu_over_s, 1)) %>%\n summarize(lam = prod(mu_over_s), .groups = \"drop\") %>%\n mutate(i.N = round(lam*N))\n\n tmp <- init.n %>% filter(ind < 8)\n init.n <- init.n %>% mutate(i.N = ifelse(ind == 8, N - sum(tmp$i.N), i.N)) %>%\n mutate(lam = ifelse(ind == 8, 1 - sum(tmp$lam), lam))\n\n #new cells\n ys <- matrix(0, nrow = 8, ncol = maxDoseT + 1)\n ys[,1] <- init.n$i.N\n\n toMerge <- toTrack %>% mutate(ind = 1:n()) \n names(toMerge) <- c(\"m1\", \"m2\", \"m3\", \"ind\")\n\n ref <- bind_rows(\n bind_cols(ind = 0, name = \"m1\"), \n bind_cols(ind = 0, name = \"m2\"),\n bind_cols(ind = 0, name = \"m3\"))\n\n\n start_time <- Sys.time()\n i <- 1\n\n res <- init.n$lam\n while(i < maxDoseT & ! stopCondition(i, ys[,i]) ){ \n\n emergingCells <- rpois(8, A_i * dt * res)\n\n rs <- arsplit[[i]]$R\n\n yvals <- ys[,i]\n \n denom <- lambda + sum(( dy * rs * yvals))\n rates <- (yvals*dy*lambda*rs*dt)/denom\n\n newys <- rpois(8, rates)\n \n mutFrom.s1 <- rbinom(8, newys, as.numeric(mutinf$mu[1]))\n mutFrom.s2 <- rbinom(8, newys, as.numeric(mutinf$mu[2]))\n mutFrom.s3 <- rbinom(8, newys, as.numeric(mutinf$mu[3]))\n\n mutFrom <- rep(0, 8)\n mutTo <- rep(0, 8)\n\n for(ind in 1:8){\n\n if(newys[ind] > 0){\n m1 <- sample(1:newys[ind], mutFrom.s1[ind], replace = FALSE)\n m2 <- sample(1:newys[ind], mutFrom.s2[ind], replace = FALSE)\n m3 <- sample(1:newys[ind], mutFrom.s3[ind], replace = FALSE)\n\n base <- toTrack[ind,]\n \n mutsTo <- bind_rows(bind_rows(\n bind_cols(ind = m1, name = rep(\"m1\", length(m1))), \n bind_cols(ind = m2, name = rep(\"m2\", length(m2))),\n bind_cols(ind = m3, name = rep(\"m3\", length(m3)))) %>% \n mutate(i = 1), ref %>% mutate(i =0)) %>%\n spread(name, i) %>% group_by(m1, m2, m3) %>% \n summarize(n = n(), .groups = \"drop\") %>% \n filter(!(m1 == 0 & m2 == 0 & m3 == 0)) %>%\n mutate(m1 = ifelse(is.na(m1), 0, m1), \n m2 = ifelse(is.na(m2), 0, m2),\n m3 = ifelse(is.na(m3), 0, m3))\n \n #So, we actually want something different here - we want to mutate from\n #based on the index we are considering\n #Here, ind = 5, or 110. Our mutation is the same (second position), \n #so we should go to 100, instead of 000 -> 010\n \n myInd <- ind\n flips <- toMerge %>% filter(ind == myInd)\n\n mutsTo <- mutsTo %>% mutate(m1 = abs(flips$m1 - m1),\n m2 = abs(flips$m2 - m2),\n m3 = abs(flips$m3 - m3))\n \n mutFrom[ind] <- sum(mutsTo$n)\n mutTo <- mutTo + (left_join(toMerge, mutsTo, by = c(\"m1\", \"m2\", \"m3\")) %>% \n mutate(n = ifelse(is.na(n), 0, n)))$n\n \n }\n\n }\n \n ys[,i + 1] <- rbinom(8, emergingCells + newys + yvals - mutFrom + mutTo, exp(-dy * dt))\n\n i <- i + 1\n\n }\n\n end_time <- Sys.time()\n print(end_time - start_time)\n \n conc_by_drug <- Rinf\n\n R_by_geno <- left_join(druginds, Rinf, by = c(\"drug\", \"mut\")) %>%\n group_by(ind, t) %>% summarize(R = Rscale * prod(R), .groups = 'drop')\n\n return(list(f = ys, drugs = conc_by_drug, R = R_by_geno))\n}\n\nstopCondition <- function(t, ysi){\n \n #every 6 months\n if(t %% (2*24*7*4*3) == 0 ){\n\n if(sum(ysi[1:8]) >= 5000){\n return(TRUE)\n }\n return(FALSE)\n }\n return(FALSE)\n\n}\n\n\n##############################################\n################ Code to run #################\n##############################################\n\n\n#Relates to parallelization - feel free to comment\nncores <- as.numeric(Sys.getenv('SLURM_CPUS_ON_NODE'))\nregisterDoParallel(ncores)\n\ntoTrack <- tbl_df(expand.grid(A = c(1, 0), B = c(1, 0), C = c(1, 0)))\ndruginds <- toTrack %>% mutate(ind = 1:n()) %>% gather(drug, mut, -ind)\nindinf <- toTrack %>% mutate(comb = paste0(A, B, C)) %>%\n mutate(ind = 1:8) %>% select(comb, ind)\n\n#2 periods/hour, 24 hours/day, 7 days/week, 4 weeks/month, 12 months/year * 10 years\nmaxDoseT <- 2 * 24 * 7 * 4 * 12 * 10\nind <- 1\n\ndirp <- \"../dat/time_model/\"\nprint(paste0(\"making directory: \", dirp))\n\nsystem(paste0(\"mkdir \", dirp))\n\n#This refers to the random nature at which doses are missed\ntreatmentType <- \"random\"\ncombs <- c(\"3TC\", \"D4T\", \"NFV\")\n\n#These nested loops draw from our cluster set up\n#As a test to see if things are working properly, I'd recommend lowering\n#these numbers\nforeach(ind = 1:20)%dopar%{\n foreach(ind = 1:75 )%do%{\n\n R00 <- 10 \n\n Ne <- floor(10^rnorm(1, 5.2, .5))\n while(Ne < 10^4 | Ne > 10^6){\n Ne <- floor(10^rnorm(1, 5.2, .5))\n }\n rseed <- sample(1:100000, 1)\n\n #Adherence\n pv <- runif(1, 0, 1)\n\n stringToPrint <- paste(paste0(combs, collapse = \"-\"),\n treatmentType,\n pv,\n R00,\n ind, Ne, rseed, sep = \"_\")\n\n dat <- runTime(combs = combs, maxDoseT = maxDoseT, missp = pv,\n Rscale = R00, doseType = treatmentType, Ne = Ne)\n\n relInds <- c(1, which(1:ncol(dat$f) %% (2 * 24 * 7 * 4 ) == 0))\n\n write.table(dat$f[,relInds], paste0(dirp, stringToPrint, \"_f.csv\"),\n quote = FALSE, sep = \",\",\n row.names = FALSE, col.names = FALSE)\n\n }\n}\n\n\n\t\t \n\n\n\n\n\n\n\n", "meta": {"hexsha": "eb423d3603f0107b9ed1e28ec652b2eaae52853a", "size": 13025, "ext": "r", "lang": "R", "max_stars_repo_path": "code/time_runner.r", "max_stars_repo_name": "federlab/HIV-MDR-evolution", "max_stars_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/time_runner.r", "max_issues_repo_name": "federlab/HIV-MDR-evolution", "max_issues_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/time_runner.r", "max_forks_repo_name": "federlab/HIV-MDR-evolution", "max_forks_repo_head_hexsha": "10665ab24f0193d620bae03d413692f063b9a165", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7435233161, "max_line_length": 146, "alphanum_fraction": 0.4509021113, "num_tokens": 3830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.33256330642072074}} {"text": "#Jenny Smith\n\n#May 8, 2017 \n\n#Purpose: Create a PCA, and MDS ordination plots given expression data and genes of interest. \n\n\nplotPCoA <- function(expnData,phenovector, title=\"\",colorCodes=NULL, geneList=NULL, size=3){\n #expnData is normalized counts, typically log2 scale. \n \n #factor is the name of the factor column \n suppressPackageStartupMessages(library(vegan))\n suppressPackageStartupMessages(library(ggplot2))\n suppressPackageStartupMessages(library(dplyr))\n \n #Ensure correct order of patients in both datasets\n expnData <- expnData[ ,intersect(names(phenovector), colnames(expnData))] \n phenovector <- phenovector[intersect(names(phenovector),colnames(expnData))]\n \n if (! is.null(geneList)){\n expnData <- t(expnData[geneList, ])\n }else{\n expnData <- t(expnData) #note: must remove all zero count genes or will fail on an error\n }\n \n PCoA <- capscale(expnData ~ 1, distance = \"bray\", add=TRUE)\n scores <- data.frame(scores(PCoA, display=\"sites\"), \n group=phenovector) %>%\n dplyr::arrange(desc(group))\n \n \n p <- ggplot(scores, aes(x=MDS1, MDS2)) +\n geom_point(aes(color=scores[,\"group\"]), size=size, alpha=0.75) +\n theme_numX +\n labs(title=title) \n \n if(!is.null(colorCodes)){\n p <- p + \n scale_color_manual(values=colorCodes)\n }\n #If wanted to add ellipses and convex hulls use the code below\n \n # k <- 4\n # clust <- kmeans(scores[,1:2], k)\n # groups <- as.factor(clust$cluster)\n # \n # scores <- scores %>%\n # mutate(group=groups,\n # Status=clinData[rownames(expnData),factor])\n # head(scores)\n # mds.plot <- ggscatter(scores, x=\"MDS1\", y=\"MDS2\", \n # size=3.5, \n # color=\"Status\",\n # group=\"group\",\n # palette = \"Set1\",\n # ellipse =FALSE,\n # ellipse.type = \"norm\",\n # repel = TRUE)\n # #https://stats.stackexchange.com/questions/22805/how-to-draw-neat-polygons-around-scatterplot-regions-in-ggplot2/22855\n # find_hull <- function(df) df[chull(df$MDS1, df$MDS2), ]\n # hulls <- ddply(scores,\"group\",find_hull )\n # \n # #add hulls or ellipses\n # mds.plot <- mds.plot + \n # # stat_ellipse(data = scores,\n # # mapping = aes(group=group, fill=group), geom = \"polygon\", alpha=0.15, color=\"black\", level=0.99)\n # geom_polygon(data=hulls, aes(fill=group), alpha=0.15) +\n # scale_fill_manual(values = rainbow_hcl(4)) + \n # theme(text = element_text(size=20))\n \n # aov <- aov(scores$MDS1 ~ df[,factor]) #NOTE: This is only valid for balanced experimental designs! Equal # of obs in each factor level.\n\n list <- list(PCoA,scores, p)\n names(list) <- c(\"PCoA\",\"scores\",\"plot\")\n \n return(list)\n}\n\n\n#from https://github.com/mikelove/DESeq2/blob/master/R/plots.R\n#Want to return the whole scores matrix so can examine 3d pca plots. \nplotPCA.DESeq.mod <- function(object, intgroup=\"condition\", ntop=500, returnData=FALSE, PC3=FALSE)\n{\n library(matrixStats)\n # calculate the variance for each gene\n rv <- rowVars(assay(object))\n \n # select the ntop genes by variance\n select <- order(rv, decreasing=TRUE)[seq_len(min(ntop, length(rv)))]\n \n # perform a PCA on the data in assay(x) for the selected genes\n pca <- prcomp(t(assay(object)[select,]))\n \n # the contribution to the total variance for each component\n percentVar <- pca$sdev^2 / sum( pca$sdev^2 )\n \n if (!all(intgroup %in% names(colData(object)))) {\n stop(\"the argument 'intgroup' should specify columns of colData(dds)\")\n }\n \n intgroup.df <- as.data.frame(colData(object)[, intgroup, drop=FALSE])\n \n # add the intgroup factors together to create a new grouping factor\n group <- if (length(intgroup) > 1) {\n factor(apply( intgroup.df, 1, paste, collapse=\":\"))\n } else {\n colData(object)[[intgroup]]\n }\n \n # assembly the data for the plot - first 10 PCs\n # d <- data.frame(PC1=pca$x[,1], PC2=pca$x[,2], group=group, intgroup.df, name=colnames(object))\n n <- min(10, ncol(as.data.frame(pca$x)))\n d <- data.frame(as.data.frame(pca$x)[,1:n], group=group, intgroup.df, name=colnames(object))\n \n if (returnData) {\n attr(d, \"percentVar\") <- percentVar[1:10]\n rot <- pca$rotation[,1:10] #for first 10 PCs\n dat <- list(\"scores\"=d,\"rotation\"=rot)\n return(dat)\n }\n \n if(PC3){\n ggplot(data=d, aes_string(x=\"PC1\", y=\"PC3\", color=\"group\")) + \n geom_point(size=3, alpha=0.75) + \n xlab(paste0(\"PC1: \",round(percentVar[1] * 100),\"% variance\")) +\n ylab(paste0(\"PC3: \",round(percentVar[3] * 100),\"% variance\"))\n \n }else{\n ggplot(data=d, aes_string(x=\"PC1\", y=\"PC2\", color=\"group\")) + \n geom_point(size=3, alpha=0.75) + \n xlab(paste0(\"PC1: \",round(percentVar[1] * 100),\"% variance\")) +\n ylab(paste0(\"PC2: \",round(percentVar[2] * 100),\"% variance\"))\n # coord_fixed()\n }\n}\n\n\n\n\n#Updated on 6/9/17 to use variance stabilized transformed data as input (not center scaled log2, like in princomp)\nPCA <- function(expnData,phenovector,title=\"\",round=TRUE,colorCodes=NULL,\n ntop=500,PC3=FALSE, GOI=NULL){\n \n suppressPackageStartupMessages(library(DESeq2))\n library(ggplot2)\n #expnData is the raw counts (not normalized) has patient IDs as colnames and genes as rownames. \n \n # countData <- expnData[,match(names(phenovector), colnames(expnData))]\n samples <- intersect(names(phenovector), colnames(expnData))\n countData <- expnData[,samples]\n phenovector <- phenovector[samples]\n \n countData <- round(countData, digits = 0)\n colData <- as.data.frame(phenovector)\n \n if(length(unique(phenovector)) < 2){\n dds <- DESeqDataSetFromMatrix(countData = countData,\n colData = colData,\n design = ~ 1)\n }else{\n dds <- DESeqDataSetFromMatrix(countData = countData,\n colData = colData,\n design = ~ phenovector)\n }\n \n #create deseq2 dataset and perform variance stabilized transformation for sample to sample comparisons\n dds <- dds[ rowSums(counts(dds)) > 10, ]\n varianceStab <- vst(dds, blind = TRUE)\n \n #if given a list of genes of interest\n if (! is.null(GOI)){\n GOI <- intersect(GOI, rownames(assay(varianceStab)))\n }else{\n GOI <- 1:nrow(varianceStab)\n }\n \n # Create a PCA plot \n plot.1 <- plotPCA.DESeq.mod(varianceStab[GOI,], intgroup = \"phenovector\", ntop = ntop, PC3=FALSE) + \n theme_numX + \n labs(title=title) \n \n if(PC3){\n plot.2 <- plotPCA.DESeq.mod(varianceStab[GOI,], intgroup = \"phenovector\", ntop = ntop, PC3=TRUE) + \n theme_numX + \n labs(title=title) \n }\n\n #change points to custom colors if provided \n if (!is.null(colorCodes)){\n plot.1 <- plot.1 + \n scale_color_manual(values=colorCodes)\n \n if(exists(\"plot.2\")){\n plot.2 <- plot.2 + \n scale_color_manual(values=colorCodes)\n }\n \n }\n \n #PCA data frame with the wieghts/loadings and eigen vectors\n pca.dat <- plotPCA.DESeq.mod(varianceStab[GOI,], intgroup = \"phenovector\", ntop = ntop,\n returnData=TRUE)\n \n #Final Results object\n res <- list(dds, varianceStab,pca.dat$scores,pca.dat$rotation, plot.1)\n names(res) <- c(\"dds\", \"vst\",\"pca_data\",\"pca_loadings\", \"pca_plot\")\n \n if(is.character(GOI)){\n res[[\"GOI\"]] <- GOI\n }\n \n if(PC3){\n res[[\"pca_plot2\"]] <- plot.2\n }\n \n return(res)\n}\n\n\npca_custom <- function(expnData,CDE,fillCol, colorCol, colorCode=NULL, PC3=FALSE,\n single.col.outline=FALSE, toHighlight=NULL, ellipse=FALSE){\n library(tibble)\n library(dplyr)\n #expn data is log2, normalized counts\n #CDE has patients as rownames. \n #fillCol == character string of column name for fill colors \n #colorCol == character string of column name for border colors\n #colorCode is an option named vector of colors. If specifying color and fill manually, create a list with length 2, with names c(\"fill\",\"color\")\n #single.col.outline is T/F for wether to susbet to dataframe for the border colors. \n #toHighlight is a character vector for if single.col.outline == TRUE. Gives the factor to highlight with borders from the colorColumn. \n #ellipse is T/F for an ellipse based on fillCol column\n expnData <- expnData[,intersect(rownames(CDE),colnames(expnData))]\n \n # print(dim(expnData))\n pca <- prcomp(t(expnData), scale=TRUE)\n summ <- summary(pca)\n \n scores <- as.data.frame(pca$x) %>%\n rownames_to_column(\"USI\") %>%\n inner_join(., dplyr::select(CDE,USI=matches(\"USI$\"), everything()), by=\"USI\") %>%\n dplyr::select(USI,fillCol, colorCol, everything())\n \n #Plot function for PC1 and either PC2 or anyother\n pca.plot_function <- function(scores,PC){\n \n idx <- as.numeric(gsub(\"[A-Za-z]{2}\",\"\", PC))\n \n \n pca.plot <- ggplot(scores, aes_string(x=\"PC1\", y=PC)) +\n labs(x=paste(\"PC1: \", round(summ$importance[2,1], digits=3)*100, \"% variance\"),\n y=paste(paste0(PC,\": \"), round(summ$importance[2,idx], digits=3)*100, \"% variance\")) +\n theme_numX +\n theme(legend.text = element_text(size=14),\n legend.title = element_text(size=16))\n \n if(single.col.outline){\n pca.plot <- pca.plot + \n geom_point(size=5,stroke=0.2, alpha=1,shape=21,color=\"white\",\n aes_string(fill=fillCol)) +\n geom_point(data=subset(scores, scores[,colorCol] == toHighlight),\n aes_string(x=\"PC1\", y=PC, color=colorCol),\n size=4, stroke=1, alpha=1,shape=21)\n \n }else{\n pca.plot <- pca.plot + \n geom_point(size=5, stroke=2, alpha=0.85,shape=21,\n aes_string(fill=fillCol, color=colorCol))\n }\n \n if(!is.null(colorCode)){\n \n if(is.list(colorCode)){\n pca.plot <- pca.plot + \n scale_fill_manual(values=colorCode[[\"fill\"]]) + \n scale_color_manual(values=colorCode[[\"color\"]])\n }else{\n pca.plot <- pca.plot + \n scale_fill_manual(values=colorCode) \n }\n }\n \n if(ellipse){\n pca.plot <- pca.plot +\n stat_ellipse(data=scores, type=\"norm\",\n aes_string(x=\"PC1\", y=PC, fill=fillCol),\n geom=\"polygon\", alpha=0.1)\n }\n \n return(pca.plot)\n }\n \n #PC1 and PC2 plot\n pc1.pc2 <- pca.plot_function(scores=scores,PC=\"PC2\")\n \n #PC1 and PC3 plot\n if(PC3){\n pc1.pc3 <- pca.plot_function(scores=scores, PC=\"PC3\") \n \n }\n \n\n res <- list(\"pca\"=pca,\"scores\"=scores,\"plot.1\"=pc1.pc2)\n \n if(PC3){\n res[[\"plot.2\"]] <- pc1.pc3\n }\n \n return(res)\n \n}\n\n\n\n\n\n\n", "meta": {"hexsha": "e28561fca3eb2a3a83609b2eae6c59dbf8514d45", "size": 10642, "ext": "r", "lang": "R", "max_stars_repo_path": "R/clusterAnalysis_Function.r", "max_stars_repo_name": "Meshinchi-Lab/DeGSEA", "max_stars_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_stars_repo_licenses": ["MIT"], "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/clusterAnalysis_Function.r", "max_issues_repo_name": "Meshinchi-Lab/DeGSEA", "max_issues_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_issues_repo_licenses": ["MIT"], "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/clusterAnalysis_Function.r", "max_forks_repo_name": "Meshinchi-Lab/DeGSEA", "max_forks_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.570977918, "max_line_length": 147, "alphanum_fraction": 0.6185867318, "num_tokens": 3102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3321753021572076}} {"text": "# Fonction R à traduire en Python\nget_pca <- function(res.pca, element = c(\"var\", \"ind\")){\n elmt <- match.arg(element)\n if(elmt ==\"var\") get_pca_var(res.pca)\n else if(elmt == \"ind\") get_pca_ind(res.pca)\n}\n\nget_pca_ind<-function(res.pca, ...){\n \n # FactoMineR package\n if(inherits(res.pca, c('PCA'))) ind <- res.pca$ind\n \n # ade4 package\n else if(inherits(res.pca, 'pca') & inherits(res.pca, 'dudi')){ \n ind.coord <- res.pca$li\n # get the original data\n data <- res.pca$tab\n data <- t(apply(data, 1, function(x){x*res.pca$norm} ))\n data <- t(apply(data, 1, function(x){x+res.pca$cent}))\n ind <- .get_pca_ind_results(ind.coord, data, res.pca$eig,\n res.pca$cent, res.pca$norm)\n }\n \n # stats package\n else if(inherits(res.pca, 'princomp')){ \n ind.coord <- res.pca$scores\n data <- .prcomp_reconst(res.pca)\n ind <- .get_pca_ind_results(ind.coord, data, res.pca$sdev^2,\n res.pca$center, res.pca$scale)\n \n }\n else if(inherits(res.pca, 'prcomp')){\n ind.coord <- res.pca$x\n data <- .prcomp_reconst(res.pca)\n ind <- .get_pca_ind_results(ind.coord, data, res.pca$sdev^2,\n res.pca$center, res.pca$scale)\n }\n # ExPosition package\n else if (inherits(res.pca, \"expoOutput\") & inherits(res.pca$ExPosition.Data,'epPCA')){\n res <- res.pca$ExPosition.Data\n ind <- list(coord = res$fi, cos2 = res$ri, contrib = res$ci*100)\n }\n else stop(\"An object of class : \", class(res.pca), \n \" can't be handled by the function get_pca_ind()\")\n \n class(ind)<-c(\"factoextra\", \"pca_ind\")\n \n ind\n}\n\n\nget_pca_var<-function(res.pca){\n # FactoMineR package\n if(inherits(res.pca, c('PCA'))) var <- res.pca$var\n # ade4 package\n else if(inherits(res.pca, 'pca') & inherits(res.pca, 'dudi')){\n var <- .get_pca_var_results(res.pca$co)\n }\n # stats package\n else if(inherits(res.pca, 'princomp')){ \n # Correlation of variables with the principal component\n var_cor_func <- function(var.loadings, comp.sdev){var.loadings*comp.sdev}\n var.cor <- t(apply(res.pca$loadings, 1, var_cor_func, res.pca$sdev))\n var <- .get_pca_var_results(var.cor)\n }\n else if(inherits(res.pca, 'prcomp')){\n # Correlation of variables with the principal component\n var_cor_func <- function(var.loadings, comp.sdev){var.loadings*comp.sdev}\n var.cor <- t(apply(res.pca$rotation, 1, var_cor_func, res.pca$sdev))\n var <- .get_pca_var_results(var.cor)\n }\n # ExPosition package\n else if (inherits(res.pca, \"expoOutput\") & inherits(res.pca$ExPosition.Data,'epPCA')){\n res <- res.pca$ExPosition.Data\n data_matrix <- res$X\n factor_scores <- res$fi\n var.coord <- var.cor <- stats::cor(res$X, res$fi) # cor(t(data_matrix), factor_scores)\n var.coord <- replace(var.coord, is.na(var.coord), 0)\n var <- list(coord = var.coord, cor = var.coord, cos2 = res$rj, contrib = res$cj*100)\n }\n else stop(\"An object of class : \", class(res.pca), \n \" can't be handled by the function get_pca_var()\")\n class(var)<-c(\"factoextra\", \"pca_var\")\n var\n}\n\n# compute all the results for individuals : coord, cor, cos2, contrib\n# ind.coord : coordinates of variables on the principal component\n# pca.center, pca.scale : numeric vectors corresponding to the pca\n# center and scale respectively\n# data : the orignal data used during the pca analysis\n# eigenvalues : principal component eigenvalues\n.get_pca_ind_results <- function(ind.coord, data, eigenvalues, pca.center, pca.scale ){\n \n eigenvalues <- eigenvalues[1:ncol(ind.coord)]\n \n if(pca.center[1] == FALSE) pca.center <- rep(0, ncol(data))\n if(pca.scale[1] == FALSE) pca.scale <- rep(1, ncol(data))\n \n # Compute the square of the distance between an individual and the\n # center of gravity\n getdistance <- function(ind_row, center, scale){\n return(sum(((ind_row-center)/scale)^2))\n }\n d2 <- apply(data, 1,getdistance, pca.center, pca.scale)\n \n # Compute the cos2\n cos2 <- function(ind.coord, d2){return(ind.coord^2/d2)}\n ind.cos2 <- apply(ind.coord, 2, cos2, d2)\n \n # Individual contributions \n contrib <- function(ind.coord, eigenvalues, n.ind){\n 100*(1/n.ind)*(ind.coord^2/eigenvalues)\n }\n ind.contrib <- t(apply(ind.coord, 1, contrib, eigenvalues, nrow(ind.coord)))\n \n colnames(ind.coord) <- colnames(ind.cos2) <-\n colnames(ind.contrib) <- paste0(\"Dim.\", 1:ncol(ind.coord)) \n \n rnames <- rownames(ind.coord)\n if(is.null(rnames)) rnames <- as.character(1:nrow(ind.coord))\n rownames(ind.coord) <- rownames(ind.cos2) <- rownames(ind.contrib) <- rnames\n \n # Individuals coord, cos2 and contrib\n ind = list(coord = ind.coord, cos2 = ind.cos2, contrib = ind.contrib)\n ind\n}\n\n# compute all the results for variables : coord, cor, cos2, contrib\n# var.coord : coordinates of variables on the principal component\n.get_pca_var_results <- function(var.coord){\n \n var.cor <- var.coord # correlation\n var.cos2 <- var.cor^2 # variable qualities \n \n # variable contributions (in percent)\n # var.cos2*100/total Cos2 of the component\n comp.cos2 <- apply(var.cos2, 2, sum)\n contrib <- function(var.cos2, comp.cos2){var.cos2*100/comp.cos2}\n var.contrib <- t(apply(var.cos2,1, contrib, comp.cos2))\n \n colnames(var.coord) <- colnames(var.cor) <- colnames(var.cos2) <-\n colnames(var.contrib) <- paste0(\"Dim.\", 1:ncol(var.coord)) \n \n # Variable coord, cor, cos2 and contrib\n list(coord = var.coord, cor = var.cor, cos2 = var.cos2, contrib = var.contrib)\n}", "meta": {"hexsha": "d8b52d248bbd6487650eb4ba6cfdd32299835206", "size": 5490, "ext": "r", "lang": "R", "max_stars_repo_path": "vizfactor/get_pca_R.r", "max_stars_repo_name": "lucayapi/vizfactor", "max_stars_repo_head_hexsha": "a9d0505a8fbf5c05acc524bac06f68accc0db222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizfactor/get_pca_R.r", "max_issues_repo_name": "lucayapi/vizfactor", "max_issues_repo_head_hexsha": "a9d0505a8fbf5c05acc524bac06f68accc0db222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vizfactor/get_pca_R.r", "max_forks_repo_name": "lucayapi/vizfactor", "max_forks_repo_head_hexsha": "a9d0505a8fbf5c05acc524bac06f68accc0db222", "max_forks_repo_licenses": ["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.3469387755, "max_line_length": 90, "alphanum_fraction": 0.6546448087, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.33217529511315264}} {"text": "\n#=========================================================\n#\n# Judas detection probability - discrete survival analysis\n#\n# Dave Ramsey (22/11/2021)\n#=========================================================\n\nlibrary(tidyverse)\nlibrary(lubridate)\nlibrary(sf)\nlibrary(purrr)\nlibrary(cmdstanr)\nlibrary(posterior)\nsource(\"R/judas functions.r\")\n\n#==================================================\n# Santiago Judas goats\n#==================================================\n\n\ngoat_dyads<- read_csv(\"data/Santiago_judas_dyads.csv\")\ngoat_dyads<- goat_dyads %>% mutate(id1 = factor(as.character(id1)), id2 = factor(as.character(id2)))\ngoat_ids<- read_csv(\"data/Santiago_judas_ID.csv\")\ngoat_ids<- goat_ids %>% mutate(ID = factor(as.character(ID)))\n\nid1<- as.vector(unclass(goat_dyads$id1))\nid2<- as.vector(unclass(goat_dyads$id2))\n\ndyad<- as.vector(unclass(factor(goat_dyads$Dyad)))\nndyads<- max(dyad)\nN<- nrow(goat_dyads)\nM<- nrow(goat_ids)\nX<- model.matrix(~ distance + Sex1 + Trans1, data=goat_dyads)[,-1]\nK<- ncol(X)\nsex<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\n#---- Calculate home range scale (sigma) from Judas locations ----\n\ngoat_locs<- read_csv(\"data/santiago_judas_locs.csv\")\ngoat_locs<- goat_locs %>% mutate(ID = factor(as.character(ID)))\ngoat_locs<- goat_locs %>% group_by(ID) %>% nest() %>% arrange(ID)\n\n\ngoat_chr<- goat_locs %>% mutate(CNorm=map(data, calc_hr))\ngoat_chr<- goat_chr %>% unnest(CNorm) %>% select(-data)\n\nmaxD<- goat_chr$sigma * 2.45\n\n#---- Discrete survival analysis -----\n\nset.seed(123)\n\nmod<- cmdstan_model(\"stan/discrete_survival.stan\")\n\ndata<- list(N=N,M=M,K=K,X=X,id1=id1,id2=id2,\n time=as.integer(goat_dyads$time),\n ev=as.integer(goat_dyads$event),sex=sex,maxD=maxD)\n \n\n## MCMC settings (for illustration - increase for serious inference)\nni <- 500\nnt <- 1\nnb <- 500\nnc <- 2\n\n \ninits <- lapply(1:nc, function(i)\n list(b1= -3, beta=c(-0.5,1,1,1), sigma_id1=runif(1), sigma_id2=runif(1), q=runif(N, 0, 0.1)))\n\nout<- mod$sample(\n data=data,\n init = inits,\n iter_warmup = nb,\n iter_sampling = ni,\n chains=nc,\n parallel_chains = nc,\n refresh = 50)\n\n\nout$summary(c(\"b1\",\"beta\",\"sigma_id1\",\"sigma_id2\"))\n\nout$summary(\"pave\")\n\nout$save_object(file=\"out/goat_surv.rds\")\n\n#==================================================\n# Santa Cruz Island Judas pigs\n#==================================================\n\npig_dyads<- read_csv(\"data/Santacruz_judas_dyads.csv\")\npig_dyads<- pig_dyads %>% mutate(id1 = factor(as.character(id1)), id2 = factor(as.character(id2)))\npig_ids<- pig_dyads %>% select(ID=id1,Sex=Sex1) %>% distinct() %>% arrange(ID)\n\nid1<- as.vector(unclass(pig_dyads$id1))\nid2<- as.vector(unclass(pig_dyads$id2))\n\ndyad<- as.vector(unclass(factor(pig_dyads$Dyad)))\nndyads<- max(dyad)\nN<- nrow(pig_dyads)\nM<- nrow(pig_ids)\nX<- model.matrix(~ distance + Sex1, data=pig_dyads)[,-1]\nK<- ncol(X)\nsex<- as.matrix(ifelse(pig_ids$Sex==\"B\", 0, 1))\n\n#--- Calculate home range scale (sigma) from Judas locations\npig_locs<- read_csv(\"data/santacruz_judas_locs.csv\")\n# rescale coordinates to km\npig_locs<- pig_locs %>% mutate(ID = factor(as.character(ID)),East=East/1000, North=North/1000)\npig_locs<- pig_locs %>% group_by(ID) %>% nest() %>% arrange(ID)\n\npig_chr<- pig_locs %>% mutate(CNorm=map(data, calc_hr))\npig_chr<- pig_chr %>% unnest(CNorm) %>% select(-data)\n\nmaxD<- pig_chr$sigma * 2.45\n\n#------------------------------------------------------\n# Discrete survival analysis\n#-----------------------------------------------------------\n\nmod<- cmdstan_model(\"stan/discrete_survival.stan\")\n\ndata<- list(N=N,M=M,K=K,X=X,id1=id1,id2=id2,\n time=as.integer(pig_dyads$time),\n ev=as.integer(pig_dyads$event),sex=sex,maxD=maxD)\n\n\n## MCMC settings\nni <- 500\nnt <- 1\nnb <- 500\nnc <- 2\n\n\ninits <- lapply(1:nc, function(i)\n list(b1= -3, beta=c(-0.5,1), sigma_id1=runif(1), sigma_id2=runif(1), q=runif(N, 0, 0.1)))\n\nout<- mod$sample(\n data=data,\n init = inits,\n iter_warmup = nb,\n iter_sampling = ni,\n chains=nc,\n parallel_chains = nc,\n refresh = 50)\n\n\nout$summary(c(\"b1\",\"beta\",\"sigma_id1\",\"sigma_id2\"))\n\nout$summary(\"pave\")\n\nout$save_object(file=\"out/pig_surv.rds\")\n\n\n#---------------------------------------------------\n# Plots \n#---------------------------------------------------\n\n# Predicted probability of detection at activity centres (i.e. distance = 0)\n\nout<- readRDS(\"out/goat_surv.rds\")\n\nfit<- as_draws_rvars(out$draws(c(\"beta0\",\"beta\")))\n\nbeta0<- draws_of(fit$beta0)\nbeta<- draws_of(fit$beta)\nbeta1<- beta[,1]\nbeta2<- beta[,-1]\n\nn<- nrow(goat_ids)\nXX<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\nplam<- matrix(NA,nrow=dim(beta)[1],ncol=n)\nfor(i in 1:n){\n plam[,i]<- 1-exp(-exp(beta0[,i] + beta2 %*% XX[i,]))\n}\n\nplam<- as.data.frame(plam)\nnames(plam)<- goat_ids$ID\nplam$samp<- 1:nrow(plam)\n\nplam<- plam %>% pivot_longer(-samp, names_to = \"ID\", values_to = \"p\")\nplam<- left_join(plam, goat_ids)\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\nwin.graph(10,5)\nplam %>% ggplot(aes(ID, p, color=interaction(Sex,Trans))) +\n geom_boxplot(fill=\"grey90\",outlier.color = NA) +\n labs(x=\"Judas ID\", y=\"Detection probability at centre of UD\") + \n theme_bw() +\n theme(axis.text.x = element_blank(),\n legend.position = \"bottom\",\n legend.title = element_blank())\n \n\n#--------------------------------------------------------\n# Predicted detection curves with distance from activity centre\n#--------------------------------------------------------\nfit<- as_draws_rvars(out$draws(c(\"beta0\",\"beta\")))\n\nbeta0<- E(fit$beta0)\nbeta<- E(fit$beta)\nbeta1<- beta[1]\nbeta2<- beta[-1]\n\nn<- nrow(goat_ids)\ndistance<- seq(0,20,0.1)\nXX<- model.matrix(~Sex + Trans, goat_ids)[,-1]\n\nplam<- matrix(NA,nrow=length(distance), ncol=n)\n\nfor(i in 1:n){\n plam[,i]<- 1-exp(-exp(beta0[i] + beta1*distance + as.vector(XX[i,] %*% beta2)))\n}\nplam<- as.data.frame(plam)\nnames(plam)<- goat_ids$ID\nplam<- plam %>% mutate(Distance=distance)\n \nplam<- plam %>% pivot_longer(-Distance, names_to = \"ID\", values_to = \"p\")\nplam<- left_join(plam, goat_ids)\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\n\nwin.graph(8,7)\nplam %>% ggplot(aes(Distance, p, group=ID)) +\n geom_line(color=\"grey50\") +\n facet_grid(rows=vars(Sex), cols=vars(Trans)) +\n labs(x=\"Distance (km)\",y=\"Probability of association\") +\n theme_bw() +\n theme(legend.position = \"none\",\n strip.text = element_text(face=\"bold\"))\n\n #--------------------------------------------------------------------\n # Unconditional detection probability (Eqn. 2)\n #-------------------------------------------------------------------- \n\nfit<- summarise_draws(out$draws(\"pave\"), mean, ~quantile(.x, c(0.05,0.95)))\n \nplam<- goat_ids %>% mutate(pave= fit$mean, lcl = fit$`5%`, ucl=fit$`95%`)\nplam<- plam %>% mutate(Sex = factor(Sex, levels=c(\"Female\",\"Super\",\"Male\")),\n Trans = factor(Trans, labels = c(\"Not Translocated\",\"Translocated\")))\n\nwin.graph(10,5)\n plam<- plam %>% arrange(pave)\n plam %>% mutate(ID = fct_reorder(ID, pave), Sex) %>%\n ggplot(aes(x=Trans, y=pave, color=Sex)) +\n geom_pointrange(aes(ymin=lcl,ymax=ucl), position=position_dodge2(width=0.5)) +\n facet_wrap(~Sex) +\n labs(x=\"\",y=\"Probability of association\",color=\"Status\") +\n theme_bw() +\n theme(legend.position = \"none\",\n strip.text = element_text(face=\"bold\"),\n axis.title = element_text(face=\"bold\", size=12),\n axis.text.x = element_text(size=11))\n\n", "meta": {"hexsha": "848d680d6fa981ff0e9269f35b35c81ac300a6e6", "size": 7639, "ext": "r", "lang": "R", "max_stars_repo_path": "R/discrete_survival_analysis.r", "max_stars_repo_name": "dslramsey/judas_detection", "max_stars_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/discrete_survival_analysis.r", "max_issues_repo_name": "dslramsey/judas_detection", "max_issues_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/discrete_survival_analysis.r", "max_forks_repo_name": "dslramsey/judas_detection", "max_forks_repo_head_hexsha": "ca73d208df5c8ec952c05f49851d8e8091067c85", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6085271318, "max_line_length": 100, "alphanum_fraction": 0.5927477419, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3312734487209058}} {"text": "\n\n# Snow crab --- Areal unit modelling of habitat -- no reliance upon stmv fields\n\n\n# -------------------------------------------------\n# Part 1 -- construct basic parameter list defining the main characteristics of the study\n# require(aegis)\n\n year.assessment = 2021\n require(bio.snowcrab) # loadfunctions(\"bio.snowcrab\") \n\n # choose one: \n if (0) {\n # default: best DIC 31457.19, WAIC 32405.81\n # P(y) = Pois(y|y>0) ; p = exp(theta) / ( 1 + exp(theta) )\n family=\"poisson\" \n carstm_model_label = \"tesselation\" \n \n # estimates suggest 30% prob of 0 overdispersion: DIC: 36196.11, WAIC 36850.04\n # P(y) = p 1_{y=0} + (1-p) Pois(y|y>0) ; pois is of positive valued only \n family=\"zeroinflatedpoisson0\" \n carstm_model_label = \"tesselation_zip0\" \n \n # unstable ... will not complete due to singularities ... might be overparamterized\n # P(y) = p 1_{y=0} + (1-p) Pois(y) ; pois is of all values\n family=\"zeroinflatedpoisson1\" \n carstm_model_label = \"tesselation_zip1\"\n \n }\n\n\n p = snowcrab_parameters(\n project_class=\"carstm\",\n yrs=2000:year.assessment,\n areal_units_type=\"tesselation\",\n# areal_units_constraint_ntarget = 20,\n# areal_units_constraint_nmin = 5,\n family=family,\n carstm_model_label = carstm_model_label,\n selection = list(type = \"number\")\n )\n\n\n\n# ------------------------------------------------\n# Part 2 -- spatiotemporal statistical model\n\n if ( spatiotemporal_model ) {\n\n if (0) {\n # polygon structure:: create if not yet made\n # adjust based upon RAM requirements and ncores\n # create if not yet made\n for (au in c(\"cfanorth\", \"cfasouth\", \"cfa4x\", \"cfaall\" )) plot(polygon_managementareas( species=\"snowcrab\", au))\n xydata = snowcrab.db( p=p, DS=\"areal_units_input\", redo=TRUE )\n\n sppoly = areal_units( p=p, hull_alpha=15, redo=TRUE, verbose=TRUE ) # create constrained polygons with neighbourhood as an attribute\n plot( sppoly[, \"npts\"] )\n\n MS = NULL\n\n # p$carstm_model_label = \"tesselation_overdispersed\" # default is the name of areal_units_type\n # p$family = \"zeroinflatedpoisson0\" # \"binomial\", # \"nbinomial\", \"betabinomial\", \"zeroinflatedbinomial0\" , \"zeroinflatednbinomial0\"\n # p$carstm_model_inla_control_familiy = NULL\n\n }\n\n sppoly = areal_units( p=p ) # to reload\n\n\n # -------------------------------------------------\n M = snowcrab.db( p=p, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n M = NULL; gc()\n\n fit = carstm_model( \n p=p, \n data='snowcrab.db( p=p, DS=\"carstm_inputs\" )', \n posterior_simulations_to_retain=\"predictions\" ,\n scale_offsets = TRUE, # required to stabilize as offsets are so small, required for : inla.mode = \"experimental\" \n # redo_fit = FALSE, # only to redo sims and extractions \n # toget=\"predictions\", # this updates a specific subset of calc\n control.inla = list( strategy='adaptive' ), # strategy='laplace', \"adaptive\" int.strategy=\"eb\" \n num.threads=\"4:2\"\n )\n\n if (0) {\n # control.compute=list(smtp=\"default\", dic=TRUE, waic=TRUE, cpo=FALSE, config=TRUE, return.marginals.predictor=TRUE)\n # control.fixed=list(prec=1,prec.intercept=1) \n # 151 configs and long optim .. 19 hrs\n # fit = carstm_model( p=p, DS=\"carstm_modelled_fit\")\n \n # extract results\n # very large files .. slow\n fit = carstm_model( p=p, DS=\"carstm_modelled_fit\" ) # extract currently saved model fit\n fit$summary$dic$dic\n fit$summary$dic$p.eff\n\n plot(fit)\n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n\n }\n\n\n res = carstm_model( p=p, DS=\"carstm_modelled_summary\" ) # to load currently saved results\n\n\n map_centre = c( (p$lon0+p$lon1)/2 - 0.5, (p$lat0+p$lat1)/2 -0.8 )\n map_zoom = 5\n\n plot_crs = p$aegis_proj4string_planar_km\n\n \n require(tmap)\n \n additional_features = \n tm_shape( aegis.polygons::area_lines.db( DS=\"cfa.regions\", returntype=\"sf\", project_to=plot_crs ), projection=plot_crs ) + \n tm_lines( col=\"slategray\", alpha=0.75, lwd=2) + \n tm_shape( aegis.bathymetry::isobath_db( depths=c( seq(0, 400, by=50), 1000), project_to=plot_crs ), projection=plot_crs ) +\n tm_lines( col=\"slategray\", alpha=0.5, lwd=0.5) +\n tm_shape( aegis.coastline::coastline_db( DS=\"eastcoast_gadm\", project_to=plot_crs ), projection=plot_crs ) +\n tm_polygons( col=\"lightgray\", alpha=0.5 , border.alpha =0.5)\n\n (additional_features)\n\n vn=c( \"random\", \"space\", \"combined\" )\n vn=c( \"random\", \"spacetime\", \"combined\" )\n vn=\"predictions\" # numerical density (km^-2)\n\n tmatch=\"2015\"\n\n # densities\n carstm_map( res=res, vn=vn, tmatch=tmatch, \n palette=\"-RdYlBu\",\n plot_elements=c( \"compass\", \"scale_bar\", \"legend\" ),\n additional_features=additional_features,\n tmap_zoom= c(map_centre, map_zoom),\n title =paste( vn, paste0(tmatch, collapse=\"-\"), \"no/km^2\" )\n )\n\n\n # map all :\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"predicted.numerical.densitites\" )\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n vn=\"predictions\"\n toplot = carstm_results_unpack( res, vn )\n brks = pretty( quantile(toplot[,,\"mean\"], probs=c(0,0.975), na.rm=TRUE ) )\n\n \n for (y in res$time ){\n tmatch = as.character(y)\n fn_root = paste(\"Predicted_numerical_abundance\", paste0(tmatch, collapse=\"-\"), sep=\"_\")\n fn = file.path( outputdir, paste(fn_root, \"png\", sep=\".\") )\n\n o = carstm_map( res=res, vn=vn, tmatch=tmatch,\n breaks =brks,\n palette=\"-RdYlBu\",\n plot_elements=c( \"compass\", \"scale_bar\", \"legend\" ),\n additional_features=additional_features,\n title=paste(\"Predicted numerical density (no./km^2) \", paste0(tmatch, collapse=\"-\") ),\n map_mode=\"plot\",\n scale=0.75,\n outformat=\"tmap\",\n outfilename=fn\n )\n\n }\n\n\n fit = meanweights_by_arealunit_modelled( p=p, redo=TRUE, returntype=\"carstm_modelled_fit\" ) ## used in carstm_output_compute\n\n if (0) {\n fit = meanweights_by_arealunit_modelled( p=p, returntype=\"carstm_modelled_fit\" ) \n \n res = meanweights_by_arealunit_modelled( p=p, returntype=\"carstm_modelled_summary\" ) ## used in carstm_output_compute\n\n map_centre = c( (p$lon0+p$lon1)/2 - 0.5, (p$lat0+p$lat1)/2 -0.8 )\n map_zoom = 5\n\n plot_crs = p$aegis_proj4string_planar_km\n\n\n additional_features = \n tm_shape( aegis.polygons::area_lines.db( DS=\"cfa.regions\", returntype=\"sf\", project_to=plot_crs ), projection=plot_crs ) + \n tm_lines( col=\"slategray\", alpha=0.75, lwd=2) + \n tm_shape( aegis.bathymetry::isobath_db( depths=c( seq(50, 400, by=50), 500), project_to=plot_crs ), projection=plot_crs ) +\n tm_lines( col=\"slategray\", alpha=0.5, lwd=0.5) +\n tm_shape( aegis.coastline::coastline_db( DS=\"eastcoast_gadm\", project_to=plot_crs ), projection=plot_crs ) +\n tm_polygons( col=\"lightgray\", alpha=0.5 , border.alpha =0.5)\n\n (additional_features)\n\n vn=\"predictions\"\n tmatch = \"2020\"\n\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"predicted.mean.weight\" )\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n fn_root = paste(\"Predicted_mean_size\", paste0(tmatch, collapse=\"-\"), sep=\"_\")\n\n fn = file.path( outputdir, paste(fn_root, \"png\", sep=\".\") )\n \n carstm_map( res=res, vn=vn, tmatch=tmatch, \n palette=\"-RdYlBu\",\n plot_elements=c( \"compass\", \"scale_bar\", \"legend\" ),\n additional_features=additional_features,\n tmap_zoom= c(map_centre, map_zoom),\n title =paste(\"Predicted mean weight of individual (kg)\", paste0(tmatch, collapse=\"-\") )\n )\n\n \n }\n\n snowcrab.db(p=p, DS=\"carstm_output_compute\" )\n\n RES = snowcrab.db(p=p, DS=\"carstm_output_timeseries\" )\n\n bio = snowcrab.db(p=p, DS=\"carstm_output_spacetime_biomass\" )\n num = snowcrab.db(p=p, DS=\"carstm_output_spacetime_number\" )\n\n\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"aggregated_biomass_timeseries\" )\n\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n\n ( fn = file.path( outputdir, \"cfa_all.png\") )\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfaall ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Biomass index (kt)\", xlab=\"\")\n lines( cfaall_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfaall_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n\n ( fn = file.path( outputdir, \"cfa_south.png\") )\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfasouth ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Biomass index (kt)\", xlab=\"\")\n lines( cfasouth_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfasouth_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n ( fn = file.path( outputdir, \"cfa_north.png\") )\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfanorth ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Biomass index (kt)\", xlab=\"\")\n lines( cfanorth_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfanorth_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n ( fn = file.path( outputdir, \"cfa_4x.png\") )\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfa4x ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Biomass index (kt)\", xlab=\"\")\n lines( cfa4x_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfa4x_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n\n\n # map it ..mean density\n\n sppoly = areal_units( p=p ) # to reload\n\n\n\n vn = paste(\"biomass\", \"predicted\", sep=\".\")\n\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"predicted.biomass.densitites\" )\n\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n B = apply( bio, c(1,2), mean ) \n \n brks = pretty( quantile( B[], probs=c(0,0.975) )* 10^6 )\n \n\n for (i in 1:length(p$yrs) ){\n y = as.character( p$yrs[i] )\n sppoly[,vn] = B[,y]* 10^6\n fn = file.path( outputdir , paste( \"biomass\", y, \"png\", sep=\".\") )\n\n carstm_map( sppoly=sppoly, vn=vn,\n breaks=brks,\n additional_features=additional_features,\n title=paste(\"Predicted biomass density\", y ),\n outfilename=fn\n )\n }\n\n plot( fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n plot( fit$marginals.hyperpar$\"Phi for space_time\", type=\"l\") # posterior distribution of phi nonspatial dominates\n plot( fit$marginals.hyperpar$\"Precision for space_time\", type=\"l\")\n plot( fit$marginals.hyperpar$\"Precision for setno\", type=\"l\")\n\n\n (res$summary)\n \n\n }\n\n\n ##########\n\n\n if (fishery_model) {\n\n # you need a stan installation on your system as well (outside of R), and the R-interface \"cmdstanr\":\n # install.packages(\"cmdstanr\", repos = c(\"https://mc-stan.org/r-packages/\", getOption(\"repos\")))\n \n require(cmdstanr)\n\n p$fishery_model = fishery_model( DS = \"logistic_parameters\", p=p, tag=p$areal_units_type )\n p$fishery_model$stancode = stan_initialize( stan_code=fishery_model( p=p, DS=\"stan_surplus_production\" ) )\n str( p$fishery_model)\n p$fishery_model$stancode$compile()\n to_look = c(\"K\", \"r\", \"q\", \"qc\", \"logtheta\")\n# to_look = c(\"K\", \"r\", \"q\", \"qc\" )\n\n if (0) {\n # testing other samplers and optimizsers ... faster , good for debugging\n\n # (penalized) maximum likelihood estimate (MLE)\n fit_mle = p$fishery_model$stancode$optimize(data =p$fishery_model$standata, seed = 123)\n fit_mle$summary( to_look )\n u = stan_extract( as_draws_df(fit_mle$draws() ) )\n\n mcmc_hist(fit$draws(\"K\")) + vline_at(fit_mle$mle(), size = 1.5)\n\n # Variational Bayes\n fit_vb = p$fishery_model$stancode$variational( data =p$fishery_model$standata, seed = 123, output_samples = 4000)\n fit_vb$summary(to_look)\n fit_vb$cmdstan_diagnose()\n fit_vb$cmdstan_summary()\n\n\n u = stan_extract( as_draws_df(fit_vb$draws() ) )\n\n bayesplot_grid(\n mcmc_hist(fit$draws(\"K\"), binwidth = 0.025),\n mcmc_hist(fit_vb$draws(\"K\"), binwidth = 0.025),\n titles = c(\"Posterior distribution from MCMC\", \"Approximate posterior from VB\")\n )\n\n color_scheme_set(\"gray\")\n mcmc_dens(fit$draws(\"K\"), facet_args = list(nrow = 3, labeller = ggplot2::label_parsed ) ) + facet_text(size = 14 )\n # mcmc_hist( fit$draws(\"K\"))\n\n # obtain mcmc samples from vb solution\n res_vb = fishery_model(\n DS=\"logistic_model\",\n p=p,\n tag=p$areal_units_type,\n fit = fit_vb\n )\n\n names(res_vb$mcmc)\n\n }\n\n\n\n fit = p$fishery_model$stancode$sample(\n data=p$fishery_model$standata,\n iter_warmup = 15000,\n iter_sampling = 10000,\n seed = 123,\n chains = 3,\n parallel_chains = 3, # The maximum number of MCMC chains to run in parallel.\n max_treedepth = 16,\n adapt_delta = 0.99,\n refresh = 1000\n )\n\n if (0) {\n fit = fishery_model( p=p, DS=\"fit\", tag=p$areal_units_type ) # to load samples (results)\n fit$summary(c(\"K\", \"r\", \"q\", \"qc\"))\n print( fit, max_rows=30 )\n fit$cmdstan_diagnose()\n fit$cmdstan_summary()\n\n\n }\n\n fit$summary(to_look)\n\n # save fit and get draws\n res = fishery_model( p=p, DS=\"logistic_model\", tag=p$areal_units_type, fit=fit ) # from here down are params for cmdstanr::sample()\n\n # frequency density of key parameters\n fishery_model( DS=\"plot\", vname=\"K\", res=res )\n fishery_model( DS=\"plot\", vname=\"r\", res=res )\n fishery_model( DS=\"plot\", vname=\"q\", res=res, xrange=c(0.5, 2.5))\n fishery_model( DS=\"plot\", vname=\"FMSY\", res=res )\n # fishery_model( DS=\"plot\", vname=\"bosd\", res=res )\n # fishery_model( DS=\"plot\", vname=\"bpsd\", res=res )\n\n # timeseries\n fishery_model( DS=\"plot\", type=\"timeseries\", vname=\"biomass\", res=res )\n fishery_model( DS=\"plot\", type=\"timeseries\", vname=\"fishingmortality\", res=res)\n\n # Summary table of mean values for inclusion in document\n biomass.summary.table(x)\n\n # Harvest control rules\n fishery_model( DS=\"plot\", type=\"hcr\", vname=\"default\", res=res )\n fishery_model( DS=\"plot\", type=\"hcr\", vname=\"simple\", res=res )\n\n # diagnostics\n # fishery_model( DS=\"plot\", type=\"diagnostic.errors\", res=res )\n # fishery_model( DS=\"plot\", type=\"diagnostic.phase\", res=res )\n\n\n NN = res$p$fishery_model$standata$N\n\n # bosd\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$bosd[,i] ), main=\"\")\n ( qs = apply( res$mcmc$bosd[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n\n # bpsd\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$bpsd[,i] ), main=\"\")\n ( qs = apply( res$mcmc$bpsd[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # rem_sd\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$rem_sd[,i] ), main=\"\")\n ( qs = apply( res$mcmc$rem_sd[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n\n # qc\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$qc[,i] ), main=\"\")\n ( qs = apply( res$mcmc$qc[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # b0\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$b0[,i] ), main=\"\")\n ( qs = apply( res$mcmc$b0[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n\n # K\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$K[,i] ), main=\"\")\n ( qs = apply( res$mcmc$K[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # R\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$r[,i] ), main=\"\")\n ( qs = apply( res$mcmc$r[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # q\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$q[,i] ), main=\"\")\n ( qs = apply( res$mcmc$q[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # FMSY\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$FMSY[,i] ), main=\"\")\n ( qs = apply( res$mcmc$FMSY[,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n\n # densities of biomass estimates for the year.assessment\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density(res$mcmc$B[,NN,i] ), main=\"\")\n ( qs = apply( res$mcmc$B[,NN,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # densities of biomass estimates for the previous year\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density( res$mcmc$B[,NN-1,i] ), main=\"\")\n ( qs = apply( res$mcmc$B[,NN-1,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n\n # densities of F in assessment year\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density( res$mcmc$F[,NN,i] ), xlim=c(0.01, 0.6), main=\"\")\n ( qs = apply( res$mcmc$F[,NN,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n ( qs = apply( res$mcmc$F[,NN,], 2, mean ) )\n\n # densities of F in previous year\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n for (i in 1:3) plot(density( res$mcmc$F[,NN-1,i] ), xlim=c(0.01, 0.6), main=\"\")\n ( qs = apply( res$mcmc$F[,NN-1,], 2, quantile, probs=c(0.025, 0.5, 0.975) ) )\n ( qs = apply( res$mcmc$F[,NN-1,], 2, mean ) )\n\n # F for table ---\n summary( res$mcmc$F, median)\n }\n\n# end\n", "meta": {"hexsha": "91e35c3a9b5b3dfc3d6d8a734172b8aece98f55b", "size": 19310, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/scripts/03.abundance_estimation_carstm_tesselation.r", "max_stars_repo_name": "jae0/bio.snowcrab", "max_stars_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_stars_repo_licenses": ["MIT"], "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_tesselation.r", "max_issues_repo_name": "jae0/bio.snowcrab", "max_issues_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_issues_repo_licenses": ["MIT"], "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_tesselation.r", "max_forks_repo_name": "jae0/bio.snowcrab", "max_forks_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:57:48.000Z", "avg_line_length": 37.4224806202, "max_line_length": 143, "alphanum_fraction": 0.5827032626, "num_tokens": 6346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.3311032973334038}} {"text": "Ghuber <- function (u, k = 30, deriv = 0)\n{\n if (!deriv)\n {\n return(pmin(1, k/abs(u)))\n } else {\n return(abs(u) <= k)\n }\n}\n\n#' Univariate LDSC\n#'\n#' Imported here to help estimate sample overlap between studies\n#'\n#' @param Z summary Z-statistics for M variants\n#' @param r2 average reference LD scores for M variants\n#' @param N GWAS sample size for each variant (could be different across variants)\n#' @param W variant weight\n#'\n#' @keywords internal\n#' @return model fit\nldsc_h2_internal <- function(Z, r2, N, W=NULL)\n{\n if (is.null(W))\n {\n W <- rep(1, length(Z))\n }\n tau <- (mean(Z^2) - 1) / mean(N * r2)\n Wv <- 1 / (1 + tau * N * r2)^2\n id <- which(Z^2 > 30)\n if (length(id) > 0)\n {\n Wv[id] <- sqrt(Wv[id])\n }\n mod <- MASS::rlm(I(Z^2) ~ I(N * r2), weight = W * Wv,\n psi = Ghuber, k = 30)\n return(summary(mod))\n}\n\n\n#' Bivariate LDSC\n#'\n#' Imported here to help estimate sample overlap between studies\n#'\n#' @param Zs Mx2 matrix of summary Z-statistics for M variants from two GWAS\n#' @param r2 average reference LD scores for M variants\n#' @param N1 sample size for the 1st GWAS\n#' @param N2 sample size for the 2nd GWAS\n#' @param Nc overlapped sample size between the two GWAS\n#' @param W variant weight\n#' @param h1 hsq for trait 1\n#' @param h2 hsq for trait 2\n#'\n#' @return List of models\n#' @references\n#' Bulik-Sullivan,B.K. et al. (2015) An atlas of genetic correlations across human diseases and traits. Nat. Genet. 47, 1236–1241.\n#'\n#' Guo,B. and Wu,B. (2018) Principal component based adaptive association test of multiple traits using GWAS summary statistics. bioRxiv 269597; doi: 10.1101/269597\n#'\n#' Gua,B. and Wu,B. (2019) Integrate multiple traits to detect novel trait-gene association using GWAS summary data with an adaptive test approach. Bioinformatics. 2019 Jul 1;35(13):2251-2257. doi: 10.1093/bioinformatics/bty961. \n#'\n#' https://github.com/baolinwu/MTAR \n#' @keywords internal\nldsc_rg_internal <- function(Zs, r2, h1, h2, N1, N2, Nc=0, W=NULL)\n{\n if(is.null(W))\n {\n W = rep(1,length(r2))\n }\n\n Y <- Zs[,1] * Zs[,2]\n\n X <- (sqrt(N1) * sqrt(N2) + sqrt(Nc/N1 * N2)) * r2\n N1r2 <- N1 * r2\n N2r2 <- N2 * r2\n r0 <- 0\n\n ## 1st round\n if(any(Nc > 0))\n {\n rcf <- as.vector(MASS::rlm(Y ~ X, psi = Ghuber)$coef)\n r0 <- rcf[1]\n gv <- rcf[-1]\n } else {\n gv <- as.vector(MASS::rlm(Y ~ X-1, psi = Ghuber)$coef)\n }\n\n ## 2nd round\n Wv <- 1 / ((h1 * N1r2 + 1) * (h2 * N2r2 + 1) + (X * gv + r0)^2)\n id <- which(abs(Zs[,1] * Zs[,2]) > 30)\n if(length(id) > 0)\n {\n Wv[id] <- sqrt(Wv[id])\n }\n\n if(any(Nc > 0))\n {\n rcf <- MASS::rlm(Y ~ X, weight = W * Wv, psi = Ghuber, k = 30)\n } else {\n rcf <- MASS::rlm(Y ~ X - 1, weight = W * Wv, psi = Ghuber, k = 30)\n }\n return(summary(rcf))\n}\n\n\n#' Univariate LDSC\n#'\n#' Imported here to help estimate sample overlap between studies\n#'\n#' @param id ID to analyse\n#' @param ancestry ancestry of traits 1 and 2 (AFR, AMR, EAS, EUR, SAS) or 'infer' (default) in which case it will try to guess based on allele frequencies\n#' @param snpinfo Output from ieugwasr::afl2_list(\"hapmap3\"), or NULL for it to be done automatically\n#' @param splitsize How many SNPs to extract at one time. Default=20000\n#'\n#' @export\n#' @return model fit\n#' @references\n#' Bulik-Sullivan,B.K. et al. (2015) An atlas of genetic correlations across human diseases and traits. Nat. Genet. 47, 1236–1241.\n#'\n#' Guo,B. and Wu,B. (2018) Principal component based adaptive association test of multiple traits using GWAS summary statistics. bioRxiv 269597; doi: 10.1101/269597\n#'\n#' Gua,B. and Wu,B. (2019) Integrate multiple traits to detect novel trait-gene association using GWAS summary data with an adaptive test approach. Bioinformatics. 2019 Jul 1;35(13):2251-2257. doi: 10.1093/bioinformatics/bty961. \n#'\n#' https://github.com/baolinwu/MTAR \nldsc_h2 <- function(id, ancestry=\"infer\", snpinfo = NULL, splitsize=20000)\n{\n if(is.null(snpinfo))\n {\n snpinfo <- ieugwasr::afl2_list(\"hapmap3\")\n }\n\n snpinfo <- snpinfo %>%\n dplyr::filter(complete.cases(.))\n\n d <- extract_split(snpinfo$rsid, id, splitsize) %>%\n ieugwasr::fill_n() %>%\n dplyr::mutate(z = beta / se) %>%\n dplyr::select(rsid, z = z, n = n, eaf) %>%\n dplyr::filter(complete.cases(.))\n\n stopifnot(nrow(d) > 0)\n\n if(ancestry == \"infer\")\n {\n ancestry <- ieugwasr::infer_ancestry(d, snpinfo)$pop[1]\n }\n\n d <- snpinfo %>% \n dplyr::select(rsid, l2=paste0(\"L2.\", ancestry)) %>%\n dplyr::inner_join(., d, by=\"rsid\") %>%\n dplyr::filter(complete.cases(.))\n\n return(ldsc_h2_internal(d$z, d$l2, d$n))\n}\n\n#' Bivariate LDSC\n#'\n#' Imported here to help estimate sample overlap between studies\n#'\n#' @param id1 ID 1 to analyse\n#' @param id2 ID 2 to analyse\n#' @param ancestry ancestry of traits 1 and 2 (AFR, AMR, EAS, EUR, SAS) or 'infer' (default) in which case it will try to guess based on allele frequencies\n#' @param snpinfo Output from ieugwasr::afl2_list(\"hapmap3\"), or NULL for it to be done automatically\n#' @param splitsize How many SNPs to extract at one time. Default=20000\n#'\n#' @export\n#' @return model fit\nldsc_rg <- function(id1, id2, ancestry=\"infer\", snpinfo = NULL, splitsize=20000)\n{\n if(is.null(snpinfo))\n {\n snpinfo <- ieugwasr::afl2_list(\"hapmap3\")\n }\n\n x <- extract_split(snpinfo$rsid, c(id1, id2), splitsize)\n d1 <- subset(x, id == id1) %>%\n ieugwasr::fill_n() %>%\n dplyr::mutate(z = beta / se) %>%\n dplyr::select(rsid, z1 = z, n1 = n, eaf) %>%\n dplyr::filter(complete.cases(.))\n\n stopifnot(nrow(d1) > 0)\n\n d2 <- subset(x, id == id2) %>%\n ieugwasr::fill_n() %>%\n dplyr::mutate(z = beta / se) %>%\n dplyr::select(rsid, z2 = z, n2 = n, eaf) %>%\n dplyr::filter(complete.cases(.))\n\n stopifnot(nrow(d2) > 0)\n\n if(ancestry == \"infer\")\n {\n ancestry1 <- ieugwasr::infer_ancestry(d1, snpinfo)\n ancestry2 <- ieugwasr::infer_ancestry(d2, snpinfo)\n if(ancestry1$pop[1] != ancestry2$pop[1])\n {\n stop(\"d1 ancestry is \", ancestry1$pop[1], \" and d2 ancestry is \", ancestry2$pop[1])\n }\n ancestry <- ancestry1$pop[1]\n }\n\n d1 <- snpinfo %>% \n dplyr::select(rsid, l2=paste0(\"L2.\", ancestry)) %>%\n dplyr::inner_join(., d1, by=\"rsid\")\n\n d2 <- snpinfo %>% \n dplyr::select(rsid, l2=paste0(\"L2.\", ancestry)) %>%\n dplyr::inner_join(., d2, by=\"rsid\")\n\n h1 <- ldsc_h2_internal(d1$z1, d1$l2, d1$n1, d1$l2)\n h2 <- ldsc_h2_internal(d2$z2, d2$l2, d2$n2, d1$l2)\n\n dat <- dplyr::inner_join(d1, d2, by=\"rsid\") %>%\n dplyr::mutate(\n l2 = l2.x,\n n1 = as.numeric(n1),\n n2 = as.numeric(n2),\n rhs = l2 * sqrt(n1 * n2)\n )\n\n gcov <- dat %>%\n {\n ldsc_rg_internal(\n Zs = cbind(.$z1, .$z2),\n r2 = .$l2,\n h1 = h1$coefficients[2,1] * nrow(d1),\n h2 = h2$coefficients[2,1] * nrow(d2),\n N1 = .$n1,\n N2 = .$n2,\n W = .$l2\n )\n }\n return(list(\n gcov = gcov,\n h1=h1,\n h2=h2,\n rg = (gcov$coefficients[1,1] * nrow(dat)) / sqrt(h1$coefficients[2,1] * nrow(d1) * h2$coefficients[2,1] * nrow(d2))\n ))\n}\n\n\nextract_split <- function(snplist, id, splitsize=20000)\n{\n nsplit <- round(length(snplist)/splitsize)\n split(snplist, 1:nsplit) %>%\n pbapply::pblapply(., function(x)\n {\n ieugwasr::associations(x, id, proxies=FALSE)\n }) %>% dplyr::bind_rows()\n}\n", "meta": {"hexsha": "1a5d4798ae9e398d044ab09f0e3af88a0fac3252", "size": 7743, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ldsc.r", "max_stars_repo_name": "simonmfr/TwoSampleMR", "max_stars_repo_head_hexsha": "c4cff8bac98114b20c927da6e9f03e48318fa143", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 142, "max_stars_repo_stars_event_min_datetime": "2016-02-10T16:58:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:46:12.000Z", "max_issues_repo_path": "R/ldsc.r", "max_issues_repo_name": "simonmfr/TwoSampleMR", "max_issues_repo_head_hexsha": "c4cff8bac98114b20c927da6e9f03e48318fa143", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 296, "max_issues_repo_issues_event_min_datetime": "2016-03-15T20:28:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:02:30.000Z", "max_forks_repo_path": "R/ldsc.r", "max_forks_repo_name": "simonmfr/TwoSampleMR", "max_forks_repo_head_hexsha": "c4cff8bac98114b20c927da6e9f03e48318fa143", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113, "max_forks_repo_forks_event_min_datetime": "2016-02-10T16:58:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T03:02:04.000Z", "avg_line_length": 30.7261904762, "max_line_length": 229, "alphanum_fraction": 0.581299238, "num_tokens": 2636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.32958408735001865}} {"text": "#written and kindly provided by Roger Mundry\nboot.glmm.pred<-function(model.res, excl.warnings=F, nboots=1000, para=F, resol=1000, level=0.95, use=NULL, circ.var.name=NULL, circ.var=NULL, use.u=F, \n\tn.cores=c(\"all-1\", \"all\"), save.path=NULL, load.lib=T, lib.loc=.libPaths(), set.all.effects.2.zero=F){\n\tif(load.lib){library(lme4, lib.loc=lib.loc)}\n\tn.cores=n.cores[1]\n\tkeepWarnings<-function(expr){\n\t\tlocalWarnings <- list()\n\t\tvalue <- withCallingHandlers(expr,\n\t\t\twarning = function(w) {\n\t\t\t\tlocalWarnings[[length(localWarnings)+1]] <<- w\n\t\t\t\tinvokeRestart(\"muffleWarning\")\n\t\t\t}\n\t\t)\n\t\tlist(value=value, warnings=localWarnings)\n\t}\n\t##define function extracting all estimated coefficients (fixed and random effects) and also the model summary wrt random effects:\n\textract.all<-function(mres){\n\t\t##extract random effects model summary:\n\t\tvc.mat=as.data.frame(summary(mres)$varcor)##... and prepare/extract variance covariance matrix from the model handed over\n\t\txx=lapply(summary(mres)$varcor, function(x){attr(x, \"stddev\")})##append residual variance\n\t\t##create vector with names of the terms in the model\n\t\txnames=c(names(fixef(mres)), paste(rep(names(xx), unlist(lapply(xx, length))), unlist(lapply(xx, names)), sep=\"@\"))\n\t\tif(class(mres)[1]==\"lmerMod\"){xnames=c(xnames, \"Residual\")}##append \"Residual\" to xnames in case of Gaussian model\n\t\tif(class(mres)[1]==\"lmerMod\"){res.sd=vc.mat[vc.mat$grp==\"Residual\", \"sdcor\"]}##extract residual sd i case of Gaussian model\n\t\t#if(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat=vc.mat[-nrow(vc.mat), ]}##and drop residuals-row from vc.mat in case of Gaussisn model\n\t\t##deal with names in vc.mat which aren't exactly the name of the resp. random effect\n\t\tr.icpt.names=names(ranef(mres))##extract names of random intercepts...\n\t\tnot.r.icpt.names=setdiff(vc.mat$grp, r.icpt.names)##... and names of the random effects having random slopes\n\t\tnot.r.icpt.names=unlist(lapply(strsplit(not.r.icpt.names, split=\".\", fixed=T), function(x){paste(x[1:(length(x)-1)], collapse=\".\")}))\n\t\tvc.mat$grp[!vc.mat$grp%in%r.icpt.names]=not.r.icpt.names\n\t\tif(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat$var1[nrow(vc.mat)]=\"\"}\n\t\txnames=paste(vc.mat$grp, vc.mat$var1, sep=\"@\")\n\t\tre.summary=unlist(vc.mat$sdcor)\n\t\tnames(re.summary)=xnames\n\t\tranef(mres)\n\t\t##extract random effects model summary: done\n\t\t##extract random effects details:\n\t\tre.detail=ranef(mres)\n\t\txnames=paste(\n\t\t\trep(x=names(re.detail), times=unlist(lapply(re.detail, function(x){nrow(x)*ncol(x)}))),\n\t\t\t\tunlist(lapply(re.detail, function(x){rep(colnames(x), each=nrow(x))})), \n\t\t\t\tunlist(lapply(re.detail, function(x){rep(rownames(x), times=ncol(x))})),\n\t\t\t\tsep=\"@\")\n\t\tre.detail=unlist(lapply(re.detail, function(x){\n\t\t\treturn(unlist(c(x)))\n\t\t}))\n\t\t#browser()\n\t\t#deal with negative binomial model to extract theta:\n\t\txx=as.character(summary(mres)$call)\n\t\tif(any(grepl(x=xx, pattern=\"negative.binomial\"))){\n\t\t\txx=xx[grepl(x=xx, pattern=\"negative.binomial\")]\n\t\t\txx=gsub(x=xx, pattern=\"negative.binomial(theta = \", replacement=\"\", fixed=T)\n\t\t\txx=gsub(x=xx, pattern=\")\", replacement=\"\", fixed=T)\n\t\t\tre.detail=c(re.detail, as.numeric(xx))\n\t\t\txnames=c(xnames, \"theta\")\n\t\t}\n\t\tnames(re.detail)=xnames\n\t\tns=c(length(fixef(mres)), length(re.summary), length(re.detail))\n\t\tnames(ns)=c(\"n.fixef\", \"n.re.summary\", \"n.re.detail\")\n\t\treturn(c(fixef(mres), re.summary, re.detail, ns))\n\t}\t\n\tif(excl.warnings){\n\t\tboot.fun<-function(x, model.res., keepWarnings., use.u., save.path.){\n\t\t\txdone=F\n\t\t\twhile(!xdone){\n\t\t\t\ti.res=keepWarnings(bootMer(x=model.res., FUN=extract.all, nsim=1, use.u=use.u.)$t)\n\t\t\t\tif(length(unlist(i.res$warnings)$message)==0){\n\t\t\t\t\txdone=T\n\t\t\t\t}\n\t\t\t}\n\t\t\test.effects=i.res$value\n\t\t\ti.warnings=NULL\n\t\t\tif(length(save.path.)>0){save(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))}\n\t\t\treturn(i.res$value)\n\t\t}\n\t}else{\n\t\tboot.fun<-function(y, model.res., keepWarnings., use.u., save.path.){\n\t\t\t#keepWarnings.(bootMer(x=model.res., FUN=fixef, nsim=1)$t)\n\t\t\ti.res=keepWarnings(bootMer(x=model.res., FUN=extract.all, nsim=1, use.u=use.u.))\n\t\t\tif(length(save.path.)>0){\n\t\t\t\test.effects=i.res$value$t\n\t\t\t\ti.warnings=i.res$warnings\n\t\t\t\tsave(file=paste(c(save.path., \"/b_\", y, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))\n\t\t\t}\n\t\t\treturn(list(ests=i.res$value$t, warns=unlist(i.res$warnings)))\n\t\t}\n\t}\n\tif(para){\n\t\ton.exit(expr = parLapply(cl=cl, X=1:length(cl), fun=function(x){rm(list=ls())}), add = FALSE)\n\t\ton.exit(expr = stopCluster(cl), add = T)\n\t\tlibrary(parallel)\n\t\tcl <- makeCluster(getOption(\"cl.cores\", detectCores()))\n\t\tif(n.cores!=\"all\"){\n\t\t\tif(n.cores==\"all-1\"){n.cores=length(cl)-1}\n\t\t\tif(n.cores0){\n\t\t#extract fixed effects terms from the model:\n\t\txcall=as.character(model.res@call)[2]\n\t\tmodel.terms=attr(terms(as.formula(xcall)), \"term.labels\")\n\t\tREs=names(ranef(model.res))\n\t\t#for(i in 1:length(REs)){\n\t\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"|\", fixed=T)]\n\t\t#}\n\t\tmodel=paste(model.terms, collapse=\"+\")\n\t\t#build model wrt to the fixed effects:\n\t\tmodel.terms=unique(unlist(strsplit(x=model.terms, split=\":\", fixed=T)))\n\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"I(\", fixed=T)]\n\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"^2)\", fixed=T)]\n\t\t#exclude interactions and squared terms from model.terms:\n\t\t#create new data to be used to determine fitted values:\n\t\tii.data=model.res@frame\n\t\t\n\t\tif(length(circ.var.name)==1){\n\t\t\tset.circ.var.to.zero=sum(circ.var.name%in%use)==0\n\t\t}else{\n\t\t\tset.circ.var.to.zero=F\n\t\t}\n\t\t\n\t\tif(length(use)==0){use=model.terms}\n\t\tnew.data=vector(\"list\", length(model.terms))\n\t\tusel=model.terms%in%use\n\t\t#if(length(use)>0)\n\t\tfor(i in 1:length(model.terms)){\n\t\t\tif(is.factor(ii.data[, model.terms[i]])){\n\t\t\t\tnew.data[[i]]=levels(ii.data[, model.terms[i]])\n\t\t\t}else if(!is.factor(ii.data[, model.terms[i]]) & usel[i] & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n\t\t\t\tnew.data[[i]]=seq(from=min(ii.data[, model.terms[i]]), to=max(ii.data[, model.terms[i]]), length.out=resol)\n\t\t\t}else if(!is.factor(ii.data[, model.terms[i]]) & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n\t\t\t\tnew.data[[i]]=mean(ii.data[, model.terms[i]])\n\t\t\t}\n\t\t}\n\t\tnames(new.data)=model.terms\n\t\tif(length(circ.var.name)==1){\n\t\t\tnew.data=new.data[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n\t\t\tif(sum(grepl(pattern=circ.var.name, x=use))>0){\n\t\t\t\tnew.data=c(new.data, list(seq(min(circ.var, na.rm=T), max(circ.var, na.rm=T), length.out=resol)))\n\t\t\t\tnames(new.data)[length(new.data)]=circ.var.name\n\t\t\t}else{\n\t\t\t\tnew.data=c(new.data, list(0))\n\t\t\t}\n\t\t\tmodel.terms=model.terms[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n\t\t}\n\t\txnames=names(new.data)\n\t\t#browser()\n\t\tnew.data=data.frame(expand.grid(new.data))\n\t\tnames(new.data)=xnames\n\t\t#names(new.data)[1:length(model.terms)]=model.terms\n\t\t#browser()\n\t\tif(length(circ.var.name)==1){\n\t\t\tnames(new.data)[ncol(new.data)]=circ.var.name\n\t\t}\n\t\t#create predictors matrix:\n# \t\tif(length(circ.var.name)>0 & length(intersect(circ.var.name, names(new.data)))>0){\n# \t\t\tnew.data=cbind(new.data, sin(new.data[, circ.var.name]), cos(new.data[, circ.var.name]))\n# \t\t\tnames(new.data)[(ncol(new.data)-1):ncol(new.data)]=paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\")\n# \t\t\tnew.data=new.data[, !names(new.data)==circ.var.name]\n# \t\t}\n# \t\tbrowser()\n\t\tr=runif(nrow(new.data))\n\t\tif(set.all.effects.2.zero){\n\t\t\tfor(iterm in setdiff(colnames(new.data), c(\"(Intercept)\", use))){\n\t\t\t\tnew.data[, iterm]=0\n\t\t\t}\n\t\t}\n\t\tm.mat=model.matrix(object=as.formula(paste(c(\"r\", model), collapse=\"~\")), data=new.data)\n\t\tif(set.circ.var.to.zero){\n\t\t\tm.mat[,paste(c(\"sin(\", circ.var.name, \")\"), collapse=\"\")]=0\n\t\t\tm.mat[,paste(c(\"cos(\", circ.var.name, \")\"), collapse=\"\")]=0\n\t\t}\n\t\t#m.mat=t(m.mat)\n\t\t#get the CIs for the fitted values:\n\t\tci=lapply(all.res, function(x){\n\t\t\t#return(apply(m.mat[names(fixef(model.res)), , drop=F]*as.vector(x[, names(fixef(model.res))]), 2, sum))\n\t\t\treturn(m.mat[, names(fixef(model.res)), drop=F]%*%as.vector(x[, names(fixef(model.res))]))\n\t\t})\n\t\tci=matrix(unlist(ci), ncol=nboots, byrow=F)\n\t\tci=t(apply(ci, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n\t\tcolnames(ci)=c(\"lower.cl\", \"upper.cl\")\n\t\tfv=m.mat[, names(fixef(model.res))]%*%fixef(model.res)\n\t\tif(class(model.res)[[1]]!=\"lmerMod\"){\n\t\t\tif(model.res@resp$family$family==\"binomial\"){\n\t\t\t\tci=exp(ci)/(1+exp(ci))\n\t\t\t\tfv=exp(fv)/(1+exp(fv))\n\t\t\t}else if(model.res@resp$family$family==\"poisson\" | (model.res@resp$family$family==\"Gamma\" & model.res@resp$family$link==\"log\") | substr(x=model.res@resp$family$family, start=1, stop=17)==\"Negative Binomial\"){\n\t\t\t\tci=exp(ci)\n\t\t\t\tfv=exp(fv)\n\t\t\t}\n\t\t}\n\t\tresult=data.frame(new.data, fitted=fv, ci)\n\t}else{\n\t\tresult=NULL\n\t}\n\tall.boots=matrix(unlist(all.res), nrow=nboots, byrow=T)\n\tcolnames(all.boots)=colnames(all.res[[1]])\n\tci.est=apply(all.boots, 2, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T)\n\tif(length(fixef(model.res))>1){\n\t\tci.est=data.frame(orig=fixef(model.res), t(ci.est)[1:length(fixef(model.res)), ])\n\t}else{\n\t\tci.est=data.frame(orig=fixef(model.res), t(t(ci.est)[1:length(fixef(model.res)), ]))\n\t}\n\treturn(list(ci.predicted=result, ci.estimates=ci.est, all.warns=all.warns, all.boots=all.boots))\n}\n###########################################################################################################\n###########################################################################################################\nboot.glmm.pred.list<-function(model.res, excl.warnings=F, nboots=1000, para=F, resol=100, level=0.95, use.list=NULL, circ.var.name=NULL, circ.var=NULL, use.u=F, \n\tn.cores=c(\"all-1\", \"all\"), save.path=NULL, load.lib=T, lib.loc=.libPaths(), set.all.effects.2.zero=F){\n\tif(load.lib){library(lme4, lib.loc=lib.loc)}\n\tn.cores=n.cores[1]\n\tkeepWarnings<-function(expr){\n\t\tlocalWarnings <- list()\n\t\tvalue <- withCallingHandlers(expr,\n\t\t\twarning = function(w) {\n\t\t\t\tlocalWarnings[[length(localWarnings)+1]] <<- w\n\t\t\t\tinvokeRestart(\"muffleWarning\")\n\t\t\t}\n\t\t)\n\t\tlist(value=value, warnings=localWarnings)\n\t}\n\t##define function extracting all estimated coefficients (fixed and random effects) and also the model summary wrt random effects:\n\textract.all<-function(mres){\n\t\t##extract random effects model summary:\n\t\tvc.mat=as.data.frame(summary(mres)$varcor)##... and prepare/extract variance covariance matrix from the model handed over\n\t\txx=lapply(summary(mres)$varcor, function(x){attr(x, \"stddev\")})##append residual variance\n\t\t##create vector with names of the terms in the model\n\t\txnames=c(names(fixef(mres)), paste(rep(names(xx), unlist(lapply(xx, length))), unlist(lapply(xx, names)), sep=\"@\"))\n\t\tif(class(mres)[1]==\"lmerMod\"){xnames=c(xnames, \"Residual\")}##append \"Residual\" to xnames in case of Gaussian model\n\t\tif(class(mres)[1]==\"lmerMod\"){res.sd=vc.mat[vc.mat$grp==\"Residual\", \"sdcor\"]}##extract residual sd i case of Gaussian model\n\t\t#if(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat=vc.mat[-nrow(vc.mat), ]}##and drop residuals-row from vc.mat in case of Gaussisn model\n\t\t##deal with names in vc.mat which aren't exactly the name of the resp. random effect\n\t\tr.icpt.names=names(ranef(mres))##extract names of random intercepts...\n\t\tnot.r.icpt.names=setdiff(vc.mat$grp, r.icpt.names)##... and names of the random effects having random slopes\n\t\tnot.r.icpt.names=unlist(lapply(strsplit(not.r.icpt.names, split=\".\", fixed=T), function(x){paste(x[1:(length(x)-1)], collapse=\".\")}))\n\t\tvc.mat$grp[!vc.mat$grp%in%r.icpt.names]=not.r.icpt.names\n\t\tif(vc.mat$grp[nrow(vc.mat)]==\"Residual\"){vc.mat$var1[nrow(vc.mat)]=\"\"}\n\t\txnames=paste(vc.mat$grp, vc.mat$var1, sep=\"@\")\n\t\tre.summary=unlist(vc.mat$sdcor)\n\t\tnames(re.summary)=xnames\n\t\tranef(mres)\n\t\t##extract random effects model summary: done\n\t\t##extract random effects details:\n\t\tre.detail=ranef(mres)\n\t\txnames=paste(\n\t\t\trep(x=names(re.detail), times=unlist(lapply(re.detail, function(x){nrow(x)*ncol(x)}))),\n\t\t\t\tunlist(lapply(re.detail, function(x){rep(colnames(x), each=nrow(x))})), \n\t\t\t\tunlist(lapply(re.detail, function(x){rep(rownames(x), times=ncol(x))})),\n\t\t\t\tsep=\"@\")\n\t\tre.detail=unlist(lapply(re.detail, function(x){\n\t\t\treturn(unlist(c(x)))\n\t\t}))\n\t\t#browser()\n\t\t#deal with negative binomial model to extract theta:\n\t\txx=as.character(summary(mres)$call)\n\t\tif(any(grepl(x=xx, pattern=\"negative.binomial\"))){\n\t\t\txx=xx[grepl(x=xx, pattern=\"negative.binomial\")]\n\t\t\txx=gsub(x=xx, pattern=\"negative.binomial(theta = \", replacement=\"\", fixed=T)\n\t\t\txx=gsub(x=xx, pattern=\")\", replacement=\"\", fixed=T)\n\t\t\tre.detail=c(re.detail, as.numeric(xx))\n\t\t\txnames=c(xnames, \"theta\")\n\t\t}\n\t\tnames(re.detail)=xnames\n\t\tns=c(length(fixef(mres)), length(re.summary), length(re.detail))\n\t\tnames(ns)=c(\"n.fixef\", \"n.re.summary\", \"n.re.detail\")\n\t\treturn(c(fixef(mres), re.summary, re.detail, ns))\n\t}\t\n\tif(excl.warnings){\n\t\tboot.fun<-function(x, model.res., keepWarnings., use.u., save.path.){\n\t\t\txdone=F\n\t\t\twhile(!xdone){\n\t\t\t\ti.res=keepWarnings(bootMer(x=model.res., FUN=extract.all, nsim=1, use.u=use.u.)$t)\n\t\t\t\tif(length(unlist(i.res$warnings)$message)==0){\n\t\t\t\t\txdone=T\n\t\t\t\t}\n\t\t\t}\n\t\t\test.effects=i.res$value\n\t\t\ti.warnings=NULL\n\t\t\tif(length(save.path.)>0){save(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))}\n\t\t\treturn(i.res$value)\n\t\t}\n\t}else{\n\t\tboot.fun<-function(y, model.res., keepWarnings., use.u., save.path.){\n\t\t\t#keepWarnings.(bootMer(x=model.res., FUN=fixef, nsim=1)$t)\n\t\t\ti.res=keepWarnings(bootMer(x=model.res., FUN=extract.all, nsim=1, use.u=use.u.))\n\t\t\tif(length(save.path.)>0){\n\t\t\t\test.effects=i.res$value$t\n\t\t\t\ti.warnings=i.res$warnings\n\t\t\t\tsave(file=paste(c(save.path., \"/b_\", y, \".RData\"), collapse=\"\"), list=c(\"est.effects\", \"i.warnings\"))\n\t\t\t}\n\t\t\treturn(list(ests=i.res$value$t, warns=unlist(i.res$warnings)))\n\t\t}\n\t}\n\tif(para){\n\t\ton.exit(expr = parLapply(cl=cl, X=1:length(cl), fun=function(x){rm(list=ls())}), add = FALSE)\n\t\ton.exit(expr = stopCluster(cl), add = T)\n\t\tlibrary(parallel)\n\t\tcl <- makeCluster(getOption(\"cl.cores\", detectCores()))\n\t\tif(n.cores!=\"all\"){\n\t\t\tif(n.cores!=\"all-1\"){n.cores=length(cl)-1}\n\t\t\tif(n.cores0){\n\t\t#extract fixed effects terms from the model:\n\t\txcall=as.character(model.res@call)[2]\n\t\tmodel.terms=attr(terms(as.formula(xcall)), \"term.labels\")\n\t\tREs=names(ranef(model.res))\n\t\t#for(i in 1:length(REs)){\n\t\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"|\", fixed=T)]\n\t\t#}\n\t\tmodel=paste(model.terms, collapse=\"+\")\n\t\t#build model wrt to the fixed effects:\n\t\tmodel.terms=unique(unlist(strsplit(x=model.terms, split=\":\", fixed=T)))\n\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"I(\", fixed=T)]\n\t\tmodel.terms=model.terms[!grepl(x=model.terms, pattern=\"^2)\", fixed=T)]\n\t\t#exclude interactions and squared terms from model.terms:\n\t\t#create new data to be used to determine fitted values:\n\t\tii.data=model.res@frame\n\t\tall.fitted=lapply(use.list, function(use){\n\t\t\tif(length(circ.var.name)==1){\n\t\t\t\tset.circ.var.to.zero=sum(circ.var.name%in%use)==0\n\t\t\t}else{\n\t\t\t\tset.circ.var.to.zero=F\n\t\t\t}\n\t\t\t\n\t\t\tif(length(use)==0){use=model.terms}\n\t\t\tnew.data=vector(\"list\", length(model.terms))\n\t\t\tusel=model.terms%in%use\n\t\t\t#if(length(use)>0)\n\t\t\tfor(i in 1:length(model.terms)){\n\t\t\t\tif(is.factor(ii.data[, model.terms[i]])){\n\t\t\t\t\tnew.data[[i]]=levels(ii.data[, model.terms[i]])\n\t\t\t\t}else if(!is.factor(ii.data[, model.terms[i]]) & usel[i] & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n\t\t\t\t\tnew.data[[i]]=seq(from=min(ii.data[, model.terms[i]]), to=max(ii.data[, model.terms[i]]), length.out=resol)\n\t\t\t\t}else if(!is.factor(ii.data[, model.terms[i]]) & ifelse(length(circ.var.name)==0, T, !grepl(x=model.terms[i], pattern=circ.var.name))){\n\t\t\t\t\tnew.data[[i]]=mean(ii.data[, model.terms[i]])\n\t\t\t\t}\n\t\t\t}\n\t\t\tnames(new.data)=model.terms\n\t\t\tif(length(circ.var.name)==1){\n\t\t\t\tnew.data=new.data[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n\t\t\t\tif(sum(grepl(pattern=circ.var.name, x=use))>0){\n\t\t\t\t\tnew.data=c(new.data, list(seq(min(circ.var, na.rm=T), max(circ.var, na.rm=T), length.out=resol)))\n\t\t\t\t\tnames(new.data)[length(new.data)]=circ.var.name\n\t\t\t\t}else{\n\t\t\t\t\tnew.data=c(new.data, list(0))\n\t\t\t\t}\n\t\t\t\tmodel.terms=model.terms[!(model.terms%in%paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\"))]\n\t\t\t}\n\t\t\txnames=names(new.data)\n\t\t\t#browser()\n\t\t\tnew.data=data.frame(expand.grid(new.data))\n\t\t\tnames(new.data)=xnames\n\t\t\t#names(new.data)[1:length(model.terms)]=model.terms\n\t\t\t#browser()\n\t\t\tif(length(circ.var.name)==1){\n\t\t\t\tnames(new.data)[ncol(new.data)]=circ.var.name\n\t\t\t}\n\t\t\t#create predictors matrix:\n\t# \t\tif(length(circ.var.name)>0 & length(intersect(circ.var.name, names(new.data)))>0){\n\t# \t\t\tnew.data=cbind(new.data, sin(new.data[, circ.var.name]), cos(new.data[, circ.var.name]))\n\t# \t\t\tnames(new.data)[(ncol(new.data)-1):ncol(new.data)]=paste(c(\"sin(\", \"cos(\"), circ.var.name, \")\", sep=\"\")\n\t# \t\t\tnew.data=new.data[, !names(new.data)==circ.var.name]\n\t# \t\t}\n\t# \t\tbrowser()\n\t\t\tr=runif(nrow(new.data))\n\t\t\tif(set.all.effects.2.zero){\n\t\t\t\tfor(iterm in setdiff(colnames(new.data), c(\"(Intercept)\", use))){\n\t\t\t\t\tnew.data[, iterm]=0\n\t\t\t\t}\n\t\t\t}\n\t\t\tm.mat=model.matrix(object=as.formula(paste(c(\"r\", model), collapse=\"~\")), data=new.data)\n\t\t\tif(set.circ.var.to.zero){\n\t\t\t\tm.mat[,paste(c(\"sin(\", circ.var.name, \")\"), collapse=\"\")]=0\n\t\t\t\tm.mat[,paste(c(\"cos(\", circ.var.name, \")\"), collapse=\"\")]=0\n\t\t\t}\n\t\t\t#m.mat=t(m.mat)\n\t\t\t#get the CIs for the fitted values:\n\t\t\tci=lapply(all.res, function(x){\n\t\t\t\t#return(apply(m.mat[names(fixef(model.res)), , drop=F]*as.vector(x[, names(fixef(model.res))]), 2, sum))\n\t\t\t\treturn(m.mat[, names(fixef(model.res)), drop=F]%*%as.vector(x[, names(fixef(model.res))]))\n\t\t\t})\n\t\t\tci=matrix(unlist(ci), ncol=nboots, byrow=F)\n\t\t\tci=t(apply(ci, 1, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T))\n\t\t\tcolnames(ci)=c(\"lower.cl\", \"upper.cl\")\n\t\t\tfv=m.mat[, names(fixef(model.res))]%*%fixef(model.res)\n\t\t\tif(class(model.res)[[1]]!=\"lmerMod\"){\n\t\t\t\tif(model.res@resp$family$family==\"binomial\"){\n\t\t\t\t\tci=exp(ci)/(1+exp(ci))\n\t\t\t\t\tfv=exp(fv)/(1+exp(fv))\n\t\t\t\t}else if(model.res@resp$family$family==\"poisson\" | substr(x=model.res@resp$family$family, start=1, stop=17)==\"Negative Binomial\"){\n\t\t\t\t\tci=exp(ci)\n\t\t\t\t\tfv=exp(fv)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn(data.frame(new.data, fitted=fv, ci))\n\t\t})\n\t\tresult=all.fitted\n\t\tnames(result)=unlist(lapply(use.list, paste, collapse=\"@\"))\n\t}else{\n\t\tresult=NULL\n\t}\n\t\n\tall.boots=matrix(unlist(all.res), nrow=nboots, byrow=T)\n\tcolnames(all.boots)=colnames(all.res[[1]])\n\tci.est=apply(all.boots, 2, quantile, prob=c((1-level)/2, 1-(1-level)/2), na.rm=T)\n\tif(length(fixef(model.res))>1){\n\t\tci.est=data.frame(orig=fixef(model.res), t(ci.est)[1:length(fixef(model.res)), ])\n\t}else{\n\t\tci.est=data.frame(orig=fixef(model.res), t(t(ci.est)[1:length(fixef(model.res)), ]))\n\t}\n\treturn(list(ci.predicted=result, ci.estimates=ci.est, all.warns=all.warns, all.boots=all.boots))\n}\n\n\n###########################################################################################################\n###########################################################################################################\nboot.glmm<-function(model.res, excl.warnings=F, nboots=1000, para=F, use.u=F, n.cores=c(\"all-1\", \"all\"), save.path=NULL){\n\tn.cores=n.cores[1]\n\tkeepWarnings<-function(expr) {\n\t\tlocalWarnings <- list()\n\t\tvalue <- withCallingHandlers(expr,\n\t\t\twarning = function(w) {\n\t\t\t\tlocalWarnings[[length(localWarnings)+1]] <<- w\n\t\t\t\tinvokeRestart(\"muffleWarning\")\n\t\t\t}\n\t\t)\n\t\tlist(value=value, warnings=localWarnings)\n\t}\n\tif(excl.warnings){\n\t\tboot.fun<-function(x, model.res., keepWarnings., use.u., save.path.){\n\t\t\txdone=F\n\t\t\twhile(!xdone){\n\t\t\t\ti.res=keepWarnings.(bootMer(x=model.res., FUN=fixef, nsim=1, use.u=use.u.)$t)\n\t\t\t\tif(length(unlist(i.res$warnings)$message)==0){\n\t\t\t\t\txdone=T\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(length(save.path.)>0){\n\t\t\t\ti.res=i.res$value\n\t\t\t\tsave(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=\"i.res\")\n\t\t\t}\n\t\t\treturn(i.res$value)\n\t\t}\n\t}else{\n\t\tboot.fun<-function(x, model.res., keepWarnings., use.u., save.path.){\n\t\t\ti.res=bootMer(x=model.res, FUN=fixef, nsim=1, use.u=use.u.)$t\n\t\t\tif(length(save.path.)>0){\n\t\t\t\tsave(file=paste(c(save.path., \"/b_\", x, \".RData\"), collapse=\"\"), list=\"i.res\")\n\t\t\t}\n\t\t\treturn(i.res)\n\t\t}\n\t}\n\tif(para){\n\t\trequire(parallel)\n cl <- makeCluster(getOption(\"cl.cores\", detectCores()))\n\t\tif(n.cores!=\"all\"){\n\t\t\tif(n.cores!=\"all-1\"){n.cores=length(cl)-1}\n\t\t\tif(n.cores 0) {\n k_singular <- sprintf(\n 'Well-specific K matrix is singular for the following well(s): %s. ',\n paste(k_singular_vec, collapse=', ')\n )\n }\n }\n \n return(list('k'=k, 'k_inv_array'=k_inv_array, 'k_singular'=k_singular))\n }\n\n\n# multi-channel deconvolution\ndeconv <- function(\n array2dcv, # dim1 must be channel, dim3 must be well; dim2 is cycle for amplification and temperature point for melting curve\n db_conn,\n calib_info\n ) {\n \n a2d_dim1 <- dim(array2dcv)[1]\n a2d_dim2 <- dim(array2dcv)[2]\n a2d_dim3 <- dim(array2dcv)[3]\n a2d_dimnames <- dimnames(array2dcv)\n \n # if data only has 1 cycle (amplification) or 1 temperature point (melt curve)\n if (is.na(a2d_dim3)) array2dcv <- array(c(array2dcv), \n dim=c(a2d_dim1, 1, a2d_dim2), \n dimnames=list(a2d_dimnames[[1]], '1', a2d_dimnames[[2]]))\n \n if (class(calib_info) == \"numeric\" || \n sum(duplicated(sapply(calib_info, function(calib_ele) calib_ele[['step_id']]))) > 0\n ) {\n k_list_temp <- k_list\n } else {\n k_list_temp <- get_k(db_conn, calib_info, 'dim3')\n }\n \n k_inv_array = k_list_temp[['k_inv_array']]\n \n dcvd_by_dim2_well <- lapply(1:a2d_dim2, \n function(dim2_i) do.call(cbind, lapply(1:a2d_dim3, \n function(well_i) k_inv_array[,,well_i] %*% array2dcv[,dim2_i,well_i]))) # dim2 is cycle_num for amp and temperature for melt curve\n \n dcvd_array <- array(NA, dim(array2dcv))\n for (dim2_i in 1:dim(array2dcv)[2]) dcvd_array[,dim2_i,] <- dcvd_by_dim2_well[[dim2_i]]\n dimnames(dcvd_array) <- dimnames(array2dcv)\n \n # scale by channel to adjust for different fluorescence excitation strengths among dyes\n for (channel in dimnames(dcvd_array)[1]) {\n dcvd_array[channel,,] <- dcvd_array[channel,,] * scaling_factors_deconv[channel] }\n \n return(list('dcvd_array'=dcvd_array, 'k_list_temp'=k_list_temp))\n }\n\n", "meta": {"hexsha": "f4fd701c9f1d5894db55c32a619a94d50117e269", "size": 4545, "ext": "r", "lang": "R", "max_stars_repo_path": "bioinformatics/deconv.r", "max_stars_repo_name": "MakerButt/chaipcr", "max_stars_repo_head_hexsha": "a4c0521d1b2ffb2aa1c90ff21f3ca4779b6831d1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-06-25T19:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T19:58:26.000Z", "max_issues_repo_path": "bioinformatics/deconv.r", "max_issues_repo_name": "MakerButt/chaipcr", "max_issues_repo_head_hexsha": "a4c0521d1b2ffb2aa1c90ff21f3ca4779b6831d1", "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": "bioinformatics/deconv.r", "max_forks_repo_name": "MakerButt/chaipcr", "max_forks_repo_head_hexsha": "a4c0521d1b2ffb2aa1c90ff21f3ca4779b6831d1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5619834711, "max_line_length": 232, "alphanum_fraction": 0.602640264, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.328425733446583}} {"text": "# Model prediction Accuracy calculating function.\r\n#The accuracy calculation function work based on +- one log bacterial count of predicted values from the actual values.\r\n\r\n# x = is predicted values using the trained model\r\n# y = is the actual test data \r\nPercentage<-function(x, y){\r\n SVMLM_TVC<-c()\r\n for ( i in 1:length(x)){\r\n if((x[i])<=((y[i])+1) & x[i]>=((y[i])-1)){\r\n G<-i\r\n SVMLM_TVC<-c(SVMLM_TVC, G)\r\n \r\n }\r\n else{\r\n \r\n }\r\n \r\n }\r\n percentage_SVMLM_TVC<- length(SVMLM_TVC)/length(y)*100\r\n}", "meta": {"hexsha": "79d197c3ec6406f905354eed0c87640bc9c1a6e0", "size": 537, "ext": "r", "lang": "R", "max_stars_repo_path": "MachineLearning/MSI/Percentage_Accuracy.r", "max_stars_repo_name": "saha-19/Food-Spoilage-API", "max_stars_repo_head_hexsha": "eb8dc55d03313c94d65013428f7e2b5084e414f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MachineLearning/MSI/Percentage_Accuracy.r", "max_issues_repo_name": "saha-19/Food-Spoilage-API", "max_issues_repo_head_hexsha": "eb8dc55d03313c94d65013428f7e2b5084e414f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MachineLearning/MSI/Percentage_Accuracy.r", "max_forks_repo_name": "saha-19/Food-Spoilage-API", "max_forks_repo_head_hexsha": "eb8dc55d03313c94d65013428f7e2b5084e414f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-14T16:25:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T16:25:57.000Z", "avg_line_length": 26.85, "max_line_length": 120, "alphanum_fraction": 0.6033519553, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.32814587438460197}} {"text": "# ruth's unifrac method\n\n\nlibrary(phangorn)\nlibrary(ape)\nlibrary(zCompositions)\n\ngm_mean = function(x, na.rm=TRUE){\n exp(mean(log(x), na.rm=na.rm) )\n}\n\n# gm_vector = function(node_count, other_counts, geometric_mean) {\n# gm_vec <- array(0,length(node_count))\n# # a count of -1 means that the OTU has been amalgamated to other OTUs in the node_count\n# zero_means <- list()\n# counter = 1\n# for (i in 1:length(node_count)) {\n# # CHECK IF THIS IS CORRECT - indexing for other_counts\n# gm_vec[i] <- gm_mean(c(node_count[i],other_counts[i,][which(other_counts[i,]!=-1)]))\n# if (gm_vec[i] == 0) {\n# gm_vec[i] = geometric_mean[i]\n# }\n# }\n# return(gm_vec)\n# }\n\ngm_from_props = function(rownum, colnums) {\n otuPropsPerNode.adjustedZeros <- get(\"otuPropsPerNode.adjustedZeros\",envir = .GlobalEnv)\n return(log2(otuPropsPerNode.adjustedZeros[rownum,colnums[1]]) - mean(log2(otuPropsPerNode.adjustedZeros[rownum,colnums])))\n}\n\nmake_otu_props_positive = function() {\n otuPropsPerNode <- get(\"otuPropsPerNode\",envir = .GlobalEnv)\n otuPropsPerNode.adjustedZeros <- get(\"otuPropsPerNode.adjustedZeros\",envir = .GlobalEnv)\n otuPropsPerNode <- abs(otuPropsPerNode)\n otuPropsPerNode.adjustedZeros <- abs(otuPropsPerNode.adjustedZeros)\n assign(\"otuPropsPerNode\", otuPropsPerNode, envir = .GlobalEnv)\n assign(\"otuPropsPerNode.adjustedZeros\", otuPropsPerNode.adjustedZeros, envir = .GlobalEnv)\n}\n\nget_children = function(root) {\n unifrac.tree <- get(\"unifrac.tree\",envir=.GlobalEnv)\n children <- unifrac.tree$edge[which(unifrac.tree$edge[,1]==root),2]\n return(children)\n}\n\nget_subtree = function() {\n otuPropsPerNode.adjustedZeros <- get(\"otuPropsPerNode.adjustedZeros\",envir = .GlobalEnv)\n return(colnames(otuPropsPerNode.adjustedZeros)[which(otuPropsPerNode.adjustedZeros[1,] < 0)])\n}\n\nbuild_weights = function(root) {\n # make all weight values positive\n make_otu_props_positive()\n # if root is leaf, then weight has already been calculated and we can skip this\n if (root > length(unifrac.tree$tip.label)) {\n \n children <- get_children(root)\n \n # construct values for left child\n build_weights(children[1])\n leftChildSubtree <- get_subtree()\n \n # construct values for right child\n build_weights(children[2])\n rightChildSubtree <- get_subtree()\n \n otuPropsPerNode <- get(\"otuPropsPerNode\",envir = .GlobalEnv)\n otuPropsPerNode.adjustedZeros <- get(\"otuPropsPerNode.adjustedZeros\",envir = .GlobalEnv)\n weightsPerNode <- get(\"weightsPerNode\",envir = .GlobalEnv)\n unifrac.tree <- get(\"unifrac.tree\",envir=.GlobalEnv)\n unifrac.treeLeaves <- get(\"unifrac.treeLeaves\",envir=.GlobalEnv)\n \n # the negative values in leftChildProportions are for all the nodes in the subtree of the left child\n # the negative values in rightChildProportions are for all the nodes in the subtree of the right child\n \n leafColumns <- colnames(otuPropsPerNode)[which(colnames(otuPropsPerNode) %in% unifrac.treeLeaves)]\n \n # make both left and right child subtrees negative\n otuPropsPerNode[,leftChildSubtree] <- (-1)*abs(otuPropsPerNode[,leftChildSubtree])\n otuPropsPerNode.adjustedZeros[,leftChildSubtree] <- (-1)*abs(otuPropsPerNode.adjustedZeros[,leftChildSubtree])\n \n # get columns for use in weight calculation (leaves not in right or left subtree plus root)\n columnsForWeightCalculation <- leafColumns\n columnsForWeightCalculation <- columnsForWeightCalculation[which(!(columnsForWeightCalculation %in% leftChildSubtree))]\n columnsForWeightCalculation <- columnsForWeightCalculation[which(!(columnsForWeightCalculation %in% rightChildSubtree))]\n columnsForWeightCalculation <- c(root, columnsForWeightCalculation)\n \n # calculate proportion of current node\n otuPropsPerNode[,root] <- abs(otuPropsPerNode[,children[1]]) + abs(otuPropsPerNode[,children[2]])\n otuPropsPerNode.adjustedZeros[,root] <- abs(otuPropsPerNode.adjustedZeros[,children[1]]) + abs(otuPropsPerNode.adjustedZeros[,children[2]])\n assign(\"otuPropsPerNode\", otuPropsPerNode, envir = .GlobalEnv)\n assign(\"otuPropsPerNode.adjustedZeros\", otuPropsPerNode.adjustedZeros, envir = .GlobalEnv)\n \n # calculate weight of current node\n weightsPerNode[,root] <- sapply(c(1:nrow(otuPropsPerNode.adjustedZeros)),function(x) { gm_from_props(x, columnsForWeightCalculation)})\n }\n # make root node values negative\n otuPropsPerNode[,root] <- (-1)*abs(otuPropsPerNode[,root])\n otuPropsPerNode.adjustedZeros[,root] <- (-1)*abs(otuPropsPerNode.adjustedZeros[,root])\n \n assign(\"otuPropsPerNode\", otuPropsPerNode, envir = .GlobalEnv)\n assign(\"otuPropsPerNode.adjustedZeros\", otuPropsPerNode.adjustedZeros, envir = .GlobalEnv)\n assign(\"weightsPerNode\", weightsPerNode, envir = .GlobalEnv)\n}\n\ncalculateDistanceMatrix <- function(weights, method, otuTable, verbose, pruneTree, normalize) {\n unifrac.tree <- get(\"unifrac.tree\",envir=.GlobalEnv)\n otuPropsPerNode <- get(\"otuPropsPerNode\",envir=.GlobalEnv)\n \n nSamples <- nrow(otuTable)\n distanceMatrix <- matrix(NA,nrow=nSamples,ncol=nSamples)\n rownames(distanceMatrix) <- rownames(otuTable)\n colnames(distanceMatrix) <- rownames(otuTable)\n \n branchLengths <- unifrac.tree$edge.length\n \n weightColnames <- as.numeric(colnames(weights))\n \n weights <- weights[,match(unifrac.tree$edge[,2], weightColnames)]\n \n\tfor (i in 1:nSamples) {\n\t\tfor (j in i:nSamples) {\n\n\t\t\t\tif (method == \"weighted\" || method == \"information\" || method == \"ratio\" || method == \"ratio_no_log\") {\n\t\t\t\t\t# the formula is sum of (proportional branch lengths * | proportional abundance for sample A - proportional abundance for sample B| )\n\t\t\t\t\tif (pruneTree==TRUE){\n\t\t\t\t\t\tincludeBranchLengths <- which( (otuPropsPerNode[i,] > 0) | (otuPropsPerNode[j,] > 0) )\n\t\t\t\t\t\tif (normalize==TRUE && (method != \"ratio\" || method != \"ratio_no_log\")) {\n\t\t\t\t\t\t\tdistance <- sum( branchLengths[includeBranchLengths] * abs(weights[i,includeBranchLengths] - weights[j,includeBranchLengths]) )/sum( branchLengths[includeBranchLengths]* (weights[i,includeBranchLengths] + weights[j,includeBranchLengths]) )\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdistance <- sum( branchLengths[includeBranchLengths] * abs(weights[i,includeBranchLengths] - weights[j,includeBranchLengths]) )/sum( branchLengths[includeBranchLengths])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdistance <- sum( branchLengths * abs(weights[i,] - weights[j,]) )/sum(branchLengths)\n\t\t\t\t\t\tif (normalize==TRUE) {\n\t\t\t\t\t\t\tdistance <- sum( branchLengths * abs(weights[i,] - weights[j,]) )/sum(branchLengths * (weights[i,] + weights[j,]))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tif (method!=\"unweighted\") {\n\t\t\t\t\twarning(paste(\"Invalid method\",method,\", using unweighted Unifrac instead\"))\n\t\t\t\t}\n\t\t\t\t# the formula is sum of (branch lengths * (1 if one sample has counts and not the other, 0 otherwise) )\n\t\t\t\t#\ti call the (1 if one sample has counts and not the other, 0 otherwise) xorBranchLength\n\t\t\t\txorBranchLength <- as.numeric(xor( weights[i,] > 0, weights[j,] > 0))\n\t\t\t\tif (pruneTree==TRUE) {\n\t\t\t\t\tincludeBranchLengths <- which( (weights[i,] > 0) | (weights[j,] > 0) )\n\t\t\t\t\tdistance <- sum( branchLengths[includeBranchLengths] * xorBranchLength[includeBranchLengths])/sum(branchLengths[includeBranchLengths])\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tdistance <- sum( branchLengths * xorBranchLength)/sum(branchLengths)\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tdistanceMatrix[i,j] <- distance\n\t\t\tdistanceMatrix[j,i] <- distance\n\n\t\t}\n\t}\n\n\tif(verbose) {\tprint(\"done\")\t}\n\n\treturn(distanceMatrix)\n\n}\n\n#valid methods are unweighted, weighted, information, and ratio. Any other method will result in a warning and the unweighted analysis\n#pruneTree option prunes the tree for each comparison to exclude branch lenxgths not present in both samples\n#normalize divides the value at each node by sum of weights to guarantee output between 0 and 1 (breaks the triangle inequality)\n\n#otuTable must have samples as rows, OTUs as columns\n#tree must be phylo tree object from ape package (can use read.tree method to read in a newick tree to this format)\n\ngetDistanceMatrix <- function(otuTable,tree,method=\"weighted\",verbose=FALSE,pruneTree=FALSE,normalize=TRUE) {\n\n\tif (length(which(is.na(otuTable))) > 0) {\n\t\tstop(\"OTU count table has NA\")\n\t}\n\n\tif (!is.rooted(tree)) {\n\t\ttree <- midpoint(tree)\n\t\tif(verbose) { print(\"Rooting tree by midpoint\") }\n\t}\n\n\tif (attributes(tree)$order!=\"postorder\") {\n\t\ttree <- reorder(tree,order=\"postorder\")\n\t\tif (verbose) { print(\"Reordering tree as postorder for distance calculation algorithm\") }\n\t}\n \n #make globally available copy of tree\n assign(\"unifrac.tree\", tree, envir = .GlobalEnv)\n unifrac.tree <- get(\"unifrac.tree\", envir = .GlobalEnv)\n \n #make globally available copy of leaves\n assign(\"unifrac.treeLeaves\", c(1:length(tree$tip.label)), envir = .GlobalEnv)\n unifrac.treeLeaves <- get(\"unifrac.treeLeaves\", envir = .GlobalEnv)\n \n\t# get proportions\n\treadsPerSample <- apply(otuTable,1,sum)\n\totu.prop <- otuTable/readsPerSample\n\totu.prop <- as.matrix(otu.prop)\n\trownames(otu.prop) <- rownames(otuTable)\n\tcolnames(otu.prop) <- colnames(otuTable)\n\tif(verbose) {\tprint(\"calculated proportional abundance\")\t}\n\n\t# add priors to zeros based on bayesian approach\n\totuTable.adjustedZeros <- cmultRepl(otuTable, method=\"CZM\", output=\"counts\")\n # make any negative numbers as close to zero as possible - this is probably due to a precision error.\n otuTable.adjustedZeros <- apply(otuTable.adjustedZeros,2,function(x) { x[which(x < 0)] <- .Machine$double.eps; return(x) })\n readsPerSample <- apply(otuTable.adjustedZeros,1,sum)\n otu.prop.adjustedZeros <- otuTable.adjustedZeros/readsPerSample\n otu.prop.adjustedZeros <- as.matrix(otu.prop.adjustedZeros)\n\trownames(otu.prop.adjustedZeros) <- rownames(otuTable)\n\tcolnames(otu.prop.adjustedZeros) <- colnames(otuTable)\n \n\t##get cumulative proportional abundance for the nodes (nodes are ordered same as in the phylo tree representation)\n\n otuPropsPerNode <- matrix(NA, ncol=length(tree$edge.length)+1, nrow=length(rownames(otuTable)))\n otuPropsPerNode.adjustedZeros <- matrix(NA, ncol=length(tree$edge.length)+1, nrow=length(rownames(otuTable)))\n weightsPerNode <- matrix(NA, ncol=length(tree$edge.length)+1, nrow=length(rownames(otuTable)))\n \n\t#each row is a sample\n rownames(otuPropsPerNode) <- rownames(otuTable)\n rownames(otuPropsPerNode.adjustedZeros) <- rownames(otuTable)\n rownames(weightsPerNode) <- rownames(otuTable)\n #each column is a node in the tree\n colnames(otuPropsPerNode) <- c(1:(length(tree$edge.length)+1))\n colnames(otuPropsPerNode.adjustedZeros) <- c(1:(length(tree$edge.length)+1))\n colnames(weightsPerNode) <- c(1:(length(tree$edge.length)+1))\n \n leafNodes <- c(1:length(tree$tip.label))\n leafOrder <- match(tree$tip.label,colnames(otu.prop))\n \n otuPropsPerNode[,leafNodes] <- otu.prop[,leafOrder]\n otuPropsPerNode.adjustedZeros[,leafNodes] <- otu.prop.adjustedZeros[,leafOrder]\n weightsPerNode[,leafNodes] <- log2(otu.prop.adjustedZeros[,leafOrder])\n weightsPerNode[,leafNodes] <- t(apply(weightsPerNode[,leafNodes],1,function(x) { return(x - mean(x))}))\n \n # the tree is in postorder, so the last edges belong to the root\n root <- tree$edge[nrow(tree$edge),1]\n\n if(verbose) {\tprint(\"calculating weights...\")\t}\n \n assign(\"otuPropsPerNode\", otuPropsPerNode, envir = .GlobalEnv)\n assign(\"otuPropsPerNode.adjustedZeros\", otuPropsPerNode.adjustedZeros, envir = .GlobalEnv)\n assign(\"weightsPerNode\", weightsPerNode, envir = .GlobalEnv)\n \n build_weights(root)\n \n otuPropsPerNode <- get(\"otuPropsPerNode\",envir = .GlobalEnv)\n otuPropsPerNode.adjustedZeros <- get(\"otuPropsPerNode.adjustedZeros\",envir = .GlobalEnv)\n weightsPerNode <- get(\"weightsPerNode\",envir = .GlobalEnv)\n \n # build_weights makes everything negative, make everything positive again\n otuPropsPerNode[,c(1:ncol(otuPropsPerNode))] <- abs(otuPropsPerNode[,c(1:ncol(otuPropsPerNode))])\n otuPropsPerNode.adjustedZeros[,c(1:ncol(otuPropsPerNode.adjustedZeros))] <- abs(otuPropsPerNode.adjustedZeros[,c(1:ncol(otuPropsPerNode.adjustedZeros))])\n \n assign(\"otuPropsPerNode\", otuPropsPerNode, envir = .GlobalEnv)\n assign(\"otuPropsPerNode.adjustedZeros\", otuPropsPerNode.adjustedZeros, envir = .GlobalEnv)\n assign(\"weightsPerNode\", weightsPerNode, envir = .GlobalEnv)\n \n if(verbose) {\tprint(\"calculating pairwise distances...\")\t}\n \n #convert table according to weight\n if (method == \"all\") {\n returnList <- list()\n # unweighted\n print(\"calculating unweighted distance matrix\")\n weights <- otuPropsPerNode\n returnList[[\"unweighted\"]] <- calculateDistanceMatrix(weights, \"unweighted\", otuTable, verbose, pruneTree, normalize)\n # weighted\n print(\"calculating weighted distance matrix\")\n weights <- otuPropsPerNode\n returnList[[\"weighted\"]] <- calculateDistanceMatrix(weights, \"weighted\", otuTable, verbose, pruneTree, normalize)\n # information\n print(\"calculating information distance matrix\")\n weights <- otuPropsPerNode.adjustedZeros*log2(otuPropsPerNode.adjustedZeros)\n returnList[[\"information\"]] <- calculateDistanceMatrix(weights, \"information\", otuTable, verbose, pruneTree, normalize)\n # ratio\n print(\"calculating ratio distance matrix\")\n weights <- weightsPerNode\n returnList[[\"ratio\"]] <- calculateDistanceMatrix(weights, \"ratio\", otuTable, verbose, pruneTree, normalize)\n # ratio no log\n print(\"calculating no log ratio distance matrix\")\n weights <- weightsPerNode\n weights <- 2^weights\n returnList[[\"ratio_no_log\"]] <- calculateDistanceMatrix(weights, \"ratio_no_log\", otuTable, verbose, pruneTree, normalize)\n return(returnList)\n } else if (method==\"information\") {\n weights <- otuPropsPerNode.adjustedZeros*log2(otuPropsPerNode.adjustedZeros)\n return(calculateDistanceMatrix(weights, method, otuTable, verbose, pruneTree, normalize))\n } else if (method == \"ratio_no_log\") {\n weights <- weightsPerNode\n weights <- 2^weights\n return(calculateDistanceMatrix(weights, method, otuTable, verbose, pruneTree, normalize))\n } else if (method == \"ratio\") {\n weights <- weightsPerNode\n return(calculateDistanceMatrix(weights, method, otuTable, verbose, pruneTree, normalize))\n }\n else {\n weights <- otuPropsPerNode\n return(calculateDistanceMatrix(weights, method, otuTable, verbose, pruneTree, normalize))\n }\n}\n", "meta": {"hexsha": "422bd39985a22defd26e6c32de3817a20b737c58", "size": 14289, "ext": "r", "lang": "R", "max_stars_repo_path": "UniFrac.r", "max_stars_repo_name": "ruthgrace/ruth_unifrac_workshop", "max_stars_repo_head_hexsha": "2597b438dcbc5676bfbb2d6029432d7936cc4b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2016-02-29T13:48:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T16:12:25.000Z", "max_issues_repo_path": "UniFrac.r", "max_issues_repo_name": "ruthgrace/ruth_unifrac_workshop", "max_issues_repo_head_hexsha": "2597b438dcbc5676bfbb2d6029432d7936cc4b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-24T20:50:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-01T15:12:18.000Z", "max_forks_repo_path": "UniFrac.r", "max_forks_repo_name": "ruthgrace/ruth_unifrac_workshop", "max_forks_repo_head_hexsha": "2597b438dcbc5676bfbb2d6029432d7936cc4b90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-05-06T16:12:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T17:53:07.000Z", "avg_line_length": 46.0935483871, "max_line_length": 246, "alphanum_fraction": 0.7287423893, "num_tokens": 4110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3279679798826485}} {"text": "\n\n#' Outlier adjustment estimation\n#' \n#' How much of the heterogeneity due to the outlier can be explained by alternative pathways?\n#' \n#' @param tryxscan Output from \\code{tryx.scan}\n#' @param id_remove List of IDs to exclude from the adjustment analysis. It is possible that in the outlier search a candidate trait will come up which is essentially just a surrogate for the outcome trait (e.g. if you are analysing coronary heart disease as the outcome then a variable related to heart disease medication might come up as a candidate trait). Adjusting for a trait which is essentially the same as the outcome will erroneously nullify the result, so visually inspect the candidate trait list and remove those that are inappropriate.\n#'\n#' @export\n#' @return data frame of adjusted effect estimates and heterogeneity stats\ntryx.adjustment <- function(tryxscan, id_remove=NULL)\n{\n\t# for each outlier find the candidate MR analyses\n\t# if only exposure then ignore\n\t# if only outcome then re-estimate the snp-outcome association\n\t# if exposure and outcome then re-estimate the snp-exposure and snp-outcome association\n\t# outlier\n\t# candidate\n\t# what \n\t# old.beta.exposure\n\t# adj.beta.exposure\n\t# old.beta.outcome\n\t# adj.beta.outcome\n\t# candidate.beta.outcome\n\t# candidate.se.outcome\n\t# candidate.beta.exposure\n\t# candidate.se.exposure\n\t# old.deviation\n\t# new.deviation\n\n\tif(!any(tryxscan$search$sig))\n\t{\n\t\treturn(tibble())\n\t}\n\n\tl <- list()\n\tsig <- subset(tryxscan$search, sig & !id.outcome %in% id_remove)\n\tsige <- subset(tryxscan$candidate_exposure_mr, sig & !id.exposure %in% id_remove)\n\tsigo <- subset(tryxscan$candidate_outcome_mr, sig & !id.exposure %in% id_remove)\n\n\tdat <- tryxscan$dat\n\tdat$qi <- cochrans_q(dat$beta.outcome / dat$beta.exposure, dat$se.outcome / abs(dat$beta.exposure))\n\tdat$Q <- sum(dat$qi)\n\tfor(i in 1:nrow(sig))\n\t{\n\t\ta <- subset(dat, SNP == sig$SNP[i], select=c(SNP, beta.exposure, beta.outcome, se.exposure, se.outcome, qi, Q))\n\t\tif(sig$id.outcome[i] %in% sigo$id.exposure)\n\t\t{\n\t\t\ta$candidate <- sig$outcome[i]\n\t\t\ta$i <- i\n\t\t\tif(sig$id.outcome[i] %in% sige$id.exposure) {\n\t\t\t\tmessage(\"x<-p->y: \", a$SNP, \"\\t- \", sig$outcome[i])\n\t\t\t\ta$what <- \"p->x; p->y\"\n\t\t\t\ta$candidate.beta.exposure <- sige$b[sige$id.exposure == sig$id.outcome[i]]\n\t\t\t\ta$candidate.se.exposure <- sige$se[sige$id.exposure == sig$id.outcome[i]]\n\t\t\t\ta$candidate.beta.outcome <- sigo$b[sigo$id.exposure == sig$id.outcome[i]]\n\t\t\t\ta$candidate.se.outcome <- sigo$se[sigo$id.exposure == sig$id.outcome[i]]\n\t\t\t\tb <- bootstrap_path(a$beta.exposure, a$se.exposure, sig$beta.outcome[i], sig$se.outcome[i], sige$b[sige$id.exposure == sig$id.outcome[i]], sige$se[sige$id.exposure == sig$id.outcome[i]])\n\t\t\t\ta$adj.beta.exposure <- b[1]\n\t\t\t\ta$adj.se.exposure <- b[2]\n\t\t\t\tb <- bootstrap_path(a$beta.outcome, a$se.outcome, sig$beta.outcome[i], sig$se.outcome[i], sigo$b[sigo$id.exposure == sig$id.outcome[i]], sigo$se[sigo$id.exposure == sig$id.outcome[i]])\n\t\t\t\ta$adj.beta.outcome <- b[1]\n\t\t\t\ta$adj.se.outcome <- b[2]\n\t\t\t} else {\n\t\t\t\tmessage(\" p->y: \", a$SNP, \"\\t- \", sig$outcome[i])\n\t\t\t\ta$what <- \"p->y\"\n\t\t\t\ta$candidate.beta.exposure <- NA\n\t\t\t\ta$candidate.se.exposure <- NA\n\t\t\t\ta$candidate.beta.outcome <- sigo$b[sigo$id.exposure == sig$id.outcome[i]]\n\t\t\t\ta$candidate.se.outcome <- sigo$se[sigo$id.exposure == sig$id.outcome[i]]\n\t\t\t\tb <- bootstrap_path(a$beta.outcome, a$se.outcome, sig$beta.outcome[i], sig$se.outcome[i], sigo$b[sigo$id.exposure == sig$id.outcome[i]], sigo$se[sigo$id.exposure == sig$id.outcome[i]])\n\t\t\t\ta$adj.beta.exposure <- a$beta.exposure\n\t\t\t\ta$adj.se.exposure <- a$se.exposure\n\t\t\t\ta$adj.beta.outcome <- b[1]\n\t\t\t\ta$adj.se.outcome <- b[2]\n\t\t\t}\n\t\t\ttemp <- dat\n\t\t\ttemp$beta.exposure[temp$SNP == a$SNP] <- a$adj.beta.exposure\n\t\t\ttemp$se.exposure[temp$SNP == a$SNP] <- a$adj.se.exposure\n\t\t\ttemp$beta.outcome[temp$SNP == a$SNP] <- a$adj.beta.outcome\n\t\t\ttemp$se.outcome[temp$SNP == a$SNP] <- a$adj.se.outcome\n\t\t\ttemp$qi <- cochrans_q(temp$beta.outcome / temp$beta.exposure, temp$se.outcome / abs(temp$beta.exposure))\n\t\t\ta$adj.qi <- temp$qi[temp$SNP == a$SNP]\n\t\t\ta$adj.Q <- sum(temp$qi)\n\n\t\t\tl[[i]] <- a\n\t\t}\n\n\t}\n\tl <- bind_rows(l)\n\tl$d <- (l$adj.qi / l$adj.Q) / (l$qi / l$Q)\n\treturn(l)\n}\n\n\ntryx.adjustment.mv <- function(tryxscan, lasso=TRUE, id_remove=NULL, proxies=FALSE)\n{\n\t# for each outlier find the candidate MR analyses\n\t# if only exposure then ignore\n\t# if only outcome then re-estimate the snp-outcome association\n\t# if exposure and outcome then re-estimate the snp-exposure and snp-outcome association\n\t# outlier\n\t# candidate\n\t# what \n\t# old.beta.exposure\n\t# adj.beta.exposure\n\t# old.beta.outcome\n\t# adj.beta.outcome\n\t# candidate.beta.outcome\n\t# candidate.se.outcome\n\t# candidate.beta.exposure\n\t# candidate.se.exposure\n\t# old.deviation\n\t# new.deviation\n\n\tif(!any(tryxscan$search$sig))\n\t{\n\t\treturn(tibble())\n\t}\n\n\tl <- list()\n\tsig <- subset(tryxscan$search, sig & !id.outcome %in% id_remove)\n\tsige <- subset(tryxscan$candidate_exposure_mr, sig & !id.exposure %in% id_remove)\n\tsigo <- subset(tryxscan$candidate_outcome_mr, sig & !id.exposure %in% id_remove)\n\n\tid.exposure <- tryxscan$dat$id.exposure[1]\n\tid.outcome <- tryxscan$dat$id.outcome[1]\n\n#\tfor each outlier SNP find its effects on \n\n\tsigo1 <- subset(sig, id.outcome %in% sigo$id.exposure) %>% group_by(SNP) %>% mutate(snpcount=n()) %>% arrange(desc(snpcount), SNP)\n\tsnplist <- unique(sigo1$SNP)\n\tmvo <- list()\n\tdat <- tryxscan$dat\n\tdat$qi <- cochrans_q(dat$beta.outcome / dat$beta.exposure, dat$se.outcome / abs(dat$beta.exposure))\n\tdat$Q <- sum(dat$qi)\n\tdat$orig.beta.outcome <- dat$beta.outcome\n\tdat$orig.se.outcome <- dat$se.outcome\n\tdat$orig.qi <- dat$qi\n\tdat$outlier <- FALSE\n\tdat$outlier[dat$SNP %in% tryxscan$outliers] <- TRUE\n\tfor(i in 1:length(snplist))\n\t{\n\t\tmessage(\"Estimating joint effects of the following trait(s) associated with \", snplist[i])\n\t\ttemp <- subset(sigo1, SNP %in% snplist[i])\n\t\tcandidates <- unique(temp$outcome)\n\t\tmessage(paste(candidates, collapse=\"\\n\"))\n\t\tif(lasso & length(candidates) == 1)\n\t\t{\n\t\t\tmessage(\"Only one candidate trait for SNP \", snplist[i], \" so performing standard MVMR instead of LASSO\")\n\t\t}\n\t\tmvexp <- suppressMessages(mv_extract_exposures(c(id.exposure, unique(temp$id.outcome)), find_proxies=proxies))\n\t\tmvout <- suppressMessages(extract_outcome_data(mvexp$SNP, id.outcome))\n\t\tmvdat <- suppressMessages(mv_harmonise_data(mvexp, mvout))\n\t\tif(lasso & length(candidates) > 1)\n\t\t{\n\t\t\tmessage(\"Performing shrinkage\")\t\t\n\t\t\tb <- glmnet::cv.glmnet(x=mvdat$exposure_beta, y=mvdat$outcome_beta, weight=1/mvdat$outcome_se^2, intercept=0)\n\t\t\tc <- coef(b, s = \"lambda.min\")\n\t\t\tkeeplist <- unique(c(rownames(c)[!c[,1] == 0], tryxscan$dat$id.exposure[1]))\n\t\t\tmessage(\"After shrinkage keeping:\")\n\t\t\tmessage(paste(keeplist, collapse=\"\\n\"))\n\t\t\tmvexp2 <- subset(mvexp, id.exposure %in% keeplist)\n\t\t\tremsnp <- group_by(mvexp2, SNP) %>% summarise(mp = min(pval.exposure)) %>% filter(mp > 5e-8) %$% as.character(SNP)\n\t\t\tmvexp2 <- subset(mvexp2, !SNP %in% remsnp)\n\t\t\tmvout2 <- subset(mvout, SNP %in% mvexp2$SNP)\n\t\t\tmvdat2 <- suppressMessages(mv_harmonise_data(mvexp2, mvout2))\n\t\t\tmvo[[i]] <- mv_multiple(mvdat2)$result\n\t\t} else {\n\t\t\tmvo[[i]] <- mv_multiple(mvdat)$result\n\t\t}\n\t\tmvo[[i]] <- subset(mvo[[i]], !exposure %in% tryxscan$dat$exposure[1])\n\t\ttemp2 <- with(temp, tibble(SNP=SNP, exposure=outcome, snpeff=beta.outcome, snpeff.se=se.outcome, snpeff.pval=pval.outcome))\n\t\tmvo[[i]] <- merge(mvo[[i]], temp2, by=\"exposure\")\n\t\tboo <- with(subset(dat, SNP == snplist[i]), \n\t\t\tbootstrap_path(\n\t\t\t\tbeta.outcome,\n\t\t\t\tse.outcome,\n\t\t\t\tmvo[[i]]$snpeff,\n\t\t\t\tmvo[[i]]$snpeff.se,\n\t\t\t\tmvo[[i]]$b,\n\t\t\t\tmvo[[i]]$se\n\t\t\t))\n\t\tdat$beta.outcome[dat$SNP == snplist[i]] <- boo[1]\n\t\tdat$se.outcome[dat$SNP == snplist[i]] <- boo[2]\n\t}\n\tmvo <- bind_rows(mvo)\n\n\tdat$qi[dat$mr_keep] <- cochrans_q(dat$beta.outcome[dat$mr_keep] / dat$beta.exposure[dat$mr_keep], dat$se.outcome[dat$mr_keep] / abs(dat$beta.exposure[dat$mr_keep]))\n\treturn(list(mvo=mvo, dat=dat))\n}\n\n\n\n\n\n\n\n\n#' Analyse tryx results\n#' \n#' This returns various heterogeneity statistics, IVW estimates for raw, \n#' adjusted and outlier removed datasets, and summary of peripheral \n#' traits detected etc.\n#' \n#' @param tryxscan Output from \\code{tryx.scan}\n#' @param plot Whether to plot or not. Default is TRUE\n#' @param id_remove List of IDs to exclude from the adjustment analysis. It is possible that in the outlier search a candidate trait will come up which is essentially just a surrogate for the outcome trait (e.g. if you are analysing coronary heart disease as the outcome then a variable related to heart disease medication might come up as a candidate trait). Adjusting for a trait which is essentially the same as the outcome will erroneously nullify the result, so visually inspect the candidate trait list and remove those that are inappropriate.\n#' @param duplicate_outliers_method Sometimes more than one trait will associate with a particular outlier. TRUE = only keep the trait that has the biggest influence on heterogeneity\n#' \n#' @export\n#' @return List of \n#' - adj_full: data frame of SNP adjustments for all candidate traits\n#' - adj: The results from adj_full selected to adjust the exposure-outcome model\n#' - Q: Heterogeneity stats\n#' - estimates: Adjusted and unadjested exposure-outcome effects\n#' - plot: Radial plot showing the comparison of different methods and the changes in SNP effects ater adjustment\ntryx.analyse <- function(tryxscan, plot=TRUE, id_remove=NULL, filter_duplicate_outliers=TRUE)\n{\n\n\tanalysis <- list()\n\tadj_full <- tryx.adjustment(tryxscan, id_remove)\n\tif(nrow(adj_full) == 0)\n\t{\n\t\treturn(NULL)\n\t}\n\tanalysis$adj_full <- adj_full\n\tif(filter_duplicate_outliers)\n\t{\n\t\tadj <- adj_full %>% arrange(d) %>% filter(!duplicated(SNP))\n\t} else {\n\t\tadj <- adj_full\n\t}\n\tanalysis$adj <- adj\n\n\t# Detection\n\t# if(\"simulation\" %in% names(tryxscan))\n\t# {\n\t# \tdetection <- list()\n\t# \tdetection$nu1_correct <- sum(adj$SNP %in% 1:tryxscan$simulation$nu1 & adj$what != \"p->y\")\n\t# \tdetection$nu1_incorrect <- sum(adj$SNP %in% 1:tryxscan$simulation$nu1 & adj$what == \"p->y\")\n\t# \tdetection$nu2_correct <- sum(adj$SNP %in% (1:tryxscan$simulation$nu2 + tryxscan$simulation$nu1) & adj$what == \"p->y\")\n\t# \tdetection$nu2_incorrect <- sum(adj$SNP %in% (1:tryxscan$simulation$nu2 + tryxscan$simulation$nu1) & adj$what != \"p->y\")\n\t# \tdetection$no_outlier_flag <- tryxscan$simulation$no_outlier_flag\n\t# \tanalysis$detection <- detection\n\t# }\n\n\tcpg <- require(ggrepel)\n\tif(!cpg)\n\t{\n\t\tstop(\"Please install the ggrepel package\\ninstall.packages('ggrepel')\")\n\t}\n\n\tdat <- subset(tryxscan$dat, mr_keep, select=c(SNP, beta.exposure, beta.outcome, se.exposure, se.outcome))\n\tdat$ratio <- dat$beta.outcome / dat$beta.exposure\n\tdat$weights <- sqrt(dat$beta.exposure^2 / dat$se.outcome^2)\n\tdat$ratiow <- dat$ratio * dat$weights\n\tdat$what <- \"Unadjusted\"\n\tdat$candidate <- \"NA\"\n\tdat$qi <- cochrans_q(dat$beta.outcome / dat$beta.exposure, dat$se.outcome / abs(dat$beta.exposure))\n\n\tanalysis$Q$full_Q <- adj$Q[1]\n\tanalysis$Q$num_reduced <- sum(adj$adj.qi < adj$qi)\n\tanalysis$Q$mean_d <- mean(adj$d)\n\n\n\ttemp <- subset(adj, select=c(SNP, adj.beta.exposure, adj.beta.outcome, adj.se.exposure, adj.se.outcome, candidate))\n\ttemp$qi <- cochrans_q(temp$adj.beta.outcome / temp$adj.beta.exposure, temp$adj.se.outcome / abs(temp$adj.beta.exposure))\n\tind <- grepl(\"\\\\|\", temp$candidate)\n\tif(any(ind))\n\t{\n\t\ttemp$candidate[ind] <- sapply(strsplit(temp$candidate[ind], split=\" \\\\|\"), function(x) x[[1]])\n\t}\n\tnames(temp) <- gsub(\"adj.\", \"\", names(temp))\n\ttemp$what <- \"Adjusted\"\n\ttemp$weights <- sqrt(temp$beta.exposure^2 / temp$se.outcome^2)\n\ttemp$ratio <- temp$beta.outcome / temp$beta.exposure\n\ttemp$ratiow <- temp$ratio * temp$weights\n\n\tdat_adj <- rbind(temp, dat) %>% filter(!duplicated(SNP))\n\tdat_adj$qi <- cochrans_q(dat_adj$beta.outcome / dat_adj$beta.exposure, dat_adj$se.outcome / abs(dat_adj$beta.exposure))\n\tanalysis$Q$adj_Q <- sum(dat_adj$qi)\n\n\tdat_rem <- subset(dat, !SNP %in% temp$SNP)\n\tdat_rem2 <- subset(dat, !SNP %in% tryxscan$outliers)\n\t# adjust everything that's possible remove remaining outliers\n\tdat_rem3 <- rbind(temp, dat_rem2) %>% filter(!duplicated(SNP))\n\n\n\n\testimates <- tibble()\n\n\t\n\t# Raw IVW\n\ttt <- dat\n\tmod <- summary(lm(ratiow ~ -1 + weights, data=tt))\n\testimates <- bind_rows(estimates, \n\t\ttibble(\n\t\t\test=\"Raw\",\n\t\t\tb=coefficients(mod)[1,1], \n\t\t\tse = coefficients(mod)[1,2],\n\t\t\tpval=coefficients(mod)[1,4],\n\t\t\tnsnp = nrow(tt),\n\t\t\tQ = sum(tt$qi),\n\t\t\tint = 0\n\t\t)\n\t)\n\n\t# Outliers removed (all)\n\ttt <- subset(dat, !SNP %in% tryxscan$outliers)\n\tmod <- try(summary(lm(ratiow ~ -1 + weights, data=tt)))\n\tif(class(mod) != \"try-error\")\n\t{\n\t\testimates <- bind_rows(estimates, \n\t\t\ttibble(\n\t\t\t\test=\"Outliers removed (all)\",\n\t\t\t\tb=coefficients(mod)[1,1], \n\t\t\t\tse = coefficients(mod)[1,2],\n\t\t\t\tpval=coefficients(mod)[1,4],\n\t\t\t\tnsnp = nrow(tt),\n\t\t\t\tQ = sum(tt$qi),\n\t\t\t\tint = 0\n\t\t\t)\n\t\t)\n\t}\n\n\t# Outliers removed (candidates)\n\ttt <- subset(dat, !SNP %in% temp$SNP)\n\tmod <- try(summary(lm(ratiow ~ -1 + weights, data=tt)))\n\tif(class(mod) != \"try-error\")\n\t{\n\t\testimates <- bind_rows(estimates, \n\t\t\ttibble(\n\t\t\t\test=\"Outliers removed (candidates)\",\n\t\t\t\tb=coefficients(mod)[1,1], \n\t\t\t\tse = coefficients(mod)[1,2],\n\t\t\t\tpval=coefficients(mod)[1,4],\n\t\t\t\tnsnp = nrow(tt),\n\t\t\t\tQ = sum(tt$qi),\n\t\t\t\tint = 0\n\t\t\t)\n\t\t)\n\t}\n\n\t# Outliers adjusted\n\ttt <- rbind(temp, dat) %>% filter(!duplicated(SNP))\n\ttt$qi <- cochrans_q(tt$beta.outcome / tt$beta.exposure, tt$se.outcome / abs(tt$beta.exposure))\n\tanalysis$Q$adj_Q <- sum(tt$qi)\n\tmod <- try(summary(lm(ratiow ~ -1 + weights, data=tt)))\n\tif(class(mod) != \"try-error\")\n\t{\n\t\testimates <- bind_rows(estimates, \n\t\t\ttibble(\n\t\t\t\test=\"Outliers adjusted\",\n\t\t\t\tb=coefficients(mod)[1,1], \n\t\t\t\tse = coefficients(mod)[1,2],\n\t\t\t\tpval=coefficients(mod)[1,4],\n\t\t\t\tnsnp = nrow(tt),\n\t\t\t\tQ = sum(tt$qi),\n\t\t\t\tint = 0\n\t\t\t)\n\t\t)\n\t}\n\n\tif(\"mvres\" %in% names(tryxscan))\n\t{\n\t\testimates <- bind_rows(estimates, \n\t\t\ttibble(\n\t\t\t\test=\"Multivariable MR\",\n\t\t\t\tb=tryxscan$mvres$result$b[1], \n\t\t\t\tse = tryxscan$mvres$result$se[1],\n\t\t\t\tpval = tryxscan$mvres$result$pval[1],\n\t\t\t\tnsnp = tryxscan$mvres$result$nsnp[1],\n\t\t\t\tQ = NA,\n\t\t\t\tint = 0\n\t\t\t)\n\t\t)\n\t}\n\n\tif(\"true_outliers\" %in% names(tryxscan))\n\t{\n\t\ttt <- subset(dat, !SNP %in% tryxscan$true_outliers)\n\t\tmod <- try(summary(lm(ratiow ~ -1 + weights, data=tt)))\n\t\tif(class(mod) != \"try-error\")\n\t\t{\n\t\t\testimates <- bind_rows(estimates,\n\t\t\t\ttibble(\n\t\t\t\t\test=c(\"Oracle\"),\n\t\t\t\t\tb=c(coefficients(mod)[1,1]), \n\t\t\t\t\tse=c(coefficients(mod)[1,2]), \n\t\t\t\t\tpval=c(coefficients(mod)[1,4]),\n\t\t\t\t\tnsnp=c(nrow(tt)),\n\t\t\t\t\tQ = c(sum(tt$qi)),\n\t\t\t\t\tint=0\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t}\n\n\n\testimates <- bind_rows(estimates)\n\testimates$Isq <- pmax(0, (estimates$Q - estimates$nsnp - 1) / estimates$Q) \n\n\tanalysis$estimates <- estimates\n\n\n\t# est3 <- summary(lm(ratiow ~ -1 + weights, data=dat_adj))\n\t# est4 <- try(summary(lm(ratiow ~ -1 + weights, data=dat_rem2)))\n\t# est5 <- try(summary(lm(ratiow ~ -1 + weights, data=dat_rem3)))\n\t# if(class(est4) == \"try-error\")\n\t# {\n\t# \test4 <- list(coefficients = matrix(NA, 2,4))\n\t# }\n\n\t# estimates <- data.frame(\n\t# \test=c(\"Raw\", \"Outliers removed (candidates)\", \"Outliers removed (all)\", \"Outliers adjusted\", \"Mixed\", \"Multivariable MR\"),\n\t# \tb=c(coefficients(est2)[1,1], coefficients(est1)[1,1], coefficients(est4)[1,1], coefficients(est3)[1,1], coefficients(est5)[1,1], tryxscan$mvres$result$b[1]), \n\t# \tse=c(coefficients(est2)[1,2], coefficients(est1)[1,2], coefficients(est4)[1,2], coefficients(est3)[1,2], coefficients(est5)[1,2], tryxscan$mvres$result$se[1]), \n\t# \tpval=c(coefficients(est2)[1,4], coefficients(est1)[1,4], coefficients(est4)[1,4], coefficients(est3)[1,4], coefficients(est5)[1,4], tryxscan$mvres$result$pval[1]),\n\t# \tnsnp=c(nrow(dat), nrow(dat_rem), nrow(dat_rem2), nrow(dat_adj), nrow(dat_rem3), tryxscan$mvres$result$nsnp[1]),\n\t# \tQ = c(sum(dat$qi), sum(dat_rem$qi), sum(dat_rem2$qi), sum(dat_adj$qi), sum(dat_rem3$qi), NA),\n\t# \tint=0\n\t# )\n\t# estimates$Isq <- pmax(0, (estimates$Q - estimates$nsnp - 1) / estimates$Q) \n\n\t# estimates$Isq <- pmax(0, (estimates$Q - estimates$nsnp - 1) / estimates$Q) \n\n\t# analysis$estimates <- estimates\n\n\tif(plot)\n\t{\t\n\t\ttemp2 <- merge(dat, temp, by=\"SNP\")\n\t\tlabs <- rbind(\n\t\t\tdata.frame(label=temp2$SNP, x=temp2$weights.x, y=temp2$weights.x * temp2$ratio.x),\n\t\t\tdata.frame(label=temp$candidate, x=temp$weights, y=temp$weights * temp$ratio)\n\t\t)\n\t\tp <- ggplot(rbind(dat, temp), aes(y=ratiow, x=weights)) +\n\t\tgeom_abline(data=estimates, aes(slope=b, intercept=0, colour=est)) +\n\t\tgeom_label_repel(data=labs, aes(x=x, y=y, label=label), size=2, segment.color = \"grey10\") +\n\t\tgeom_point() +\n\t\tgeom_segment(data=temp2, colour=\"grey50\", aes(x=weights.x, xend=weights.y, y=ratiow.x, yend=ratiow.y), arrow = arrow(length = unit(0.02, \"npc\"))) +\n\t\tlabs(colour=\"\") +\n\t\txlim(c(0, max(dat$weights))) +\n\t\tylim(c(min(0, dat$ratiow, temp$ratiow), max(dat$ratiow, temp$ratiow))) +\n\t\tscale_colour_brewer(type=\"qual\")\n\t\tanalysis$plot <- p\n\t}\n\treturn(analysis)\n}\n\n\n\n#' Analyse tryx results\n#' \n#' This returns various heterogeneity statistics, IVW estimates for raw, \n#' adjusted and outlier removed datasets, and summary of peripheral \n#' traits detected etc.\n#' \n#' @param tryxscan Output from \\code{tryx.scan}\n#' @param plot Whether to plot or not. Default is TRUE\n#' @param filter_duplicate_outliers Whether to only allow each putative outlier to be adjusted by a single trait (in order of largest divergence). Default is TRUE.\n#' \n#' @export\n#' @return List of \n#' - adj_full: data frame of SNP adjustments for all candidate traits\n#' - adj: The results from adj_full selected to adjust the exposure-outcome model\n#' - Q: Heterogeneity stats\n#' - estimates: Adjusted and unadjested exposure-outcome effects\n#' - plot: Radial plot showing the comparison of different methods and the changes in SNP effects ater adjustment\n\n\n\n#' Adjust and analyse the tryx results\n#'\n#' Similar to tryx.analyse, but when there are multiple traits associated with a single variant then we use a LASSO-based multivariable approach \n#'\n#' @param tryxscan Output from \\code{tryx.scan}\n#' @param lasso Whether to shrink the estimates of each trait within SNP. Default=TRUE.\n#' @param plot Whether to plot or not. Default is TRUE\n#' @param id_remove List of IDs to exclude from the adjustment analysis. It is possible that in the outlier search a candidate trait will come up which is essentially just a surrogate for the outcome trait (e.g. if you are analysing coronary heart disease as the outcome then a variable related to heart disease medication might come up as a candidate trait). Adjusting for a trait which is essentially the same as the outcome will erroneously nullify the result, so visually inspect the candidate trait list and remove those that are inappropriate.\n#' @param proxies Look for proxies in the MVMR methods. Default = FALSE.\n#'\n#' @export\n#' @return List of \n#' - adj_full: data frame of SNP adjustments for all candidate traits\n#' - adj: The results from adj_full selected to adjust the exposure-outcome model\n#' - Q: Heterogeneity stats\n#' - estimates: Adjusted and unadjested exposure-outcome effects\n#' - plot: Radial plot showing the comparison of different methods and the changes in SNP effects ater adjustment\ntryx.analyse.mv <- function(tryxscan, lasso=TRUE, plot=TRUE, id_remove=NULL, proxies=FALSE)\n{\n\tadj <- tryx.adjustment.mv(tryxscan, lasso=lasso, id_remove=id_remove, proxies=proxies)\n\tdat <- subset(adj$dat, mr_keep)\n\tdat$orig.ratio <- dat$orig.beta.outcome / dat$beta.exposure\n\tdat$orig.weights <- sqrt(dat$beta.exposure^2 / dat$orig.se.outcome^2)\n\tdat$orig.ratiow <- dat$orig.ratio * dat$orig.weights\n\tdat$ratio <- dat$beta.outcome / dat$beta.exposure\n\tdat$weights <- sqrt(dat$beta.exposure^2 / dat$se.outcome^2)\n\tdat$ratiow <- dat$ratio * dat$weights\n\n\test_raw <- summary(lm(orig.ratiow ~ -1 + orig.weights, data=dat))\n\test_adj <- summary(lm(ratiow ~ -1 + weights, data=dat))\n\test_out1 <- summary(lm(orig.ratiow ~ -1 + orig.weights, data=subset(dat, !SNP %in% tryxscan$outliers)))\n\test_out2 <- summary(lm(orig.ratiow ~ -1 + orig.weights, data=subset(dat, !SNP %in% adj$mvo$SNP)))\n\n\testimates <- data.frame(\n\t\test=c(\"Raw\", \"Outliers removed (all)\", \"Outliers removed (candidates)\", \"Outliers adjusted\"),\n\t\tb=c(coefficients(est_raw)[1,1], coefficients(est_out2)[1,1], coefficients(est_out1)[1,1], coefficients(est_adj)[1,1]), \n\t\tse=c(coefficients(est_raw)[1,2], coefficients(est_out2)[1,2], coefficients(est_out1)[1,2], coefficients(est_adj)[1,2]), \n\t\tpval=c(coefficients(est_raw)[1,4], coefficients(est_out2)[1,4], coefficients(est_out1)[1,4], coefficients(est_adj)[1,4]),\n\t\tnsnp=c(nrow(dat), nrow(subset(dat, !SNP %in% tryxscan$outliers)), nrow(subset(dat, !SNP %in% adj$mvo$SNP)), nrow(dat)),\n\t\tQ = c(sum(dat$orig.qi), sum(subset(dat, !SNP %in% tryxscan$outliers)$qi), sum(subset(dat, !SNP %in% adj$mvo$SNP)$qi), sum(dat$qi)),\n\t\tint=0\n\t)\n\testimates$Isq <- pmax(0, (estimates$Q - estimates$nsnp - 1) / estimates$Q) \n\n\tanalysis <- list(\n\t\testimates=estimates,\n\t\tmvo=adj$mvo,\n\t\tdat=adj$dat\n\t)\n\n\tif(plot)\n\t{\t\n\t\tdato <- subset(dat, SNP %in% tryxscan$outliers)\n\t\tdatadj <- subset(dat, SNP %in% adj$mvo$SNP)\n\t\tdatadj$x <- datadj$orig.weights\n\t\tdatadj$xend <- datadj$weights\n\t\tdatadj$y <- datadj$orig.ratiow\n\t\tdatadj$yend <- datadj$ratiow\n\n\t\tmvog <- tidyr::separate(adj$mvo, exposure, sep=\"\\\\|\", c(\"exposure\", \"temp\", \"id\"))\n\t\tmvog$exposure <- gsub(\" $\", \"\", mvog$exposure)\n\t\tmvog <- group_by(mvog, SNP) %>% summarise(label = paste(exposure, collapse=\"\\n\"))\n\t\tdatadj <- merge(datadj, mvog, by=\"SNP\")\n\n\t\tlabs <- rbind(\n\t\t\ttibble(label=dato$SNP, x=dato$orig.weights, y=dato$orig.ratiow, col=\"grey50\"),\n\t\t\ttibble(label=datadj$label, x=datadj$weights, y=datadj$ratiow, col=\"grey100\")\n\t\t)\n\n\n\t\tp <- ggplot(dat, aes(y=orig.ratiow, x=orig.weights)) +\n\t\tgeom_abline(data=estimates, aes(slope=b, intercept=0, linetype=est)) +\n\t\tgeom_label_repel(data=labs, aes(label=label, x=x, y=y, colour=col), size=2, segment.color = \"grey50\", show.legend = FALSE) +\n\t\tgeom_point(data=dato, size=4) +\n\t\t# geom_label_repel(data=labs, aes(label=label, x=weights, y=ratiow), size=2, segment.color = \"grey50\") +\n\t\tgeom_point(data=datadj, aes(x=weights, y=ratiow)) +\n\t\tgeom_point(aes(colour=SNP %in% dato$SNP), show.legend=FALSE) +\n\t\tgeom_segment(data=datadj, colour=\"grey50\", aes(x=x, xend=xend, y=y, yend=yend), arrow = arrow(length = unit(0.01, \"npc\"))) +\n\t\tlabs(colour=NULL, linetype=\"Estimate\", x=\"w\", y=\"beta * w\")\n\t\t# xlim(c(0, max(dat$weights))) +\n\t\t# ylim(c(min(0, dat$ratiow, temp$ratiow), max(dat$ratiow, temp$ratiow)))\n\t\tanalysis$plot <- p\n\t}\n\treturn(analysis)\n\n}\n\n#' Cochran's Q statistic\n#' \n#' @param b vector of effecti \n#' @param se vector of standard errors\n#' \n#' @return q values\n#' \n#' @export\ncochrans_q <- function(b, se)\n{\n\txw <- sum(b / se^2) / sum(1/se^2)\n\tqi <- (1/se^2) * (b - xw)^2\n\treturn(qi)\n}\n\nbootstrap_path1 <- function(gx, gx.se, gp, gp.se, px, px.se, nboot=1000)\n{\n\tres <- rnorm(nboot, gx, gx.se) - rnorm(nboot, gp, gp.se) * rnorm(nboot, px, px.se)\n\tpe <- gx - gp * px\n\treturn(c(pe, sd(res)))\n}\n\nbootstrap_path <- function(gx, gx.se, gp, gp.se, px, px.se, nboot=1000)\n{\n\tnalt <- length(gp)\n\taltpath <- tibble(\n\t\tp = rnorm(nboot * nalt, gp, gp.se) * rnorm(nboot * nalt, px, px.se),\n\t\tb = rep(1:nboot, each=nalt)\n\t)\n\taltpath <- group_by(altpath, b) %>%\n\t\tsummarise(p = sum(p))\n\tres <- rnorm(nboot, gx, gx.se) - altpath$p\n\tpe <- gx - sum(gp * px)\n\treturn(c(pe, sd(res)))\n}\n\n\nradialmr <- function(dat, outlier=NULL)\n{\n\tlibrary(ggplot2)\n\tbeta.exposure <- dat$beta.exposure\n\tbeta.outcome <- dat$beta.outcome\n\tse.outcome <- dat$se.outcome\n\tw <- sqrt(beta.exposure^2 / se.outcome^2)\n\tratio <- beta.outcome / beta.exposure\n\tratiow <- ratio*w\n\tdat <- data.frame(w=w, ratio=ratio, ratiow=ratiow)\n\tif(is.null(outlier))\n\t{\n\t\tdat2 <- dat\n\t} else {\n\t\tdat2 <- dat[-c(outlier), ]\n\t}\n\tmod <- lm(ratiow ~ -1 + w, dat2)$coefficients[1]\n\tggplot(dat, aes(x=w, y=ratiow)) +\n\tgeom_point() +\n\tgeom_abline(slope=mod, intercept=0)\n}\n", "meta": {"hexsha": "6a87484a3dd8ffe1e0d1298a5aeaf1a0dfaa1bd0", "size": 23846, "ext": "r", "lang": "R", "max_stars_repo_path": "R/adjustment.r", "max_stars_repo_name": "explodecomputer/tryx", "max_stars_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-03-14T14:33:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T15:46:39.000Z", "max_issues_repo_path": "R/adjustment.r", "max_issues_repo_name": "explodecomputer/tryx", "max_issues_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20, "max_issues_repo_issues_event_min_datetime": "2018-02-17T23:54:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T07:42:06.000Z", "max_forks_repo_path": "R/adjustment.r", "max_forks_repo_name": "explodecomputer/tryx", "max_forks_repo_head_hexsha": "f86a10402dd12b79a510dbff1764dcddf09707c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-05-13T13:29:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T13:29:03.000Z", "avg_line_length": 38.5234248788, "max_line_length": 549, "alphanum_fraction": 0.6815398809, "num_tokens": 7735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3279621255806566}} {"text": "# /* !/usr/bin/Rscript */\n\n#' ## Data munging\n#' Pre-process and explore datasets in preparation for feature creation.\n#'\n#'
\n#'
survival
\n#'
Survival (0 = No; 1 = Yes)
\n#'
pclass
\n#'
Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd)
\n#'
name
\n#'
Name (Title-Firstnames-Surname)
\n#'
sex
\n#'
Sex (Male/Female)\n#'
age
\n#'
Age (in years, float)\n#'
sibsp
\n#'
Number of Siblings/Spouses aboard
\n#'
parch
\n#'
Number of Parents/Children aboard
\n#'
ticket
\n#'
Ticket Number (alphanumeric)
\n#'
fare
\n#'
Passenger Fare (in US$)
\n#'
cabin
\n#'
Cabin (alphanumeric)
\n#'
embarked
\n#'
Port of Embarkation (C=Cherbourg; Q=Queenstown; S=Southampton)
\n#'
\n#'\n#' #### Family Relation Details\n#' With respect to the family relation variables (i.e. *Sibsp* and\n#' *Parch*) some relations were ignored. The following are the\n#' definitions used for sibsp and parch (aboard Titanic):\n#' - Sibling: Brother, Sister, Stepbrother, or Stepsister of Passenger\n#' - Spouse: Husband or Wife of Passenger (Mistresses and Fiances\n#' ignored)\n#' - Parent: Mother or Father of Passenger\n#' - Child: Son, Daughter, Stepson, or Stepdaughter of Passenger\n#'\n#' Other family relatives excluded from this study include cousins,\n#' nephews/nieces, aunts/uncles, and in-laws. Some children travelled\n#' only with a nanny, therefore `parch=0` for them. As well, some\n#' travelled with very close friends or neighbors in a village, however,\n#' the definitions do not support such relations.\n\n# /*\nwriteLines(\"\\n-------------\")\nwriteLines(\"Combining datasets, cleaning & imputing for exploration\")\n# */\n\n#' ### Combine raw datasets\n#' The data provided by Kaggle is pre-split into \"Training\" and \"Test\" sets,\n#' the former possessing the \"ground truth\" (or real outcome), the latter\n#' requiring prediction.\n#'\n#' In order to obtain the clearest possible picture of the date, as well as\n#' clean, impute missing data, and create new features, it is necessary to\n#' combine the two sets into one. The two sets will be re-created based on\n#' record ID before the modelling phase of the analysis.\n#'\n#' First a `Survived` column is added to the \"Test\" set (since it was missing\n#' and is required to match the columns in the \"Training\" set), and then the\n#' two combined:\ntest$Survived <- NA\ncombi <- rbind(raw, test)\n\n#' ### Inspection\n#' First assert the viability of creating a predictor for the response\n#' variable by examining the proportions of each level. Prevailing wisdom\n#' holds that if any proportion < 15% (0.15) then it might be classifed\n#' \"rare\", in which case it is much more difficult to model.\nprop.table(table(combi$Survived))\n\n#' Next use str to obtain a quick overview of the combined dataset dimensions\n#' and features (auto-created onRead).\nstr(combi)\n\n#' Looks like *Name* and *Cabin* should be of type `character`, not `factor`:\ncombi$Name <- as.character(combi$Name)\ncombi$Cabin <- as.character(combi$Cabin)\n\n#' Determine missing values:\n#' - is.na tests for any missing vals\n#' - missmap in Amelia package visualizes this\nsum(is.na(combi))\n\nmissmap(combi,\n main=\"Titanic Training Data - Missings Map\",\n col=c(\"yellow\", \"black\"),\n legend=FALSE\n)\n\n#' *Age*, *Cabin*, *Fare* and *Embarkation* have missing data points. Impute\n#' *Embarkation* data using most common value. The others require the\n#' creation of new synthetic features for optimal imputation.\nsummary(combi$Embarked)\ncombi$Embarked[which(combi$Embarked == \"\")] <- \"S\"\n\n#' Before engineering new features, convert and re-level `numeric` classes to\n#' factors, and rename *Survived* => *Fate* (as \"Survived\" is one of the\n#' levels). This aids understanding of confusion matrices, visualizations,\n#' and summary output.\ncombi$Class <- as.factor(combi$Pclass)\nlevels(combi$Class) <- c(\"Upper\", \"Middle\", \"Lower\")\ncombi$Fate <- as.factor(combi$Survived)\nlevels(combi$Fate) <- c(\"Perished\", \"Survived\")\n\n# /*\nwriteLines(\"\\n-------------\")\nwriteLines(\"Munging DONE\")\n# */\n\n", "meta": {"hexsha": "f98635b7e8f5c98a958473ca940be179ed00edec", "size": 4110, "ext": "r", "lang": "R", "max_stars_repo_path": "src/clean.r", "max_stars_repo_name": "andybeeching/kaggle-titanic", "max_stars_repo_head_hexsha": "df1000173aa9e7e5846611fd0be1223e709fbe06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-07-13T14:20:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-13T14:20:50.000Z", "max_issues_repo_path": "src/clean.r", "max_issues_repo_name": "andybeeching/kaggle-titanic", "max_issues_repo_head_hexsha": "df1000173aa9e7e5846611fd0be1223e709fbe06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clean.r", "max_forks_repo_name": "andybeeching/kaggle-titanic", "max_forks_repo_head_hexsha": "df1000173aa9e7e5846611fd0be1223e709fbe06", "max_forks_repo_licenses": ["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.0526315789, "max_line_length": 77, "alphanum_fraction": 0.6941605839, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.32714953320033724}} {"text": "#iv fastplm boot\r\nivfastplm.boot <- function(seed, \r\n y = NULL, \r\n x = NULL, \r\n z = NULL,\r\n ind = NULL, \r\n sfe.index = NULL, \r\n cfe.index = NULL, \r\n cluster = NULL,\r\n robust = FALSE,\r\n parallel = FALSE,\r\n wild = FALSE, \r\n jackknife = FALSE,\r\n refinement = FALSE, \r\n pos = NULL,\r\n test.value = NULL,\r\n nboots = 200, \r\n bootcluster = NULL, #2-way clusters in wild (refinement)\r\n core.num = 1){\r\n p <- dim(x)[2]\r\n if(is.null(z)){\r\n stop(\"No exogenous variables.\\n\")\r\n }\r\n\r\n if(is.null(colnames(x))){\r\n colnames(x) <- paste0(\"x.\",c(1:dim(x)[2]))\r\n }\r\n\r\n if(is.null(colnames(z))){\r\n colnames(z) <- paste0(\"z.\",c(1:dim(z)[2]))\r\n }\r\n\r\n if(is.null(colnames(y))){\r\n colnames(y) <- 'y'\r\n }\r\n\r\n if (jackknife == 1) {\r\n wild <- 0\r\n }\r\n\r\n # get \r\n model.iv <- ivfastplm.core(y = y, x = x, z = z, \r\n ind = ind, se = 1, \r\n robust = robust,\r\n sfe.index = sfe.index, \r\n cfe.index = cfe.index, \r\n cl = cluster, \r\n core.num = core.num, \r\n need.fe = TRUE,\r\n iv.test = FALSE)\r\n\r\n dy <- model.iv$demeaned$dy\r\n dx <- model.iv$demeaned$dx\r\n dz <- model.iv$demeaned$dz\r\n\r\n y.fit <- fitted.y <- model.iv$fitted.values\r\n res <- residual.y <- model.iv$residuals\r\n\r\n iv.name <- model.iv$names\r\n en.var.x <- iv.name$en.var.x\r\n ex.var.x <- iv.name$ex.var.x\r\n include.iv <- iv.name$include.iv\r\n exclude.iv <- iv.name$exclude.iv\r\n \r\n iv.matrix <- model.iv$matrix\r\n inv.z <- iv.matrix$inv.z # inv(z'z)\r\n inv.xPzx <- iv.matrix$inv.xPzx\r\n\r\n #save df.original & df.cl for wild bootstrap(only)\r\n df.use <- df.original <- model.iv$df.original\r\n df.cl.use <- df.cl <- model.iv$df.cl\r\n\r\n ## function to get two-sided p-values\r\n get.pvalue <- function(vec,to_test=0) {\r\n if (NaN%in%vec|NA%in%vec) {\r\n nan.pos <- is.nan(vec)\r\n na.pos <- is.na(vec)\r\n pos <- c(which(nan.pos),which(na.pos))\r\n vec.a <- vec[-pos]\r\n a <- sum(vec.a >= to_test)/(length(vec)-sum(nan.pos|na.pos)) * 2\r\n b <- sum(vec.a <= to_test)/(length(vec)-sum(nan.pos|na.pos)) * 2 \r\n } else {\r\n a <- sum(vec >= to_test)/length(vec) * 2\r\n b <- sum(vec <= to_test)/length(vec) * 2 \r\n }\r\n return(min(as.numeric(min(a, b)),1))\r\n }\r\n\r\n if(parallel==TRUE){\r\n core.num <- 1\r\n requireNamespace(\"doParallel\")\r\n\t\t## require(iterators)\r\n\t\tmaxcores <- detectCores()\r\n\t\tcores <- min(maxcores, 4)\r\n\t\tpcl<-makeCluster(cores) \r\n\t\tdoParallel::registerDoParallel(pcl)\r\n\t cat(\"Parallel computing with\", cores,\"cores...\\n\")\r\n use.fun <- c(\"SEQ\",\"name.fe.model\",\"ivfastplm.core\",\"get.dof\",\"iv.cluster.se\",\"fastplm.core\")\r\n }\r\n\r\n if(wild==TRUE){\r\n raw.cluster <- level.cluster <- level.count <- NULL\r\n if (!is.null(cluster)) {\r\n if(dim(cluster)[2]==1){\r\n ## one-way cluster \r\n raw.cluster <- as.numeric(as.factor(cluster))\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }\r\n if(dim(cluster)[2]==2){\r\n if(is.null(bootcluster)){\r\n level.cluster.1 <- unique(as.numeric(as.factor(cluster[,1])))\r\n level.cluster.2 <- unique(as.numeric(as.factor(cluster[,2])))\r\n if(length(level.cluster.1)<=length(level.cluster.2)){\r\n raw.cluster <- as.numeric(as.factor(cluster[,1]))\r\n bootcluster <- colnames(cluster)[1]\r\n }else{\r\n raw.cluster <- as.numeric(as.factor(cluster[,2]))\r\n bootcluster <- colnames(cluster)[2]\r\n }\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }else{\r\n raw.cluster <- as.numeric(as.factor(cluster[,bootcluster]))\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }\r\n cat(paste0(\"Mutiple Clustered Wild Bootstrap: (Boot)Clustered at \",bootcluster,\" level.\\n\"))\r\n }\r\n }\r\n\r\n if(length(en.var.x)>0){\r\n en.var.x.matrix <- matrix(dx[,en.var.x],ncol=length(en.var.x))\r\n sub.lm <- simpleols(Y=en.var.x.matrix,X=dz)\r\n en.var.x.coef <- sub.lm[['coef']]\r\n colnames(en.var.x.coef) <- en.var.x\r\n en.var.x.hat <- sub.lm[['Y_hat']]\r\n colnames(en.var.x.hat) <- en.var.x\r\n res.en.x <- en.var.x.res <- sub.lm[[\"u_hat\"]]\r\n en.var.x.fitted <- matrix(x[,en.var.x],ncol=length(en.var.x)) - en.var.x.res\r\n colnames(en.var.x.fitted) <- colnames(en.var.x.res) <- colnames(en.var.x.hat) <- en.var.x \r\n }\r\n ####\r\n\r\n if (refinement == 0) {\r\n ## wild bootstrap\r\n cat(\"Wild Bootstrap without Percentile-t Refinement.\\n\")\r\n boot.coef <- matrix(NA, p, nboots)\r\n \r\n one.boot <- function(num = NULL) { \r\n if (!is.null(cluster)) {\r\n ## wild boot by cluster \r\n res.p <- rep(0,dim(cluster)[1])\r\n for (j in 1:length(level.cluster)) {\r\n temp.level <- sample(c(-1,1), 1)\r\n res.p[which(raw.cluster==level.cluster[j])] <- temp.level\r\n }\r\n res.p <- as.matrix(res.p)\r\n } else {\r\n res.p <- as.matrix(sample(c(-1, 1), dim(y)[1], replace = TRUE))\r\n }\r\n\r\n y.boot <- y.fit + res.p * res \r\n \r\n if(length(en.var.x)>0){\r\n x.boot.en <- matrix(en.var.x.fitted + sweep(en.var.x.res, MARGIN=1, res.p, `*`),ncol=length(en.var.x)) \r\n colnames(x.boot.en) <- en.var.x\r\n }else{\r\n x.boot.en <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n }\r\n \r\n if(length(ex.var.x)>0){\r\n x.boot.ex <- matrix(x[,ex.var.x],ncol=length(ex.var.x))\r\n colnames(x.boot.ex) <- ex.var.x\r\n }else{\r\n x.boot.ex <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n }\r\n\r\n x.boot <- cbind(x.boot.en,x.boot.ex)\r\n x.boot <- x.boot[,colnames(x)]\r\n #only need coefficients, don't need se\r\n boot.model.iv <- try(ivfastplm.core(y = y.boot, x = x.boot,z=z, ind = ind, \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num,\r\n df.use = df.use, df.cl.use = df.cl.use, need.fe = FALSE, iv.test = FALSE\r\n ))\r\n\r\n if ('try-error' %in% class(boot.model.iv)) {\r\n return(rep(NA, p))\r\n } else {\r\n return(c(boot.model.iv$coefficients))\r\n }\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n\r\n P_x <- as.matrix(apply(boot.coef, 1, get.pvalue))\r\n stderror <- as.matrix(apply(boot.coef, 1, sd, na.rm = TRUE))\r\n\r\n CI <- t(apply(boot.coef, 1, quantile, c(0.025, 0.975), na.rm = TRUE))\r\n ## rewrite uncertainty estimates\r\n est.coefficients <- cbind(model.iv$coefficients, stderror,model.iv$coefficients/stderror, P_x, CI)\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\",\"Z Value\", \"P Value\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(dx)\r\n model.iv$est.coefficients <- est.coefficients\r\n\r\n vcov <- as.matrix(cov(t(boot.coef),use=\"na.or.complete\"))\r\n colnames(vcov) <- colnames(dx)\r\n rownames(vcov) <- colnames(dx)\r\n model.iv$vcov <- vcov\r\n }\r\n\r\n if(refinement==1){\r\n if(is.null(pos)==TRUE){\r\n cat(\"Unrestricted Wild Bootstrap with Percentile-t Refinement.\\n\")\r\n boot.coef <- matrix(NA, p, nboots)\r\n boot.wald <- rep(NA, nboots)\r\n one.boot <- function(num = NULL) {\r\n if (!is.null(cluster)) {\r\n ## wild boot by cluster \r\n res.p <- rep(0,dim(cluster)[1])\r\n for (j in 1:length(level.cluster)) {\r\n temp.level <- sample(c(-1,1), 1)\r\n res.p[which(raw.cluster==level.cluster[j])] <- temp.level\r\n }\r\n res.p <- as.matrix(res.p)\r\n } else {\r\n res.p <- as.matrix(sample(c(-1, 1), dim(y)[1], replace = TRUE))\r\n }\r\n y.boot <- y.fit + res.p * res \r\n \r\n if(length(en.var.x)>0){\r\n x.boot.en <- matrix(en.var.x.fitted + sweep(en.var.x.res, MARGIN=1, res.p, `*`),ncol=length(en.var.x)) \r\n colnames(x.boot.en) <- en.var.x\r\n }else{\r\n x.boot.en <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n }\r\n \r\n if(length(ex.var.x)>0){\r\n x.boot.ex <- matrix(x[,ex.var.x],ncol=length(ex.var.x))\r\n colnames(x.boot.ex) <- ex.var.x\r\n }else{\r\n x.boot.ex <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n } \r\n x.boot <- cbind(x.boot.en,x.boot.ex)\r\n x.boot <- x.boot[,colnames(x)]\r\n\r\n boot.model <- try(ivfastplm.core(y = y.boot, x = x.boot, z = z, ind = ind, robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = cluster, core.num = core.num,\r\n df.use = df.use,\r\n df.cl.use = df.cl.use))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(NA)\r\n } else {\r\n boot.use <- (boot.model$est.coefficients[, \"Coef\"]-model.iv$est.coefficients[, \"Coef\"])/boot.model$est.coefficients[, \"Std. Error\"]\r\n return(c(boot.use))\r\n }\r\n }\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n wald.refinement <- matrix(NA,nrow=0,ncol=6)\r\n null.totest <- model.iv$est.coefficients[,'t value']\r\n for(k in 1:length(null.totest)){\r\n p.refine <- get.pvalue(boot.coef[k,],to_test=null.totest[k])\r\n CI.refine <- quantile(boot.coef[k,], probs = c(0.025,0.975), na.rm = TRUE)*model.iv$est.coefficients[k,'Std. Error'] + model.iv$est.coefficients[k,'Coef']\r\n refine.sub <- c(model.iv$est.coefficients[k,'Coef'],\r\n model.iv$est.coefficients[k,'Std. Error'],\r\n model.iv$est.coefficients[k,'t value'],\r\n p.refine,\r\n CI.refine[1],\r\n CI.refine[2])\r\n wald.refinement <- rbind(wald.refinement,refine.sub)\r\n }\r\n colnames(wald.refinement) <- c(\"Coef\",\"Std Error\",\"t value\",\r\n \"Refined P value\",\"Refined CI_lower\",\r\n \"Refined CI_upper\")\r\n rownames(wald.refinement) <- colnames(dx)\r\n model.iv$refinement <- list(wald.refinement = wald.refinement, boot.wald = boot.coef)\r\n }\r\n\r\n if(is.null(pos)==FALSE){\r\n\r\n if(is.null(test.value)==TRUE){\r\n test.value <- 0\r\n }\r\n\r\n if(pos %in% en.var.x){\r\n cat(\"Restricted Wild Efficient Residual Bootstrap with Percentile-t Refinement.\\n\")\r\n if(length(en.var.x)==1){\r\n dy.restricted <- dy - test.value*dx[,en.var.x]\r\n dx1 <- matrix(dx[,ex.var.x],ncol=length(ex.var.x))\r\n inv.dx1 <- solve(t(dx1)%*%dx1)\r\n reg1.coef <- inv.dx1%*%t(dx1)%*%dy.restricted\r\n u.hat1 <- dy.restricted - dx1%*%reg1.coef\r\n \r\n dy2 <- dx[,en.var.x]\r\n dx2 <- cbind(dz,u.hat1)\r\n inv.dx2 <- solve(t(dx2)%*%dx2)\r\n reg2.coef <- inv.dx2%*%t(dx2)%*%dy2\r\n u.hat2 <- dy2 - dx2%*%reg2.coef + reg2.coef[dim(dz)[2]+1,1]*u.hat1\r\n\r\n one.boot <- function(num = NULL) {\r\n if (!is.null(cluster)) {\r\n ## wild boot by cluster \r\n res.p <- rep(0,dim(cluster)[1])\r\n for (j in 1:length(level.cluster)) {\r\n temp.level <- sample(c(-1,1), 1)\r\n res.p[which(raw.cluster==level.cluster[j])] <- temp.level\r\n }\r\n res.p <- as.matrix(res.p)\r\n } else {\r\n res.p <- as.matrix(sample(c(-1, 1), dim(y)[1], replace = TRUE))\r\n }\r\n\r\n y.boot <- y-u.hat1+res.p * u.hat1\r\n en.x.boot <- x[,en.var.x] - u.hat2 + res.p * u.hat2\r\n\r\n if(length(ex.var.x)>0){\r\n x.boot.ex <- matrix(x[,ex.var.x],ncol=length(ex.var.x))\r\n colnames(x.boot.ex) <- ex.var.x\r\n }else{\r\n x.boot.ex <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n } \r\n\r\n x.boot <- cbind(en.x.boot,x.boot.ex)\r\n colnames(x.boot) <- c(en.var.x,ex.var.x) \r\n x.boot <- x.boot[,colnames(x)] \r\n\r\n boot.model <- try(ivfastplm.core(y = y.boot, x = x.boot, z = z, ind = ind, robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = cluster, core.num = core.num,\r\n df.use = df.use,\r\n df.cl.use = df.cl.use))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(NA)\r\n } else {\r\n boot.use <- (boot.model$est.coefficients[pos, \"Coef\"]-test.value)/boot.model$est.coefficients[pos, \"Std. Error\"]\r\n return(c(boot.use))\r\n }\r\n }\r\n }\r\n\r\n if(length(en.var.x)>1){\r\n dy.restricted <- dy - test.value*dx[,pos]\r\n en.dx <- dx[,en.var.x]\r\n pos.index <- which(colnames(en.dx)==pos)\r\n en.dx.other <- matrix(en.dx[,-pos.index],ncol=dim(en.dx)[2]-1)\r\n \r\n #a simple 2sls\r\n dx1 <- cbind(en.dx.other,dx[,ex.var.x])\r\n inv.dx1 <- solve(t(dx1)%*%dx1)\r\n dz1 <- dz\r\n inv.dz1 <- inv.z\r\n Pdz1 <- dz1%*%inv.dz1%*%t(dz1)\r\n inv.dxPzdx1 <- solve(t(dx1)%*%Pdz1%*%dx1)\r\n reg1.coef <- matrix(inv.dxPzdx1%*%t(dx1)%*%Pdz1%*%dy.restricted,ncol=1)\r\n u.hat1 <- matrix(dy.restricted-dx1%*%reg1.coef,ncol=1)\r\n\r\n dy2 <- dx[,en.var.x]\r\n dx2 <- cbind(dz,u.hat1)\r\n inv.dx2 <- solve(t(dx2)%*%dx2)\r\n reg2.coef <- inv.dx2%*%t(dx2)%*%dy2\r\n\r\n reg2.coef.slice <- matrix(reg2.coef[(dim(dz)[2]+1),],ncol=dim(reg2.coef)[2])\r\n u.hat2 <- dy2 - dx2%*%reg2.coef + kronecker(reg2.coef.slice,u.hat1)\r\n\r\n one.boot <- function(num = NULL) {\r\n if (!is.null(cluster)) {\r\n ## wild boot by cluster \r\n res.p <- rep(0,dim(cluster)[1])\r\n for (j in 1:length(level.cluster)) {\r\n temp.level <- sample(c(-1,1), 1)\r\n res.p[which(raw.cluster==level.cluster[j])] <- temp.level\r\n }\r\n res.p <- as.matrix(res.p)\r\n } else {\r\n res.p <- as.matrix(sample(c(-1, 1), dim(y)[1], replace = TRUE))\r\n }\r\n\r\n y.boot <- y-u.hat1+res.p * u.hat1\r\n en.x.boot <- matrix(x[,en.var.x] - u.hat2 + sweep(u.hat2, MARGIN=1, res.p, `*`),ncol=length(en.var.x))\r\n if(length(ex.var.x)>0){\r\n x.boot.ex <- matrix(x[,ex.var.x],ncol=length(ex.var.x))\r\n colnames(x.boot.ex) <- ex.var.x\r\n }else{\r\n x.boot.ex <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n } \r\n\r\n x.boot <- cbind(en.x.boot,x.boot.ex)\r\n colnames(x.boot) <- c(en.var.x,ex.var.x) \r\n x.boot <- x.boot[,colnames(x)] \r\n\r\n boot.model <- try(ivfastplm.core(y = y.boot, x = x.boot, z = z, ind = ind, robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = cluster, core.num = core.num,\r\n df.use = df.use,\r\n df.cl.use = df.cl.use))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(NA)\r\n } else {\r\n boot.use <- (boot.model$est.coefficients[pos, \"Coef\"]-test.value)/boot.model$est.coefficients[pos, \"Std. Error\"]\r\n return(c(boot.use))\r\n }\r\n }\r\n }\r\n\r\n boot.wald <- rep(NA, nboots)\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n boot.wald <- c(unlist(boot.out)) \r\n } else {\r\n for (i in 1:nboots) {\r\n boot.wald[i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n\r\n p.refine <- get.pvalue(boot.wald,to_test=(model.iv$est.coefficients[pos, \"Coef\"]-test.value)/model.iv$est.coefficients[pos, \"Std. Error\"])\r\n CI.refine <- quantile(boot.wald, probs = c(0.025,0.975), na.rm = TRUE)*model.iv$est.coefficients[pos,'Std. Error'] + model.iv$est.coefficients[pos, \"Coef\"]\r\n\r\n refine.sub <- c(model.iv$est.coefficients[pos,'Coef'],\r\n model.iv$est.coefficients[pos,'Std. Error'],\r\n (model.iv$est.coefficients[pos, \"Coef\"]-test.value)/model.iv$est.coefficients[pos, \"Std. Error\"],\r\n p.refine,\r\n #paste0(pos,\"=\",test.value),\r\n CI.refine[1],\r\n CI.refine[2])\r\n \r\n refine.sub <- matrix(refine.sub,nrow=1)\r\n #refine.sub <- as.data.frame(refine.sub)\r\n rownames(refine.sub) <- pos\r\n colnames(refine.sub) <- c(\"Coef\",\"Std Error\",\"t value(H0)\",\r\n \"Refined P value\",\"Refined CI_lower\",\"Refined CI_upper\")\r\n model.iv$refinement <- list(wald.refinement = refine.sub, boot.wald = boot.wald)\r\n }\r\n\r\n if(pos %in% ex.var.x){\r\n # wild restricted residual bootstrap\r\n cat(\"Wild Restricted Bootstrap with Percentile-t Refinement.\\n\")\r\n boot.wald <- rep(NA, nboots)\r\n\r\n dy.restricted <- dy - test.value*dx[,pos]\r\n pos.index <- which(colnames(dx)==pos)\r\n dx.other <- matrix(dx[,-pos.index],ncol=dim(dx)[2]-1)\r\n\r\n #a simple 2sls\r\n dx1 <- dx.other\r\n inv.dx1 <- solve(t(dx1)%*%dx1)\r\n dz1 <- dz\r\n inv.dz1 <- inv.z\r\n Pdz1 <- dz1%*%inv.dz1%*%t(dz1)\r\n inv.dxPzdx1 <- solve(t(dx1)%*%Pdz1%*%dx1)\r\n reg1.coef <- matrix(inv.dxPzdx1%*%t(dx1)%*%Pdz1%*%dy.restricted,ncol=1)\r\n u.hat1 <- matrix(dy.restricted-dx1%*%reg1.coef,ncol=1)\r\n\r\n boot.wald <- rep(NA, nboots)\r\n one.boot <- function(num = NULL) {\r\n if (!is.null(cluster)) {\r\n ## wild boot by cluster \r\n res.p <- rep(0,dim(cluster)[1])\r\n for (j in 1:length(level.cluster)) {\r\n temp.level <- sample(c(-1,1), 1)\r\n res.p[which(raw.cluster==level.cluster[j])] <- temp.level\r\n }\r\n res.p <- as.matrix(res.p)\r\n } else {\r\n res.p <- as.matrix(sample(c(-1, 1), dim(y)[1], replace = TRUE))\r\n }\r\n y.boot <- y - u.hat1 + res.p * u.hat1\r\n x.boot.en <- matrix(en.var.x.fitted + sweep(en.var.x.res, MARGIN=1, res.p, `*`),ncol=length(en.var.x))\r\n colnames(x.boot.en) <- en.var.x\r\n\r\n if(length(ex.var.x)>0){\r\n x.boot.ex <- matrix(x[,ex.var.x],ncol=length(ex.var.x))\r\n colnames(x.boot.ex) <- ex.var.x\r\n }else{\r\n x.boot.ex <- matrix(NA,ncol=0,nrow=dim(dy)[1])\r\n } \r\n\r\n x.boot <- cbind(x.boot.en,x.boot.ex)\r\n colnames(x.boot) <- c(en.var.x,ex.var.x) \r\n x.boot <- x.boot[,colnames(x)] \r\n\r\n boot.model <- try(ivfastplm.core(y = y.boot, x = x.boot, z = z, ind = ind, robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = cluster, core.num = core.num,\r\n df.use = df.use,\r\n df.cl.use = df.cl.use))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(NA)\r\n } else {\r\n boot.use <- (boot.model$est.coefficients[pos, \"Coef\"]-test.value)/boot.model$est.coefficients[pos, \"Std. Error\"]\r\n return(c(boot.use))\r\n }\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.wald[j] <- c(unlist(boot.out[[j]])) \r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.wald[i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n \r\n p.refine <- get.pvalue(boot.wald,to_test=(model.iv$est.coefficients[pos, \"Coef\"]-test.value)/model.iv$est.coefficients[pos, \"Std. Error\"])\r\n CI.refine <- quantile(boot.wald, probs = c(0.025,0.975), na.rm = TRUE)*model.iv$est.coefficients[pos,'Std. Error'] + model.iv$est.coefficients[pos, \"Coef\"]\r\n\r\n refine.sub <- c(model.iv$est.coefficients[pos,'Coef'],\r\n model.iv$est.coefficients[pos,'Std. Error'],\r\n (model.iv$est.coefficients[pos, \"Coef\"]-test.value)/model.iv$est.coefficients[pos, \"Std. Error\"],\r\n p.refine,\r\n #paste0(pos,\"=\",test.value),\r\n CI.refine[1],\r\n CI.refine[2])\r\n \r\n refine.sub <- matrix(refine.sub,nrow=1)\r\n #refine.sub <- as.data.frame(refine.sub)\r\n rownames(refine.sub) <- pos\r\n colnames(refine.sub) <- c(\"Coef\",\"Std Error\",\"t value(H0)\",\r\n \"Refined P value\",\"Refined CI_lower\",\"Refined CI_upper\")\r\n model.iv$refinement <- list(wald.refinement = refine.sub, boot.wald = boot.wald)\r\n }\r\n }\r\n }\r\n }\r\n else{\r\n \r\n if (jackknife ==1 || is.null(cluster)) { \r\n jack.pos <- 1\r\n if (jackknife == 1) {\r\n nboots <- length(unique(ind[,1]))\r\n jack.pos <- as.numeric(as.factor(ind[,1]))\r\n }\r\n boot.coef <- matrix(NA, p, nboots)\r\n \r\n if(refinement==0){\r\n if (jackknife == 1){\r\n cat(\"Jackknife without Percentile-t Refinement.\\n\")\r\n }else{\r\n cat(\"Pairs Bootstrap without Percentile-t Refinement.\\n\")\r\n }\r\n\r\n one.boot <- function(num = NULL) {\r\n if (is.null(num)) {\r\n boot.id <- sample(1:dim(y)[1], dim(y)[1], replace = TRUE)\r\n } else {\r\n boot.id <- (1:dim(y)[1])[which(jack.pos != num)]\r\n }\r\n \r\n boot.model <- try(ivfastplm.core(y = as.matrix(y[boot.id,]), \r\n x = as.matrix(x[boot.id,]),\r\n z = as.matrix(z[boot.id,]), \r\n ind = as.matrix(ind[boot.id,]), \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num))\r\n \r\n if ('try-error' %in% class(boot.model)) {\r\n return(rep(NA, p))\r\n } else {\r\n return(c(boot.model$coefficients))\r\n }\r\n }\r\n\r\n boot.seq <- NULL\r\n if (jackknife == 1) {\r\n boot.seq <- unique(jack.pos)\r\n }\r\n \r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot(boot.seq[j]))\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot(boot.seq[i])\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n\r\n if (jackknife == 0) {\r\n P_x <- as.matrix(apply(boot.coef, 1, get.pvalue))\r\n stderror <- as.matrix(apply(boot.coef, 1, sd, na.rm = TRUE))\r\n CI <- t(apply(boot.coef, 1, quantile, c(0.025, 0.975), na.rm = TRUE))\r\n ## rewrite uncertainty estimates\r\n est.coefficients <- cbind(model.iv$coefficients, stderror,model.iv$coefficients/stderror, P_x, CI)\r\n vcov <- as.matrix(cov(t(boot.coef),use=\"na.or.complete\"))\r\n } else {\r\n beta.j <- jackknifed(model.iv$coefficients, boot.coef, 0.05)\r\n est.coefficients <- cbind(model.iv$coefficients, beta.j$se,model.iv$coefficients/beta.j$se, beta.j$P, beta.j$CI.l, beta.j$CI.u)\r\n vcov <- beta.j$Yvcov\r\n }\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\",\"Z Value\", \"P Value\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(dx)\r\n model.iv$est.coefficients <- est.coefficients\r\n\r\n colnames(vcov) <- colnames(dx)\r\n rownames(vcov) <- colnames(dx)\r\n model.iv$vcov <- vcov\r\n }\r\n\r\n if(refinement==1){\r\n if (jackknife == 1){\r\n stop(\"Can't refine a Jackknife P-Value,\\n\")\r\n #cat(\"Jackknife with Percentile-t Refinement.\\n\")\r\n }else{\r\n cat(\"Pairs Bootstrap with Percentile-t Refinement.\\n\")\r\n }\r\n\r\n one.boot <- function(num = NULL) {\r\n boot.id <- sample(1:dim(y)[1], dim(y)[1], replace = TRUE)\r\n boot.model <- try(ivfastplm.core(y = as.matrix(y[boot.id,]), \r\n x = as.matrix(x[boot.id,]), \r\n z = as.matrix(z[boot.id,]),\r\n ind = as.matrix(ind[boot.id,]), \r\n robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = NULL, core.num = core.num))\r\n \r\n if ('try-error' %in% class(boot.model)) {\r\n return(rep(NA, p))\r\n } else {\r\n boot.use <- (boot.model$est.coefficients[, \"Coef\"]-model.iv$est.coefficients[, \"Coef\"])/boot.model$est.coefficients[, \"Std. Error\"]\r\n return(c(boot.use))\r\n }\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n \r\n wald.refinement <- matrix(NA,nrow=0,ncol=6)\r\n null.totest <- model.iv$est.coefficients[,'t value']\r\n for(k in 1:length(null.totest)){\r\n p.refine <- get.pvalue(boot.coef[k,],to_test=null.totest[k])\r\n CI.refine <- quantile(boot.coef[k,], probs = c(0.025,0.975), na.rm = TRUE)*model.iv$est.coefficients[k,'Std. Error'] + model.iv$est.coefficients[k,'Coef']\r\n refine.sub <- c(model.iv$est.coefficients[k,'Coef'],\r\n model.iv$est.coefficients[k,'Std. Error'],\r\n model.iv$est.coefficients[k,'t value'],\r\n p.refine,\r\n CI.refine[1],\r\n CI.refine[2])\r\n wald.refinement <- rbind(wald.refinement,refine.sub)\r\n }\r\n colnames(wald.refinement) <- c(\"Coef\",\"Std Error\",\"t value\",\r\n \"Refined P value\",\"Refined CI_lower\",\r\n \"Refined CI_upper\")\r\n rownames(wald.refinement) <- colnames(dx)\r\n model.iv$refinement <- list(wald.refinement = wald.refinement, boot.wald = boot.coef)\r\n }\r\n }\r\n else{ #clustered\r\n if (refinement == 0) {\r\n cat(\"Pairs Bootstrap without Percentile-t Refinement.\\n\")\r\n boot.coef <- matrix(NA, p, nboots)\r\n if (dim(cluster)[2] == 1) {\r\n ## one-way cluster \r\n raw.cluster <- as.numeric(as.factor(cluster))\r\n level.cluster <- unique(raw.cluster)\r\n ## level.count <- table(raw.cluster)\r\n split.id <- split(1:dim(y)[1], raw.cluster)\r\n one.boot <- function(num = NULL) {\r\n level.id <- sample(level.cluster, length(level.cluster), replace = TRUE)\r\n boot.id <- c()\r\n for (j in 1:length(level.id)) {\r\n boot.id <- c(boot.id, split.id[[level.id[j]]])\r\n }\r\n boot.model <- try(ivfastplm.core(y = as.matrix(y[boot.id,]), \r\n x = as.matrix(x[boot.id,]), \r\n z = as.matrix(z[boot.id,]),\r\n ind = as.matrix(ind[boot.id,]), \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(rep(NA, p))\r\n } else {\r\n return(c(boot.model$coefficients))\r\n }\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n\r\n P_x <- as.matrix(apply(boot.coef, 1, get.pvalue))\r\n stderror <- as.matrix(apply(boot.coef, 1, sd, na.rm = TRUE))\r\n CI <- t(apply(boot.coef, 1, quantile, c(0.025, 0.975), na.rm = TRUE))\r\n ## rewrite uncertainty estimates\r\n est.coefficients <- cbind(model.iv$coefficients, stderror,model.iv$coefficients/stderror, P_x, CI)\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\",\"Z Value\", \"P Value\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(dx)\r\n model.iv$est.coefficients <- est.coefficients\r\n\r\n vcov <- as.matrix(cov(t(boot.coef),use=\"na.or.complete\"))\r\n colnames(vcov) <- colnames(dx)\r\n rownames(vcov) <- colnames(dx)\r\n model.iv$vcov <- vcov\r\n }\r\n else if (dim(cluster)[2] == 2) {\r\n ## two-way cluster\r\n boot.coef1 <- boot.coef2 <- boot.coef3 <- matrix(NA, p, nboots)\r\n ## level 1\r\n raw.cluster1 <- as.numeric(as.factor(cluster[,1]))\r\n level.cluster1 <- unique(raw.cluster1)\r\n ## level 2\r\n raw.cluster2 <- as.numeric(as.factor(cluster[,2]))\r\n level.cluster2 <- unique(raw.cluster2)\r\n ## intersection\r\n raw.cluster3 <- as.numeric(as.factor(paste(cluster[,1], \"-:-\", cluster[,2], sep = \"\")))\r\n level.cluster3 <- unique(raw.cluster3)\r\n\r\n split.id1 <- split(1:dim(y)[1], raw.cluster1)\r\n split.id2 <- split(1:dim(y)[1], raw.cluster2)\r\n split.id3 <- split(1:dim(y)[1], raw.cluster3)\r\n\r\n one.boot <- function(num = NULL) {\r\n ## level 1\r\n level.id1 <- sample(level.cluster1, length(level.cluster1), replace = TRUE)\r\n boot.id1 <- c()\r\n for (j in 1:length(level.id1)) {\r\n boot.id1 <- c(boot.id1, split.id1[[level.id1[j]]])\r\n }\r\n\r\n ## level 2\r\n level.id2 <- sample(level.cluster2, length(level.cluster2), replace = TRUE)\r\n boot.id2 <- c()\r\n for (j in 1:length(level.id2)) {\r\n boot.id2 <- c(boot.id2, split.id2[[level.id2[j]]])\r\n }\r\n\r\n ## intersection\r\n level.id3 <- sample(level.cluster3, length(level.cluster3), replace = TRUE)\r\n boot.id3 <- c()\r\n for (j in 1:length(level.id3)) {\r\n boot.id3 <- c(boot.id3, split.id3[[level.id3[j]]])\r\n }\r\n\r\n ## level 1\r\n boot.model1 <- try(ivfastplm.core(y = as.matrix(y[boot.id1,]), \r\n x = as.matrix(x[boot.id1,]),\r\n z = as.matrix(z[boot.id1,]), \r\n ind = as.matrix(ind[boot.id1,]), \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num))\r\n if ('try-error' %in% class(boot.model1)) {\r\n oneboot.coef1 <- rep(NA, p)\r\n } else {\r\n oneboot.coef1 <- c(boot.model1$coefficients)\r\n }\r\n\r\n ## level 2\r\n boot.model2 <- try(ivfastplm.core (y = as.matrix(y[boot.id2,]), \r\n x = as.matrix(x[boot.id2,]), \r\n z = as.matrix(z[boot.id2,]),\r\n ind = as.matrix(ind[boot.id2,]), \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num))\r\n if ('try-error' %in% class(boot.model2)) {\r\n oneboot.coef2 <- rep(NA, p)\r\n } else {\r\n oneboot.coef2 <- c(boot.model2$coefficients)\r\n }\r\n\r\n ## intersection\r\n boot.model3 <- try(ivfastplm.core (y = as.matrix(y[boot.id3,]), \r\n x = as.matrix(x[boot.id3,]), \r\n z = as.matrix(z[boot.id3,]),\r\n ind = as.matrix(ind[boot.id3,]), \r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 0, cl = NULL, core.num = core.num))\r\n if ('try-error' %in% class(boot.model3)) {\r\n oneboot.coef3 <- rep(NA, p)\r\n } else {\r\n oneboot.coef3 <- c(boot.model3$coefficients)\r\n }\r\n\r\n return(list(oneboot.coef1 = oneboot.coef1, \r\n oneboot.coef2 = oneboot.coef2,\r\n oneboot.coef3 = oneboot.coef3))\r\n\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef1[, j] <- c(boot.out[[j]]$oneboot.coef1)\r\n boot.coef2[, j] <- c(boot.out[[j]]$oneboot.coef2)\r\n boot.coef3[, j] <- c(boot.out[[j]]$oneboot.coef3)\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.sub <- one.boot()\r\n boot.coef1[, i] <- c(boot.sub$oneboot.coef1)\r\n boot.coef2[, i] <- c(boot.sub$oneboot.coef2)\r\n boot.coef3[, i] <- c(boot.sub$oneboot.coef3)\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n \r\n stderror1 <- as.matrix(apply(boot.coef1, 1, sd, na.rm = TRUE))\r\n stderror2 <- as.matrix(apply(boot.coef2, 1, sd, na.rm = TRUE))\r\n stderror3 <- as.matrix(apply(boot.coef3, 1, sd, na.rm = TRUE))\r\n stderror <- stderror1 + stderror2 - stderror3\r\n\r\n vcov1 <- as.matrix(cov(t(boot.coef1),use=\"na.or.complete\"))\r\n vcov2 <- as.matrix(cov(t(boot.coef2),use=\"na.or.complete\"))\r\n vcov3 <- as.matrix(cov(t(boot.coef3),use=\"na.or.complete\"))\r\n vcov <- vcov1 + vcov2 - vcov3\r\n colnames(vcov) <- colnames(dx)\r\n rownames(vcov) <- colnames(dx)\r\n model.iv$vcov <- vcov\r\n\r\n CI <- cbind(c(model.iv$coefficients) - qnorm(0.975)*c(stderror), c(model.iv$coefficients) + qnorm(0.975)*c(stderror))\r\n Zx <- c(model.iv$coefficients)/c(stderror)\r\n P_z <- 2 * min(1 - pnorm(Zx), pnorm(Zx))\r\n ## rewrite uncertainty estimates\r\n est.coefficients <- cbind(model.iv$coefficients, stderror, Zx, P_z, CI)\r\n colnames(est.coefficients) <- c(\"Coef\", \"Std. Error\", \"Z value\", \"Pr(>|Z|)\", \"CI_lower\", \"CI_upper\")\r\n rownames(est.coefficients) <- colnames(dx)\r\n model.iv$est.coefficients <- est.coefficients\r\n }\r\n }\r\n\r\n if(refinement==1){\r\n cat(\"Pairs Bootstrap with Percentile-t Refinement.\\n\")\r\n ## bootstrap refinement \r\n boot.coef <- matrix(NA, p, nboots)\r\n\r\n if(dim(cluster)[2]==1){\r\n ## one-way cluster \r\n raw.cluster <- as.numeric(as.factor(cluster))\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }\r\n if(dim(cluster)[2]==2){\r\n stop(\"For pairs bootstrap with refinement, please only specify one cluster variable.\\n\")\r\n if(is.null(bootcluster)){\r\n level.cluster.1 <- unique(as.numeric(as.factor(cluster[,1])))\r\n level.cluster.2 <- unique(as.numeric(as.factor(cluster[,2])))\r\n if(length(level.cluster.1)<=length(level.cluster.2)){\r\n raw.cluster <- as.numeric(as.factor(cluster[,1]))\r\n bootcluster <- colnames(cluster)[1]\r\n }else{\r\n raw.cluster <- as.numeric(as.factor(cluster[,2]))\r\n bootcluster <- colnames(cluster)[2]\r\n }\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }else{\r\n raw.cluster <- as.numeric(as.factor(cluster[,bootcluster]))\r\n level.cluster <- unique(raw.cluster)\r\n level.count <- table(raw.cluster)\r\n }\r\n cat(paste0(\"Mutiple Clustered Pairs Bootstrap with Refinement: (Boot)Clustered at \",bootcluster,\" level.\\n\"))\r\n }\r\n\r\n split.id <- split(1:dim(y)[1], raw.cluster)\r\n\r\n one.boot <- function(num = NULL) {\r\n level.id <- sample(level.cluster, length(level.cluster), replace = TRUE)\r\n boot.id <- c()\r\n boot.cluster <- c()\r\n for (j in 1:length(level.id)) {\r\n boot.id <- c(boot.id, split.id[[level.id[j]]])\r\n boot.cluster <- c(boot.cluster, rep(j, level.count[level.id[j]]))\r\n }\r\n boot.cluster <- as.matrix(boot.cluster)\r\n\r\n boot.model <- try(ivfastplm.core (y = as.matrix(y[boot.id,]), \r\n x = as.matrix(x[boot.id,]), \r\n z = as.matrix(z[boot.id,]),\r\n ind = as.matrix(ind[boot.id,]), robust = robust,\r\n sfe.index = sfe.index, cfe.index = cfe.index, \r\n se = 1, cl = boot.cluster, core.num = core.num))\r\n if ('try-error' %in% class(boot.model)) {\r\n return(rep(NA, p))\r\n } else {\r\n return(c(boot.model$coefficients - model.iv$coefficients)/c(boot.model$est.coefficients[, \"Std. Error\"]))\r\n }\r\n }\r\n\r\n if (parallel == TRUE) {\r\n boot.out <- foreach(j = 1:nboots, \r\n .inorder = FALSE,\r\n .export = use.fun,\r\n .packages = c(\"fastplm\")\r\n ) %dopar% {\r\n return(one.boot())\r\n }\r\n for (j in 1:nboots) { \r\n boot.coef[, j] <- c(boot.out[[j]])\r\n }\r\n } else {\r\n for (i in 1:nboots) {\r\n boot.coef[, i] <- one.boot()\r\n if (i%%50==0) cat(i) else cat(\".\")\r\n }\r\n }\r\n \r\n wald.refinement <- matrix(NA,nrow=0,ncol=6)\r\n null.totest <- model.iv$est.coefficients[,'t value']\r\n for(k in 1:length(null.totest)){\r\n p.refine <- get.pvalue(boot.coef[k,],to_test=null.totest[k])\r\n CI.refine <- quantile(boot.coef[k,], probs = c(0.025,0.975), na.rm = TRUE)*model.iv$est.coefficients[k,'Std. Error'] + model.iv$est.coefficients[k,'Coef']\r\n refine.sub <- c(model.iv$est.coefficients[k,'Coef'],\r\n model.iv$est.coefficients[k,'Std. Error'],\r\n model.iv$est.coefficients[k,'t value'],\r\n p.refine,\r\n CI.refine[1],\r\n CI.refine[2])\r\n wald.refinement <- rbind(wald.refinement,refine.sub)\r\n }\r\n colnames(wald.refinement) <- c(\"Coef\",\"Std Error\",\"t value\",\r\n \"Refined P value\",\"Refined CI_lower\",\r\n \"Refined CI_upper\")\r\n rownames(wald.refinement) <- colnames(dx)\r\n model.iv$refinement <- list(wald.refinement = wald.refinement, boot.wald = boot.coef)\r\n } \r\n }\r\n }\r\n if(parallel==TRUE){\r\n suppressWarnings(stopCluster(pcl))\r\n }\r\n\r\n \r\n\r\n\r\n\r\n\r\n return(model.iv)\r\n \r\n}", "meta": {"hexsha": "210511ea28e2a5e24171b46db561384b267f8e40", "size": 52831, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ivfastplm_boot.r", "max_stars_repo_name": "xuyiqing/fastplm", "max_stars_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-09-02T17:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T12:54:00.000Z", "max_issues_repo_path": "R/ivfastplm_boot.r", "max_issues_repo_name": "xuyiqing/fastplm", "max_issues_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-01-07T17:07:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T05:58:47.000Z", "max_forks_repo_path": "R/ivfastplm_boot.r", "max_forks_repo_name": "xuyiqing/fastplm", "max_forks_repo_head_hexsha": "f80a68cfa890774f83713637ce969ace4bb0c9c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6, "max_forks_repo_forks_event_min_datetime": "2019-09-02T00:58:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T00:55:38.000Z", "avg_line_length": 51.7950980392, "max_line_length": 176, "alphanum_fraction": 0.3678332797, "num_tokens": 10901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.32660313102624683}} {"text": "# 4. faza: Napredna analiza podatkov\nsetwd(\"/Users/blazpovh/Documents/R_projektna_naloga/APPR-2021-22-Blaz-Povh/\")\nTabela_porabe1 <- read.csv(\"~/Documents/R_projektna_naloga/APPR-2021-22-Blaz-Povh/podatki/zdruzeni_podatki/Tabela_porabe.csv\", sep=\"\")\n\ndnevna_poraba <-rowSums(Tabela_porabe1[ ,3:98],is.na(Tabela_porabe1) == FALSE)\nlength(dnevna_poraba)\nporabniki <- labels(table(Tabela_porabe1$porabnik))[[1]]\n\npovpr_poraba=c()\nfor (i in 1:length(porabniki)){\n print(i)\n poraba=dnevna_poraba[Tabela_porabe1$porabnik==porabniki[i]]\n povpr_poraba[i]=mean(poraba)\n}\nfrekvenca <- c(1:51)\ndata_povpr_poraba <- data.frame(povpr_poraba,frekvenca)\n\njpeg(\"slike/prikaz_skupne_povprecne_porabe_za_razlicne_porabnike.jpg\")\nchol <- data_povpr_poraba\nqplot(chol$povpr_poraba, \n geom = \"histogram\",\n binwidth= 40,\n main = \"Povprečna poraba el. energije za različne porabnike\",\n xlab = \"Povprečna poraba\",\n ylab = \"Frekvenca\",\n ylim = c(0,10))\ndev.off()\njpeg(\"slike/prikaz_skupne_povprecne_porabe_za_razlicne_meritve.jpg\")\nTabela_delovnih_dni <- filter(Tabela_porabe1, Prosti_dan == \"FALSE\")\nmeritev3 <- colMeans(Tabela_delovnih_dni[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np3 <-plot(meritev3, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za različne tipe dni\",xaxt='n')\nmeritev1 <- colMeans(Tabela_porabe1[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np1 <-points(meritev1, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za razl. meritve\",xaxt='n',col=\"blue\")\nTabela_prostih_dni <- filter(Tabela_porabe1, Prosti_dan == \"TRUE\")\nmeritev2 <- colMeans(Tabela_prostih_dni[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np2 <-points(meritev2, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za proste dni\",xaxt='n',col=\"red\")\nTabela_delovnih_dni <- filter(Tabela_porabe1, Prosti_dan == \"FALSE\")\nmeritev3 <- colMeans(Tabela_delovnih_dni[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np3 <-points(meritev3, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za delavne dni\",xaxt='n',col=\"green\")\nxlabels=c(\"3h\",\"6h\",\"9h\",\"12h\",\"15h\",\"18h\",\"21h\",\"24h\")\naxis(side=1, at=c(12,24,36,48,60,72,84,96),labels=xlabels)\nlegend(title = \"Legenda\", legend = c(\"vsi dnevi\",\"prosti dnevi\",\"delovni dnevi\"),\"topright\",col = c(\"blue\",\"red\",\"green\"),lty = 1)\ndev.off()\n\njpeg(\"slike/prikaz_skupne_povprecne_porabe_za_proste_dni.jpg\")\nTabela_prostih_dni <- filter(Tabela_porabe1, Prosti_dan == \"TRUE\")\nmeritev2 <- colMeans(Tabela_prostih_dni[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np2 <-plot(meritev2, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za proste dni\",xaxt='n')\nxlabels=c(\"3h\",\"6h\",\"9h\",\"12h\",\"15h\",\"18h\",\"21h\",\"24h\")\naxis(side=1, at=c(12,24,36,48,60,72,84,96),labels=xlabels)\ndev.off()\n\njpeg(\"slike/prikaz_skupne_povprecne_porabe_za_delovne_dni.jpg\")\nTabela_delovnih_dni <- filter(Tabela_porabe1, Prosti_dan == \"FALSE\")\nmeritev3 <- colMeans(Tabela_delovnih_dni[ , 3:98 ],is.na(Tabela_porabe1)== FALSE)\np3 <-plot(meritev3, type = \"o\",pch = 20, xlab=\"čas\",ylab = \"povprečna poraba\",main = \"Graf povprečne poraba el. energije za delavne dni\",xaxt='n')\nxlabels=c(\"3h\",\"6h\",\"9h\",\"12h\",\"15h\",\"18h\",\"21h\",\"24h\")\naxis(side=1, at=c(12,24,36,48,60,72,84,96),labels=xlabels)\ndev.off()\n\njpeg(\"slike/prikaz_skupne_povprecne_porabe_za_razlicne_dneve.jpg\")\npar(mar=c(5,6,4,1)+.0001)\nplot(c(0,97),c(0.5,4),main=\"Povprečna poraba za dneve v tednu\",type = \"n\",pch=20, xlab = \"čas\", ylab = \"povprečna poraba\",xaxt='n')\npovpr_poraba_ponedeljek <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Monday\")[ ,3:98])\ngraf_ponedeljek <- points(povpr_poraba_ponedeljek,type = \"o\",pch=20,xaxt='n',col=\"black\")\npovpr_poraba_torek <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Tuesday\")[ ,3:98])\ngraf_torek <- points(povpr_poraba_torek, type = \"o\",pch=20,xaxt='n',col=\"red\")\npovpr_poraba_sreda <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Wednesday\")[ ,3:98])\ngraf_sreda <- points(povpr_poraba_sreda, type = \"o\",pch=20,xaxt='n',col=\"blue\")\npovpr_poraba_cetrtek <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Thursday\")[ ,3:98])\ngraf_cetrtek <- points(povpr_poraba_cetrtek, type = \"o\",pch=20,xaxt='n',col=\"green\")\npovpr_poraba_petek <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Friday\")[ ,3:98])\ngraf_petek <- points(povpr_poraba_petek, type = \"o\",pch=20,xaxt='n',col=\"orange\")\npovpr_poraba_sobota <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Saturday\")[ ,3:98])\ngraf_sobota <- points(povpr_poraba_sobota, type = \"o\",pch=20,xaxt='n',col=\"yellow\")\npovpr_poraba_nedelja <- colMeans(filter(Tabela_porabe1, Ime_dneva ==\"Sunday\")[ ,3:98])\ngraf_nedelja <- points(povpr_poraba_nedelja, type = \"o\",pch=20,xaxt='n',col=\"purple\")\nxlabels=c(\"3h\",\"6h\",\"9h\",\"12h\",\"15h\",\"18h\",\"21h\",\"24h\")\naxis(side=1, at=c(12,24,36,48,60,72,84,96),labels=xlabels)\nlegend(title = \"Legenda\", legend = c(\"ponedeljek\",\"torek\",\"sreda\",\"cetrtek\",\"petek\",\"sobota\",\"nedelja\"),\"topright\",col = c(\"black\",\"red\",\"blue\",\"green\",\"orange\",\"yellow\",\"purple\"),lty=1)\ndev.off()\n\n\n# *********************************************** \n# od tu naprej imam analizo za vremenske podatke\n# **********************************************\ndata_vreme2_tidy <- read.table(\"podatki/zdruzeni_podatki/data_vreme2_tidy.txt\",sep=\" \")\ndatumi <- (data_vreme2_tidy$datum)\npadavine_po_dnevih <- data.frame(rowSums(data_vreme2_tidy[ ,4:51], is.na(data_vreme2_tidy) == FALSE))\ncolnames(padavine_po_dnevih) <- c('Kolicina padavin za dan')\nrownames(padavine_po_dnevih) <-c(datumi)\nwrite.table(padavine_po_dnevih,\"podatki/zdruzeni_podatki/padavine_po_dnevih.txt\",sep=\" \")\n\ntemperature_po_dnevih <- data.frame(rowMeans(data_vreme2_tidy[ ,52:99], is.na(data_vreme2_tidy) == FALSE))\ncolnames(temperature_po_dnevih) <- c('Skupna temperatura za dan')\nrownames(temperature_po_dnevih) <-c(datumi)\nwrite.table(temperature_po_dnevih,\"podatki/zdruzeni_podatki/temperature_po_dnevih.txt\",sep=\" \")\n\npadavine_po_urah <- data.frame(colSums(data_vreme2_tidy[ ,4:51]))\ncolnames(padavine_po_urah) <- c('Povprecna kol padavina za to uro')\nwrite.table(padavine_po_urah,\"podatki/zdruzeni_podatki/padavine_po_urah.txt\",sep=\" \")\n\ntemperature_po_urah <- data.frame(colMeans(data_vreme2_tidy[ ,52:99], is.na(data_vreme2_tidy) == FALSE))\ncolnames(temperature_po_urah) <- c('Povprecna temperatura za vsako casovno obdobje')\nwrite.table(temperature_po_urah,\"podatki/zdruzeni_podatki/temperature_po_urah.txt\",sep=\" \")\n\n\n# *************************************************\n# Korelacije\n# *************************************************\npovpr_poraba_za_vsak_dan <-rowMeans(Tabela_porabe1[ ,3:98])\npovpr_poraba_matrika <- t(matrix(povpr_poraba_za_vsak_dan,198,51))\npovpr_poraba_za_vsak_dan1 <- as.vector(colSums(povpr_poraba_matrika))\npovpr_poraba_za_vsak_dan1<-povpr_poraba_za_vsak_dan1[-198]\npovprecna_T_za_vsak_dan <- temperature_po_dnevih$`Skupna temperatura za dan`\nskupne_padavine_za_vsak_dan <- padavine_po_dnevih$`Kolicina padavin za dan`\nr12=cor(povpr_poraba_za_vsak_dan1,povprecna_T_za_vsak_dan[1:197]) #brisem zato ker za porabo na koncu 0\nr13=cor(povpr_poraba_za_vsak_dan1,skupne_padavine_za_vsak_dan[1:197])\n\n\n# ***************************************************\n# Napovedni model s časovnimi vrstami\n# ***************************************************\npovpr_poraba_za_vsak_dan_ts <- ts(povpr_poraba_za_vsak_dan1, frequency = 365, start = c(2021,1))\narima_model <- auto.arima(povpr_poraba_za_vsak_dan_ts)\nsummary(arima_model)\nholt_model <- holt(povpr_poraba_za_vsak_dan_ts, h=1)\nsummary(holt_model)\nse_model <- ses(povpr_poraba_za_vsak_dan_ts, h = 1)\nsummary(se_model)\nnaive_mod <- naive(povpr_poraba_za_vsak_dan_ts, h = 1)\nsummary(naive_mod, \"NA\"= 0)\n\n\njpeg(\"slike/prikaz_natancnosti_razlicnih_napovednih_modelov.jpg\")\nmar.default <- c(5,2,4,2) + 0.1\npar(mar = mar.default + c(0, 4, 0, 0),family=\"serif\") #axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, ...)\ntitle=\"Povprečna poraba in njene napovedi\"\nplot(c(2021,2021.6), c(0,170),yaxt='n',xaxt='n',main=title, type = \"n\", pch=19,cex.lab=1.2, cex.axis=1.3, cex.main=1.5,xlab = \"Čas\",ylab = \"Povprečna poraba\") # setting up coord. system\nxlabels = c(2021,2021.1, 2021.2, 2021.3, 2021.4, 2021.5, 2021.6)\nylabels = c(1:10)*17\naxis(side=1,at=xlabels)\naxis(side=2,at=ylabels)\nlines(arima_model$fitted, type = \"l\", col = \"blue\",lwd=1,cex = 1,pch=16)\nlines(holt_model$fitted, type = \"l\", col = \"green\",lwd=1,cex = 1,pch=16)\nlines(se_model$fitted, type = \"l\", col = \"red\",lwd=1,cex = 1,pch=16)\nlines(naive_mod$fitted, type = \"l\", col = \"purple\",lwd=1,cex = 1,pch=16)\nlines(povpr_poraba_za_vsak_dan_ts, type = \"l\", col = \"orange\",lwd=2,cex = 1,pch=16)\nlegend(\"top\", legend=(c(\"Dejanska poraba\",\"Arima model\", \"Holt model\", \"Se model\", \"Naive mod\")), pch=c(16,16),cex=c(1.2,1.2),col=c(\"orange\",\"blue\", \"green\", \"red\", \"purple\"),y.intersp=0.8)\ndev.off()\n# ***************************************************\n# Grupiranje rezultatov\n# ***************************************************\npovpr_poraba_za_vsak_dan <-rowMeans(Tabela_porabe1[ ,3:98])\npovpr_poraba_matrika <- t(matrix(povpr_poraba_za_vsak_dan,198,51))\nset.seed(123)\n\n# *************************************************************\n# Ugotavljanje optimalnega števila skupin s silhuetnim diagramom\n# *************************************************************\nobrisi = function(podatki, hc = TRUE, od = 2, do = NULL) {\n n = nrow(podatki)\n if (is.null(do)) {\n do = n - 1\n }\n \n razdalje = dist(podatki)\n \n k.obrisi = tibble()\n for (k in od:do) {\n if (hc) {\n o.k = hclust(razdalje) %>%\n cutree(k) %>%\n silhouette(razdalje)\n } else {\n set.seed(42) # zato, da so rezultati ponovljivi\n o.k = kmeans(podatki, k)$cluster %>%\n silhouette(razdalje)\n }\n k.obrisi = k.obrisi %>% bind_rows(\n tibble(\n k = rep(k, n),\n obrisi = o.k[, \"sil_width\"]\n )\n )\n }\n k.obrisi$k = as.ordered(k.obrisi$k)\n \n k.obrisi\n}\n\nobrisi.povprecje = function(k.obrisi) {\n k.obrisi.povprecje = k.obrisi %>%\n group_by(k) %>%\n summarize(obrisi = mean(obrisi))\n}\n\nobrisi.k = function(k.obrisi) {\n obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n summarize(k = min(k)) %>%\n unlist() %>%\n as.character() %>%\n as.integer()\n}\n\nr.hc = povpr_poraba_matrika[c(1:9,11:43,45:51),] %>% obrisi(hc = TRUE, od=2, do=20)\nr.km = povpr_poraba_matrika[c(1:9,11:43,45:51),] %>% obrisi(hc = FALSE,od=2, do=20)\n\n\n\ndiagram.obrisi = function(k.obrisi) {\n ggplot() +\n geom_boxplot(\n data = k.obrisi,\n mapping = aes(x = k, y = obrisi)\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = k, y = obrisi),\n color = \"red\"\n ) +\n geom_line(\n data = obrisi.povprecje(k.obrisi),\n mapping = aes(x = as.integer(k), y = obrisi),\n color = \"red\"\n ) +\n geom_point(\n data = obrisi.povprecje(k.obrisi) %>%\n filter(obrisi == max(obrisi)) %>%\n filter(k == min(k)),\n mapping = aes(x = k, y = obrisi),\n color = \"blue\"\n ) +\n xlab(\"število skupin (k)\") +\n ylab(\"obrisi (povprečje obrisov)\") +\n ggtitle(paste(\"Maksimalno povprečje obrisov pri k =\", obrisi.k(k.obrisi))) +\n theme_classic()\n}\njpeg(\"slike/hirarhicni_model.jpg\")\ndiagram.obrisi(r.hc)\ndev.off()\n\njpeg(\"slike/model_k_tih_voditeljev.jpg\")\ndiagram.obrisi(r.km)\ndev.off()\n# ***************************************************\n# Generiranje skupin\n# ***************************************************\nklas <- kmeans(povpr_poraba_matrika,2)\nklasifikacija <- klas$cluster\npovpr_poraba_matrika1 <- cbind(povpr_poraba_matrika, klasifikacija)\n\nM=max(max(povpr_poraba_matrika1[,1:198]))\nm=min(min(povpr_poraba_matrika1[,1:198]))\n\nTabela_razred1 <- povpr_poraba_matrika1[povpr_poraba_matrika1[,199] == \"1\",1:198]\nTabela_razred2 <- povpr_poraba_matrika1[povpr_poraba_matrika1[,199] == \"2\",1:198]\n\n\njpeg(\"slike/prikaz_povprecne_porabe_za_razlicne_razrede.jpg\")\nmar.default <- c(5,2,4,2) + 0.1\npar(mar = mar.default + c(0, 4, 0, 0),family=\"serif\") #axis(side, at=, labels=, pos=, lty=, col=, las=, tck=, ...)\ntitle=\"Povprečna poraba za različne razrede porabnikov\"\nplot(c(0,199), c(0,100),yaxt='n',xaxt='n',main=title, type = \"n\", pch=19,cex.lab=1.2, cex.axis=1.3, cex.main=1.5,xlab = \"Dnevi\",ylab = \"Povprečna poraba\") # setting up coord. system\nxlabels=c(1:19)*10\naxis(side=1,at=xlabels,labels=xlabels)\naxis(side=2,at=c(0:6)*20,labels=as.factor(c(0:6)*20))\nlines(Tabela_razred1, type = \"l\", col = \"black\",lwd=2,cex = 1,pch=16)\nlines(colSums(Tabela_razred2), type = \"l\", col = \"red\",lwd=2,cex = 1,pch=16)\nlegend(\"top\", legend=(c(\"Sk1\",\"Sk2\")), pch=c(16,16),cex=c(1,1),col=c(\"black\",\"red\"),y.intersp=1.5,horiz=T)\ndev.off()\n\n\n", "meta": {"hexsha": "d25ab287190e5190d2c99c499bddfe2e82674854", "size": 12805, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "Blazpovh/APPR-2021-22", "max_stars_repo_head_hexsha": "ba8161ec0636ba4ef31ebf36e8bab2f236f8859c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "Blazpovh/APPR-2021-22", "max_issues_repo_head_hexsha": "ba8161ec0636ba4ef31ebf36e8bab2f236f8859c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-04T12:41:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T19:45:52.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "Blazpovh/APPR-2021-22", "max_forks_repo_head_hexsha": "ba8161ec0636ba4ef31ebf36e8bab2f236f8859c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5636363636, "max_line_length": 189, "alphanum_fraction": 0.6662241312, "num_tokens": 4875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.3258202232299139}} {"text": "#UPDATED August 5, 2021\r\n\r\nnumber_of_threads <- as.numeric(readLines(\"THREADS\"))\r\n\r\nalleles = list()\r\nfrequencies = list()\r\n\r\nfor (j in 1:nloci) {\r\n\tlocicolumns = grepl(paste(locinames[j],\"\",sep=\"\"),colnames(data))\r\n\traw_alleles = c(as.matrix(data[,locicolumns]))\r\n\traw_alleles[raw_alleles == \"NA\"] = NA\r\n\traw_alleles[raw_alleles == 0] = NA\r\n\talleles[[j]] = unique(raw_alleles[!is.na(raw_alleles)])\r\n\tfrequencies[[j]] = sapply(alleles[[j]], function(x) sum(raw_alleles == x,na.rm=TRUE))\r\n\tfrequencies[[j]] = frequencies[[j]] / sum(frequencies[[j]])\r\n}\r\n\r\n\r\nobserveddatamatrix = list()\r\nfor (j in 1:nloci) {\r\n\tlocus = locinames[j]\r\n\tlocicolumns = grepl(paste(locus,\"\",sep=\"\"),colnames(data))\r\n\toldalleles = as.vector(data[,locicolumns])\r\n\toldalleles [oldalleles == \"NA\"] = NA\r\n\toldalleles [oldalleles == 0] = NA\r\n\tif (length(dim(oldalleles)[2]) == 0) {\r\n\t\toldalleles = matrix(oldalleles,length(oldalleles),1)\r\n\t}\r\n\tobserveddatamatrix[[j]] = oldalleles \r\n}\r\n\r\nm <<- rep(1,nloci)\r\n\r\nH_nu = sapply(1:nloci, function (j) -sum(frequencies[[j]] * logb(frequencies[[j]],2)))\r\n\r\nsub_per_locus = function(isolate1,isolate2,j) {\r\n\t\tv1 = observeddatamatrix[[j]][isolate1,]\r\n\t\tv1 = v1[!is.na(v1)]\r\n\t\tp1 = frequencies[[j]][match(v1,alleles[[j]])]\r\n\t\tv2 = observeddatamatrix[[j]][isolate2,]\r\n\t\tv2 = v2[!is.na(v2)]\r\n\t\tp2 = frequencies[[j]][match(v2,alleles[[j]])]\r\n\r\n\r\n\t\tif (ploidy[j] > 1) {\r\n\t\t\tx = length(unique(v1)) + length(unique(v2))\r\n\t\t\tn = min(length(unique(v1)),length(unique(v2)))\r\n\t\t\tw = x * (n > 1) + 4 * (n == 1) * (x == 2) + (1+x) * (n== 1) * (x > 2)\r\n\t\t\tjj = 2 * (m[j] == 1) + m[j] * (m[j] > 1)\r\n\t\t\ty = length(intersect(v1,v2))\r\n\t\t\tz = 3 * (((2*(n == 1) + 1 * (y == 1) * (x > 2)))==3) + 2 * (y *(n>1)*(jj>=y)+jj*(n > 1)* (y > jj) + jj * (n==1) * (x==2) * (y==1))\r\n\t\t\tdelta_nu_raw = w * (y == 0) + 2 * jj * (y > 0) + sum(sapply(jj:(2*jj), function (ii) -ii*(z == ii)))\r\n\t\t\r\n\t\t\tshared_alleles = intersect(v1 , v2)\r\n\t\t\tif (length(shared_alleles) > 0) {\r\n\t\t\t\ttemp_shared = sapply(1:nids, function (x) sum(shared_alleles %in% as.matrix(observeddatamatrix[[j]][x,])))\r\n\t\t\t\tnotmissing = sapply(1:nids, function (x) sum(!is.na(observeddatamatrix[[j]][x,])))\r\n\t\t\t\r\n\t\t\t\tP_nu = (sum(temp_shared == length(shared_alleles)) / sum(notmissing != 0))^2\r\n\t\t\t} else {\r\n\t\t\t\tP_nu = 1\r\n\t\t\t}\r\n\t\t\tk = 1 * (y == 0) + P_nu * (y > 0)\r\n\t\t\tdelta_nu = H_nu[j] * ( delta_nu_raw * (delta_nu_raw > 0) + P_nu * (delta_nu_raw == 0))*k\r\n\t\t\tdelta = delta_nu\r\n\t\t} else {\r\n\t\t\tdelta_ex_raw = 0\r\n\t\t\tx = length(unique(v1)) + length(unique(v2))\r\n\t\t\ty = length(intersect(v1,v2))\r\n\t\t\tdelta_ex_raw = 2*x*(y == 0)\r\n\t\t\tshared_alleles = intersect(v1 , v2)\r\n\t\t\tif (length(shared_alleles) > 0) {\r\n\t\t\t\ttemp_shared = sapply(1:nids, function (x) sum(shared_alleles %in% as.matrix(observeddatamatrix[[j]][x,])))\r\n\t\t\t\tnotmissing = sapply(1:nids, function (x) sum(!is.na(observeddatamatrix[[j]][x,])))\r\n\t\t\t\tP_ex = (sum(temp_shared == length(shared_alleles)) / sum(notmissing != 0))^2\r\n\t\t\t} else {\r\n\t\t\t\tP_ex = 1\r\n\t\t\t}\r\n\t\t\tk = 1 * (y == 0) + P_ex * (y > 0)\r\n\t\t\tdelta_ex = H_nu[j] * ( delta_ex_raw * (delta_ex_raw > 0) + P_ex * (delta_ex_raw == 0))*k\r\n\t\t\tdelta = delta_ex\r\n\t\t}\r\n\t\tif (sum(!is.na(v1)) == 0 | sum(!is.na(v2)) == 0) { delta = NA }\r\n\t\tdelta\r\n}\r\n\r\npairwisedistance_heuristic = function(isolate1,isolate2){\r\n\tprint(((isolate2-1)*nids+isolate1)/ (nids*nids))\r\n\tdelta = sapply(1:nloci, function (x) sub_per_locus(isolate1,isolate2,x))\r\n\tc(delta,sum(delta))\t\r\n}\r\n\r\nallpossiblepairs = expand.grid(1:nids,1:nids)\r\nallpossiblepairs = unique(allpossiblepairs[allpossiblepairs[,1] <= allpossiblepairs[,2],])\r\npairwisedistancevector = do.call(cbind,mclapply(1:dim(allpossiblepairs)[1], function (x) pairwisedistance_heuristic(allpossiblepairs[x,1],allpossiblepairs[x,2]),mc.cores=number_of_threads))\r\n\r\npairwisedistancematrix_components = list()\r\nfor (j in 1:(nloci+1)) { \r\n\tpairwisedistancematrix_temp = matrix(NA,nids,nids)\r\n\tsapply(1:dim(allpossiblepairs)[1], function (x) pairwisedistancematrix_temp[allpossiblepairs[x,1],allpossiblepairs[x,2]] <<- pairwisedistancevector[j,x])\r\n\tsapply(1:dim(allpossiblepairs)[1], function (x) pairwisedistancematrix_temp[allpossiblepairs[x,2],allpossiblepairs[x,1]] <<- pairwisedistancevector[j,x])\r\n\tpairwisedistancematrix_components[[j]] = pairwisedistancematrix_temp\r\n}\r\n\r\n\r\n#### impute missing values\r\npairwisedistancematrix_components_imputed = pairwisedistancematrix_components\r\nwhichna = which(rowSums(is.na(pairwisedistancematrix_components[[nloci+1]])) == nids)\r\n\r\nimputemissing = function(isolate1) {\r\n\tmissingloci = which(sapply(1:nloci, function (j) sum(!is.na(observeddatamatrix[[j]][isolate1,]))) == 0)\r\n\tnonmissingloci = (1:nloci)[-missingloci]\r\n\tmatchingsamples = which(rowSums(rbind(sapply(nonmissingloci, function (j) sapply(1:nids, function (x) (setequal(observeddatamatrix[[j]][x,],observeddatamatrix[[j]][isolate1,]))))))==length(nonmissingloci))\r\n\tmatchingsamples = setdiff( matchingsamples , whichna)\r\n\tfor (j in missingloci ) {\r\n\t\tif (length(matchingsamples) > 0) {\r\n\t\t\tsapply(1:nids, function (x) pairwisedistancematrix_components_imputed[[j]][isolate1,x] <<- mean(pairwisedistancematrix_components[[j]][x,matchingsamples],na.rm=TRUE))\r\n\t\t\tsapply(1:nids, function (x) pairwisedistancematrix_components_imputed[[j]][x,isolate1] <<- mean(pairwisedistancematrix_components[[j]][x,matchingsamples],na.rm=TRUE))\r\n\t\t\tpairwisedistancematrix_components_imputed[[j]][isolate1,isolate1] <<- mean(diag(pairwisedistancematrix_components_imputed[[j]])[matchingsamples],na.rm=TRUE)\r\n\t\t} else {\r\n\t\t\tpairwisedistancematrix_components_imputed[[j]][isolate1,] <<-mean(pairwisedistancematrix_components[[j]],na.rm=TRUE)\r\n\t\t\tpairwisedistancematrix_components_imputed[[j]][,isolate1] <<-mean(pairwisedistancematrix_components[[j]],na.rm=TRUE)\r\n\t\t\tpairwisedistancematrix_components_imputed[[j]][isolate1,isolate1] <<-mean(diag(pairwisedistancematrix_components_imputed[[j]]),na.rm=TRUE)\r\n\t\t}\r\n\t}\r\n}\r\nsapply(whichna, imputemissing)\r\n\r\ntemppairwisedistancematrix = matrix(0,nids,nids)\r\nfor (j in 1:(nloci)) { \r\n\ttemppairwisedistancematrix = temppairwisedistancematrix + pairwisedistancematrix_components_imputed[[j]]\r\n}\r\nwhichna2 = which(rowSums(is.na(temppairwisedistancematrix )) != 0)\r\n\r\npairwisedistancematrix_components_imputed_secondpass = pairwisedistancematrix_components_imputed\r\n\r\nimputemissing_secondpass = function(isolate1) {\r\n\tmissingloci = which(sapply(1:nloci, function (j) sum(!is.na(observeddatamatrix[[j]][isolate1,]))) == 0)\r\n\tnonmissingloci = (1:nloci)[-missingloci]\r\n\tmatchingsamples = which(rowSums(rbind(sapply(nonmissingloci, function (j) sapply(1:nids, function (x) (setequal(observeddatamatrix[[j]][x,],observeddatamatrix[[j]][isolate1,]))))))==length(nonmissingloci))\r\n\tmatchingsamples = setdiff( matchingsamples , whichna)\r\n\tfor (j in missingloci ) {\r\n\t\tif (length(matchingsamples) > 0) {\r\n\t\t\tsapply(1:nids, function (x) pairwisedistancematrix_components_imputed_secondpass[[j]][isolate1,x] <<- mean(pairwisedistancematrix_components_imputed[[j]][x,matchingsamples],na.rm=TRUE))\r\n\t\t\tsapply(1:nids, function (x) pairwisedistancematrix_components_imputed_secondpass[[j]][x,isolate1] <<- mean(pairwisedistancematrix_components_imputed[[j]][x,matchingsamples],na.rm=TRUE))\r\n\t\t\tpairwisedistancematrix_components_imputed_secondpass[[j]][isolate1,isolate1] <<- mean(diag(pairwisedistancematrix_components_imputed[[j]])[matchingsamples],na.rm=TRUE)\r\n\t\t} else {\r\n\t\t\tpairwisedistancematrix_components_imputed_secondpass[[j]][isolate1,] <<-mean(pairwisedistancematrix_components_imputed[[j]],na.rm=TRUE)\r\n\t\t\tpairwisedistancematrix_components_imputed_secondpass[[j]][,isolate1] <<-mean(pairwisedistancematrix_components_imputed[[j]],na.rm=TRUE)\r\n\t\t\tpairwisedistancematrix_components_imputed_secondpass[[j]][isolate1,isolate1] <<-mean(diag(pairwisedistancematrix_components_imputed[[j]]),na.rm=TRUE)\r\n\t\t}\r\n\t}\r\n}\r\n\r\nsapply(whichna2, imputemissing_secondpass)\r\n\r\n\r\n\r\n# calculate final\r\nfinalpairwisedistancematrix = matrix(0,nids,nids)\r\nfor (j in 1:(nloci)) { \r\n\tfinalpairwisedistancematrix = finalpairwisedistancematrix + pairwisedistancematrix_components_imputed_secondpass[[j]]\r\n}\r\n\r\n\r\ncolnames(pairwisedistancematrix) = ids \r\nrownames(pairwisedistancematrix) = ids\r\n\r\nHeuristic_pairwisedistancematrix = finalpairwisedistancematrix \r\n\r\n\r\n", "meta": {"hexsha": "ef67c1cef4ceb11a80c590f093aa89fadbffd198", "size": 8237, "ext": "r", "lang": "R", "max_stars_repo_path": "Complete_Cyclospora_typing_workflow_MacOS_High_Sierra_ALPHA_TEST/EUKARYOTYPING/euk_heuristic_fulldataset.r", "max_stars_repo_name": "Joel-Barratt/CDC-Complete-Cyclospora-typing-workflow-ALPHA-TEST", "max_stars_repo_head_hexsha": "bb50a804b834925d1bec4687cdf16f9f524d14e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Complete_Cyclospora_typing_workflow_MacOS_High_Sierra_ALPHA_TEST/EUKARYOTYPING/euk_heuristic_fulldataset.r", "max_issues_repo_name": "Joel-Barratt/CDC-Complete-Cyclospora-typing-workflow-ALPHA-TEST", "max_issues_repo_head_hexsha": "bb50a804b834925d1bec4687cdf16f9f524d14e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Complete_Cyclospora_typing_workflow_MacOS_High_Sierra_ALPHA_TEST/EUKARYOTYPING/euk_heuristic_fulldataset.r", "max_forks_repo_name": "Joel-Barratt/CDC-Complete-Cyclospora-typing-workflow-ALPHA-TEST", "max_forks_repo_head_hexsha": "bb50a804b834925d1bec4687cdf16f9f524d14e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8895348837, "max_line_length": 207, "alphanum_fraction": 0.6975840719, "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.32515961491573514}} {"text": "#!/usr/bin/env Rscript\n\n#########################################\n# Author: [Ivan Juric](https://github.com/ijuric)\n# File: MAPS_regression_and_peak_caller.r\n# Source: https://github.com/ijuric/MAPS/blob/master/bin/MAPS/MAPS_regression_and_peak_caller.r\n# Source+commit: https://github.com/ijuric/MAPS/blob/e6d5fdee7241b8f9a466cc778be6d0769b984e81/bin/MAPS/MAPS_regression_and_peak_caller.r\n# Data: 11/08/2021, commit: e6d5fde\n# modified by Jianhong:\n# ## 1. set the Rscript environment.\n# ## 2. export the COUNT_CUTOFF, RATIO_CUTOFF and FDR parameters\n# ## 3. Automatic detect the chromosome names\n# ## 4. Handle the error if the input count table is empty\n# ## 5. Prefilter the data before fit to vglm to handle the NA error by replace the loglikelihood function.\n# ## 6. Handle the error if output is empty\n# ## 7. Handle the error if AND or XOR table is empty\n# ## 8. clean unused code\n# ## 9. fix the indent space\n#########################################\n\n## run example:\n## Rscript MAPS_regression_and_peak_caller.r /home/jurici/work/PLACseq/MAPS_pipe/results/mESC_test/ MY_115.5k 5000 1 None pospoisson NA\n##\n## arguments:\n## INFDIR - dir with reg files\n## SET - dataset name\n## RESOLUTION - resolution (for example 5000 or 10000)\n## COUNT_CUTOFF - count cutoff, default 12\n## RATIO_CUTOFF - ratio cutoff, default 2.0\n## FDR - -log10(fdr) cutoff, default 2\n## FILTER - file containing bins that need to be filtered out. Format: two columns \"chrom\", \"bin\". \"chrom\" contains 'chr1','chr2',.. \"bin\" is bin label\n## regresison_type - pospoisson for positive poisson regression, negbinom for negative binomial. default is pospoisson\n\nlibrary(VGAM)\nlibrary(MASS)\noptions(warn=-1)\n\n### constants\nchroms = NULL\nruns = c(1)\nRESOLUTION = NULL\n\nCOUNT_CUTOFF = 12\nRATIO_CUTOFF = 2.0\nGAP = 15000\nFDR = 2\n\nREG_TYPE = 'pospoisson'\n###\n\nargs <- commandArgs(trailingOnly=TRUE)\nfltr = data.frame(chr='chrNONE',bin=-1)\n\nif (length(args) < 3 || length(args) > 8) {\n print('Wrong number of arguments. Stopping.')\n print('Arguments needed (in this order): INFDIR, SET, RESOLUTION, COUNT_CUTOFF, RATIO_CUTOFF, FDR, FILTER, regression_type.')\n print('FILTER is optional argument. Omitt it if no filtering required.')\n print(paste('Number of arguments entered:',length(args)))\n print('Arguments entered:')\n print(args)\n quit()\n} else {\n print(args)\n INFDIR = args[1]\n SET = args[2]\n RESOLUTION = as.integer(args[3])\n SET <- paste0(SET, \".\", ceiling(RESOLUTION/1e3), \"k\")\n chroms <- dir(INFDIR, \"reg_raw.*\")\n chroms <- unique(sub(\"reg_raw\\\\.(.*?)\\\\..*$\", \"\\\\1\", chroms))\n if(length(args)>3){\n COUNT_CUTOFF = as.numeric(args[4])\n RATIO_CUTOFF = as.numeric(args[5])\n FDR = as.numeric(args[6])\n print('filter used (if any):')\n if (length(args) > 6) {\n if (args[7] != 'None') {\n FILTER = args[7]\n fltr = read.table(FILTER,header=T)\n print(fltr)\n } else {\n print('None')\n }\n ## this done so that the script is compatible with previous run_pipeline scripts\n if (length(args) > 7) {\n if (args[8] != 'pospoisson' && args[8] != 'negbinom') {\n print(paste('wrong regression choice. Your choice:', args[8], '. Avaiable choices: pospoisson or negbinom'),sep = ' ')\n quit()\n }\n REG_TYPE = args[8]\n }\n } else {\n print('None')\n }\n }\n}\n\n## loading data\nmm_combined_and = data.frame()\nmm_combined_xor = data.frame()\noutf_names = c()\nfor (i in chroms) {\n for (j in c('.and','.xor')) {\n print(paste('loading chromosome ',i,' ',j,sep=''))\n inf_name = paste(INFDIR,'reg_raw.',i,'.',SET,sep='')\n if(file.exists(paste(inf_name,j,sep=''))){\n outf_names = c(outf_names, paste(inf_name,j,'.MAPS2_',REG_TYPE,sep = ''))\n mm = read.table(paste(inf_name,j,sep=''),header=T)\n mm$chr = rep(i, nrow(mm))\n mm = subset( mm, dist > 1) # removing adjacent bins\n mm = subset(mm, !(mm$chr %in% fltr$chr & (mm$bin1_mid %in% fltr$bin | mm$bin2_mid %in% fltr$bin ))) ## filtering out bad bins\n if (j == '.and') {\n mm_combined_and = rbind(mm_combined_and, mm)\n } else if (j == '.xor') {\n mm_combined_xor = rbind(mm_combined_xor, mm)\n }\n }\n }\n}\n\ndataset_length_and = length(mm_combined_and$bin1_mid)\ndataset_length_xor = length(mm_combined_xor$bin1_mid)\ndataset_length = dataset_length_and + dataset_length_xor\n\n## doing statistics and resampling\nloglikelihood <- function (mu, y, w, residuals = FALSE, eta, extra = NULL, summation = TRUE) {\n lambda <- eta2theta(eta, \"loglink\", earg = list(bvalue = NULL, inverse = FALSE, deriv = 0, short = TRUE,\n tag = FALSE))\n if (residuals) {\n stop(\"loglikelihood residuals not implemented yet\")\n }\n else {\n ll.elts <- c(w) * dgaitpois(y, lambda, truncate = 0,\n log = TRUE)\n if (summation) {\n sum(ll.elts[!is.infinite(ll.elts)])\n }\n else {\n ll.elts\n }\n }\n}\npospoisson_regression <- function(mm, dataset_length) {\n family <- pospoisson()\n family@loglikelihood <- loglikelihood\n # fit <- vglm(count ~ logl + loggc + logm + logdist + logShortCount, family = pospoisson(), data = mm)\n fit <- vglm(count ~ loggc + logm + logdist + logShortCount, family = family, data = mm)\n mm$expected = fitted(fit)\n mm$p_val = ppois(mm$count, mm$expected, lower.tail = FALSE, log.p = FALSE) / ppois(0, mm$expected, lower.tail = FALSE, log.p = FALSE)\n m1 = mm[ mm$p_val > 1/length(mm$p_val),]\n # fit <- vglm(count ~ logl + loggc + logm + logdist + logShortCount, family = pospoisson(), data = m1)\n fit <- vglm(count ~ loggc + logm + logdist + logShortCount, family = family, data = m1)\n coeff<-round(coef(fit),10)\n # mm$expected2 <- round(exp(coeff[1] + coeff[2]*mm$logl + coeff[3]*mm$loggc + coeff[4]*mm$logm + coeff[5]*mm$logdist + coeff[6]*mm$logShortCount), 10)\n mm$expected2 <- round(exp(coeff[1] + coeff[2]*mm$loggc + coeff[3]*mm$logm + coeff[4]*mm$logdist + coeff[5]*mm$logShortCount), 10)\n mm$expected2 <- mm$expected2 /(1-exp(-mm$expected2))\n mm$ratio2 <- mm$count / mm$expected2\n mm$p_val_reg2 = ppois(mm$count, mm$expected2, lower.tail = FALSE, log.p = FALSE) / ppois(0, mm$expected2, lower.tail = FALSE, log.p = FALSE)\n mm$p_bonferroni = mm$p_val_reg2 * dataset_length\n mm$fdr <- p.adjust(mm$p_val_reg2, method='fdr')\n return(mm)\n}\n\nnegbinom_regression <- function(mm, dataset_length) {\n #fit <- glm.nb(count ~ logl + loggc + logm + logdist + logShortCount, data = mm)\n fit <- glm.nb(count ~ loggc + logm + logdist + logShortCount, data = mm)\n mm$expected = fitted(fit)\n sze = fit$theta ##size parameter\n mm$p_val = pnbinom(mm$count, mu = mm$expected, size = sze, lower.tail = FALSE)\n m1 = mm[ mm$p_val > ( 1 / length(mm$p_val)),]\n ## second regression\n # fit <- glm.nb(count ~ logl + loggc + logm + logdist + logShortCount, data = m1)\n fit <- glm.nb(count ~ loggc + logm + logdist + logShortCount, data = m1)\n coeff<-round(fit$coefficients,10)\n sze = fit$theta\n #mm$expected2 <- round(exp(coeff[1] + coeff[2]*mm$logl + coeff[3]*mm$loggc + coeff[4]*mm$logm + coeff[5]*mm$logdist + coeff[6]*mm$logShortCount), 10) ## mu parameter\n mm$expected2 <- round(exp(coeff[1] + coeff[2]*mm$loggc + coeff[3]*mm$logm + coeff[4]*mm$logdist + coeff[5]*mm$logShortCount), 10) ## mu parameter\n mm$ratio2 <- mm$count / mm$expected2\n mm$p_val_reg2 = pnbinom(mm$count, mu = mm$expected2, size = sze, lower.tail = FALSE)\n mm$p_bonferroni = mm$p_val_reg2 * dataset_length\n mm$fdr <- p.adjust(mm$p_val_reg2, method='fdr')\n return(mm)\n}\n\ndo_summaries <- function(peaks_and,peaks_xor, peaks, fraction, r) {\n ## no peaks with this fdr\n if (ncol(peaks_and) == 0) {\n peaks_and = data.frame('count' = NA, 'dist'=NA, 'p_val_reg2'=NA, 'fdr'=NA)\n }\n if (ncol(peaks_xor) == 0) {\n peaks_xor = data.frame('count' = NA, 'dist'=NA, 'p_val_reg2'=NA, 'fdr'=NA)\n }\n if (ncol(peaks_and) == 0 & ncol(peaks_xor) == 0) {\n peaks = data.frame('count' = NA, 'dist'=NA, 'p_val_reg2'=NA, 'fdr'=NA)\n }\n summary_one_fdr_val = data.frame('run' = r, 'log10_fdr_cutoff' = fdr_cutoff, 'singleton_fraction' = fraction,\n'AND_size'=length(peaks_and$count), 'AND_mean_dist'=mean(peaks_and$dist)*RESOLUTION,'AND_median_dist'=median(peaks_and$dist)*RESOLUTION,\n'AND_min_count'=min(peaks_and$count), 'AND_max_pval'=max(peaks_and$p_val_reg2), 'AND_max_fdr'=max(peaks_and$fdr),\n'XOR_size'=length(peaks_xor$count), 'XOR_mean_dist'=mean(peaks_xor$dist)*RESOLUTION,'XOR_median_dist'=median(peaks_xor$dist)*RESOLUTION,\n'XOR_min_count'=min(peaks_xor$count), 'XOR_max_pval'=max(peaks_xor$p_val_reg2), 'XOR_max_fdr'=max(peaks_xor$fdr),\n'size'=length(peaks$count), 'mean_dist'=mean(peaks$dist)*RESOLUTION,'median_dist'=median(peaks$dist)*RESOLUTION,\n'min_count'=min(peaks$count), 'max_pval'=max(peaks$p_val_reg2), 'max_fdr'=max(peaks$fdr)\n )\n return(summary_one_fdr_val)\n}\n\nlabel_peaks <- function(df) {\n chroms = unique(df$chr)\n print('chromosomes with potential interactions:')\n print(chroms)\n final = data.frame()\n for (CHR in chroms) {\n y = df[df$chr == CHR,]\n y$p_val_reg2[ y$p_val_reg2 == 0 ] = 1111111\n y$p_val_reg2[ y$p_val_reg2 == 1111111 ] = min(y$p_val_reg2)\n for(i in 1:nrow(y)) {\n z <- y[ abs(y$bin1_mid - y$bin1_mid[i])<=GAP & abs(y$bin2_mid - y$bin2_mid[i])<=GAP,]\n y$CountNei[i] <- nrow(z)\n }\n u <- y[ y$CountNei == 1 ,] # singletons\n v <- y[ y$CountNei >= 2 ,] # peak cluster: sharp peak + broad peak\n out <- NULL\n if(nrow(u)>0) {\n u$label <- 0 # for singletons, assign cluster label 0\n # for singletons, cluster size = 1\n u$NegLog10P <- -log10(u$p_val_reg2 )\n u$ClusterSize <- 1\n out <- rbind(out, u)\n }\n if(nrow(v)>0) {\n v$label <- seq(1,nrow(v),1) # for peak cluster, assign label 1, 2, ..., N\n # for all bin pairs within the neighborhood\n # assign the same cluster label, using the minimal label\n for(i in 1:nrow(v)) {\n w <- v[ abs(v$bin1_mid - v$bin1_mid[i])<=GAP & abs(v$bin2_mid - v$bin2_mid[i])<=GAP ,]\n w.min <- min(w$label)\n w.label <- sort(unique(w$label))\n for(j in 2:length(w.label)) {\n v$label[ v$label == w.label[j] ] <- w.min\n }\n }\n # step 4: assign consecutive label number\n v.rec <- sort( unique( v$label ) )\n v.rec <- cbind(v.rec, seq(1, length(v.rec), 1))\n for(i in 1:nrow(v)) {\n v$label[i] <- v.rec[ v.rec[,1]==v$label[i] ,2]\n }\n # step 5: calculate cumulative NegLog10P and the cluster size\n v$NegLog10P <- 0\n v$ClusterSize <- 0\n for(i in 1:nrow(v.rec)) {\n # find all bin pairs within the same cluster i\n vtmp <- v[ v$label == i ,]\n v$NegLog10P[ v$label == i ] <- sum( -log10( vtmp$p_val_reg2 ) )\n v$ClusterSize[ v$label == i ] <- nrow(vtmp)\n }\n out <- rbind(out, v)\n }\n final<-rbind(final, out)\n }\n print(dim(final))\n return(final)\n}\n\nclassify_peaks <- function(final) {\n\n # only keep unique peak clusters, not bin pairs\n x <- unique( final[ final$label != 0, c('chr', 'label', 'NegLog10P', 'ClusterSize')] )\n if(nrow(x)==0){\n final$ClusterType <- 'Singleton'\n return(final)\n }\n\n # sort rows by cumulative -log10 P-value\n x <- x[ order(x$NegLog10P) ,]\n y<-sort(x$NegLog10P)\n z<-cbind( seq(1,length(y),1), y )\n\n # keep a record of z before normalization\n z0 <- z\n\n z[,1]<-z[,1]/max(z[,1])\n z[,2]<-z[,2]/max(z[,2])\n\n u<-z\n u[,1] <- 1/sqrt(2)*z[,1] + 1/sqrt(2)*z[,2]\n u[,2] <- -1/sqrt(2)*z[,1] + 1/sqrt(2)*z[,2]\n\n v<-cbind(u, seq(1,nrow(u),1) )\n RefPoint <- v[ v[,2]==min(v[,2]) , 3] # 1423\n RefValue <- z0[RefPoint,2]\n\n # define peak cluster type\n final$ClusterType <- '0'\n final$ClusterType[ final$label==0 ] <- 'Singleton'\n final$ClusterType[ final$label>=1 & final$NegLog10P=1 & final$NegLog10P>=RefValue ] <- 'BroadPeak'\n #table(final$ClusterType)\n return(final)\n}\n\n\nmx_combined_and = data.frame()\nmx_combined_xor = data.frame()\nsummary_all_runs = data.frame()\n\nsingletons_names = paste(chroms,'_0',sep='')\nfor (r in runs) {\n## in case you want to do resampling\n## you'd put resampling code here\n name_counter = 1\n for (i in chroms) {\n ## regression\n tryCatch({\n print(paste('run',r,': regression on chromosome',i))\n print(outf_names[name_counter])\n mm = subset(mm_combined_and, chr == i)\n if(nrow(mm)>6){\n if (REG_TYPE == 'pospoisson') {\n mm = pospoisson_regression(mm, dataset_length)\n } else if (REG_TYPE == 'negbinom') {\n mm = negbinom_regression(mm, dataset_length)\n }\n mx_combined_and = rbind(mx_combined_and, mm)\n }\n write.table(mm,outf_names[name_counter],row.names = TRUE,col.names = TRUE,quote=FALSE)\n name_counter = name_counter + 1\n print(outf_names[name_counter])\n mm = subset(mm_combined_xor, chr == i)\n if(nrow(mm)>6){\n if (REG_TYPE == 'pospoisson') {\n mm = pospoisson_regression(mm, dataset_length)\n } else if (REG_TYPE == 'negbinom') {\n mm = negbinom_regression(mm, dataset_length)\n }\n mx_combined_xor = rbind(mx_combined_xor, mm)\n }\n write.table(mm,outf_names[name_counter],row.names = TRUE,col.names = TRUE,quote=FALSE)\n }, error=function(.e){\n message(.e)\n })\n name_counter = name_counter + 1\n ## finding min FDR so I can set appropriate lower boundary for FDR\n }\n ## save QC file\n qc_out = paste(INFDIR,SET,'.maps.qc',sep = '')\n qc_label = c('AND_set','XOR_set')\n qc_val = c(sum(mm_combined_and$count), sum(mm_combined_xor$count))\n qc_name = c('number of sequencing pairs in AND set', 'number of sequencing pairs in XOR set')\n df_qc = data.frame()\n\n summary_one_run = data.frame()\n singletons = data.frame()\n for (fdr_cutoff in FDR) {\n peaks_and = if(nrow(mx_combined_and)>0) subset(mx_combined_and, count >= COUNT_CUTOFF & ratio2 >= RATIO_CUTOFF & -log10(fdr) > fdr_cutoff) else data.frame()\n peaks_xor = if(nrow(mx_combined_xor)>0) subset(mx_combined_xor, count >= COUNT_CUTOFF & ratio2 >= RATIO_CUTOFF & -log10(fdr) > fdr_cutoff) else data.frame()\n print(\"finding peaks\")\n peaks = rbind(peaks_and, peaks_xor)\n if (dim(peaks)[1] == 0) {\n print(paste('ERROR MAPS_regression_and_peak_caller.r: 0 bin pairs with count >= ',COUNT_CUTOFF,' observed/expected ratio >= ',RATIO_CUTOFF,' and -log10(fdr) > ',fdr_cutoff,sep=''))\n quit()\n }\n peaks = label_peaks(peaks)\n peaks$lab = paste(peaks$chr, peaks$label,sep='_')\n peak_types = classify_peaks(peaks)\n outf_name = paste(INFDIR,SET, '.',fdr_cutoff,'.peaks',sep='')\n write.table(peak_types,outf_name, row.names = FALSE, col.names = TRUE, quote=FALSE)\n print(\"finding singletons\")\n peak_classes = table(peaks$lab)\n n_singletons = sum(peak_classes[names(peak_classes) %in% singletons_names])\n n_singleton_chroms = length(peak_classes[names(peak_classes) %in% singletons_names])\n\n fraction= n_singletons / (length(peak_classes) + n_singletons - n_singleton_chroms)\n fraction = n_singletons / (length(peak_classes) + n_singletons - n_singleton_chroms)\n\n singletons_one_run = data.frame('fdr'=fdr_cutoff, 'fraction'=fraction)\n singletons = rbind(singletons, singletons_one_run)\n print(paste(fdr_cutoff,':',singletons))\n summary_one_run = rbind(summary_one_run, do_summaries(peaks_and, peaks_xor, peaks, fraction, r))\n }\n ## find singletons, sharp peaks, broad peaks\n summary_all_runs = rbind(summary_all_runs, summary_one_run)\n}\nsummary_outf_name = paste(INFDIR,'summary.',SET,'.txt',sep='')\nwrite.table(summary_all_runs, summary_outf_name, row.names = FALSE, col.names = TRUE, quote=FALSE)\n", "meta": {"hexsha": "d63018913ff9e14a5138234c08205dcecebdde6e", "size": 16824, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/MAPS_regression_and_peak_caller.r", "max_stars_repo_name": "jianhong/nf-core-hicar", "max_stars_repo_head_hexsha": "27158ef8e8a4b28363b52959bdf4ab634f3256fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-29T15:59:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T02:49:42.000Z", "max_issues_repo_path": "bin/MAPS_regression_and_peak_caller.r", "max_issues_repo_name": "nf-core/nf-core-hicar", "max_issues_repo_head_hexsha": "343641e56d3a3edf30dbf72eac604ac59b5e1b3d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 49, "max_issues_repo_issues_event_min_datetime": "2021-11-02T21:05:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T10:45:36.000Z", "max_forks_repo_path": "bin/MAPS_regression_and_peak_caller.r", "max_forks_repo_name": "nf-core/nf-core-hicar", "max_forks_repo_head_hexsha": "343641e56d3a3edf30dbf72eac604ac59b5e1b3d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-08-12T15:11:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T08:37:05.000Z", "avg_line_length": 43.6987012987, "max_line_length": 192, "alphanum_fraction": 0.6005111745, "num_tokens": 4944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3242369731791636}} {"text": "#!/usr/bin/env Rscript\n#\n# Use generalized linear mixed models to test for differences in allele\n# frequency.\n#\n# Each read is treated as an observation, and pools are treated as random\n# effects. A likelihood ratio test is used to produce a p-value.\n#\n# Usage:\n#\n# snp_by_snp_glmm_test.r \n# \n#\n# The names of the pools in each group should be separated by commas.\n#\n#==============================================================================#\n\n\nlibrary(data.table)\nlibrary(lme4)\n\noptions(warn=1)\n\n#==============================================================================#\n\n## From a sync file row, get read counts.\nget_counts = function(sync_row, pools, pool_names) {\n contig = sync_row[[1]]\n pos = sync_row[[2]]\n ref_allele = toupper(sync_row[[3]])\n counts = structure(vector('list', length=length(pools)),\n names=pools)\n for(pn in pools) {\n x = sync_row[[which(pool_names == pn) + 3]]\n cnts = as.numeric(unlist(strsplit(x, ':')))\n names(cnts) = c('A', 'T', 'C', 'G', 'N', 'D')\n ref_cnt = cnts[ref_allele]\n alt_cnt = (sum(cnts) - cnts['N']) - ref_cnt\n counts[[pn]] = c('ref'=ref_cnt, 'alt'=alt_cnt)\n }\n counts\n}\n\n## Test if this set of counts is variable\nis_variable = function(counts) {\n ref = sum(sapply(counts, function(x) x[1]))\n alt = sum(sapply(counts, function(x) x[2]))\n return((ref != 0) && (alt != 0))\n}\n\nnull_result = list('p'=NaN, 'effect'=NaN, term=NA, converged=NA,\n 'wald_p'=NaN, 'freqs0'=NA, 'freqs1'=NA)\n\n## Run a GLMM with pool as a random effect. Use the default\n## Wald Z-test and likelihood ratio test to get p-values\ntest = function(counts, groups) {\n resp = unlist(sapply(counts, function(x) c(rep(0, x[1]), rep(1, x[2]))))\n n_reads = sapply(counts, sum)\n freqs = structure(round(sapply(counts, function(x) x[1] / sum(x)), 4),\n names=names(counts))\n pools = factor(rep(names(counts), n_reads))\n trt = rep(names(groups),\n sapply(groups, function(x) sum(n_reads[x])))\n freqs0 = paste(freqs[names(freqs) %in% groups[[1]]], collapse=',')\n freqs1 = paste(freqs[names(freqs) %in% groups[[2]]], collapse=',')\n ret = null_result\n if(length(unique(trt)) > 1) {\n ## Random intercept for each pool\n m = glmer(resp ~ trt + (1|pools), family=binomial('logit'))\n mnull = glmer(resp ~ (1|pools), family=binomial('logit'))\n lrt_p = anova(m, mnull)[['Pr(>Chisq)']][2]\n s = summary(m)\n conv = (length(s$optinfo$conv$lme4) == 0) &&\n (length(mnull@optinfo$conv$lme4) == 0)\n p = s$coefficients[2, 4]\n fe = fixef(m)[2]\n ret = list('p'=lrt_p, 'wald_p'=p, 'effect'=fe, 'term'=names(fe),\n 'converged'=as.numeric(conv),\n 'freqs0'=freqs0, 'freqs1'=freqs1)\n }\n ret\n}\n\n#==============================================================================#\n\n## Get arguments to the script\ncargs = commandArgs(trailingOnly=TRUE)\nsync_file_name = cargs[1]\npool_file_name = cargs[2]\ngroup_1 = Filter(function(x) x != '', unlist(strsplit(cargs[3], ',')))\ngroup_2 = Filter(function(x) x != '', unlist(strsplit(cargs[4], ',')))\n\n## Read in data\nread_counts = fread(sync_file_name, sep='\\t', stringsAsFactors=FALSE)\npool_names = scan(pool_file_name, what='character')\n\ntrts = list('group1'=group_1, 'group2'=group_2)\n\n## Test every SNP and print results\ncat('contig\\tpos\\tref\\tp\\twald_p\\teffect\\tterm\\tconverged\\tfreqs0\\tfreqs1\\n', file=stdout())\nfor(i in 1:nrow(read_counts)) {\n row_data = read_counts[i]\n contig = row_data[[1]]\n pos = row_data[[2]]\n ref = row_data[[3]]\n counts = get_counts(row_data, unlist(trts), pool_names)\n if(is_variable(counts)) {\n test_results = tryCatch(test(counts, trts),\n error=function(e) null_result)\n } else {\n test_results = null_result\n }\n\n cat(paste(contig, pos, ref, test_results$p, test_results$wald_p,\n test_results$effect, test_results$term, test_results$converged,\n test_results$freqs0, test_results$freqs1,\n sep='\\t'),\n '\\n', sep='', file=stdout())\n}\n", "meta": {"hexsha": "56b6beebaf1329f21c116863d671c05a95eb57d3", "size": 4270, "ext": "r", "lang": "R", "max_stars_repo_path": "snp_by_snp_glmm_test.r", "max_stars_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_stars_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snp_by_snp_glmm_test.r", "max_issues_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_issues_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-17T11:14:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T11:14:13.000Z", "max_forks_repo_path": "snp_by_snp_glmm_test.r", "max_forks_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_forks_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5833333333, "max_line_length": 92, "alphanum_fraction": 0.5733021077, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.32156667484722096}} {"text": "# TODO: model with subj as third cue.\n\n# source(\"act-s.r\")\n# reset_params()\n \n\n######################################################################\n##\n## Standard reflexive interference model with 4 conditions.\n##\n## Uses csim to compute fan\n## Includes a variation of fan effect size determined by the activation of competing chunk\n## Parameters:\n## abl= antecedent base level activation\n## dbl= distractor base level activation\n## Returns a list of \n## l= latencies by condition\n## m= misretrievals by condition\n## a= activations of antecedent and distractor AT RETRIEVAL for interference conditions\n## b= \"BASE\" activations without fan for interference conditions \n##\n######################################################################\nrefl_model_4cond_orig <- function(iterations=1000, csim=cuesim, ND=1, cweights=c(strWeight(),semWeight()), print=0){\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,8),nrow=4) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n b[1] <- activation(fan=c(1,1), match=c(0,0), bl=blc, times=lp, weights=cweights) # +c +a\n b[2] <- activation(fan=c(NA,1), match=c(-1,0), bl=dbl, times=ldp, weights=cweights) # -c +a\n fs[1] <- fan_strength(b[1],b[2])\n fs[2] <- fan_strength(b[2],b[1])\n a[1,1] <- activation(fan=c(1+(ND*(1+csim)*fs[1]), 1+(ND*fs[1])), match=c(0,0), bl=blc, times=lp, weights=cweights) # +c +a\n a[1,2] <- activation(fan=c(NA, ND+((1)*fs[2])), match=c(-1,0), bl=dbl, times=ldp, weights=cweights) # -c +a\n ##\n ## b) MATCH/NOINT: full match, no fan\n a[2,1] <- activation(fan=c(1,1), match=c(0,0), bl=blc, times=lp, weights=cweights) # +c +a\n a[2,2] <- activation(fan=c(NA,NA), match=c(-1,-1), bl=dbl, times=ldp, weights=cweights) # -c -a\n ##\n ## c) MISMATCH/INT: partial match with fan from partially matching chunk\n b[3] <- activation(fan=c(1,NA), match=c(0,-1), bl=blc, times=lp, weights=cweights) # +c -a\n b[4] <- activation(fan=c(NA,1), match=c(-1,0), bl=dbl, times=ldp, weights=cweights) # -c +a\n fs[3] <- fan_strength(b[3],b[4])\n fs[4] <- fan_strength(b[4],b[3])\n a[3,1] <- activation(fan=c(1+(ND*(1+csim)*fs[3]), NA), match=c(0,-1), bl=blc, times=lp, weights=cweights) # +c -a\n a[3,2] <- activation(fan=c(NA, ND+((1+csim)*fs[4])), match=c(-1,0), bl=dbl, times=ldp, weights=cweights) # -c +a\n ##\n ## d) MISMATCH/NOINT: partial match, no fan\n a[4,1] <- activation(fan=c(1,NA), match=c(0,-1), bl=blc, times=lp, weights=cweights) # +c -a\n a[4,2] <- activation(fan=c(NA,NA), match=c(-1,-1), bl=dbl, times=ldp, weights=cweights) # -c -a\n ##\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,f=f,m=m,baseact=baseact,act=finalact))\n}\n\n\n\nrefl_model_4cond <- function(iterations=1000, csim=cuesim, ND=1, cweights=c(strWeight(),semWeight()), print=0){\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,8),nrow=4) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n res <- final_activation(c(1,1), c(NA,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[1,1] <- res$a1\n a[1,2] <- res$a2\n b[1] <- res$b1\n b[2] <- res$b2\n ##\n ## b) MATCH/NOINT: full match, no fan\n res <- final_activation(c(1,1), c(NA,NA), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[2,1] <- res$a1\n a[2,2] <- res$a2\n # b[1] <- res$b1\n # b[2] <- res$b2\n ##\n ## c) MISMATCH/INT: partial match with fan from partially matching chunk\n res <- final_activation(c(1,NA), c(NA,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[3,1] <- res$a1\n a[3,2] <- res$a2\n b[3] <- res$b1\n b[4] <- res$b2\n ##\n ## d) MISMATCH/NOINT: partial match, no fan\n res <- final_activation(c(1,NA), c(NA,NA), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[4,1] <- res$a1\n a[4,2] <- res$a2\n # b[1] <- res$b1\n # b[2] <- res$b2\n ##\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,f=f,m=m,baseact=baseact,act=finalact))\n}\n\n\n######################################################################\n##\n## Reflexive interference model including +subj as cue\n##\n######################################################################\nrefl_model_4cond_subj_cue <- function(iterations=1000, ND=1, cweights=c(strWeight(),semWeight(), semWeight()), subj=TRUE, print=0){\n SF <- ifelse(subj, 1, NA) ## Distractor subject feature\n SFM <- ifelse(subj, 0, -1) ## Subject feature match\n SFC <- ifelse(subj, 0, 1) ## Cuesim multiplicator\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,8),nrow=4) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n res <- final_activation(c(1,1,1), c(NA,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[1,1] <- res$a1\n a[1,2] <- res$a2\n b[1] <- res$b1\n b[2] <- res$b2\n ##\n ## b) MATCH/NOINT:\n res <- final_activation(c(1,1,1), c(NA,NA,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[2,1] <- res$a1\n a[2,2] <- res$a2\n # b[] <- res$b1\n # b[] <- res$b2\n ##\n ## c) MISMATCH/INT: partial match with fan from partially matching chunk\n res <- final_activation(c(1,NA,1), c(NA,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[3,1] <- res$a1\n a[3,2] <- res$a2\n b[3] <- res$b1\n b[4] <- res$b2\n ##\n ## d) MISMATCH/NOINT: partial match, no fan\n res <- final_activation(c(1,NA,1), c(NA,NA,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[4,1] <- res$a1\n a[4,2] <- res$a2\n # b[] <- res$b1\n # b[] <- res$b2\n ##\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,f=f,m=m,baseact=baseact,act=finalact))\n}\n\n\n\n\n\n\n######################################################################\n##\n## Multiple feature mismatch model (Parker & Phillips, 2014)\n##\n######################################################################\nrefl_model_4cond_mult_feature_mismatch_orig <- function(iterations=1000, csim=cuesim, ND=1, cweights=c(strWeight(),semWeight(),semWeight()), print=0){\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,12),ncol=2) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n b[1] <- activation(fan=c(1,1,1), match=c(0,0,0), bl=blc, times=lp, weights=cweights) # +c +g +n\n b[2] <- activation(fan=c(NA,1,1), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights) # -c +g +n\n fs[1] <- fan_strength(b[1],b[2])\n fs[2] <- fan_strength(b[2],b[1])\n a[1,1] <- activation(fan=c(1+(ND*(1+csim)*fs[1]), 1+(ND*fs[1]), 1+(ND*fs[1])), match=c(0,0,0), bl=blc, times=lp, weights=cweights) \n a[1,2] <- activation(fan=c(NA, ND+(1*fs[2]), ND+(1*fs[2])), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights)\n ##\n ## b) MATCH/NOINT: full match, no fan\n b[3] <- activation(fan=c(1,1,1), match=c(0,0,0), bl=blc, times=lp, weights=cweights) # +c +g +n\n b[4] <- activation(fan=c(NA,NA,1), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -c -g +n\n fs[3] <- fan_strength(b[3],b[4])\n fs[4] <- fan_strength(b[4],b[3])\n a[2,1] <- activation(fan=c(1+(ND*(1+csim)*fs[3]),1+(ND*(1+csim)*fs[3]),1+(ND*fs[3])), match=c(0,0,0), bl=blc, times=lp, weights=cweights) # +c +g +n\n a[2,2] <- activation(fan=c(NA,NA,ND+(1*fs[4])), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -c -g +n\n ##\n ## c) 1MISMATCH/INT: partial match with fan from partially matching chunk\n b[5] <- activation(fan=c(1,NA,1), match=c(0,-1,0), bl=blc, times=lp, weights=cweights) # +c -g +n\n b[6] <- activation(fan=c(NA,1,1), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights) # -c +g +n\n fs[5] <- fan_strength(b[5],b[6])\n fs[6] <- fan_strength(b[6],b[5])\n a[3,1] <- activation(fan=c(1+(ND*(1+csim)*fs[5]), NA, 1+(ND*fs[5])), match=c(0,-1,0), bl=blc, times=lp, weights=cweights)\n a[3,2] <- activation(fan=c(NA, ND+((1+csim)*fs[6]), ND+(1*fs[6])), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights)\n ##\n ## d) 1MISMATCH/NOINT: partial match, no fan\n b[7] <- activation(fan=c(1,NA,1), match=c(0,-1,0), bl=blc, times=lp, weights=cweights) # +c -g +n\n b[8] <- activation(fan=c(NA,NA,1), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -c -g +n\n fs[7] <- fan_strength(b[7],b[8])\n fs[8] <- fan_strength(b[8],b[7])\n a[4,1] <- activation(fan=c(1+(ND*(1+csim)*fs[7]),NA,1+(ND*fs[7])), match=c(0,-1,0), bl=blc, times=lp, weights=cweights) # +c -g +n\n a[4,2] <- activation(fan=c(NA,NA,ND+(1*fs[8])), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -c -g +n\n ##\n ## e) 2MISMATCH/INT: \n b[9] <- activation(fan=c(1,NA,NA), match=c(0,-1,-1), bl=blc, times=lp, weights=cweights) # +c -g -n\n b[10] <- activation(fan=c(NA,1,1), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights) # -c +g +n\n fs[9] <- fan_strength(b[9],b[10])\n fs[10] <- fan_strength(b[10],b[9])\n a[5,1] <- activation(fan=c(1+(ND*(1+csim)*fs[9]), NA, NA), match=c(0,-1,-1), bl=blc, times=lp, weights=cweights)\n a[5,2] <- activation(fan=c(NA, ND+((1+csim)*fs[10]), ND+((1+csim)*fs[10])), match=c(-1,0,0), bl=dbl, times=ldp, weights=cweights)\n ##\n ## f) 2MISMATCH/NOINT: \n b[11] <- activation(fan=c(1,NA,NA), match=c(0,-1,-1), bl=blc, times=lp, weights=cweights) # +c -g -n\n b[12] <- activation(fan=c(NA,NA,1), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -c -g +n\n fs[11] <- fan_strength(b[11],b[12])\n fs[12] <- fan_strength(b[12],b[11])\n a[6,1] <- activation(fan=c(1+(ND*(1+csim)*fs[11]), NA, NA), match=c(0,-1,-1), bl=blc, times=lp, weights=cweights) # +c -g +n\n a[6,2] <- activation(fan=c(NA,NA,ND+((1+csim)*fs[12])), match=c(-1,-1,0), bl=dbl, times=ldp, weights=cweights) # -\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n # finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n # colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n # colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,m=m,f=f,baseact=baseact))\n}\n\n\n\n\n######################################################################\n##\n## Multiple feature mismatch model (Parker & Phillips, 2014)\n##\n######################################################################\nrefl_model_4cond_mult_feature_mismatch <- function(iterations=1000, csim=cuesim, ND=1, cweights=c(strWeight(),semWeight(),semWeight()), print=0){\n SF <- ifelse(subj, 1, NA) ## Distractor subject feature\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,12),ncol=2) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n ## +c +g +n +s\n ## -c +g +n +s\n res <- final_activation(c(1,1,1), c(NA,1,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[1,1] <- res$a1\n a[1,2] <- res$a2\n b[1] <- res$b1\n b[2] <- res$b2\n ##\n ## b) MATCH/NOINT: full match, no fan\n res <- final_activation(c(1,1,1), c(NA,NA,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[2,1] <- res$a1\n a[2,2] <- res$a2\n b[3] <- res$b1\n b[4] <- res$b2\n ##\n ## c) 1MISMATCH/INT: partial match with fan from partially matching chunk\n res <- final_activation(c(1,NA,1), c(NA,1,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[3,1] <- res$a1\n a[3,2] <- res$a2\n b[5] <- res$b1\n b[6] <- res$b2\n ##\n ## d) 1MISMATCH/NOINT: partial match, no fan\n res <- final_activation(c(1,NA,1), c(NA,NA,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[4,1] <- res$a1\n a[4,2] <- res$a2\n b[7] <- res$b1\n b[8] <- res$b2\n ##\n ## e) 2MISMATCH/INT: \n res <- final_activation(c(1,NA,NA), c(NA,1,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[5,1] <- res$a1\n a[5,2] <- res$a2\n b[9] <- res$b1\n b[10] <- res$b2\n ##\n ## f) 2MISMATCH/NOINT: \n res <- final_activation(c(1,NA,NA), c(NA,NA,1), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[6,1] <- res$a1\n a[6,2] <- res$a2\n b[11] <- res$b1\n b[12] <- res$b2\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n # finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n # colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n # colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,m=m,f=f,baseact=baseact))\n}\n\n\n\n\n######################################################################\n##\n## Multiple feature mismatch model (Parker & Phillips, 2014)\n##\n######################################################################\nrefl_model_4cond_mult_feature_mismatch_subj_cue <- function(iterations=1000, csim=cuesim, ND=1, cweights=c(strWeight(),semWeight(),semWeight(),semWeight()), subj=TRUE, print=0){\n SF <- ifelse(subj, 1, NA) ## Distractor subject feature\n ta <- NULL ## collects target activations\n l <- NULL ## collects latencies\n r <- NULL ## collects retrievals\n baseact <- NULL ## collects chunk base activations\n finalact <- NULL ## collects chunk act including fan / interference\n for(i in 1:iterations){\n a <- matrix(rep(NA,12),ncol=2) ## Chunk activations\n b <- NULL\n fs <- NULL\n ##\n ##\n ## a) MATCH/INT: full match with fan from partially matching chunk\n ## +c +g +n +s\n ## -c +g +n +s\n res <- final_activation(c(1,1,1,1), c(NA,1,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[1,1] <- res$a1\n a[1,2] <- res$a2\n b[1] <- res$b1\n b[2] <- res$b2\n ##\n ## b) MATCH/NOINT: full match, no fan\n res <- final_activation(c(1,1,1,1), c(NA,NA,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[2,1] <- res$a1\n a[2,2] <- res$a2\n b[3] <- res$b1\n b[4] <- res$b2\n ##\n ## c) 1MISMATCH/INT: partial match with fan from partially matching chunk\n res <- final_activation(c(1,NA,1,1), c(NA,1,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[3,1] <- res$a1\n a[3,2] <- res$a2\n b[5] <- res$b1\n b[6] <- res$b2\n ##\n ## d) 1MISMATCH/NOINT: partial match, no fan\n res <- final_activation(c(1,NA,1,1), c(NA,NA,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[4,1] <- res$a1\n a[4,2] <- res$a2\n b[7] <- res$b1\n b[8] <- res$b2\n ##\n ## e) 2MISMATCH/INT: \n res <- final_activation(c(1,NA,NA,1), c(NA,1,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[5,1] <- res$a1\n a[5,2] <- res$a2\n b[9] <- res$b1\n b[10] <- res$b2\n ##\n ## f) 2MISMATCH/NOINT: \n res <- final_activation(c(1,NA,NA,1), c(NA,NA,1,SF), N2=ND, csim=cuesim, weights=cweights, bl1=blc, bl2=dbl, times1=lp, times2=ldp)\n a[6,1] <- res$a1\n a[6,2] <- res$a2\n b[11] <- res$b1\n b[12] <- res$b2\n ##\n r <- rbind(r, apply(a,1,retrieve)) ## retrieved chunk index\n maxacts <- apply(a,1,max) ## maximum activation per condition\n l <- rbind(l, latency(maxacts)) ## latencies\n ##\n ta <- rbind(ta, a[,1]) ## target activations\n #\n baseact <- rbind(baseact, b)\n # finalact <- rbind(finalact, c(a[1,],a[3,]))\n }\n ## correct retrievals:\n c <- r \n c[r!=1] <- 0\n ## retrieval failures:\n f <- r \n f[r==0] <- 1; f[r!=0] <- 0\n ## misretrievals:\n m <- 1-c \n m[f==1] <- 0\n ##\n if(print!=0) print(colMeans(l))\n if(print!=0) print(colMeans(m))\n if(print!=0) print(colMeans(f))\n # colnames(baseact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n # colnames(finalact) <- c(\"match.int.ant\",\"match.int.dis\",\"mismatch.int.ant\", \"mismatch.int.dis\")\n return(list(l=l,c=c,m=m,f=f,baseact=baseact))\n}\n\n\n\n\n\n########################################################\n##\n## Test-run models\n##\n########################################################\n# reset_params()\n\n# lf <<- 0.4\n# mp <<- 0.2\n# ans <<- 0.15\n# cuesim <<- -1\n# fsf <<- 0\n# mas <<- 1\n# rth <<- -1.5\n# ldp <<- 1.5\n# cueweighting <<- 1\n# normalizeWeights <<- FALSE\n# model <- refl_model_4cond_mult_feature_mismatch(iterations=3000,print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4],colMeans(l)[5]-colMeans(l)[6]))\n\n\n# ## Original model: inhib/facil\n# gaze\n# rbrt\n# lf <<- .15\n# mp <<- 1.2\n# ans <<- 0.15\n# cuesim <<- 0\n# fsf <<- 0\n# mas <<- 3\n# w <<- 1\n# dbl <<- 0\n# model <- refl_model_4cond(print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4]))\n\n# ## Original model, prominent distr.:\n# dbl <<- 1\n# model <- refl_model_4cond(print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4]))\n\n\n\n# ## Exp1: none/inhib\n# lf <<- .3\n# mp <<- 1\n# ans <<- 0.2\n# cuesim <<- -1\n# fsf <<- 4\n# dbl <<- 0\n# model <- refl_model_4cond(iterations=3000,print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4]))\n\n\n# ## Prominent distr. \n# lf <<- .15\n# mp <<- 1.2\n# ans <<- 0.15\n# cuesim <<- -1\n# fsf <<- 0\n# dbl <<- 1\n# model <- refl_model_4cond(print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4]))\n\n\n# ## Exp2: mult distr\n# lf <<- .15\n# mp <<- 1.2\n# ans <<- 0.15\n# cuesim <<- 0\n# fsf <<- 0\n# mas <<- 3\n# w <<- 1\n# dbl <<- 0\n# model <- refl_model_4cond_mult_distr(print=1)\n# with(model, c(colMeans(l)[1]-colMeans(l)[2],colMeans(l)[3]-colMeans(l)[4]))\n\n\n\n\n\n# ########################################################\n# #########################################################\n\n# ## Exp2: inhib/-\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- -.6\n# fsf <- 4\n# ans <- 0.1\n# model <- similarity_model_3_exp2(1000, csim=cuesim, data=exp2, print=2)\n# fit2(exp2, round(colMeans(model$l)), print=2)\n\n# ## Multiple distr.: inhib/-\n# gaze\n# rbrt\n# lf <- .15\n# mp <- 1.2\n# cuesim <- -.3\n# fsf <- 4\n# ans <- 0.15\n# model <- similarity_model_3_mult_distr(1000, csim=cuesim, data=exp2, print=2)\n# fit(rbrt, round(colMeans(model$l)), print=2)\n\n\n\n# ## none/none\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- -.8\n# fsf <- 4\n# ans <- 0.1\n# similarity_model_3_exp1(1000, csim=cuesim, data=gaze, print=2)\n\n# ## none/facil\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- -.9\n# fsf <- 4\n# ans <- 0.1\n# similarity_model_3_exp1(1000, csim=cuesim, data=gaze, print=2)\n\n# ## inhib/facil\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- -.9\n# fsf <- 1\n# ans <- 0.1\n# similarity_model_3_exp1(1000, csim=cuesim, data=gaze, print=2)\n\n# ## inhib/none\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- -.8\n# fsf <- 1\n# ans <- 0.1\n# similarity_model_3_exp1(1000, csim=cuesim, data=gaze, print=2)\n\n\n# ## inhib/-\n# gaze\n# rbrt\n# lf <- .13\n# mp <- 1.2\n# cuesim <- 0\n# fsf <- 4\n# ans <- 0.1\n# similarity_model_3_exp1(1000, csim=cuesim, data=gaze, print=2)\n\n\n", "meta": {"hexsha": "ec3eecbd85f75510709d153732abc869acecff51", "size": 24260, "ext": "r", "lang": "R", "max_stars_repo_path": "chapters4to6_simulations/chapter_4/model/models-old.r", "max_stars_repo_name": "vasishth/RetrievalModels", "max_stars_repo_head_hexsha": "fc2a2843302ae8aef0c7309f1d5dae8a77ebab8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-03-05T15:49:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T15:49:49.000Z", "max_issues_repo_path": "chapters4to6_simulations/chapter_4/model/models-old.r", "max_issues_repo_name": "vasishth/RetrievalModels", "max_issues_repo_head_hexsha": "fc2a2843302ae8aef0c7309f1d5dae8a77ebab8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-06-08T10:53:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T11:14:40.000Z", "max_forks_repo_path": "chapters4to6_simulations/chapter_4/model/models-old.r", "max_forks_repo_name": "vasishth/RetrievalModels", "max_forks_repo_head_hexsha": "fc2a2843302ae8aef0c7309f1d5dae8a77ebab8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8345642541, "max_line_length": 177, "alphanum_fraction": 0.5561005771, "num_tokens": 8904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3214943326964557}} {"text": "## https://israeldi.github.io/bookdown/_book/monte-carlo-simulation-of-stock-portfolio-in-r-matlab-and-python.html\n\n##-----------------------------------------------------------------------------\n## setup\nos <- .Platform$OS.type\nif (os == 'windows') {\n ## load generic modules\n source(\"F:\\\\Documents\\\\01_Dave's Stuff\\\\Programs\\\\GitHub_home\\\\R-setup\\\\setup.r\")\n ## identify working folder\n path <- c(\"f:/Documents/01_Dave's Stuff/Programs/GitHub_home/Retirement/\")\n} else {\n ## os == unix\n source('~/GitHub_repos/R-setup/setup.r')\n path <- c('~/GitHub_repos/Retirement/')\n}\n## set working folder\nsetwd(path)\n## load local modules\nr_files <- list.files(paste(path, 'modules/', sep=''), pattern=\"*.[rR]$\", full.names=TRUE)\nfor (f in r_files) {\n ## cat(\"f =\",f,\"\\n\")\n source(f)\n}\n\nis.date <- function(x) inherits(x, 'Date')\n\n##-----------------------------------------------------------------------------\n## SET PARAMETERS FOR MONTE CARLO SIMULATIONS\n## Set number of Monte Carlo Simulations\nmc_rep <- 10\nperiod <- 'years'\n## Set simulation start and approximate end dates\nsim_start <- as.Date(format(Sys.Date(), \"%Y-%m-01\"))\nsim_end <- as.Date('2030-11-30') # must be a day in the period\n\n\n##-----------------------------------------------------------------------------\n## Define starting value and weights for each asset and total value\n## create matrix of values for each account\nvalue0 <- cbind(invest = 100000,\n ira = 200000,\n roth = 300000)\nnacct <- ncol(value0)\ntvalue0 <- sum(value0)\nweights <- c(value0[[1]]/tvalue0,\n value0[[2]]/tvalue0,\n value0[[3]]/tvalue0)\nprint(weights)\n\n## Define asset allocation for each account\nallocation <- '\naccount US_L US_S Inter Fixed Cash\ninvest 50 10 0 30 10\nira 40 30 5 20 5\nroth 50 30 10 10 0\n'\nallocation <- readall(allocation)\nrownames(allocation) <- allocation$account\nallocation$account <- NULL\nallocation <- as.matrix(allocation / 100)\nprint(allocation)\n\n\n##-----------------------------------------------------------------------------\n## OBTAIN BENCHMARK HISTORICAL DATA\n## category ETF description\n## ------------- --- ---------------\n## USL SPY S&P 500\n## USS IWM Russell 2000\n## International EFA MSCI EAFE (TRN)\n## Fixed AGG Bloomberg US Aggregate Bond\n## Cash SHV FTSE 3-month treasury bill\n\n## periods per year\nif (period == 'years') {\n nperiod <- 1\n} else if (period == 'months') {\n nperiod <- 12\n} else if (period == 'weeks') {\n nperiod <- 52\n} else {\n ## days\n ## number of periods will change a bit each year\n ## 365.25 (days on average per year) * 5/7 (proportion work days per week)\n ## - 6 (weekday holidays) - 3*5/7 (fixed date holidays) = 252.75 ≈ 253\n nperiod <- 253\n}\n\nout <- equityget(c('SPY', 'IWM', 'EFA', 'AGG', 'SHV'), from='1995-01-01',\n period=period)\nbenchclose <- out$close\nbenchtwr <- out$twr\ncolnames(benchclose) <- c('US_L', 'US_S', 'Inter', 'Fixed', 'Cash')\ncolnames(benchtwr) <- c('US_L', 'US_S', 'Inter', 'Fixed', 'Cash')\n## plot closing prices and TWR\nplotspace(1,2)\nplotxts(benchclose)\n## plotzoo(benchclose)\nplotxts(benchtwr)\n\n## only keep twr for dates where all are defined\nbenchtwr <- na.omit(benchtwr)\n\n\n##-----------------------------------------------------------------------------\n## DATA FOR EACH ASSET\n\n## Determine mean for each asset and covariance matrix\nreturn <- '\n Date invest ira roth\n1/31/17 0.01 0.02 0.03\n2/28/17 0.02 0.03 0.05\n3/31/17 0.05 0.04 0.30\n4/30/17 0.03 0.05 0.02\n5/31/17 0.05 0.04 0.02\n6/30/17 0.07 0.08 0.01\n7/31/17 0.08 0.07 -0.02\n8/31/17 0.05 0.07 0.02\n9/30/17 0.08 0.10 0.03\n10/31/17 0.09 0.10 0.05\n11/30/17 0.10 0.09 0.02\n12/31/17 0.10 0.09 0.03\n1/31/17 0.06 0.08 0.05\n2/28/17 0.03 0.04 0.06\n3/31/17 0.01 0.05 0.06\n'\n\n## set monthly changes to account\nmonthly_spending <- c( 1000, \n 0, \n 0)\nmonthly_saving <- c( 500, \n 0, \n 0)\nmonthly_change <- monthly_saving - monthly_spending\n\n## calculate changes per period\nperiod_change <- monthly_change * 12 / nperiod\n\n\n## set specific date spending and saving (specify at end of a period)\nsaving <- '\n Date invest ira roth\n2/28/22 0 2000 0 \n3/30/22 0 0 500\n4/30/22 0 1000 1000\n'\nsaving <- readall(saving)\n\nspending <- '\n Date invest ira roth\n1/31/22 1000 0 0\n4/30/22 0 500 0\n'\nspending <- readall(spending)\n\n## convert to XTS\n## note the format used below must match that in the dataframe being read\nsaving <- xts::as.xts(zoo::read.zoo(saving, index.column = 1, format = \"%m/%d/%y\" ))\nspending <- xts::as.xts(zoo::read.zoo(spending, index.column = 1, format = \"%m/%d/%y\" ))\n\n\n\n##-----------------------------------------------------------------------------\n## determine number of timesteps and create date sequence\nif (period == 'years') {\n ntimestep <- as.numeric(format(sim_end, \"%Y\")) - as.numeric(format(sim_start,\"%Y\"))\n ## Create sequence of dates at ends of periods for simulation \n ## (+1 on ntimestep is so start with initial value)\n Date <- seq(as.Date(sim_start), length=ntimestep+1, by=period) - 1\n} else if (period == 'months') {\n ntimestep <- lubridate::interval(sim_start, sim_end) %/% months(1) + 1\n Date <- seq(as.Date(sim_start), length=ntimestep+1, by=period) - 1\n} else if (period == 'weeks') {\n ntimestep <- ceiling( (sim_end - sim_start) / 7 ) # rounds up\n Date <- seq(as.Date(sim_start), length=ntimestep+1, by=period) - 1\n} else {\n ## period = 'days'\n ## install.packages('bizdays')\n holidays <- timeDate::holidayNYSE(year = c(2021:2051))\n bizdays::create.calendar(\"USA\", holiday =holidays, weekdays=c(\"saturday\", \"sunday\"))\n Date <- bizdays::bizseq(sim_start, sim_end, \"USA\")\n}\n## Number of timesteps for the simulation\nntimestep = length(Date) - 1 # minus 1 because Date constains time zero\n\n## split off 1st date since mc will only iterate on future dates\ndate0 <- Date[1]\ndatesim <- Date[2:length(Date)]\n\n\n##-----------------------------------------------------------------------------\n## READ IN DATA FOR EACH ASSET\n\n## ##----------------------\n## ## OLD\n## return_in <- as_tibble(readall(return))\n## \n## ## convert date field to date format\n## return_in$Date <- as.Date(return_in$Date, \"%m/%d/%y\")\n## \n## ## convert return columns as matrix for efficiency later\n## returnm <- as.matrix(return_in[2:ncol(return_in)])\n##\n## use above plus following to get old results\n## benchtwr <- returnm\n## ## OLD\n## ##----------------------\n\n## number of benchmarks used\nnbench <- ncol(benchtwr)\n\n## calculate mean return for each benchmark asset\nmeans <- colMeans(benchtwr)\n\n## Get the Variance Covariance Matrix of benchmark returns\n## pairsdf(as.matrix(benchtwr))\ncovarm <- cov(benchtwr)\nprint(covarm)\n\n## Lower Triangular Matrix from Choleski Factorization, L where L * t(L) = covarm\n## check with as.matrix(L) %*% as.matrix(t(L)) = covarm\n## needed for R_i = mean_i + L_ij * Z_ji\nL = t( chol(covarm) )\nprint(L)\n\n\ndlh need to rethink save_expand and spend_expand\ncurrently, there is no entry for the 0th year,\nbut I say additions and subtractions are at the end of every year\n\n\n\n## create xts object with row for each datesim and column for each account\naccounts <- names(spending)\nzeros <- xts::xts(matrix(0, length(datesim), length(accounts)),\n datesim, dimnames=list(NULL, accounts))\nsave_expand <- zeros\nspend_expand <- zeros\n\n## add user specified entries to saving\nfor (i in 1:nrow(saving)) {\n irow <- birk::which.closest(datesim, zoo::index(saving[i]))\n save_expand[irow,] <- saving[i,]\n}\n\n## add usser speified spending entries\nfor (i in 1:nrow(spending)) {\n irow <- birk::which.closest(datesim, zoo::index(spending[i]))\n spend_expand[irow,] <- spending[i,]\n}\n\n## create single xts object with the total amount added and removed\ninout <- save_expand - spend_expand\n\n## add every period additions and subtractions\nfor (i in 1:nacct) {\n inout[,i] <- inout[,i] + period_change[i]\n}\n\n\n##-----------------------------------------------------------------------------\n## START MONTE CARLO SIMULATION\n\n## initialize variables\n## twr and totalvalue matrices\n## row for each timestep\n## column for each mc sim\ntwr <- matrix(0, ntimestep, mc_rep)\ntotalvalue <- twr\n## same as above for value but with 2nd dimension for each account\nvalue <- array(0, dim=c(ntimestep, nacct, mc_rep))\n\n## Extend means vector to a matrix\n## one row for each benchmark repeated in columns for each timestep\nmeansm <- matrix(rep(means, ntimestep), nrow = nbench)\n\n## set seed if want to repeat exactly\nset.seed(200)\nfor (i in 1:mc_rep) {\n ## do following for each monte carlo simulation\n\n cat('simulation', i, '\\n')\n\n ## start with initial values for each account\n valueold <- value0\n \n ## obtain random z values for each account (rows) for each date increment (columns)\n Z <- matrix( rnorm( nbench * ntimestep ), ncol = ntimestep)\n\n ## simulate returns for each increment forward in time (assumed same as whatever data was)\n sim_benchtwr <- meansm + L %*% Z\n ## to view as a dataframe\n ## dfsim <- as_tibble(as.data.frame(t(sim_benchtwr)))\n\n ## Calculate vector of portfolio returns\n twr_i <- cumprod( weights %*% allocation %*% sim_benchtwr + 1 ) -1 # ntimestep entries\n \n ## Add it to the monte-carlo matrix\n twr[,i] <- twr_i;\n\n ## figure out account values and new weights\n for (j in 1:ntimestep) {\n ## for each time increment\n ## if (j == ntimestep-1) browser()\n cat('simulation', i, '; timestep', j, '\\n')\n \n ## growth due to market\n sb <- sim_benchtwr[,j] # vector of bencmark returns for time j\n growth <- t( allocation %*% sb ) * valueold\n \n ## add or remove funds at end of each period\n in_out <- inout[j,]\n \n ## value for simulation i\n value[j,,i] <- as.numeric(valueold + growth + in_out)\n ## value for each account\n valueold <- value[j,,i]\n ## total value for all accounts combined\n totalvalue[j,i] <- sum(valueold)\n \n ## recalculate weights after adjustments\n weights <- as.numeric(valueold / sum(valueold))\n }\n}\n\n##-----------------------------------------------------------------------------\n## GATHER RESULTS\n\n## put twr results into dataframe\ntwr <- as.data.frame(twr)\n## add row for starting value\nones <- rep(0, ncol(twr))\ntwr <- rbind(ones, twr)\n## ## add date\n## twr <- as_tibble(cbind(Date=Date, twr))\n\n## put total value results into dataframe\ntotalvalue <- as.data.frame(totalvalue)\ntotalvalue <- rbind(sum(value0), totalvalue)\n## totalvalue <- as_tibble(cbind(Date=Date, totalvalue))\n\n## value is size ntimestep x nbench x mc_rep\n## e.g., value[1,,2] returns 1st timestep results for all account values for mc_rep=2\n## value[,,1] returns all timestep results for all account values for mc_rep=1\n## value[,1,] returns all timestep results for 1st account for all mc_reps\n\n\n\n##-----------------------------------------------------------------------------\n## DISPLAY RESULTS\n\n## plot results\nplotspace(2,1)\n\n## PLOT TWR\n## --------\n## first establish plot area\nylim <- range(twr)\nplot(Date, twr$V1, type='n',\n ylab='Simulation Returns',\n ylim=ylim)\nfor (i in 2:ncol(twr)) {\n lines(Date, t(twr[i]), type='l')\n}\n\n## Construct Confidential Intervals for returns\n## first define function\nci <- function(df, conf) {\n ## calculate confidence limit for specified confidence level\n ## note specified conf = 1 - alpha\n ## i.e., if want alpha=0.05 to get 95% conf limit, specify 0.95\n apply(df, 1, function(x) quantile(x, conf))\n}\n## create dataframe of confidence intervals\ndf <- twr\ncis <- as_tibble( data.frame(Date,\n conf_99.9_upper_percent = ci(df, 0.999),\n conf_99.0_upper_percent = ci(df, 0.99),\n conf_95.0_upper_percent = ci(df, 0.95),\n conf_50.0_percent = ci(df, 0.5),\n conf_95.0_lower_percent = ci(df, 0.05),\n conf_99.0_lower_percent = ci(df, 0.01),\n conf_99.9_lower_percent = ci(df, 0.001)) )\n\n## plot confidence intervals on simulation\nlines(cis$Date, cis$conf_99.9_upper_percent, lwd=4, lty=2, col='red')\nlines(cis$Date, cis$conf_50.0_percent , lwd=4, col='red')\nlines(cis$Date, cis$conf_99.9_lower_percent, lwd=4, lty=2, col='red')\nlegend('topleft', \n legend=c('simulation', 'upper 99.99', 'mean', 'lower 99.99'),\n col=c('black', 'red', 'red', 'red'),\n lty=c(1,2,1,2))\n\n\n\n\n\n## PLOT VALUE\n## ----------\n## first establish plot area\nylim <- range(totalvalue)\nplot(Date, totalvalue$V1, type='n',\n ylab='Simulation Value',\n ylim=ylim)\nfor (i in 2:ncol(totalvalue)) {\n lines(Date, t(totalvalue[i]), type='l')\n}\n\n## Construct Confidential Intervals for returns\n## first define function\nci <- function(df, conf) {\n ## calculate confidence limit for specified confidence level\n ## note specified conf = 1 - alpha\n ## i.e., if want alpha=0.05 to get 95% conf limit, specify 0.95\n apply(df, 1, function(x) quantile(x, conf))\n}\n## create dataframe of confidence intervals\ndf <- totalvalue\ncis <- as_tibble( data.frame(Date,\n conf_99.9_upper_percent = ci(df, 0.999),\n conf_99.0_upper_percent = ci(df, 0.99),\n conf_95.0_upper_percent = ci(df, 0.95),\n conf_90.0_upper_percent = ci(df, 0.90),\n conf_50.0_percent = ci(df, 0.50),\n conf_90.0_lower_percent = ci(df, 0.10),\n conf_95.0_lower_percent = ci(df, 0.05),\n conf_99.0_lower_percent = ci(df, 0.01),\n conf_99.9_lower_percent = ci(df, 0.001)) )\n\n## plot confidence intervals on simulation\nlines(cis$Date, cis$conf_99.9_upper_percent, lwd=4, lty=2, col='red')\nlines(cis$Date, cis$conf_50.0_percent , lwd=4, col='red')\nlines(cis$Date, cis$conf_99.9_lower_percent, lwd=4, lty=2, col='red')\nlegend('topleft', \n legend=c('simulation', 'upper 99.99', 'mean', 'lower 99.99'),\n col=c('black', 'red', 'red', 'red'),\n lty=c(1,2,1,2))\n\n\n##-----------------------------------------------------------------------------\n## final results at end of simulation\n## Porfolio Returns statistics at end of simulation\ncum_final <- as.numeric( twr[nrow(twr),] )\ncum_final_stats <- data.frame(mean = mean(cum_final),\n median = median(cum_final),\n sd = sd(cum_final))\nprint(cum_final_stats)\n\nfinal <- cbind(save_expand, spend_expand[2:ncol(spend_expand)],\n ci(twr, 0.001), ci(totalvalue, 0.001))\ncat(' Saving Spending TWR (99.9% LB CI) Value (99.9% LB CI)\\n',\n ' ------------------ ------------------ ------------------ -------------------\\n')\nprint(final)\nci(twr, 0.999)\n\n\n## ## create dataframe of mean and upper/lower ci for each account\n## value <- data.frame(matrix(0, # Create data frame of zeros\n## nrow = length(datesim),\n## ncol = mc_rep))\n## for (i in 1:nbench) {\n## cat('account', i, '\\n')\n## value <- value[,i,]\n## }\n", "meta": {"hexsha": "d324470a6993ab80f8133f5fd6757add4cf154e1", "size": 15841, "ext": "r", "lang": "R", "max_stars_repo_path": "retire.r", "max_stars_repo_name": "dhjelmar/Retirement", "max_stars_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "retire.r", "max_issues_repo_name": "dhjelmar/Retirement", "max_issues_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "retire.r", "max_forks_repo_name": "dhjelmar/Retirement", "max_forks_repo_head_hexsha": "2f844025e72d89c241aac5a6bd14780c48bb8dbb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9935622318, "max_line_length": 114, "alphanum_fraction": 0.5694716243, "num_tokens": 4462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3214674503658705}} {"text": "# Calculate warming of the hottest hour\n# Also calculate hottest future hours (add to climatology)\n\n\nrequire(ncdf4)\nrequire(abind)\nrequire(raster)\nrequire(data.table)\n\n###################\n## Read in data\n###################\n\n# read in TXx rcp26\ninfile <- nc_open('data_dl/cmip5/txx_yr_modmean_rcp26_ave.nc') # tasmax for each month\n\t# print(infile)\n\ttasmax26 <- ncvar_get(infile, 'txxETCCDI') # 144 x 72 x 240 lon x lat x years 1861-2100)\n\tdim(tasmax26)\n\tdimnames(tasmax26) <- list(lon=1:144, lat=1:72, time=1:240)\n\tdimnames(tasmax26)[[1]] <- infile$var[['txxETCCDI']]$dim[[1]]$vals # add lon\n\tdimnames(tasmax26)[[2]] <- infile$var[['txxETCCDI']]$dim[[2]]$vals # add lat\n\tdimnames(tasmax26)[[3]] <- 1861:2100 # year of the CMIP5 time dimension\n\tnc_close(infile)\n\n\n# read in tos rcp26\ninfile <- nc_open('data_dl/cmip5/tos_Omon_modmean_rcp26_ave.nc') # tos for each month\n\t# print(infile)\n\ttos26 <- ncvar_get(infile, 'tos') # tos 288 x 144 x 2800 lon x lat x months 1861-2100\n\tdim(tos26)\n\tdimnames(tos26) <- list(lon=1:288, lat=1:144, time=1:2880)\n\tdimnames(tos26)[[1]] <- infile$var[['tos']]$dim[[1]]$vals # add lon\n\tdimnames(tos26)[[2]] <- infile$var[['tos']]$dim[[2]]$vals # add lat\n\tdimnames(tos26)[[3]] <- paste(rep(1861:2100, rep(12, length(1861:2100))), paste('_', 1:12, sep=''), sep='') # year and month of the CMIP5 time dimension\n\tnc_close(infile)\n\n# read in TXx rcp85\ninfile <- nc_open('data_dl/cmip5/txx_yr_modmean_rcp85_ave.nc') # tasmax for each month\n\t# print(infile)\n\ttasmax85 <- ncvar_get(infile, 'txxETCCDI') # 144 x 72 x 240 lon x lat x years 1861-2100)\n\tdim(tasmax85)\n\tdimnames(tasmax85) <- list(lon=1:144, lat=1:72, time=1:240)\n\tdimnames(tasmax85)[[1]] <- infile$var[['txxETCCDI']]$dim[[1]]$vals # add lon\n\tdimnames(tasmax85)[[2]] <- infile$var[['txxETCCDI']]$dim[[2]]$vals # add lat\n\tdimnames(tasmax85)[[3]] <- 1861:2100 # year of the CMIP5 time dimension\n\tnc_close(infile)\n\n\n# read in tos rcp85\ninfile <- nc_open('data_dl/cmip5/tos_Omon_modmean_rcp85_ave.nc') # tos for each month\n\t# print(infile)\n\ttos85 <- ncvar_get(infile, 'tos') # tos 288 x 144 x 2800 lon x lat x months 1861-2100\n\tdim(tos85)\n\tdimnames(tos85) <- list(lon=1:288, lat=1:144, time=1:2880)\n\tdimnames(tos85)[[1]] <- infile$var[['tos']]$dim[[1]]$vals # add lon\n\tdimnames(tos85)[[2]] <- infile$var[['tos']]$dim[[2]]$vals # add lat\n\tdimnames(tos85)[[3]] <- paste(rep(1861:2100, rep(12, length(1861:2100))), paste('_', 1:12, sep=''), sep='') # year and month of the CMIP5 time dimension\n\tnc_close(infile)\n\n# read in DTR (daily temperature range)\nload('temp/dtrclimatology_interp1.25.rdata') # dtr125\n\n\n# read in max hr climatologies\nload('temp/tosmax.rdata') # tosmax 0.25x0.25 from OISST daily + HadDTR\nload('temp/hadex2_txx.rdata') # hadex2txx 2.5x3.75 from HadEX2\n\ttasmax <- hadex2txx\n\n##################################################################################\n# permute CMIP5 dimensions: lat x lon x time\n# lat 90 to -90; lon 0 to 360\n##################################################################################\n# change dimension order\ntasmax26 <- aperm(tasmax26, c(2,1,3))\ntasmax85 <- aperm(tasmax85, c(2,1,3))\ntos26 <- aperm(tos26, c(2,1,3))\ntos85 <- aperm(tos85, c(2,1,3))\n\n# rotate so columns 0 -> 360 lon, rows 90 -> -90 lat\n\t# tasmax26\nlons <- as.numeric(colnames(tasmax26)) # good\n\nlats <- as.numeric(rownames(tasmax26))\nnewlatord <- sort(lats, decreasing=TRUE)\nnewrownms <- as.character(newlatord)\nnewlatord <- as.character(newlatord)\n\ntasmax26 <- tasmax26[newlatord, ,]\n\n\t#image(tasmax26[,,1]) # north pole should be at the left, America at the top\n\n\t# tasmax85\nlons <- as.numeric(colnames(tasmax85)) # good\n\nlats <- as.numeric(rownames(tasmax85))\nnewlatord <- sort(lats, decreasing=TRUE)\nnewrownms <- as.character(newlatord)\nnewlatord <- as.character(newlatord)\n\ntasmax85 <- tasmax85[newlatord, ,]\n\n\t#image(tasmax85[,,1])\n\n\t# tos26\nlons <- as.numeric(colnames(tos26)) # good\n\nlats <- as.numeric(rownames(tos26))\nnewlatord <- sort(lats, decreasing=TRUE)\nnewrownms <- as.character(newlatord)\nnewlatord <- as.character(newlatord)\n\ntos26 <- tos26[newlatord, ,]\n\n\t#image(tos26[,,1])\n\n\t# tos85\nlons <- as.numeric(colnames(tos85)) # good\n\nlats <- as.numeric(rownames(tos85))\nnewlatord <- sort(lats, decreasing=TRUE)\nnewrownms <- as.character(newlatord)\nnewlatord <- as.character(newlatord)\n\ntos85 <- tos85[newlatord, ,]\n\n\t#image(tos85[,,1])\n\n############################\n# Compute tosmax26 and 86 (CMIP5 temperatures)\n# Irrelevant since we compute a delta?\n############################\n# extend dtr125 so that it matches the dimensions of tos85\ndtr125l <- abind(list(dtr125)[rep(1,dim(tos85)[3]/dim(dtr125)[3])], along=3)\n\tdim(dtr125l)\n\tdim(tos26)\n\tdim(tos85)\n\n# add to get daily maximum\ntosmax26 <- tos26 + 0.5*dtr125l\ntosmax85 <- tos85 + 0.5*dtr125l\n\n\n#############################################\n# Calculate CMIP5 anomalies from 1986-2005\n#############################################\nclimtime <- as.character(1986:2005) # year of the climatology period\nfuttime <- as.character(2006:2100) # year the future period\n\n# Reshape CMIP5 to lat x lon x month x year\n\t# not needed for tasmax26 and tasmax85 since already annual TXx\n\t\n\t# tosmax26\nnms <- dimnames(tosmax26)\nmos <- as.numeric(unlist(strsplit(nms[[3]], split='_'))[seq(2,length(nms[[3]])*2,by=2)]) # months\nyrs <- as.numeric(unlist(strsplit(nms[[3]], split='_'))[seq(1,length(nms[[3]])*2,by=2)]) # years\ndm <- dim(tosmax26)\ntosmax26bymo <- array(tosmax26, dim=c(dm[1], dm[2], 12, dm[3]/12), dimnames=list(lat=nms[[1]], lon=nms[[2]], mo=1:12, year=sort(unique(yrs)))) # add a month dimension (3rd dimension)\n\n\t# tosmax85\nnms <- dimnames(tosmax85)\nmos <- as.numeric(unlist(strsplit(nms[[3]], split='_'))[seq(2,length(nms[[3]])*2,by=2)]) # months\nyrs <- as.numeric(unlist(strsplit(nms[[3]], split='_'))[seq(1,length(nms[[3]])*2,by=2)]) # years\ndm <- dim(tosmax85)\ntosmax85bymo <- array(tosmax85, dim=c(dm[1], dm[2], 12, dm[3]/12), dimnames=list(lat=nms[[1]], lon=nms[[2]], mo=1:12, year=sort(unique(yrs)))) # add a month dimension (3rd dimension)\n\n\n# find highest daily max within years (TXx)\ntasmax26yr <- tasmax26 # already annual TXx on land (HadEX2)\ntasmax85yr <- tasmax85\ntosmax26yr <- apply(tosmax26bymo, MARGIN=c(1,2,4), FUN=max)\ntosmax85yr <- apply(tosmax85bymo, MARGIN=c(1,2,4), FUN=max)\n\n# calculate climatology as the highest TXx across 20-year chunk\ntasmax26clim <- apply(tasmax26yr[,,climtime], MARGIN=c(1,2), FUN=max) # climatological average for CMIP5\ntasmax26climlong <- abind(list(tasmax26clim)[rep(1,length(futtime))], along=3) # expand to match future projections\n\tdim(tasmax26climlong) \n\ntasmax85clim <- apply(tasmax85yr[,,climtime], MARGIN=c(1,2), FUN=max) # climatological average for CMIP5\ntasmax85climlong <- abind(list(tasmax85clim)[rep(1,length(futtime))], along=3) # expand to match future projections\n\tdim(tasmax85climlong) \n\ntosmax26clim <- apply(tosmax26yr[,,climtime], MARGIN=c(1,2), FUN=max)\ntosmax26climlong <- abind(list(tosmax26clim)[rep(1,length(futtime))], along=3)\n\tdim(tosmax26climlong)\n\ntosmax85clim <- apply(tosmax85yr[,,climtime], MARGIN=c(1,2), FUN=max)\ntosmax85climlong <- abind(list(tosmax85clim)[rep(1,length(futtime))], along=3)\n\tdim(tosmax85climlong)\n\n\n# calculate deltas by years\ntasmax26dyr <- tasmax26yr[,,futtime] - tasmax26climlong # CMIP5 deltas\ntasmax85dyr <- tasmax85yr[,,futtime] - tasmax85climlong # CMIP5 deltas\ntosmax26dyr <- tosmax26yr[,,futtime] - tosmax26climlong\ntosmax85dyr <- tosmax85yr[,,futtime] - tosmax85climlong\n\n\n# write out for use in future_tsm_byyear.r\nsave(tasmax26dyr, file='temp/tasmax26dyr.rdata')\nsave(tasmax85dyr, file='temp/tasmax85dyr.rdata')\nsave(tosmax26dyr, file='temp/tosmax26dyr.rdata')\nsave(tosmax85dyr, file='temp/tosmax85dyr.rdata')\n\n\n#######################################################\n# average warming by latitude for 2081-2100 and write out\n# for use in figure\n#######################################################\n# Make a \"not ocean\" mask\nsearast <- raster(!is.na(tos26[,,1]), xmn=0, xmx=360, ymn=-90, ymx=90) # 1 for ocean, 0 for land\nlandrast <- raster(tasmax26dyr[,,1], xmn=0, xmx=360, ymn=-90, ymx=90)\nseamask <- round(resample(searast, landrast, method='bilinear')) # includes areas >=50% land as land (floor): 0 is land, 1 is ocean\nseamask <- as.matrix(seamask)\nseamask[seamask==1] <- NA # turn ocean to NA\nseamask <- abind(list(seamask)[rep(1,dim(tasmax26dyr)[3])], along=3) # expand to match future projections\n\n# mask out ocean for terrestrial air temp\ntasmax26dyrmask <- tasmax26dyr + seamask\ntasmax85dyrmask <- tasmax85dyr + seamask\n\n# data.frame to hold results\nlstwarmingbylat <- data.table(lat=as.numeric(dimnames(tasmax26dyr)[[1]]))\nsstwarmingbylat <- data.table(lat=as.numeric(dimnames(tosmax26dyr)[[1]]))\n\n# average by lat\nlstwarmingbylat$tasmax26 <- apply(tasmax26dyrmask[,,as.character(2081:2100)], MARGIN=1, FUN=mean, na.rm=TRUE)\nlstwarmingbylat$tasmax85 <- apply(tasmax85dyrmask[,,as.character(2081:2100)], MARGIN=1, FUN=mean, na.rm=TRUE)\nsstwarmingbylat$tosmax26 <- apply(tosmax26dyr[,,as.character(2081:2100)], MARGIN=1, FUN=mean, na.rm=TRUE)\nsstwarmingbylat$tosmax85 <- apply(tosmax85dyr[,,as.character(2081:2100)], MARGIN=1, FUN=mean, na.rm=TRUE)\n\t\n\t# plot to check\n\tlstwarmingbylat[,plot(lat, tasmax26, type='l', ylim=c(0,6))]\n\tlstwarmingbylat[,lines(lat, tasmax85, lty=2)]\n\tsstwarmingbylat[,lines(lat, tosmax26, col='blue')]\n\tsstwarmingbylat[,lines(lat, tosmax85, col='blue', lty=2)]\n\n# SD by lat\nlstwarmingbylat$tasmax26sd <- apply(tasmax26dyrmask[,,as.character(2081:2100)], MARGIN=1, FUN=sd, na.rm=TRUE)\nlstwarmingbylat$tasmax85sd <- apply(tasmax85dyrmask[,,as.character(2081:2100)], MARGIN=1, FUN=sd, na.rm=TRUE)\nsstwarmingbylat$tosmax26sd <- apply(tosmax26dyr[,,as.character(2081:2100)], MARGIN=1, FUN=sd, na.rm=TRUE)\nsstwarmingbylat$tosmax85sd <- apply(tosmax85dyr[,,as.character(2081:2100)], MARGIN=1, FUN=sd, na.rm=TRUE)\n\n# Sample size by lat\nlstwarmingbylat$tasmax26n <- apply(tasmax26dyrmask[,,as.character(2081)], MARGIN=1, FUN=function(x) sum(!is.na(x)))\nlstwarmingbylat$tasmax85n <- apply(tasmax85dyrmask[,,as.character(2081)], MARGIN=1, FUN=function(x) sum(!is.na(x)))\nsstwarmingbylat$tosmax26n <- apply(tosmax26dyr[,,as.character(2081)], MARGIN=1, FUN=function(x) sum(!is.na(x)))\nsstwarmingbylat$tosmax85n <- apply(tosmax85dyr[,,as.character(2081)], MARGIN=1, FUN=function(x) sum(!is.na(x)))\n\n\n# write out\nwrite.csv(lstwarmingbylat, file='temp/warmingmaxhr_bylat_land.csv')\nwrite.csv(sstwarmingbylat, file='temp/warmingmaxhr_bylat_ocean.csv')\n\n\n\n##################################################################\n# Add deltas to climatology to get future temperatures 2081-2100\n##################################################################\n# average deltas for 2081-2100\ntasmax26d2100 <- apply(tasmax26dyr[,,dimnames(tasmax26dyr)[[3]] %in% 2081:2100], MARGIN=c(1,2), FUN=max)\ntasmax85d2100 <- apply(tasmax85dyr[,,dimnames(tasmax85dyr)[[3]] %in% 2081:2100], MARGIN=c(1,2), FUN=max)\ntosmax26d2100 <- apply(tosmax26dyr[,,dimnames(tosmax26dyr)[[3]] %in% 2081:2100], MARGIN=c(1,2), FUN=max)\ntosmax85d2100 <- apply(tosmax85dyr[,,dimnames(tosmax85dyr)[[3]] %in% 2081:2100], MARGIN=c(1,2), FUN=max)\n\n# create rasters for interpolation\ntasmax26d2100r <- raster(tasmax26d2100, xmn=0, xmx=360, ymn=-90, ymx=90)\ntasmax85d2100r <- raster(tasmax85d2100, xmn=0, xmx=360, ymn=-90, ymx=90)\ntosmax26d2100r <- raster(tosmax26d2100, xmn=0, xmx=360, ymn=-90, ymx=90)\ntosmax85d2100r <- raster(tosmax85d2100, xmn=0, xmx=360, ymn=-90, ymx=90)\n\ntasmaxr <- raster(tasmax, xmn=0, xmx=360, ymn=-90, ymx=90)\ntosmaxr <- raster(tosmax, xmn=0, xmx=360, ymn=-90, ymx=90)\n\n# interpolate to resolution of the climatology (2.5x3.75 on land, 0.25x0.25 in ocean)\ntasmax26d2100_025r <- resample(tasmax26d2100r, tasmaxr, method='bilinear')\ntasmax85d2100_025r <- resample(tasmax85d2100r, tasmaxr, method='bilinear')\ntosmax26d2100_025r <- resample(tosmax26d2100r, tosmaxr, method='bilinear')\ntosmax85d2100_025r <- resample(tosmax85d2100r, tosmaxr, method='bilinear')\n\n# add deltas to climatologies\ntasmax26_2100r <- tasmaxr + tasmax26d2100_025r\ntasmax85_2100r <- tasmaxr + tasmax85d2100_025r\ntosmax26_2100r <- tosmaxr + tosmax26d2100_025r\ntosmax85_2100r <- tosmaxr + tosmax85d2100_025r\n\n# convert to matrices\ntasmax26_2100 <- as.matrix(tasmax26_2100r)\ntasmax85_2100 <- as.matrix(tasmax85_2100r)\ntosmax26_2100 <- as.matrix(tosmax26_2100r)\ntosmax85_2100 <- as.matrix(tosmax85_2100r)\n\n\n\n#############################################\n# Average future temperatures by latitude\n#############################################\n\n# data.frame to hold results\nlstmaxhrlat_2100 <- data.table(lat=yFromRow(tasmax26_2100r, 1:nrow(tasmax26_2100r)))\nsstmaxhrlat_2100 <- data.table(lat=yFromRow(tosmax26_2100r,1:nrow(tosmax26_2100r)))\n\n# average by lat\nlstmaxhrlat_2100$tasmax26 <- apply(tasmax26_2100, MARGIN=1, FUN=mean, na.rm=TRUE)\nlstmaxhrlat_2100$tasmax85 <- apply(tasmax85_2100, MARGIN=1, FUN=mean, na.rm=TRUE)\nsstmaxhrlat_2100$tosmax26 <- apply(tosmax26_2100, MARGIN=1, FUN=mean, na.rm=TRUE)\nsstmaxhrlat_2100$tosmax85 <- apply(tosmax85_2100, MARGIN=1, FUN=mean, na.rm=TRUE)\n\t\n\t# plot to check\n\tlstmaxhrlat_2100[,plot(lat, tasmax26, type='l', ylim=c(0,50))]\n\tlstmaxhrlat_2100[,lines(lat, tasmax85, lty=2)]\n\tsstmaxhrlat_2100[,lines(lat, tosmax26, col='blue')]\n\tsstmaxhrlat_2100[,lines(lat, tosmax85, col='blue', lty=2)]\n\n# SD by lat\nlstmaxhrlat_2100$tasmax26sd <- apply(tasmax26_2100, MARGIN=1, FUN=sd, na.rm=TRUE)\nlstmaxhrlat_2100$tasmax85sd <- apply(tasmax85_2100, MARGIN=1, FUN=sd, na.rm=TRUE)\nsstmaxhrlat_2100$tosmax26sd <- apply(tosmax26_2100, MARGIN=1, FUN=sd, na.rm=TRUE)\nsstmaxhrlat_2100$tosmax85sd <- apply(tosmax85_2100, MARGIN=1, FUN=sd, na.rm=TRUE)\n\n# Sample size by lat\nlstmaxhrlat_2100$tasmax26n <- apply(tasmax26_2100, MARGIN=1, FUN=function(x) sum(!is.na(x)))\nlstmaxhrlat_2100$tasmax85n <- apply(tasmax85_2100, MARGIN=1, FUN=function(x) sum(!is.na(x)))\nsstmaxhrlat_2100$tosmax26n <- apply(tosmax26_2100, MARGIN=1, FUN=function(x) sum(!is.na(x)))\nsstmaxhrlat_2100$tosmax85n <- apply(tosmax85_2100, MARGIN=1, FUN=function(x) sum(!is.na(x)))\n\n# write out\nwrite.csv(lstmaxhrlat_2100, file='temp/lstmaxhrlat_2081-2100.csv')\nwrite.csv(sstmaxhrlat_2100, file='temp/sstmaxhrlat_2081-2100.csv')\n", "meta": {"hexsha": "107238a4967b6faf7e6885ccef06967ac03addac", "size": 14158, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/future_temperatures_maxhr.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/future_temperatures_maxhr.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/future_temperatures_maxhr.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_forks_repo_licenses": ["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.0334346505, "max_line_length": 182, "alphanum_fraction": 0.6917643735, "num_tokens": 5239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.32115228960449516}} {"text": "\n\n# Snow crab --- Areal unit modelling of habitat \n\n# -------------------------------------------------\n# Part 1 -- construct basic parameter list defining the main characteristics of the study\n\n\n year.assessment = 2020\n\n p = bio.snowcrab::snowcrab_parameters( \n project_class=\"carstm\", \n yrs=2000:year.assessment, \n areal_units_type=\"tesselation\", \n arstm_model_label = \"nonseparable_space-time_pa_fishable_binomial\",\n selection = list(type = \"presence_absence\")\n )\n\n if (0) {\n\n p$selection$type = \"presence_absence\"\n p$selection$biologicals=list(\n spec_bio=bio.taxonomy::taxonomy.recode( from=\"spec\", to=\"parsimonious\", tolookup=p$groundfish_species_code ),\n sex=0, # male\n mat=1, # do not use maturity status in groundfish data as it is suspect ..\n len= c( 95, 200 )/10, # mm -> cm ; aegis_db in cm\n ranged_data=\"len\"\n )\n p$selection$survey=list(\n data.source = c(\"snowcrab\", \"groundfish\", \"logbook\"),\n yr = p$yrs, # time frame for comparison specified above\n settype = 1, # same as geartype in groundfish_survey_db\n polygon_enforce=TRUE, # make sure mis-classified stations or incorrectly entered positions get filtered out\n strata_toremove = NULL #, # emphasize that all data enters analysis initially ..\n # ranged_data = c(\"dyear\") # not used .. just to show how to use range_data\n )\n p$variabletomodel = \"pa\"\n \n p$carstm_model_label = \"nonseparable_space-time_pa_fishable_binomial\"\n p$carstm_modelengine = \"inla\"\n p$formula = as.formula( paste(\n p$variabletomodel, ' ~ 1 ',\n ' + f( dyri, model=\"ar1\", hyper=H$ar1 ) ',\n ' + f( inla.group( t, method=\"quantile\", n=11 ), model=\"rw2\", scale.model=TRUE, hyper=H$rw2) ',\n ' + f( inla.group( z, method=\"quantile\", n=11 ), model=\"rw2\", scale.model=TRUE, hyper=H$rw2) ',\n ' + f( inla.group( substrate.grainsize, method=\"quantile\", n=11 ), model=\"rw2\", scale.model=TRUE, hyper=H$rw2) ',\n ' + f( inla.group( pca1, method=\"quantile\", n=11 ), model=\"rw2\", scale.model=TRUE, hyper=H$rw2) ',\n ' + f( inla.group( pca2, method=\"quantile\", n=11 ), model=\"rw2\", scale.model=TRUE, hyper=H$rw2) ',\n ' + f( space, model=\"bym2\", graph=slot(sppoly, \"nb\"), scale.model=TRUE, constr=TRUE, hyper=H$bym2 ) '\n ' + f( space_time, model=\"bym2\", graph=slot(sppoly, \"nb\"), group=time_space, scale.model=TRUE, constr=TRUE, hyper=H$bym2, control.group=list(model=\"ar1\", hyper=H$ar1_group)) '\n ) )\n\n p$family = \"binomial\" # \"nbinomial\", \"betabinomial\", \"zeroinflatedbinomial0\" , \"zeroinflatednbinomial0\"\n p$carstm_model_inla_control_familiy = list(control.link=list(model='logit'))\n\n # p$family = \"zeroinflatedbinomial1\", # \"binomial\", # \"nbinomial\", \"betabinomial\", \"zeroinflatedbinomial0\" , \"zeroinflatednbinomial0\"\n # p$carstm_model_inla_control_familiy = NULL\n\n }\n\n\n\n sppoly = areal_units( p=p ) # to reload\n plot( sppoly[, \"au_sa_km2\"] )\n\n\n M = snowcrab.db( p=p, DS=\"carstm_inputs\", redo=TRUE ) # will redo if not found\n\n fit = carstm_model( p=p, data='snowcrab.db( p=p, DS=\"carstm_inputs\" )' ) # 151 configs and long optim .. 19 hrs\n \n\n\n\n # fit = carstm_model( p=p, DS=\"carstm_modelled_fit\")\n\n # extract results\n if (0) {\n # very large files .. slow \n fit = carstm_model( p=p, DS=\"carstm_modelled_fit\" ) # extract currently saved model fit\n plot(fit)\n plot(fit, plot.prior=TRUE, plot.hyperparameters=TRUE, plot.fixed.effects=FALSE )\n }\n\n\n res = carstm_model( p=p, DS=\"carstm_modelled_summary\" ) # to load currently saved results\n res$summary$dic$dic\n res$summary$dic$p.eff\n res$dyear\n\n\n plot_crs = p$aegis_proj4string_planar_km\n coastline=aegis.coastline::coastline_db( DS=\"eastcoast_gadm\", project_to=plot_crs )\n isobaths=aegis.bathymetry::isobath_db( depths=c(50, 100, 200, 400), project_to=plot_crs )\n managementlines = aegis.polygons::area_lines.db( DS=\"cfa.regions\", returntype=\"sf\", project_to=plot_crs )\n\n time_match = list( year=as.character(2020) )\n carstm_map( res=res, \n vn=\"predictions\", \n time_match=time_match , \n coastline=coastline,\n managementlines=managementlines,\n isobaths=isobaths,\n main=paste(\"Habitat probability - mature male \", paste0(time_match, collapse=\"-\") ) \n )\n \n\n # map all :\n vn \"= predictions\"\n\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"predicted.probability.observation\" )\n\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n brks = pretty( res[[vn]] )\n\n for (y in res$year ){\n\n time_match = list( year=y )\n fn_root = paste(\"Predicted_abundance\", paste0(time_match, collapse=\"-\"), sep=\"_\")\n fn = file.path( outputdir, paste(fn_root, \"png\", sep=\".\") )\n\n carstm_map( \n res=res, \n vn=vn, \n time_match=time_match, \n breaks =brks,\n# palette=\"-RdYlBu\",\n coastline=coastline,\n isobaths=isobaths,\n managementlines=managementlines,\n main=paste(\"Habitat probability - mature male \", paste0(time_match, collapse=\"-\") ),\n outfilename=fn\n ) \n\n }\n \n\n\n snowcrab.db(p=p, DS=\"carstm_output_compute\" )\n \n RES = snowcrab.db(p=p, DS=\"carstm_output_timeseries\" )\n\n pa = snowcrab.db(p=p, DS=\"carstm_output_spacetime_pa\" )\n\n# plots with 95% PI\n\n outputdir = file.path( p$modeldir, p$carstm_model_label, \"aggregated_biomass_timeseries\" )\n\n if ( !file.exists(outputdir)) dir.create( outputdir, recursive=TRUE, showWarnings=FALSE )\n\n (fn = file.path( outputdir, \"cfa_all.png\"))\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfaall ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Prob of observing snow crab\", xlab=\"\", ylim=c(0,1))\n lines( cfaall_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfaall_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n (fn = file.path( outputdir, \"cfa_south.png\") )\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfasouth ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Prob of observing snow crab\", xlab=\"\", ylim=c(0,1))\n lines( cfasouth_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfasouth_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n (fn = file.path( outputdir, \"cfa_north.png\"))\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfanorth ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Prob of observing snow crab\", xlab=\"\", ylim=c(0,1))\n lines( cfanorth_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfanorth_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n (fn = file.path( outputdir, \"cfa_4x.png\"))\n png( filename=fn, width=3072, height=2304, pointsize=12, res=300 )\n plot( cfa4x ~ yrs, data=RES, lty=\"solid\", lwd=4, pch=20, col=\"slateblue\", type=\"b\", ylab=\"Prob of observing snow crab\", xlab=\"\", ylim=c(0,1))\n lines( cfa4x_lb ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n lines( cfa4x_ub ~ yrs, data=RES, lty=\"dotted\", lwd=2, col=\"slategray\" )\n dev.off()\n\n\n\n\n\n \n# end\n", "meta": {"hexsha": "85b18217b656d60dba7e0d8dd151369db13b96e0", "size": 7362, "ext": "r", "lang": "R", "max_stars_repo_path": "inst/scripts/03.habitat_estimation_carstm.r", "max_stars_repo_name": "jae0/bio.snowcrab", "max_stars_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_stars_repo_licenses": ["MIT"], "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.habitat_estimation_carstm.r", "max_issues_repo_name": "jae0/bio.snowcrab", "max_issues_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_issues_repo_licenses": ["MIT"], "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.habitat_estimation_carstm.r", "max_forks_repo_name": "jae0/bio.snowcrab", "max_forks_repo_head_hexsha": "07b2daa7ddb0d5281b62b5f3b49b3f6f68230720", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-04-21T12:57:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:57:48.000Z", "avg_line_length": 39.7945945946, "max_line_length": 185, "alphanum_fraction": 0.6407226297, "num_tokens": 2373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.32084478001900096}} {"text": "subroutine baklo(x,y,w,npetc,wddnfl,spatol,match,\n\t\tetal,s,eta,beta,var,dof,\n\t\tqr,qraux,qpivot,effect,iv,v,iwork,work)\nimplicit double precision(a-h,o-z)\ninteger n,p,q,nit,maxit,qrank\ninteger npetc(7),wddnfl(*),match(*),qpivot(*),iv(*),iwork(*)\n##integer which(q),dwhich(q),degree(q),nef(q),liv(q),lv(q),nvmax(q)\ndouble precision x(*),y(*),w(*),spatol(*),\n\tetal(*),s(*),eta(*),beta(*),var(*),dof(*),\n\tqr(*),qraux(*),v(*),effect(*),work(*)\n#work size: 4*n + sum( nef(k)*(pj+dj+4)+5+3*pj )\t+5*n\n# = 9*n + sum( nef(k)*(pj+dj+4)+5+3*pj )\n\nn=npetc(1)\np=npetc(2)\nq=npetc(3)\nmaxit=npetc(5)\nqrank=npetc(6)\ncall baklo0(x,n,p,y,w,q,wddnfl(1),wddnfl(q+1),wddnfl(2*q+1),\n spatol(1),wddnfl(3*q+1),dof,match,wddnfl(4*q+1),\n etal,s,eta,beta,var,spatol(q+1),\n nit,maxit,qr,qraux,qrank,qpivot,effect,\n work(1),work(n+1),work(2*n+1),work(3*n+1),\n iv,wddnfl(5*q+1),wddnfl(6*q+1),v,wddnfl(7*q+1),\n iwork(1),work(4*n+1))\nnpetc(4)=nit\nnpetc(6)=qrank\nreturn\nend\n\nsubroutine baklo0(x,n,p,y,w,q,which,dwhich,pwhich,span,degree,dof,match,nef,\n\t\t\tetal,s,eta,beta,var,tol,nit,maxit,\n\t\t\tqr,qraux,qrank,qpivot,effect,z,old,sqwt,sqwti,\n\t\t\tiv,liv,lv,v,nvmax,iwork,work)\nimplicit double precision(a-h,o-z)\ninteger n,p,q,which(q),dwhich(q),pwhich(q),degree(q),match(n,q),nef(q),nit,\n\t\tmaxit,qrank,qpivot(p),iv(*),liv(q),lv(q),nvmax(q),iwork(q)\ndouble precision x(n,p),y(n),w(n),span(q),dof(q),\n\t\t\tetal(n),s(n,q),eta(n),beta(p),var(n,q),tol,\n\t\t\tqr(n,p),qraux(p),v(*),effect(n),work(*)\n#work should be sum( nef(k)*(pj+dj+4)+5+3*pj )\t+5*n\ndouble precision z(*),old(*),dwrss,ratio\ndouble precision sqwt(n),sqwti(n)\nlogical anyzwt\ndouble precision deltaf, normf,onedm7\ninteger job,info,slv,sliv,iw,j,dj,pj\nonedm7=1d-7\njob=1101;info=1\nif(q==0)maxit=1 \nratio=1d0\n# fix up sqy's for weighted problems.\nanyzwt=.false.\ndo i=1,n{\n\tif(w(i)>0d0){\n\t\tsqwt(i)=dsqrt(w(i))\n\t\tsqwti(i)=1d0/sqwt(i)\n\t}\n\telse{\n\t\tsqwt(i)=0d0\n\t\tsqwti(i)=0d0\n\t\tanyzwt=.true.\n\t\t}\n\t}\n# if qrank > 0 then qr etc contain the qr decomposition\n# else baklo computes it. \nif(qrank==0){\n\tdo i=1,n{\n\t\tdo j=1,p{\n\t\t\tqr(i,j)=x(i,j)*sqwt(i)\n\t\t\t}\n\t\t}\n\tdo j=1,p{qpivot(j)=j}\n\tcall dqrdca(qr,n,n,p,qraux,qpivot,work,qrank,onedm7)\n\t}\ndo i=1,n{\n\teta(i)=0d0\n\tfor(j=1;j<=q;j=j+1){\n\t\teta(i)=eta(i)+s(i,j)\n\t\t}\n\t}\nnit=0\nwhile ((ratio > tol )&(nit < maxit)){\n\t# first the linear fit\n\tdeltaf=0d0\n\tnit=nit+1\n\tdo i=1,n{\n\t\tz(i)=(y(i)-eta(i))*sqwt(i)\n\t\told(i)=etal(i)\n\t}\n#\tcall dqrsl1(qr,dq,qraux,qrank,sqz,one,work(1),etal,two,three)\n#job=1101 -- computes fits, effects and beta\n\tcall dqrsl(qr,n,n,qrank,qraux,z,work(1),effect(1),beta,\n\t\twork(1),etal,job,info)\n\n# now unsqrt the fits\n#Note: we dont have to fix up the zero weights till the end, since their fits\n#are always immaterial to the computation\n\tdo i=1,n{\n\t\tetal(i)=etal(i)*sqwti(i)\n\t\t}\n\t# now a single non-linear backfitting loop \n\tsliv=1\n\tslv=1\n\tiw=5*n+1\n\tfor(k=1;k<=q;k=k+1){\n\n\t\tj=which(k)\n\t\tdj=dwhich(k)\n\t\tpj=pwhich(k)\n\t\tdo i=1,n{\n\t\t\told(i)=s(i,k)\n\t\t\tz(i)=y(i)-etal(i)-eta(i)+old(i)\n\t\t}\ncall lo1(x(1,j),z,w,n,dj,pj,nvmax(k),span(k),degree(k),match(1,k),\n\t\tnef(k),nit,dof(k),s(1,k),var(1,k),work(iw),\n#\txin,win\n\twork(iw+pj+1),work(iw+nef(k)*dj+pj+1),\n#\tsqwin,sqwini,\n\twork(iw+nef(k)*(dj+1)+pj+2),work(iw + nef(k)*(dj+2)+pj+2),\n#\txqr,qrank,\t\n\twork(iw+nef(k)*(dj+3)+pj+2),work(iw+nef(k)*(pj+dj+4)+pj+2),\n#\tqpivot,qraux,\t\n#\twork(iw+nef(k)*(pj+dj+4)+pj+3),work(iw+nef(k)*(pj+dj+4)+4+2*pj),\n\tiwork(1),work(iw+nef(k)*(pj+dj+4)+4+2*pj),\n\tiv(sliv),liv(k),lv(k),v(slv),\n\twork(1) )\n#work should be sum( nef(k)*(pj+dj+4)+5+3*pj )\t+5*n\n# In the call above I give lo1 pieces of work to use for storing\n# the qr decomposition, and it gets the same undisturbed portion\n# each time. The fact that it is given a double work word for qrank\n# is irrelevant but convenient; it still stores the integer qrank there.\n# I do this because there is a partition like this for each lo() term\n# in the model, and the number of them is variable\n\t\tsliv=sliv+liv(k)\n\t\tslv=slv+lv(k)\n\t\tiw=iw+nef(k)*(pj+dj+4)+5+3*pj\n\t\tdo i=1,n{\n\t\t\teta(i)=eta(i)+s(i,k)-old(i)\n\t\t\t}\n\t\tdeltaf=deltaf+dwrss(n,old,s(1,k),w)\n\t\t}\n\tnormf=0d0\n\tdo i=1,n{\n\t\tnormf=normf+w(i)*eta(i)*eta(i)\n\t\t}\n\tif(normf>0d0){\n\t\tratio=dsqrt(deltaf/normf)\n\t\t}\n\t else {ratio = 0d0}\n\t}\n#now package up the results\ndo j=1,p {work(j)=beta(j)}\ndo j=1,p {beta(qpivot(j))=work(j)}\nif(anyzwt){\n\tdo i=1,n {\n\t\tif(w(i) <= 0d0){\n\t\t\tetal(i)=0d0\n\t\t\tdo j=1,p{\n\t\t\t\tetal(i)=etal(i)+beta(j)*x(i,j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\t\ndo i=1,n\n\teta(i)=eta(i)+etal(i)\n\t\n\nreturn\nend\n", "meta": {"hexsha": "2df87f2250adb48988e3e48f71aef89c020ead12", "size": 4502, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/backlo.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/backlo.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/backlo.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 26.3274853801, "max_line_length": 77, "alphanum_fraction": 0.6179475789, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3200746249532436}} {"text": "#!/usr/bin/env Rscript\nlibrary(\"rstan\")\nlibrary(\"parallel\")\nlibrary(\"bayesplot\")\nlibrary(\"raster\")\noptions(mc.cores = parallel::detectCores())\n\nload(\"dat/shw_scale.Rdata\")\n\n#### DELETE THIS LINE ONCE EFFORT IS ADDED\nshw_scale$effort <- 1\n\n# set up an environmental data frame for stan\n# start with just cells where we have all data\n# include linear terms plus interactions for region\nenvDatAll <- with(shw_scale, data.frame(intercept=1, bathy=bathy, chla=chla, sst=sst, varsst=varsst,\n dist=dist, east_region = as.integer(region=='E')))\n\nenvDatAll <- within(envDatAll, {\n east_chla <- east_region*chla\n east_sst <- east_region*sst\n east_varsst <- east_region*varsst\n east_dist <- east_region*dist\n})\n\n\n# counts, no gps, and no environmental NAs\n# counts, GPS, and no environmental NAs\n# GPS only, no environmental NAs\ncountRows <- which(!is.na(shw_scale$count) & is.na(shw_scale$ninds) & complete.cases(envDatAll))\ngpsCountRows <- which(!is.na(shw_scale$ninds) & !is.na(shw_scale$count) & complete.cases(envDatAll))\ngpsRows <- which(!is.na(shw_scale$ninds) & is.na(shw_scale$count) & complete.cases(envDatAll))\n\n\n# data for fitting\nenvCount <- envDatAll[countRows,]\nenvCountGPS <- envDatAll[gpsCountRows,]\nenvGPS <- envDatAll[gpsRows,]\n\n# set up remaining stan data\nstanDat <- list(\n nCounts = nrow(envCount),\n nCountsGPS = nrow(envCountGPS),\n nGPS = nrow(envGPS),\n nEnvVars = ncol(envCount),\n envCount = as.matrix(envCount),\n envCountGPS = as.matrix(envCountGPS),\n envGPS = as.matrix(envGPS),\n counts = shw_scale[countRows,'count'],\n countsGPS = shw_scale[gpsCountRows,'count'],\n gpsCounts = shw_scale[gpsCountRows,'ninds'],\n gps = shw_scale[gpsRows,'ninds'],\n surveyEffortCounts = shw_scale[countRows,'effort'],\n surveyEffortCountsGPS = shw_scale[gpsCountRows,'effort'])\n\nenvAbunOnly <- rbind(envCount, envCountGPS)\nstanDatAbun <- list(nCounts = nrow(envAbunOnly),\n nEnvVars = ncol(envAbunOnly),\n envCount = as.matrix(envAbunOnly),\n counts = shw_scale[c(countRows, gpsCountRows),'count'],\n surveyEffortCounts = shw_scale[c(countRows, gpsCountRows),'effort'])\n\nenvGPSOnly <- rbind(envCountGPS, envGPS)\nstanDatGPS <- list(nGPS = nrow(envGPSOnly),\n nEnvVars = ncol(envGPSOnly),\n envGPS = as.matrix(envGPSOnly),\n gps = shw_scale[c(gpsCountRows, gpsRows),'ninds'])\n\n \n# launch stan\nmodFull <- stan('shear.stan', data=stanDat, chains=4, iter=1000, cores=4)\nmodAerial <- stan('shear_abun_only.stan', data=stanDatAbun, chains=4, iter=1000, cores=4)\nmodGPS <- stan('shear_gps_only.stan', data=stanDatGPS, chains=4, iter=1000, cores=4)\n\n# visualize results\nparamsFull <- as.array(modFull)\nbetasFull <- rstan::extract(modFull)$beta\nparamsAerial <- as.array(modAerial)\nbetasAerial <- rstan::extract(modAerial)$beta\nparamsGPS <- as.array(modGPS)\nbetasGPS <- rstan::extract(modGPS)$beta\n\n# look at betas and hyperparams\n# mcmc_dens(paramsFull, pars=c('gpsScale', 'gpsSD'), regex_pars='beta')\n\n# predict abundance for all replicates across entire region\nlogAbunFull <- as.matrix(envDatAll) %*% t(betasFull)\nlogAbunAerial <- as.matrix(envDatAll) %*% t(betasAerial)\nlogAbunGPS <- as.matrix(envDatAll) %*% t(betasGPS)\n\n# make posterior mean and SD rasters\nabunFullMeanRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, exp(rowMeans(logAbunFull))))\nabunFullSDRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, apply(logAbunFull, 1, sd)))\nabunAerialMeanRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, exp(rowMeans(logAbunAerial))))\nabunAerialSDRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, apply(logAbunAerial, 1, sd)))\nabunGPSMeanRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, exp(rowMeans(logAbunGPS))))\nabunGPSSDRas <- rasterFromXYZ(cbind(shw_scale$lon, shw_scale$lat, apply(logAbunGPS, 1, sd)))\n\naCols <- colorRampPalette(rev(c('#032838', '#4E788F', '#80A4B7', '#BAD0D9', '#F1EBDC')), bias=3)(100)\npdf(\"results.pdf\", h=10, w=10)\npar(mfrow=c(3,2), mar=c(0.5,0.5,4,4))\nplot(abunFullMeanRas, col=aCols, xaxt='n', yaxt='n', zlim=c(0, maxValue(abunFullMeanRas)), main=\"Mean Predicted Abundance (Integrated)\")\nplot(abunFullSDRas, col=heat.colors(100), xaxt='n', yaxt='n', zlim=c(0, maxValue(abunFullSDRas)), main=\"SD Predicted Abundance\")\nplot(abunAerialMeanRas, col=aCols, xaxt='n', yaxt='n', zlim=c(0, maxValue(abunAerialMeanRas)), main=\"Mean Predicted Abundance (Aerial Only)\")\nplot(abunAerialSDRas, col=heat.colors(100), xaxt='n', yaxt='n', zlim=c(0, maxValue(abunAerialSDRas)), main=\"SD Predicted Abundance\")\nplot(abunGPSMeanRas, col=aCols, xaxt='n', yaxt='n', zlim=c(0, maxValue(abunGPSMeanRas)), main=\"Mean Predicted Abundance (GPS Only)\")\nplot(abunGPSSDRas, col=heat.colors(100), xaxt='n', yaxt='n', zlim=c(0, maxValue(abunGPSSDRas)), main=\"SD Predicted Abundance\")\ndev.off()", "meta": {"hexsha": "f33193df6d884f3d9c909218e40e249282a4e519", "size": 4751, "ext": "r", "lang": "R", "max_stars_repo_path": "shear.r", "max_stars_repo_name": "mtalluto/gps_integration", "max_stars_repo_head_hexsha": "8a75fae3ce8fa808cdf95e2927e37a9cc5fe1777", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shear.r", "max_issues_repo_name": "mtalluto/gps_integration", "max_issues_repo_head_hexsha": "8a75fae3ce8fa808cdf95e2927e37a9cc5fe1777", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shear.r", "max_forks_repo_name": "mtalluto/gps_integration", "max_forks_repo_head_hexsha": "8a75fae3ce8fa808cdf95e2927e37a9cc5fe1777", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9907407407, "max_line_length": 141, "alphanum_fraction": 0.7360555672, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3193195762812715}} {"text": "#Title: Estimate fitting decay curve\r\n#Auther: Naoto Imamachi\r\n#ver: 1.0.0\r\n#Date: 2015-10-24\r\n\r\n###Estimate_normalization_factor_function###\r\nBridgeRHalfLifeCalcR2Select <- function(InputFile = \"BridgeR_4_Normalized_expression_dataset.txt\",\r\n group, \r\n hour, \r\n InforColumn = 4, \r\n CutoffDataPointNumber = 4,\r\n CutoffDataPoint1 = c(1,2),\r\n CutoffDataPoint2 = c(8,12),\r\n ThresholdHalfLife = c(8,12),\r\n OutputFile = \"BridgeR_5C_HalfLife_calculation_R2_selection.txt\"){\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 output_file <- paste(OutputFile,\".log\",sep=\"\")\r\n log_file <- OutputFile\r\n \r\n ###print_header###\r\n cat(\"\",file=output_file)\r\n cat(\"\",file=log_file)\r\n hour_label <- NULL\r\n CutoffDataPoint1 <- sort(CutoffDataPoint1, decreasing = T)\r\n CutoffDataPoint2 <- sort(CutoffDataPoint2, decreasing = F)\r\n CutoffDataPoint1_length <- length(CutoffDataPoint1)\r\n CutoffDataPoint2_length <- length(CutoffDataPoint2)\r\n \r\n for_iteration_number <- CutoffDataPoint1_length + CutoffDataPoint2_length\r\n for(a in 1:group_number){\r\n if(!is.null(hour_label)){\r\n cat(\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", file=log_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(infor,hour_label, sep=\"\\t\", file=log_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=log_file, append=T)\r\n \r\n for_iteration_number2 <- for_iteration_number + 1\r\n for(number in 1:for_iteration_number2){\r\n cat(\"Model\",\"Decay_rate_coef\",\"coef_error\",\"coef_p-value\",\r\n \"R2\",\"Adjusted_R2\",\"Residual_standard_error\",\"half_life\",\r\n sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n cat(\"Model\",\"R2\",\"half_life\", sep=\"\\t\", file=output_file, append=T)\r\n cat(\"Model\",\"R2\",\"half_life\", sep=\"\\t\", file=log_file, append=T)\r\n }\r\n cat(\"\\n\", sep=\"\", file=output_file, append=T)\r\n cat(\"\\n\", sep=\"\", file=log_file, append=T)\r\n \r\n ###calc_RNA_half_lives###\r\n ###Function1#################################\r\n half_calc <- function(time_exp_table,label){\r\n data_point <- length(time_exp_table$exp)\r\n if(!is.null(time_exp_table)){\r\n if(data_point >= CutoffDataPointNumber){\r\n if(as.numeric(as.vector(as.matrix(time_exp_table$exp[1]))) > 0){\r\n model <- lm(log(time_exp_table$exp) ~ time_exp_table$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 cat(label,coef,coef_error,coef_p,r_squared,adj_r_squared,residual_standard_err,half_life, sep=\"\\t\", file=output_file, append=T)\r\n return(c(half_life,r_squared))\r\n }else{\r\n cat(\"low_expresion\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n return(c(\"NA\",\"NA\"))\r\n }\r\n }else{\r\n cat(\"few_data\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n return(c(\"NA\",\"NA\"))\r\n }\r\n }else{\r\n cat(\"low_expresion\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n return(c(\"NA\",\"NA\"))\r\n }\r\n }\r\n #############################################\r\n \r\n ###Function2#################################\r\n test_R2 <- function(time_point_exp_raw, cutoff_data_point, halflife_Raw, R2_Raw){\r\n test_times <- cutoff_data_point\r\n times_length <- length(test_times)\r\n times_index <- c(times_length)\r\n add_index <- times_length\r\n \r\n R2_list <- c(R2_Raw)\r\n half_list <- c(halflife_Raw)\r\n label_list <- c(\"Raw\")\r\n for(counter in times_length:1){\r\n #excepted_time_points\r\n check_times <- test_times[times_index] #c(24), c(24,12), c(24,12,8)\r\n time_point_exp_del <- NULL\r\n time_point_exp_del_label <- paste(\"Delete_\",paste(check_times,collapse=\"hr_\"),\"hr\",sep=\"\")\r\n label_list <- append(label_list, time_point_exp_del_label) #\r\n time_point_exp_del <- time_point_exp_raw\r\n for(times_list in check_times){\r\n time_point_exp_del <- time_point_exp_del[time_point_exp_del$hour != as.numeric(times_list),]\r\n }\r\n time_point_exp_del <- time_point_exp_del[time_point_exp_del$exp > 0,]\r\n halflife_R2_result <- half_calc(time_point_exp_del, time_point_exp_del_label)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n \r\n R2_list <- append(R2_list, halflife_R2_result[2]) #\r\n half_list <- append(half_list, halflife_R2_result[1]) #\r\n \r\n #Counter\r\n add_index <- add_index - 1\r\n times_index <- append(times_index, add_index)\r\n }\r\n \r\n R2_table <- data.frame(label=label_list, R2=R2_list, half=half_list)\r\n #R2_table <- R2_table[R2_table$R2 != \"NA\",]\r\n #sortlist <- order(R2_table$R2, decreasing = T)\r\n #R2_table <- R2_table[sortlist,]\r\n #result <- as.vector(as.matrix(R2_table[1,]))\r\n #cat(result, sep=\"\\t\", file=output_file, append=T)\r\n return(R2_table)\r\n }\r\n #############################################\r\n \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 for(a in 1:group_number){\r\n if(a != 1){\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=log_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 cat(gene_infor, sep=\"\\t\", file=log_file, append=T)\r\n cat(\"\\t\", file=log_file, append=T)\r\n \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 cat(exp, sep=\"\\t\", file=log_file, append=T)\r\n cat(\"\\t\", file=log_file, append=T)\r\n \r\n ###Raw_data\r\n time_point_exp_raw <- data.frame(hour,exp)\r\n time_point_exp_base <- time_point_exp_raw[time_point_exp_raw$exp > 0, ]\r\n test <- half_calc(time_point_exp_base,\"Exponential_Decay_Model\") #T1/2 - R2\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n \r\n ###Re-calculation of RNA half-life(Default: ThresholdHalfLife - 12hr)\r\n R2_list <- NULL\r\n half_list <- NULL\r\n label_list <- NULL\r\n if(test[1] == \"NA\"){\r\n for(number in 1:for_iteration_number){\r\n cat(\"Notest\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n cat(\"Notest\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n cat(\"Notest\",\"NA\",\"NA\", sep=\"\\t\", file=log_file, append=T)\r\n }else if(test[1] < ThresholdHalfLife[1]){ #Default: <12hr => Delete 8,12hr\r\n for(number in 1:CutoffDataPoint1_length){\r\n cat(\"Notest\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n R2_table <- test_R2(time_point_exp_raw, CutoffDataPoint2, test[1], test[2]) #test[1], test[2] => T1/2, R2\r\n \r\n }else if(test[1] >= ThresholdHalfLife[1] && test[1] < ThresholdHalfLife[2]){\r\n R2_table1 <- test_R2(time_point_exp_raw, CutoffDataPoint1, test[1], test[2]) #test[1], test[2] => T1/2, R2\r\n R2_table2 <- test_R2(time_point_exp_raw, CutoffDataPoint2, test[1], test[2]) #test[1], test[2] => T1/2, R2\r\n R2_table <- rbind(R2_table1, R2_table2)\r\n \r\n }else if(test[1] >= ThresholdHalfLife[2]){ #Default: >=12hr => Delete 1,2hr\r\n for(number in 1:CutoffDataPoint2_length){\r\n cat(\"Notest\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n R2_table <- test_R2(time_point_exp_raw, CutoffDataPoint1, test[1], test[2]) #test[1], test[2] => T1/2, R2\r\n \r\n }\r\n ###R2_Selection###\r\n if(test[1] != \"NA\"){\r\n R2_table <- R2_table[R2_table$R2 != \"NA\",]\r\n sortlist <- order(R2_table$R2, decreasing = T)\r\n R2_table <- R2_table[sortlist,]\r\n result <- as.vector(as.matrix(R2_table[1,]))\r\n cat(result, sep=\"\\t\", file=output_file, append=T)\r\n cat(result, sep=\"\\t\", file=log_file, append=T)\r\n }\r\n }\r\n cat(\"\\n\", file=output_file, append=T)\r\n cat(\"\\n\", file=log_file, append=T)\r\n }\r\n}\r\n\r\n###TEST###\r\n#output_file <- \"test.txt\"\r\n#CutoffDataPointNumber <- 4\r\n#x <- c(0,1,2,4,8,12)\r\n#y <- c(1,0.9,0.8,0.5,0.3,0.1)\r\n#table <- data.frame(hour=x,exp=y)\r\n#test_data_point <- c(8,12)\r\n#test_R2(table, test_data_point, 4.5, 0.992)\r\n\r\n# R2_list half_list label_list\r\n#1 0.9919170 4.547501 Delete_12hr\r\n#2 0.9720505 4.378777 Delete_12hr_8hr\r\n\r\n#########################\r\n#test <- c(8,12,24,2,12,21,1)\r\n#test_length <- length(test)\r\n#test_index <- c(test_length)\r\n#add_index <- test_length\r\n\r\n#for(x in test_length:1){\r\n# print(test[test_index])\r\n# add_index <- add_index - 1\r\n# test_index <- append(test_index,add_index)\r\n#}\r\n", "meta": {"hexsha": "0653dc67cef1be92e395f2ee1546961dcc1b4a40", "size": 11331, "ext": "r", "lang": "R", "max_stars_repo_path": "R/Z5C_estimate_fitting_decay_curve_R2_selection.r", "max_stars_repo_name": "ChristophRau/BridgeR", "max_stars_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-10T15:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T15:03:45.000Z", "max_issues_repo_path": "R/Z5C_estimate_fitting_decay_curve_R2_selection.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/Z5C_estimate_fitting_decay_curve_R2_selection.r", "max_forks_repo_name": "ChristophRau/BridgeR", "max_forks_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T14:15:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T14:15:15.000Z", "avg_line_length": 46.8223140496, "max_line_length": 148, "alphanum_fraction": 0.5223722531, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3163091066880139}} {"text": "#!/usr/bin/env Rscript\n\n############################################################################################################\n# Convert ASTER L1T HDF-EOS VNIR/TIR datasets from Radiance \n# and exports GeoTIFF files.\n# Author: Alfonso Crisci \n# Contact: a.crisci@ibimet.cnr.it\n# Organization: Istituto di Biometeorologia\n# Date last modified: 24-11-2017\n\n# DESCRIPTION:\n# This script is used for batch processing of ASTER Images\n# The script uses an ASTER L1T HDF-EOS file (.hdf) as the input.\n# It based on the work of Cole Krehbiel\n# https://git.earthdata.nasa.gov/projects/LPDUR/repos/aster-l1t\n\n# USAGE: Rscript aster_layer_calc.r path/filename name_city city type\n\n\n##############################################################################################################\n\nin_dir <- args[1]\nname <- args[2]\ncity <- args[3]\ntype <- args[4]\n\nemis=0.95\n\nmessage(paste(in_dir,name,city,type))\n\nif (length(args) !=4) {\n stop(\"At least four argument must be supplied (working dir, input file, name of output directory )\\n\", call.=FALSE)\n} \n\n\n\ncalc_lst=function(rbright,emis=0.92,c2micro=14388,Lwave=10.16,kelvin=F) {\n temp=rbright / ( 1 + ( Lwave * (rbright / c2micro)) * log(emis))\n if ( kelvin==F) { temp=temp-273.15}\n return(temp)\n} \n\n\ncalc_tbright=function(r,band=13) {\n k=band-9\n ucc <- c(0.006822, 0.00678, 0.00659, 0.005693, 0.005225)\n k1 <- c(3024, 2460, 1909, 890, 646.4)\n k2 <- c(1733, 166, 1581, 1357, 1273)\n tir_rad <- ((r - 1) * ucc[k])\n sat_brit <- k2[k]/log((k1[k]/tir_rad) + 1)\n return(sat_brit)\n }\n\nretrieve_aster_hdf=function(file,user='',password=\"\") \n {download.file(url=paste0(\"http://e4ftl01.cr.usgs.gov/ASTT/AST_L1T.003/\",\n substr(file,16,19),\".\",\n substr(file,12,13),\".\",\n substr(file,14,15),\"/\",file,'.hdf'),\n destfile=paste0(file,'.hdf'),\n method=\"wget\",\n extra=paste0(\"--http-user=\",user,\" --http-password=\",password))\n }\n\naster_date_hdf=function(file) {aster_date=as.Date(paste(substr(file,16,19),substr(file,12,13),substr(file,14,15),sep=\"-\"))\n return(aster_date)\n }\n\n#############################################################################################################\n# Convert ASTER L1T HDF-EOS VNIR/TIR datasets from Radiance \n# and exports as GeoTIFF files.\n#-------------------------------------------------------------------------------\n# Author: Cole Krehbiel\n# Contact: LPDAAC@usgs.gov \n# Organization: Land Processes Distributed Active Archive Center\n# Date last modified: 03-06-2017\n#-------------------------------------------------------------------------------\n# DESCRIPTION:\n# This script demonstrates how to convert ASTER L1T data from Digital Number(DN)\n# to radiance (w/m2/sr/�m), and from radiance into Top of Atmosphere (TOA) \n# reflectance. \n\n# The script uses an ASTER L1T HDF-EOS file (.hdf) as the input and outputs \n# georeferenced tagged image file format (GeoTIFF) files for each of the VNIR \n# and SWIR science datasets contained in the original ASTER L1T file.\n##############################################################################################################\n\nrequire(rgdal)\nrequire(raster)\nrequire(gdalUtils)\nrequire(tiff)\nrequire(rgdal)\n\n\nargs = commandArgs(trailingOnly=TRUE)\n\n\n\n#############################################################################################################\n# Set up calculations\n# 1. DN to Radiance (Abrams, 1999)\n# Radiance = (DN-1)* Unit Conversion Coefficient\n\n# 2. Radiance to TOA Reflectance\n# Reflectance_TOA = (pi*Lrad*d2)/(esuni*COS(z))\n\n# Define the following:\n# Unit Conversion Coefficient = ucc\n# pi = pi\n# Radiance,Lrad = rad\n# esuni = esun \n# z = solare\n\n# Order for ucc (Abrams, 1999) is: Band 1 high, normal, low; Band 2 h, n, l; \n# b3 h, n, l (3N & 3B the same) \n# Construct a dataframe for the UCC values:\n\nbands <- c('1', '2', '3N', '3B', '4', '5', '6', '7', '8', '9')\ngain_names <- c('Band', 'High Gain', 'Normal', 'Low Gain 1', 'Low Gain 2')\nucc_vals <- matrix( c(0.676, 1.688, 2.25, 0, 0.708, 1.415, 1.89, 0, 0.423, \n 0.862, 1.15, 0, 0.423, 0.862, 1.15, 0, 0.1087, 0.2174, \n 0.2900, 0.2900, 0.0348, 0.0696, 0.0925, 0.4090, 0.0313,\n 0.0625, 0.0830, 0.3900, 0.0299, 0.0597, 0.0795, 0.3320,\n 0.0209,0.0417, 0.0556, 0.2450, 0.0159, 0.0318, 0.0424, \n 0.2650), nrow = 10, ncol = 4, byrow = TRUE)\nucc <- data.frame( bands, ucc_vals )\n\nnames(ucc) <- gain_names\n\n# Remove unneccessary variables\nrm(bands,gain_names,ucc_vals)\n\n# Thome et al (B) is used, which uses spectral irradiance values from MODTRAN\n# Ordered b1, b2, b3N, b4, b5...b9\n\nirradiance <- c(1848,1549,1114,225.4,86.63,81.85,74.85,66.49,59.85)\n\n#############################################################################################################\n# Next, define functions for calculations\n# Write a function to convert degrees to radians\n\ncalc_radians <- function(x) {(x * pi) / (180)}\n \n# Write a function to calculate the Radiance from DN values\ncalc_radiance <- function(x){(x - 1) * ucc1}\n\n# Write a function to calculate the TOA Reflectance from Radiance\n\ncalc_reflectance <- function(x){\n (pi * x * (earth_sun_dist^2)) / (irradiance1 * sin(pi * sza / 180))\n }\n\n\n\n\n\n\n\nold_dir=getwd()\n\n#############################################################################################################\n\nsetwd(in_dir)\n\n# Maintains the original filename\nfile_name <- paste0(name,\".hdf\")\n \n# if (!file.exists(file_list)) {retrieve_aster_hdf(file_list)}}\n\n# Create and set output directory\n\n\nout_dir <- paste(in_dir,'/',city,\"_\",as.character(aster_date_hdf(file_name)),'/', sep='')\n\nsuppressWarnings(dir.create(out_dir))\n\n###################################################################\n# grab DOY from the filename and convert to day of year\n\n month <- substr(file_name, 12, 13)\n day <- substr(file_name, 14, 15)\n year <- substr(file_name, 16, 19)\n date <- paste(year, month, day, sep = '-') \n doy <- as.numeric(strftime(date, format = '%j'))\n \n# Remove unneccessary variables\n\n rm(month, day, year, date)\n \n # need SZA--calculate by grabbing solar elevation info \n\n md <- gdalinfo(file_name)\n sza <- md[grep('SOLARDIRECTION=', md)]\n clip3 <- regexpr(', ', sza) \n sza <- as.numeric((substr(sza, (clip3 + 2), 10000)))\n \n # Need the gain designation for each band\n gain_01 <- gsub(' ', '', strsplit(md[grep('GAIN.*=01', md)], ',')[[1]][[2]])\n gain_02 <- gsub(' ', '', strsplit(md[grep('GAIN.*=02', md)], ',')[[1]][[2]])\n gain_04 <- gsub(' ', '', strsplit(md[grep('GAIN.*=04', md)], ',')[[1]][[2]])\n gain_05 <- gsub(' ', '', strsplit(md[grep('GAIN.*=05', md)], ',')[[1]][[2]])\n gain_06 <- gsub(' ', '', strsplit(md[grep('GAIN.*=06', md)], ',')[[1]][[2]])\n gain_07 <- gsub(' ', '', strsplit(md[grep('GAIN.*=07', md)], ',')[[1]][[2]])\n gain_08 <- gsub(' ', '', strsplit(md[grep('GAIN.*=08', md)], ',')[[1]][[2]])\n gain_09 <- gsub(' ', '', strsplit(md[grep('GAIN.*=09', md)], ',')[[1]][[2]])\n gain_03b <- gsub(' ', '', strsplit(md[grep('GAIN.*=3B', md)], ',')[[1]][[2]])\n gain_03n <- gsub(' ', '', strsplit(md[grep('GAIN.*=3N', md)], ',')[[1]][[2]])\n \n # Calculate Earth Sun Distance (Achard and D'Souza 1994; Eva and Lambin, 1998)\n earth_sun_dist <- (1 - 0.01672 * cos(calc_radians(0.9856 * (doy - 4))))\n #-----------------------------------------------------------------------------\n # Define CRS\n # Define Upper left and lower right--need for x, y min/max\n # For offset (pixel size / 2), needs to be defined for ASTER pixel \n # resolutions (15, 30)\n \n # Grab LR and UL values\n lr <- substr(md[grep('LOWERRIGHTM', md)], 15, 50)\n ul <- substr(md[grep('UPPERLEFTM', md)], 14, 50)\n clip4 <- regexpr(', ' , ul) \n clip5 <- regexpr(', ', lr) \n \n # Define LR and UL x and y values for 15m VNIR Data\n ul_y <- as.numeric((substr(ul, 1, (clip4 - 1)))) + 7.5\n ul_x <- as.numeric((substr(ul, (clip4 + 2), 10000))) - 7.5\n lr_y <- as.numeric((substr(lr, 1, (clip5 - 1)))) - 7.5\n lr_x <- as.numeric((substr(lr, (clip5 + 2) , 10000))) + 7.5\n \n # Define LR and UL x and y values for 30m SWIR Data\n ul_y_30m <- as.numeric((substr(ul, 1, (clip4 - 1)))) + 15\n ul_x_30m <- as.numeric((substr(ul, (clip4 + 2), 10000))) - 15\n lr_y_30m <- as.numeric((substr(lr, 1, (clip5 - 1)))) - 15\n lr_x_30m <- as.numeric((substr(lr, (clip5 + 2) , 10000))) + 15\n \n # Define LR and UL x and y values for 90m TIR Data\n ul_y_90m <- as.numeric((substr(ul, 1, (clip4 - 1)))) + 45\n ul_x_90m <- as.numeric((substr(ul, (clip4 + 2), 10000))) - 45\n lr_y_90m <- as.numeric((substr(lr, 1, (clip5 - 1)))) - 45\n lr_x_90m <- as.numeric((substr(lr, (clip5 + 2) , 10000))) + 45\n\n # Define UTM zone\n utm_row <- grep('UTMZONECODE', md)\n utm_zone <- substr(md[utm_row[1]], 1, 50)\n clip6 <- regexpr('=', utm_zone) \n utm_zone <- substr(utm_zone, clip6 + 1, 50)\n \n # Configure extent properties (15m VNIR)\n y_min <- min(ul_y, lr_y)\n y_max <- max(ul_y, lr_y)\n x_max <- max(ul_x, lr_x)\n x_min <- min(ul_x, lr_x)\n \n # Configure extent properties (30m SWIR)\n\n y_min_30m <- min(ul_y_30m, lr_y_30m)\n y_max_30m <- max(ul_y_30m, lr_y_30m)\n x_max_30m <- max(ul_x_30m, lr_x_30m)\n x_min_30m <- min(ul_x_30m, lr_x_30m)\n\n # Configure extent properties (90m TIR)\n\n y_min_90m <- min(ul_y_90m, lr_y_90m); \n y_max_90m <- max(ul_y_90m, lr_y_90m)\n x_max_90m <- max(ul_x_90m, lr_x_90m); \n x_min_90m <- min(ul_x_90m, lr_x_90m)\n \n \n raster_dims_15m <- extent(x_min, x_max, y_min, y_max)\n raster_dims_30m <- extent(x_min_30m, x_max_30m, y_min_30m, y_max_30m)\n raster_dims_90m <- extent(x_min_90m, x_max_90m, y_min_90m, y_max_90m)\n \n # Compile Cordinate Reference System string to attach projection information\n crs_string <- paste('+proj=utm +zone=', utm_zone, ' +datum=WGS84 +units=m \n +no_defs +ellps=WGS84 +towgs84=0,0,0', sep = '')\n \n # Remove unneccessary variables\n rm(clip4, clip5, clip6, lr, lr_x, lr_y, md, ul, ul_x, ul_y, utm_zone,\n x_min, x_max, y_min, y_max, utm_row)\n \n # Get a list of sds names\n sds <- get_subdatasets(file_name)\n \n # Limit loop to SDS that contain VNIR/SWIR data (9 max)\n \n match_vnir <- grep('VNIR_Swath', sds)\n match_tir <- grep('TIR_Swath', sds) \n \n###################################################################################################################à\n\n if (length(match_vnir) > 1){\n for (k in min(match_vnir):max(match_vnir)) {\n \n # Isolate the name of the first sds\n sub_dataset <- sds[k]\n \n # Get the name of the specific SDS\n clip2 <- max(unlist((gregexpr(':', sub_dataset)))) \n \n # Generate output name for tif\n new_file_name <- strsplit(file_name, '.hdf')\n tif_name <- paste(out_dir, new_file_name, '_', substr(sub_dataset, \n (clip2 + 1), 10000),'.tif', sep='')\n sd_name <- paste(new_file_name, substr(sub_dataset, (clip2 + 1), 10000), \n sep = '_')\n sub_name <- paste(new_file_name, 'ImageData', sep = '_')\n ast_band_name <- gsub(sub_name, '', sd_name)\n \n # Extract specified SDS and export as Geotiff\n \n gdal_translate(file_name, tif_name, sd_index=k)\n \n aster_file <- raster(tif_name, crs = crs_string)\n \n if (ast_band_name == '1'){\n # Need to know which gain value you use\n if (gain_01 == 'HGH'){\n ucc1 <- ucc[1, 2] \n }else if(gain_01 == 'NOR'){\n ucc1 <- ucc[1, 3] \n }else{\n ucc1 <- ucc[1, 4] \n }\n irradiance1 <- irradiance[1]\n \n # Define Extent\n extent(aster_file) <- raster_dims_15m\n \n }else if (ast_band_name == '2'){\n # Need to know which gain value you use\n if (gain_02 == 'HGH'){\n ucc1 <- ucc[2, 2] \n }else if(gain_02 == 'NOR'){\n ucc1 <- ucc[2, 3] \n }else{\n ucc1 <- ucc[2, 4] \n }\n irradiance1 <- irradiance[2]\n \n # Define Extent\n extent(aster_file) <- raster_dims_15m\n \n } else if (ast_band_name == '3N'){\n # Need to know which gain value you use\n if (gain_03n == 'HGH'){\n ucc1 <- ucc[3, 2] \n } else if(gain_03n == 'NOR'){\n ucc1 <- ucc[3, 3] \n } else{\n ucc1 <- ucc[3, 4] \n }\n irradiance1 <- irradiance[3]\n \n # Define Extent\n extent(aster_file) <- raster_dims_15m\n\n }\n\n\n # Set up output file names\n ref_out_name <- gsub(paste(ast_band_name, '.tif', sep = ''), \n paste(ast_band_name, '_reflectance.tif', sep = ''), \n tif_name)\n rad_out_name <- gsub(paste(ast_band_name, '.tif', sep = ''), \n paste(ast_band_name, '_radiance.tif', sep = ''),\n tif_name)\n # Convert DN to large raster layer\n aster_file <- calc(aster_file, fun =function(x){x})\n \n # Export the DN raster layer file (Geotiff format) to the output directory\n writeRaster(aster_file, filename = tif_name, options = 'INTERLEAVE=BAND',\n NAflag = 0, format = 'GTiff', datatype = 'INT1U', \n overwrite = TRUE)\n \n # Convert from DN to Radiance\n rad <- calc(aster_file, calc_radiance)\n rad[rad == calc_radiance(0)] <- 0\n rm(aster_file)\n # export the raster layer file (Geotiff format) to the output directory\n writeRaster(rad, filename = rad_out_name, options = 'INTERLEAVE=BAND', \n NAflag = 0, format = 'GTiff', datatype = 'FLT8S', \n overwrite = TRUE)\n \n # Convert from Radiance to TOA Reflectance\n ref <- calc(rad, calc_reflectance)\n rm(rad)\n # export the raster layer file (Geotiff format) to the output directory\n \n writeRaster(ref, filename = ref_out_name, options = 'INTERLEAVE=BAND', \n NAflag = 0, format = 'GTiff', datatype = 'FLT8S', \n overwrite = TRUE)\n \n # Remove unneccessary variables\n \n rm(ucc1, irradiance1, ref_out_name, rad_out_name, ref, sub_dataset,sd_name, sub_name, tif_name, new_file_name)\n \n }\n }\n \n###################################################################################################################à\n \n if (length(match_tir) > 0) {\n \n for (k in min(match_tir):max(match_tir)){\n \n # Isolate the name of the first sds\n sub_dataset<- sds[k]\n \n # Get the name of the specific SDS\n clip2 <- max(unlist((gregexpr(':', sub_dataset)))) \n \n # Generate output name for tif\n new_file_name <- strsplit(file_name, '.hdf')\n tif_name <- paste(out_dir, new_file_name, '_', substr(sub_dataset, \n (clip2 + 1), 10000),'.tif', sep='')\n sd_name <- paste(new_file_name, substr(sub_dataset, (clip2 + 1), 10000),\n sep = '_')\n sub_name <- paste(new_file_name, 'ImageData', sep = '_')\n ast_band_name <- gsub(sub_name, '', sd_name)\n \n # Extract specified SDS and export as Geotiff\n \n gdal_translate(file_name, tif_name, sd_index=k, output_Raster = FALSE)\n \n # Open geotiff and add projection (CRS)\n \n aster_file <- suppressWarnings(raster(readGDAL(tif_name,as.is=T)))\n proj4string(aster_file)=crs_string\n extent(aster_file) <- raster_dims_90m\n\n # Convert to large raster layer\n aster_file <- calc(aster_file, fun =function(x){x} )\n \n # Export the raster layer file (Geotiff format) to the output directory\n writeRaster(aster_file, filename = tif_name, options = 'INTERLEAVE=BAND',\n format = 'GTiff', datatype = 'INT2U', overwrite = TRUE, \n NAflag = 0)\n # Remove unneccessary variables\n \n \n rm(aster_file, sub_dataset, sd_name, sub_name, tif_name, new_file_name)\n }\n } \n \n###################################################################################################################à\n# Remove unneccessary variables\n \n \n rm( earth_sun_dist, doy,gain_01,gain_02, gain_03b, \n gain_03n, gain_04, gain_05, gain_06, gain_07, gain_08, gain_09, sza,\n ast_band_name, clip2, crs_string, file_name,sds, lr_x_30m, lr_x_90m, \n lr_y_30m, lr_y_90m, raster_dims_15m, \n raster_dims_30m, raster_dims_90m, ul_x_30m, ul_x_90m, ul_y_30m, ul_y_90m,\n x_max_30m, x_max_90m, x_min_30m, x_min_90m, y_max_30m, y_max_90m,y_min_30m,\n y_min_90m)\n\n###################################################################################################################à\nres=list()\n\nif (length(match_vnir) > 0 ) {\n blue_radiance=raster(paste0(out_dir,name,\"_\",\"ImageData1_radiance.tif\"))\n blue_reflectance=raster(paste0(out_dir,name,\"_\",\"ImageData1_reflectance.tif\"))\n green_radiance=raster(paste0(out_dir,name,\"_\",\"ImageData2_radiance.tif\"))\n green_reflectance=raster(paste0(out_dir,name,\"_\",\"ImageData2_reflectance.tif\"))\n red_radiance=raster(paste0(out_dir,name,\"_\",\"ImageData3N_radiance.tif\"))\n red_reflectance=raster(paste0(out_dir,name,\"_\",\"ImageData3N_reflectance.tif\"))\n ASTERVNIR=stack(blue_radiance,blue_reflectance, green_radiance,green_reflectance,red_radiance,red_reflectance)\n # writeRaster(ASTERVNIR, filename=paste0(out_dir,name,\"_stackVNIR.tif\"), overwrite=TRUE)\n}\n\nif (length(match_tir) > 0 ) {\n \n res=list()\n \n res$b13_tbright=calc_tbright(suppressWarnings(raster(readGDAL(paste0(out_dir,name,\"_\",\"ImageData13.tif\"),as.is=T))),band=13)\n res$b14_tbright=calc_tbright(suppressWarnings(raster(readGDAL(paste0(out_dir,name,\"_\",\"ImageData14.tif\"),as.is=T))),band=14)\n \n res$b13_LST=calc_lst(res$b13_tbright,emis=emis,Lwave=10.6)\n res$b14_LST=calc_lst(res$b14_tbright,emis=emis,Lwave=11.3)\n \n writeRaster(res$b13_LST, filename=paste0(out_dir,name,\"_\",type,\"_b13_LST.tif\"), overwrite=TRUE)\n writeRaster(res$b14_LST, filename=paste0(out_dir,name,\"_\",type,\"_b14_LST.tif\"), overwrite=TRUE)\n writeRaster(res$b13_tbright, filename=paste0(out_dir,name,\"_\",type,\"_b13_TB.tif\"), overwrite=TRUE)\n writeRaster(res$b14_tbright, filename=paste0(out_dir,name,\"_\",type,\"_b14_TB.tif\"), overwrite=TRUE)\n}\n\n\nsetwd(out_dir)\nolds=list.files(pattern=name, full.names = F)\nnews=gsub(name,paste0(city,\"_\",as.character(aster_date_hdf(name)),\"_\",type),olds)\nnews=gsub(paste0(\"_\",type,\"_\",type),news)\nfile.rename(olds,news)\nsaveRDS(res,file = paste0(city,\"_\",as.character(aster_date_hdf(file_name)),\"_\",type,'.rds'))\n\nsetwd(old_dir)\n\n\n###################################################################################################################à\n# References\n# ABRAMS, M., HOOK, S., and RAMACHANDRAN, B., 1999, Aster user handbook,\n# Version 2, NASA/Jet Propulsion Laboratory, Pasadena, CA, at \n# https://asterweb.jpl.nasa.gov/content/03_data/04_Documents/\n# aster_user_guide_v2.pdf\n\n# ARCHARD, F., AND D'SOUZA, G., 1994, Collection and pre-processing of \n# NOAA-AVHRR 1km resolution data for tropical forest resource assessment. \n# Report EUR 16055, European Commission, Luxembourg, at \n# http://bookshop.europa.eu/en/collection-and-pre-processing-of-noaa-avhrr-1-km\n# -resolution-data-for-tropical-forest-resource-assessment-pbCLNA16055/\n\n# EVA, H., AND LAMBIN, E.F., 1998, Burnt area mapping in Central Africa using \n# ATSR data, International Journal of Remote Sensing, v. 19, no. 18, 3473-3497, \n# at http://dx.doi.org/10.1080/014311698213768\n\n# Thome, K.J., Biggar, S.F., and Slater, P.N., 2001, Effects of assumed solar\n# spectral irradiance on intercomparisons of earth-observing sensors. In \n# International Symposium on Remote Sensing, International Society for Optics\n# and Photonics, pp. 260-269, at http://dx.doi.org/10.1117/12.450668.\n###################################################################################################################à\n", "meta": {"hexsha": "7f135a034bde881a66becb24aed06d85a539359c", "size": 20298, "ext": "r", "lang": "R", "max_stars_repo_path": "code/aster_layer_calc.r", "max_stars_repo_name": "meteosalute/Parma_urban_imperviouness", "max_stars_repo_head_hexsha": "317f0dc34316fe4f52d7da58d7f2672ef6fc9ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2018-10-29T01:33:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T01:33:41.000Z", "max_issues_repo_path": "aster_layer_calc.r", "max_issues_repo_name": "alfcrisci/ASTER_data_retrieve", "max_issues_repo_head_hexsha": "c497b6b02e7774d6c3ad453317133665f2ca8e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aster_layer_calc.r", "max_forks_repo_name": "alfcrisci/ASTER_data_retrieve", "max_forks_repo_head_hexsha": "c497b6b02e7774d6c3ad453317133665f2ca8e64", "max_forks_repo_licenses": ["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.1853281853, "max_line_length": 135, "alphanum_fraction": 0.5603507735, "num_tokens": 6063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.31423091646803714}} {"text": "#-------PAMGuide.R\n\n# Computes calibrated or relative acoustic metrics from WAV audio files.\n \n# This code accompanies the manuscript: \n \n# Merchant et al. (2015). Measuring Acoustic Habitats. Methods \n# in Ecology and Evolution\n \n# and follows the equations presented in Appendix S1. It is not necessarily\n# optimised for efficiency or concision.\n\n###############################################################################\n######\tSee Appendix S1 of the above manuscript for detailed instructions #####\n###############################################################################\n \n# Copyright (c) 2014 The Authors.\n \n# Author: Nathan D. Merchant. Last modified 22 Sep 2014\n\n# PREREQUISITES: PAMGuide.R uses package \"tuneR\", which can be installed\n# using the R Package Installer:\n\n## Install tuneR if not installed---------------------------------------------\n\nif (!is.element('tuneR', installed.packages()[,1])){\t\t\t#if tuneR is not installed\nr <- getOption(\"repos\")\t\t\t\t\t\t\t\t#assign R mirror for download\nr[\"CRAN\"] <- \"http://cran.us.r-project.org\"\noptions(repos = r)\nrm(r)\ninstall.packages('tuneR', dep = TRUE)\t\t\t#install tuneR\nrequire('tuneR', character.only = TRUE)}\n\nlibrary(tuneR)\t\t\t\t\t\t\t\t\t#load tuneR package\n\n\n## Begin PAMGuide--------------------------------------------------------------\n\nPAMGuide <- function(fullfile='',...,atype='PSD',plottype='Both',envi='Air',calib=0,ctype = 'TS',Si=-159,Mh=-36,G=0,vADC=1.414,r=50,N=Fs,winname='Hann',lcut=Fs/N,hcut=Fs/2,timestring=\"\",outdir=dirname(fullfile),outwrite=0,disppar=1,welch=\"\",chunksize=\"\",linlog = \"Log\", isvector=0, y=\"\", Fs=\"\", Nbit=24 ){\n\n#graphics.off()\t\t\t\t\t\t\t\t\t#close plot windows\naid <- 0\t\t\t\t\t\t\t\t\t\t#reset metadata code\nif (calib == 0) {aid <- aid + 20\t\t\t\t#add calibration element to metadata code\n\t} else {aid <- aid + 10}\nif (timestring != \"\"){aid <- aid + 1000} else {aid <- aid + 2000}\t#add time stamp element to metadata code\n\n\n## Select input file and get file info-----------------------------------------\n\n#fullfile <- file.choose()\t\t\t\nifile <- basename(fullfile)\t\t\t\t\t\t#file name\nif (isvector == 0){\n\tfIN <- readWave(fullfile,header = TRUE)\t\t\t#read file header\t\n\tFs <- fIN[[1]]\t\t\t\t\t\t\t\t\t#sampling frequency\n\tNbit <- fIN[[3]]\t\t\t\t\t\t\t\t#bit depth\n\txl <- fIN[[4]]\t\t\t\t\t\t\t\t\t#length of file in samples\t\t\t\n\txlglo <- xl\t\t\t\t\t\t\t\t\t\t#back-up file length\n}\nelse {\n\t#Nbit <- 10\n\txbit <- y\n\txl <- length(xbit) \n\t#Fs <- 48000\n\txlglo <- xl\n\tcat('File length:',xl,'samples =',xl/Fs,'s\\n')\n}\n\n\n## Read time stamp data if provided-----------------------------------------\n\nif (timestring != \"\") {tstamp <- as.POSIXct(strptime(ifile,timestring) ,origin=\"1970-01-01\")\n\tif (disppar == 1){cat('Time stamp start time: ',format(tstamp),'\\n')}\n\t} \nif (timestring == \"\"){tstamp <- \"\"}\t\t#compute time stamp in R POSIXct format\n\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n## Display user-defined settings------------------------------------------\n\nif (disppar == 1){\n\tcat('File name:',ifile,'\\n')\n\tcat('File length:',xl,'samples =',xl/Fs,'s\\n')\n\tcat('Analysis type:',atype,'\\n')\n\tcat('Plot type:',plottype,'\\n')\n\tif (calib == 1){\n\t\tif (ctype == 'EE'){\n\t\t\tcat('End-to-end system sensitivity =',sprintf('%.01f',Si),'dB\\n')\n\t\t\tif (envi == 'Wat') {cat('In-air measurement\\n')}\n\t\t\tif (envi == 'Wat') {cat('Underwater measurement\\n')}}\n\t\tif (ctype == 'RC'){\n\t\t\tcat('System sensitivity of recorder (excluding transducer) =',sprintf('%.01f',Si),'dB\\n')}\n\t\tif (ctype == 'TS' || ctype == 'RC'){\n\t\tif (envi == 'Air') {cat('In-air measurement\\n')\n\t\t\tcat('Microphone sensitivity:',Mh,'dB re 1 V/Pa\\n')\n\t\t\tMh <- Mh - 120}\t\t#convert to dB re 1 V/uPa\n\t\tif (envi == 'Wat') {cat('Underwater measurement\\n')\n\t\t\tcat('Hydrophone sensitivity:',Mh,'dB re 1 V/uPa\\n')}}\n\t\tif (ctype == 'TS'){\t\n\t\tcat('Preamplifier gain:',G,'dB\\n')\n\t\tcat('ADC peak voltage:',vADC,'V\\n')}\n\t} else {cat('Uncalibrated analysis. Output in relative units.\\n')\n\t\t\t}\n\tcat('Time segment length:',N,'samples =',N/Fs,'s\\n')\n\tcat('Window function:',winname,'\\n')\n\tcat('Window overlap:',r,'%\\n')\n}\nr<-r/100\n\n## Read input file------------------------------------------------------------------\n\nif (chunksize == \"\"){nchunks = 1\t\t\t\t#if loading whole file, nchunks = 1\n\t} else if (chunksize != \"\") {\t\t\t\t#if loading file in stages\n\t\tnchunks <- ceiling(xl/(Fs*as.numeric(chunksize)))\t#number of chunks of length chunksize in file\n\t}\n\t\nfor (q in 1:nchunks){\t\t\t\t\t\t\t#loop through file chunks\n\tif (nchunks == 1){\t\t\t\t\t\t\t#if loading whole file at once\nt1=proc.time()\t\t\t\t\t\t\t\t\t#start timer\ncat('Loading input file... ')\nif (isvector == 0){\n\t# Read the wave file:\n\txbit <- readWave(fullfile)\n\txbit <- xbit@left/(2^(Nbit-1))\t\t\t\t\t#convert to full scale (+/- 1) via bit depth\n\t} else {\n\t\t# Take the user-specified input vector.\n\n\txbit <- xbit/(2^(Nbit-1))\t\t\t\t\t#convert to full scale (+/- 1) via bit depth\n}\t\t\t\t\t\t#read file\ncat('done in',(proc.time()-t1)[3],'s.\\n')\n\n\n} else if (nchunks > 1) {\t\t\t\t\t\t#if loading file in stages\n\tif (q == nchunks){\t\t\t\t\t\t\t#load qth chunk\n\t\txbit <- readWave(fullfile,from=((q-1)*as.numeric(chunksize)*Fs+1),to=xlglo,units=\"samples\")\n\t\txbit <- xbit@left/(2^(Nbit-1))\t\t\t#convert to full scale (+/- 1) via bit depth\n\t\txl <- length(xbit)\t\t\t\t\t\t#final chunk length\n\t} else {\n\t\txbit <- readWave(fullfile,from=((q-1)*as.numeric(chunksize)*Fs+1),to=(q*as.numeric(chunksize)*Fs),units=\"samples\")\n\t\txbit <- xbit@left/(2^(Nbit-1))\t\t\t#convert to full scale (+/- 1) via bit depth\n\t\txl <- length(xbit)\t\t\t\t\t\t#chunk length\n\t}\n}\n\nif (envi == 'Air'){pref<-20; aid <- aid+100}\t#set reference pressure depending for in-air or underwater\nif (envi == 'Wat'){pref<-1; aid <- aid+200}\n\n\t\n## Compute system sensitivity if provided-----------------------------------------------\n\nif (calib == 1){\n\tif (ctype == 'EE') {\t\t#'EE' = end-to-end calibration\n\t\tS <- Si}\n\tif (ctype == 'RC') {\t\t#'RC' = recorder calibration with separate transducer sensitivity defined by Mh\n\t\tS <- Si + Mh}\n\tif (ctype == 'TS') {\t\t#'TS' = manufacturer's specifications\n\t\tMh\n\t\tG\n\t\t20*log10((1/vADC))\n\t\tS <- Mh + G + 20*log10(1/vADC);\t\t#EQUATION 4\n\t} \n\n\tif (disppar == 1){cat('System sensitivity correction factor, S = ',sprintf('%.01f',S),' dB\\n')}\n} else {S <- 0}\t\t\t\t#if not calibrated (calib == 0), S is zero\n\n## Compute waveform if selected----------------------------------------------------\n\nif (atype == 'Waveform') {\n\tif (calib == 1){\na <- xbit/(10^(S/20)) \t\t\t\t#EQUATION 21\t\n} else {a <- xbit/(max(xbit))}\nt <- seq(1/Fs,length(a)/Fs,1/Fs)\t#time vector\ntana = proc.time()\n}\n\n## Compute DFT-based metrics if selected----------------------------------------\n\nif (atype != 'Waveform') {\n\tif (nchunks == 1){\n\tif (atype == 'PSD'){cat('Computing PSD...')}\n\tif (atype == 'PowerSpec'){cat('Computing power spectrum...')}\n\tif (atype == 'TOL'){cat('Computing TOLs by DFT method...')}\n\tif (atype == 'Broadband'){cat('Computing broadband level...')}\n\ttana = proc.time()}\n\n# Divide signal into data segments (corresponds to EQUATION 5)\nN = round(N)\t\t\t\t\t\t#ensure N is an integer\nnsam = ceiling((xl)-r*N)/((1-r)*N)\t#number of segments of length N with overlap r\nxgrid <- matrix(nrow = N,ncol = nsam)\t#initialise grid of segmented data for analysis\nfor (i in 1:nsam) {\t\t\t\t\t#make grid of segmented data for analysis\n\tloind <- (i-1)*(1-r)*N+1\n\thiind <- (i-1)*(1-r)*N+N\n\txgrid[,i] = xbit[loind:hiind]\n}\n\nM <- length(xgrid[1,])\n\n# Apply window function (corresponds to EQUATION 6)\nif (winname == 'Rectangular') {\t\t\t#rectangular (Dirichlet) window\n\tw <- matrix(1,1,N)\n\talpha <- 1 }\t\t\t\t\t#scaling factor\nif (winname == 'Hann') {\t\t\t#Hann window\n\tw <- (0.5 - 0.5*cos(2*pi*(1:N)/N))\n\talpha <- 0.5 }\t\t\t\t\t#scaling factor\nif (winname == 'Hamming') {\t\t\t#Hamming window\n\tw <- (0.54 - 0.46*cos(2*pi*(1:N)/N))\n\talpha <- 0.54 }\t\t\t\t\t#scaling factor\nif (winname == 'Blackman') {\t\t#Blackman window\n\tw <- (0.42 - 0.5*cos(2*pi*(1:N)/N) + 0.08*cos(4*pi*(1:N)/N))\n\talpha <- 0.42 }\t\t\t\t\t#scaling factor\n\nxgrid <- xgrid*w/alpha \t\t\t\t#apply window function\n\n\n#Compute DFT (corresponds to EQUATION 7)\nX <- abs(mvfft(xgrid))\n\n#Compute power spectrum (EQUATION 8)\nP <- (X/N)^2\n\n#Compute single-side power spectrum (EQUATION 9)\nPss <- 2*P[0:round(N/2)+1,]\n\n#Compute frequencies of DFT bins\nf <- floor(Fs/2)*seq(1/(N/2),1,len=N/2)\nflow <- which(f >= lcut)[1]\t\t\t#find index of lcut frequency\nfhigh <- max(which(f <= hcut))\t\t#find index of hcut frequency\nf <- f[flow:fhigh]\t\t\t\t\t#limit frequencies to user-defined range\nnf <- length(f)\t\t\t\t\t\t#number of frequency bins\n\n\n#Compute PSD in dB if selected\nif (atype == 'PSD') {\nB <- (1/N)*(sum((w/alpha)^2))\t\t#noise power bandwidth (EQUATION 12)\ndelf <- Fs/N;\t\t\t\t\t\t#frequency bin width\na <- 10*log10((1/(delf*B))*Pss[flow:fhigh,]/(pref^2))-S\n}\t\t\t\t\t\t\t\t\t#PSD (EQUATION 11)\n\n#Compute power spectrum in dB if selected\nif (atype == 'PowerSpec') {\t\t\t\n\ta <- 10*log10(Pss[flow:fhigh,]/(pref^2))-S\n}\t\t\t\t\t\t\t\t\t#EQUATION 10\n\n#Compute broadband level if selected\nif (atype == 'Broadband') {\n\ta <- 10*log10(colSums(Pss[flow:fhigh,])/(pref^2))-S\n}\t\t\t\t\t\t\t\t\t#EQUATION 17\n\n#Compute 1/3-octave band levels if selected\nif (atype == 'TOL') {\n\tif (lcut <25){\t\t\t\t\t#limit TOL analysis to > 25 Hz\n\tlcut <- 25}\n\t\n\t#Generate 1/3-octave freqeuncies\n\tlobandf <- floor(log10(lcut))\t#lowest power of 10 for TOL computation\n\thibandf <- ceiling(log10(hcut))\t#highest power of 10 for TOL computation\n\tnband <- 10*(hibandf-lobandf)+1\t#number of 1/3-octave bands\n\tfc <- matrix(0,nband)\t\t\t#initialise 1/3-octave frequency vector\n\tfc[1] <- 10^lobandf;\n\t\n\t#Calculate centre frequencies (corresponds to EQUATION 13)\n\tfor (i in 2:nband) {\n\t\tfc[i] <- fc[i-1]*10^0.1}\t\n\tfc <- fc[which(fc >= lcut)[1]:max(which(fc <= hcut))]\n\t\n\tnfc <- length(fc)\t\t\t\t#number of 1/3-octave bands\n\t\n\t#Calculate boundary frequencies of each band (EQUATIONS 14-15)\n\tfb <- fc*10^-0.05\t\t\t\t#lower bounds of 1/3-octave bands\n\tfb[nfc+1] <- fc[nfc]*10^0.05\t#upper bound of highest band\n\tif (max(fb) > hcut) {\t\t\t#if upper bound exceeds highest\n\t\tnfc <- nfc-1\t\t\t\t# frequency in DFT, remove\n\t\tfc <- fc[1:nfc]}\n\t\n\t#Calculate TOLs (corresponds to EQUATION 16)\n\tP13 <- matrix(nrow = M,ncol = nfc)\n\tfor (i in 1:nfc) {\n\t\tfli <- which(f >= fb[i])[1]\n\t\tfui <- max(which(f < fb[i+1]))\n\t\tfor (k in 1:M) {\n\t\t\tfcl <- sum(Pss[fli:fui,k])\n\t\t\tP13[k,i] <- fcl\n\t\t}\n\t}\n\ta <- t(10*log10(P13/(pref^2)))-S\n}\n\n# Compute time vector\ntint <- (1-r)*N/Fs\nttot <- M*tint-tint\nt <- seq(0,ttot,tint)\n}\n\nif (nchunks>1){\t\t\t\t\t\t\t\t#if loading in stages, concatenate analyses in each loop iteration\n\tif (q == 1){\n\t\tnewa <- a\n\t\tnewt <- t\n\t\tcat('Chunk size:',chunksize,'s\\nAnalysing in',nchunks,'chunks. Analysing chunk 1')\n\t} else if (q > 1){\n\t\tdima <- dim(a)\n\t\tnewa <- cbind(newa,a)\n\t\tif (timestring != \"\"){\n\t\t\tnewt <- c(newt,t)\n\t\t} else {\n\t\t\tnewt <- c(newt,t+(q-1)*as.numeric(chunksize))\n\t\t} \n\t\tcat(' ',q)\n\t}\n} else {cat('done in',(proc.time()-tana)[3],'s.\\n')}\n}\n\nif (nchunks>1){a <- newa\t\t\t\t\t#reassign output array\n\tt <- newt\n\tcat('\\n')}\n\n# If not calibrated, scale relative dB to zero\nif (calib == 0 & atype != 'Waveform') {a <- a-max(a)}\n\nif (tstamp != \"\"){t <- t+tstamp\n\ttdiff <- max(t)-min(t)\t\t\t\t\t#define time format for x-axis of time plot\n\tif (tdiff < 10){\n\t\ttform <- \"%H:%M:%S:%OS3\"}\n\telse if (tdiff > 10 & tdiff < 86400){ \n\t\ttform <- \"%H:%M:%S\"}\n\telse if (tdiff > 86400 & tdiff < 86400*7){ \n\t\ttform <- \"%H:%M \\n %d %b\"}\n\telse if (tdiff > 86400*7){tform <- \"%d %b %y\"}\n}\n\n## Construct output array------------------------------------------------\n\nif (atype == 'PSD' | atype == 'PowerSpec') {\t \t\t\t\t\n\tA <- cbind(t,t(a))\n\tA <- rbind(c(0,f),A)\n\tif (atype == 'PSD'){aid <- aid + 1}\n\tif (atype == 'PowerSpec'){aid <- aid + 2}\n\tA[1,1] <- aid\n}\n\nif (atype == 'TOL') {\n\tA <- cbind(t,t(a))\n\tA <- rbind(c(0,fc),A)\n\taid <- aid + 3\n\tA[1,1] <- aid\n\tf <- fc\n\t}\n\nif (atype == 'Broadband') {\n\tA <- t(rbind(t,a))\n\taid <- aid + 4\n\tA[1,1] <- aid\n}\n\nif (atype == 'Waveform') {\n\tA <- t(rbind(t,a))\t\t#define output array\n\tA <- rbind(c(0,0),A)\t#add zero top row for metadata\n\taid <- aid + 5\t\t\t#add index to metadata for Waveform\n\tA[1,1] <- aid\t\t\t#encode output array with metadata\n}\n\n## Reduce time resolution if selected------------------------------------------\n\ndimA <- dim(A)\t\t\t\t#dimensions of output array\n\nif (welch != \"\" && atype != \"Waveform\"){\n\tlout <- ceiling(dimA[1]/welch)+1\t#length of new, Welch-averaged, output array\n\tAWelch <- matrix(, nrow = lout, ncol = dimA[2])\t#initialise Welch array\n\tAWelch[1,] <- A[1,]\t\t\t\t\t#assign frequency vector\n\ttint <- A[3,1] - A[2,1]\t\t\t\t#time interval between segments\n\tcat('Welch factor =',welch,'x\\nNew time resolution =',welch,'(Welch factor) x',N/Fs,'s (time segment length) x',r*100,'% (overlap) =',welch*tint,'s\\n')\n\tif (lout == 2){\t\t\t\t\t\t#if Welch factor too large for number of time data points, abort averaging\n\t\tstop(paste('Welch factor is greater than half the number of samples. Set welch <=',dimA[1]/2,', or reduce N.',sep=\"\"),call.=FALSE)\n\t}\telse {\n\t\tfor (i in 2:lout) {\t\t\t\t\t\t#loop through Welch segments for averaging\n\t\t\tstt <- A[2,1] + (i-2)*tint*welch\t#start time\n\t\t\tett <- stt + welch*tint\t\t\t\t#end time\n\t\t\tstiv <- which(A[2:dimA[1]]>=stt)\n\t\t\tsti <- min(stiv)+1\t\t\t\t\t#start index\n\t\t\tetiv <- which(A[2:dimA[1]]0 & P<=1)) # sort, and keep only 00 & d<1] # only Ps between 0 and 1\n \n \n\tif (!is.null(highlight) | !is.null(annotate)){\n\t\tif (is.null(names(d))) stop(\"P-value vector must have names to use highlight or annotate features.\")\n\t\td = d[!is.na(names(d))]\n\t\tif (!is.null(highlight) & FALSE %in% (highlight %in% names(d))) stop (\"D'oh! Highlight vector must be a subset of names(pvector).\")\n\t\tif (!is.null(annotate) & FALSE %in% (annotate %in% names(d))) stop (\"D'oh! Annotate vector must be a subset of names(pvector).\")\n\t}\n\t\n\td = d[order(d,decreasing=F)] # sort\n\to = -log10(d)\n \n e = -log10( ppoints(length(d) ))\n if (!is.null(highlight) | !is.null(annotate)) names(e) = names(o) = names(d)\n\t\n\tif (!is.numeric(ymax) | ymax6.0] <- 6.0\n\t#ymax=6.0+0.2\n\t#xmax=6.0+0.2\n\tplot(0,xlab=expression(Expected~~-log[10](italic(p))),ylab=expression(Observed~~-log[10](italic(p))),\n\t\t\tcol=F,las=1,xaxt='n',xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty='n',xaxs='i',yaxs='i',cex.axis=cex.axis)\n # added DE\n\taxis(side=1,labels=seq(0,6,1),at=seq(0,6,1),cex.axis=cex.axis,lwd=0,lwd.ticks=1)\n\t#axis(side=1,labels=seq(0,max(e),1),at=seq(0,max(e),1),cex.axis=cex.axis,lwd=0,lwd.ticks=1)\n\t\n\t# Grid lines\n\tif (isTRUE(gridlines)){\n\t\tyvals = par('yaxp')\n\t\tyticks = seq(yvals[1],yvals[2],yvals[2]/yvals[3])\n\t\tabline(v=seq(0,max(e),1),col=gridlines.col[1],lwd=gridlines.lwd,lty=gridlines.lty)\n\t\tabline(h=yticks,col=gridlines.col[1],lwd=gridlines.lwd,lty=gridlines.lty)\n\t}\n\t\n\t #Confidence intervals\n\t find_conf_intervals = function(row){\n\t \ti = row[1]\n\t \tlen = row[2]\n\t \tif (i < 10000 | i %% 100 == 0){\n\t \t\treturn(c(-log10(qbeta(0.95,i,len-i+1)), -log10(qbeta(0.05,i,len-i+1))))\n\t \t} else { # Speed up\n\t \t\treturn(c(NA,NA))\n\t \t}\n\t }\n\n\t # Find approximate confidence intervals\n\tif (isTRUE(confidence)){\n\t\t#print('Plotting confidence intervals.')\n\t\tci = apply(cbind( 1:length(e), rep(length(e),length(e))), MARGIN=1, FUN=find_conf_intervals)\n\t \tbks = append(seq(10000,length(e),100),length(e)+1)\n\t\t# added DE\n\t \t#bks = append(seq(1000,length(e),10),length(e)+1)\n\t\tfor (i in 1:(length(bks)-1)){\n\t \t\tci[1, bks[i]:(bks[i+1]-1)] = ci[1, bks[i]]\n\t \t\tci[2, bks[i]:(bks[i+1]-1)] = ci[2, bks[i]]\n\t\t}\n\t\tcolnames(ci) = names(e)\n\t\t# Extrapolate to make plotting prettier (doesn't affect intepretation at data points)\n\t\tslopes = c((ci[1,1] - ci[1,2]) / (e[1] - e[2]), (ci[2,1] - ci[2,2]) / (e[1] - e[2]))\n\t\textrap_x = append(e[1]+xspace,e) #extrapolate slightly for plotting purposes only\n\t\textrap_y = cbind( c(ci[1,1] + slopes[1]*xspace, ci[2,1] + slopes[2]*xspace), ci)\n\t\t\n\t\t# added DE\n\t\tpolygon(c(extrap_x, rev(extrap_x)), c(extrap_y[1,], rev(extrap_y[2,])),col = confidence.col[1], border = \"red\")\t\n\t\t#polygon(c(extrap_x, rev(extrap_x)), c(extrap_y[1,], rev(extrap_y[2,])),col = confidence.col[1], border = confidence.col[1])\t\n\t}\n\t\n\t# Points (with optional highlighting)\n\t#print('Plotting data points.')\n\tfills = rep(pt.bg,length(o))\n\tborders = rep(pt.col,length(o))\n\tnames(fills) = names(borders) = names(o)\n\tif (!is.null(highlight)){\t\n\t\tborders[highlight] = rep(NA,length(highlight))\n\t\tfills[highlight] = rep(NA,length(highlight))\n\t}\n\tpoints(e,o,pch=pch,cex=pt.cex,col=borders,bg=fills)\n\t# added DE\n\ttitle(main=title)\n\ttext(2,1,paste(\"lambda=\", round(lambda, 3), \"; lambda_1000=\", round(lambda_1000, 3), \"\\nN(pvals)=\", length(pvector), sep=\"\"), cex=1.5, pos=4)\n\t\n\tif (!is.null(highlight)){\n\t\tpoints(e[highlight],o[highlight],pch=pch,cex=pt.cex,col=highlight.col,bg=highlight.bg)\n\t}\n\t\n\t#Abline\n # added DE\n\t#segments(0,0,extrap_x,extrap_y,col=abline.col,lwd=abline.lwd,lty=abline.lty)\n\tabline(0,1,col=abline.col,lwd=abline.lwd,lty=abline.lty)\n\t\n\t# Annotate SNPs\n\tif (!is.null(annotate)){\n\t\tx = e[annotate] # x will definitely be the same\n\t\ty = -0.1 + apply(rbind(o[annotate],ci[1,annotate]),2,min)\n\t\ttext(x,y,labels=annotate,srt=90,cex=annotate.cex,adj=c(1,0.48),font=annotate.font)\t\t\n\t}\n\t# Box\n\tbox()\n}\n\n\n\n\n\n\n\n\n# Old ggplot2 code --------------------------------------------------------\n#\n## manhattan plot using ggplot2\n# gg.manhattan = function(dataframe, title=NULL, max.y=\"max\", suggestiveline=0, genomewideline=-log10(5e-8), size.x.labels=9, size.y.labels=10, annotate=F, SNPlist=NULL) {\n# library(ggplot2)\n# if (annotate & is.null(SNPlist)) stop(\"You requested annotation but provided no SNPlist!\")\n# \td=dataframe\n# \t#limit to only chrs 1-23?\n# \td=d[d$CHR %in% 1:23, ]\n# \tif (\"CHR\" %in% names(d) & \"BP\" %in% names(d) & \"P\" %in% names(d) ) {\n# \t\td=na.omit(d)\n# \t\td=d[d$P>0 & d$P<=1, ]\n# \t\td$logp = -log10(d$P)\n# \t\td$pos=NA\n# \t\tticks=NULL\n# \t\tlastbase=0\n# \t\t#new 2010-05-10\n# \t\tnumchroms=length(unique(d$CHR))\n# \t\tif (numchroms==1) {\n# \t\t\td$pos=d$BP\n# \t\t} else {\n# \t\t\n# \t\t\tfor (i in unique(d$CHR)) {\n# \t\t\t\tif (i==1) {\n# \t\t\t\t\td[d$CHR==i, ]$pos=d[d$CHR==i, ]$BP\n# \t\t\t\t}\telse {\n# \t\t\t\t\tlastbase=lastbase+tail(subset(d,CHR==i-1)$BP, 1)\n# \t\t\t\t\td[d$CHR==i, ]$pos=d[d$CHR==i, ]$BP+lastbase\n# \t\t\t\t}\n# \t\t\t\tticks=c(ticks, d[d$CHR==i, ]$pos[floor(length(d[d$CHR==i, ]$pos)/2)+1])\n# \t\t\t}\n# \t\t\tticklim=c(min(d$pos),max(d$pos))\n# \n# \t\t}\n# \t\tmycols=rep(c(\"gray10\",\"gray60\"),max(d$CHR))\n# \t\tif (max.y==\"max\") maxy=ceiling(max(d$logp)) else maxy=max.y\n# \t\tif (maxy<8) maxy=8\n# \t\tif (annotate) d.annotate=d[as.numeric(substr(d$SNP,3,100)) %in% SNPlist, ]\n# \t\tif (numchroms==1) {\n# \t\t\tplot=qplot(pos,logp,data=d,ylab=expression(-log[10](italic(p))), xlab=paste(\"Chromosome\",unique(d$CHR),\"position\"))\n# \t\t}\telse {\n# \t\t\tplot=qplot(pos,logp,data=d, ylab=expression(-log[10](italic(p))) , colour=factor(CHR))\n# \t\t\tplot=plot+scale_x_continuous(name=\"Chromosome\", breaks=ticks, labels=(unique(d$CHR)))\n# \t\t\tplot=plot+scale_y_continuous(limits=c(0,maxy), breaks=1:maxy, labels=1:maxy)\n# \t\t\tplot=plot+scale_colour_manual(value=mycols)\n# \t\t}\n# \t\tif (annotate) \tplot=plot + geom_point(data=d.annotate, colour=I(\"green3\")) \n# \t\tplot=plot + opts(legend.position = \"none\") \n# \t\tplot=plot + opts(title=title)\n# \t\tplot=plot+opts(\n# \t\t\tpanel.background=theme_blank(), \n# \t\t\tpanel.grid.minor=theme_blank(),\n# \t\t\taxis.text.x=theme_text(size=size.x.labels, colour=\"grey50\"), \n# \t\t\taxis.text.y=theme_text(size=size.y.labels, colour=\"grey50\"), \n# \t\t\taxis.ticks=theme_segment(colour=NA)\n# \t\t)\n# \t\tif (suggestiveline) plot=plot+geom_hline(yintercept=suggestiveline,colour=\"blue\", alpha=I(1/3))\n# \t\tif (genomewideline) plot=plot+geom_hline(yintercept=genomewideline,colour=\"red\")\n# \t\tplot\n# \t}\telse {\n# \t\tstop(\"Make sure your data frame contains columns CHR, BP, and P\")\n# \t}\n# }\n# \n# ## QQ plot using ggplot2\n# gg.qq = function(pvector, title=NULL, spartan=F) {\n# \tlibrary(ggplot2)\n# \to = -log10(sort(pvector,decreasing=F))\n# \t#e = -log10( 1:length(o)/length(o) )\n# \te = -log10( ppoints(length(pvector) ))\n# \tplot=qplot(e,o, xlim=c(0,max(e)), ylim=c(0,max(o))) + stat_abline(intercept=0,slope=1, col=\"red\")\n# \tplot=plot+opts(title=title)\n# \tplot=plot+scale_x_continuous(name=expression(Expected~~-log[10](italic(p))))\n# \tplot=plot+scale_y_continuous(name=expression(Observed~~-log[10](italic(p))))\n# \tif (spartan) plot=plot+opts(panel.background=theme_rect(col=\"grey50\"), panel.grid.minor=theme_blank())\n# \tplot\n# }\n# \n# ## Make a qq and manhattan plot\n# gg.qqman = function(data=\"plinkresults\") {\n# \tmyqqplot = ggqq(data$P)\n# \tmymanplot = ggmanhattan(data)\n# \tggsave(file=\"qqplot.png\",myqqplot,w=5,h=5,dpi=100)\n# \tggsave(file=\"manhattan.png\",mymanplot,width=12,height=9,dpi=100)\n# }\n# \n# ## make qq and manhattan plots for a list of files\n# gg.qqmanall= function(command=\"ls *assoc\") {\n# \tfilelist=system(command,intern=T)\n# \tdatalist=NULL\n# \tfor (i in filelist) {datalist[[i]]=read.table(i,T)}\n# \thighestneglogp=ceiling(max(sapply(datalist, function(df) max(na.omit(-log10(df$P))))))\n# \tprint(paste(\"Highest -log10(P) = \",highestneglogp),quote=F)\n# \tstart=Sys.time()\n# \tfor (i in names(datalist)) {\n# \t\tmyqqplot=ggqq(datalist[[i]]$P, title=i)\n# \t\tggsave(file=paste(\"qqplot-\", i, \".png\", sep=\"\"),myqqplot, width=5, height=5,dpi=100)\n# \t\tmymanplot=ggmanhattan(datalist[[i]], title=i, max.y=highestneglogp)\n# \t\tggsave(file=paste(\"manhattan-\", i, \".png\", sep=\"\"),mymanplot,width=12,height=9,dpi=100)\n# \t}\n# \tend=Sys.time()\n# \tprint(elapsed<-end-start)\n# }\n", "meta": {"hexsha": "b3d8cf47e3671008caf45b10a661222e8cdf436e", "size": 19957, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/qqman_dev2.r", "max_stars_repo_name": "jkaessens/gwas-assoc", "max_stars_repo_head_hexsha": "1053c94222701f108362e33c99155cfc148f4ca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/qqman_dev2.r", "max_issues_repo_name": "jkaessens/gwas-assoc", "max_issues_repo_head_hexsha": "1053c94222701f108362e33c99155cfc148f4ca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/qqman_dev2.r", "max_forks_repo_name": "jkaessens/gwas-assoc", "max_forks_repo_head_hexsha": "1053c94222701f108362e33c99155cfc148f4ca2", "max_forks_repo_licenses": ["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.4407114625, "max_line_length": 171, "alphanum_fraction": 0.6246930901, "num_tokens": 6946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3117102658359745}} {"text": "#' Network data formats\n#'\n#' List of accepted graph formats\n#'\n#' @name netdiffuseR-graphs\n#' @details The \\pkg{netdiffuseR} package can handle different types of graph\n#' objects. Two general classes are defined across the package's functions:\n#' static graphs, and dynamic graphs.\n#' \\itemize{\n#' \\item{In the case of \\strong{static graphs}, these are represented as adjacency\n#' matrices of size \\eqn{n\\times n}{n * n} and can be either \\code{\\link{matrix}}\n#' (dense matrices) or \\code{\\link[Matrix:dgCMatrix-class]{dgCMatrix}}\n#' (sparse matrix from the \\pkg{\\link[Matrix:Matrix]{Matrix}} package). While\n#' most of the package functions are defined for both classes, the default output\n#' graph is sparse, i.e. \\code{dgCMatrix}.}\n#' \\item{With respect to \\strong{dynamic graphs}, these are represented by either\n#' a \\code{\\link{diffnet}} object, an \\code{\\link{array}} of size\n#' \\eqn{n\\times n \\times T}{n * n * T}, or a list of size \\eqn{T}\n#' with sparse matrices (class \\code{dgCMatrix}) of size \\eqn{n\\times n}{n * n}.\n#' Just like the static graph case, while most of the functions accept both\n#' graph types, the default output is \\code{dgCMatrix}.}\n#' }\n#' @section diffnet objects:\n#' In the case of \\code{diffnet}-class objects, the following arguments can be omitted\n#' when calling fuictions suitable for graph objects:\n#' \\itemize{\n#' \\item{\\code{toa}: Time of Adoption vector}\n#' \\item{\\code{adopt}: Adoption Matrix}\n#' \\item{\\code{cumadopt}: Cumulative Adoption Matrix}\n#' \\item{\\code{undirected}: Whether the graph is directed or not}\n#' }\n#'\n#' @section Objects' names:\n#' When possible, \\pkg{netdiffuseR} will try to reuse graphs dimensional names,\n#' this is, \\code{\\link{rownames}}, \\code{\\link{colnames}}, \\code{\\link{dimnames}}\n#' and \\code{\\link{names}} (in the case of dynamic graphs as lists). Otherwise,\n#' when no names are provided, these will be created from scratch.\n#' @include imports.r\n#' @author George G. Vega Yon\n#' @family graph formats\nNULL\n\n\nas_generic_graph <- function(graph) UseMethod(\"as_generic_graph\")\n\n# Method for igraph objects\nas_generic_graph.igraph <- function(graph) {\n\n # If multiple then warn\n if (igraph::any_multiple(graph))\n warning(\"The -igraph- object has multiple edges. Only one of each will be retrieved.\")\n if (\"weight\" %in% igraph::graph_attr_names(graph)) {\n adjmat <- igraph::as_adj(graph, attr=\"weight\")\n } else {\n adjmat <- igraph::as_adj(graph)\n }\n\n # Converting to dgCMatrix\n env <- environment()\n ans <- new_generic_graph()\n suppressWarnings(add_to_generic_graph(\"ans\", \"graph\", list(`1`=adjmat), env))\n meta <- c(classify_graph(adjmat), list(\n self = any(igraph::is.loop(graph)),\n undirected = FALSE, # For now we will assume it is undirected\n multiple = FALSE, # And !multiple\n class = \"igraph\"\n ))\n add_to_generic_graph(\"ans\", \"meta\", meta, env)\n\n return(ans)\n}\n\nnew_generic_graph <- function() {\n list(graph=NULL, meta=NULL)\n}\n\n# This function adds an element checking that the slot exits\nadd_to_generic_graph <- function(gg,nam,val,env=environment()) {\n obj <- get(gg, envir = env)\n if (!(nam %in% names(obj))) stop(nam,\" unknown slot.\")\n obj[[nam]] <- val\n assign(gg,obj,envir = env)\n invisible(NULL)\n}\n\n# Method for network objects\nas_generic_graph.network <- function(graph) {\n # If multiple then warn\n if (network::is.multiplex(graph))\n warning(\"The -network- object has multiple edges. These will be added up.\")\n\n # Converting to an adjacency matrix (dgCMatrix)\n adjmat <- edgelist_to_adjmat(\n network::as.edgelist(graph),\n undirected = !network::is.directed(graph),\n multiple = network::is.multiplex(graph),\n self = network::has.loops(graph)\n )\n\n ord <- network::network.vertex.names(graph)\n ord <- match(ord, rownames(adjmat))\n adjmat <- adjmat[ord,ord]\n\n env <- environment()\n ans <- new_generic_graph()\n suppressWarnings(add_to_generic_graph(\"ans\", \"graph\", list(`1`=adjmat), env))\n\n meta <- c(classify_graph(adjmat), list(\n self = network::has.loops(graph),\n undirected = !network::is.directed(graph),\n multiple = network::is.multiplex(graph),\n class = \"network\"\n ))\n\n add_to_generic_graph(\"ans\", \"meta\", meta, env)\n\n return(ans)\n}\n\nstopifnot_graph <- function(x)\n stop(\"No method for graph of class -\",class(x),\"- for \", deparse(sys.call()) #match.call()\n ,\". Please refer to the manual 'netdiffuseR-graphs'.\")\n\n#' Analyze an R object to identify the class of graph (if any)\n#' @template graph_template\n#' @details This function analyzes an R object and tries to classify it among the\n#' accepted classes in \\pkg{netdiffuseR}. If the object fails to fall in one of\n#' the types of graphs the function returns with an error indicating what (and\n#' when possible, where) the problem lies.\n#'\n#' The function was designed to be used with \\code{\\link{as_diffnet}}.\n#' @seealso \\code{\\link{as_diffnet}}, \\code{\\link{netdiffuseR-graphs}}\n#' @return Whe the object fits any of the accepted graph formats, a list of attributes including\n#' \\item{type}{Character scalar. Whether is a static or a dynamic graph}\n#' \\item{class}{Character scalar. The class of the original object}\n#' \\item{ids}{Character vector. Labels of the vertices}\n#' \\item{pers}{Integer vector. Labels of the time periods}\n#' \\item{nper}{Integer scalar. Number of time periods}\n#' \\item{n}{Integer scalar. Number of vertices in the graph}\n#' Otherwise returns with error.\n#' @author George G. Vega Yon\n#' @export\nclassify_graph <- function(graph) {\n\n # Diffnet object\n if (inherits(graph, \"diffnet\")) {\n return(classify_graph(graph$graph))\n } else if (inherits(graph, \"matrix\") || inherits(graph, \"dgCMatrix\")) { # Static graphs\n # Step 0: Should have length\n d <- dim(graph)\n if (!d[1])\n stop(\"Nothing to do. Empty matrix.\")\n\n # Step 1: Should be square\n if (d[1] != d[2])\n stop(\"-graph- must be a square matrix\\n\\tdim(graph) = c(\",\n paste0(d, collapse=\",\"),\").\")\n\n # Step 3: Should be numeric\n m <- mode(graph)\n if (!inherits(graph, \"dgCMatrix\") && !(m %in% c(\"numeric\", \"integer\")))\n stop(\"-graph- should be either numeric or integer.\\n\\tmode(graph) = \\\"\",\n m, \"\\\".\")\n\n # Step 4: Dimension names\n ids <- rownames(graph)\n if (!length(ids)) ids <- 1:d[1]\n\n return(invisible(list(\n type=\"static\",\n class=\"matrix\",\n ids=ids,\n pers=1,\n nper=1,\n n=d[1]\n )))\n }\n # Dynamic graphs (list) ------------------------------------------------------\n else if (inherits(graph, \"list\")) {\n # Step 0: Should have length!\n t <- length(graph)\n if (t < 2)\n stop(\"-graph- must be at least of length 2.\")\n\n # Step 1: All should be of class -dgCMatrix-\n c <- sapply(graph, inherits, \"dgCMatrix\")\n if (!all(c))\n stop(\"The following elements are not of class -dgCMatrix-:\\n\\t\",\n paste0(which(!c), collapse=\", \"),\".\")\n\n # Step 2.1: All must be square matrices\n d <- lapply(graph, dim)\n s <- sapply(d, function(x) x[1] == x[2])\n\n # Step 2.2: It must have some people!\n if (!d[[1]][1])\n stop(\"Nothing to do. Empty graph.\")\n\n if (!all(s))\n stop(\"The following adjmat are not square:\\n\\t\",\n paste0(which(!s), collapse=\", \"),\".\")\n\n # Step 3: All must have the same dimension\n e <- unlist(d, TRUE) == d[[1]][1]\n if (!all(e))\n stop(\"The dimensions of all slices must be equal. \",\n \"The following elements don't coincide with the first slice:\\n\\t\",\n paste0(which(!e), collapse=\", \"),\".\")\n\n # Step 4.1: Individual's ids\n ids <- rownames(graph[[1]])\n if (!length(ids)) ids <- 1:d[[1]][1]\n\n # Step 4.2 Time ids\n suppressWarnings(pers <- as.integer(names(graph)))\n if (!length(pers)) pers <- 1:t\n else {\n # Step 4.2.1: Must be coercible into integer\n if (any(is.na(pers))) stop(\"names(graph) should be either numeric or integer.\")\n\n # Step 4.2.1: Must keep uniqueness\n if (length(unique(pers)) != t) stop(\"When coercing names(graph) into integer,\",\n \"some slices acquired the same name.\")\n }\n\n return(invisible(list(\n type=\"dynamic\",\n class=\"list\",\n ids=as.character(ids),\n pers=pers,\n nper=t,\n n=d[[1]][1])\n ))\n\n }\n # Dynamic graphs (array) -----------------------------------------------------\n else if (inherits(graph, \"array\")) {\n # Step 0: it should have length!\n d <- dim(graph)\n if (d[3] < 2)\n stop(\"-graph- must be at least of length 2.\")\n\n # Step 1: there must be some people\n if (!d[1])\n stop(\"Nothing to do. Empty matrix.\")\n\n # Step 2: It must be square\n if (d[1] != d[2])\n stop(\"Each adjmat in -graph- must be a square matrix\\n\\tdim(graph) = c(\",\n paste0(d, collapse=\",\"),\").\")\n\n # Step 3: Should be numeric\n m <- mode(graph)\n if (!(m %in% c(\"numeric\", \"integer\")))\n stop(\"-graph- should be either numeric or integer.\\n\\tmode(graph) = \\\"\",\n m, \"\\\".\")\n\n # Step 4: Dimension names\n ids <- rownames(graph)\n if (!length(ids)) ids <- 1:d[1]\n\n pers <- as.numeric(dimnames(graph)[[3]])\n if (!length(pers)) pers <- 1:d[3]\n else {\n # Step 4.2.1: Must be coercible into integer\n suppressWarnings(alters <- as.integer(floor(pers)))\n if (any(is.na(alters))) stop(\"names(graph) should be either numeric or integer.\")\n\n # Step 4.2.1: Must keep uniqueness\n if (length(unique(alters)) != length(pers))\n stop(\"When coercing names(graph) into integer,\",\n \"some slices acquired the same name.\")\n pers <- alters\n }\n\n return(invisible(list(\n type=\"dynamic\",\n class=\"array\",\n ids=ids,\n pers=pers,\n nper=d[3],\n n=d[1])\n ))\n }\n\n # Other case (ERROR) ---------------------------------------------------------\n stop(\"Not an object allowed in netdiffuseR. It must be either:\\n\\t\",\n \"matrix, dgCMatrix, list or array.\\n\", \"Please refer to ?\\\"netdiffuseR-graphs\\\" \")\n}\n\n# Auxiliar function to check if there's any attribute of undirectedness\ncheckingUndirected <- function(graph, warn=TRUE, default=getOption(\"diffnet.undirected\")) {\n\n # Ifendifying the class of graph\n if (inherits(graph, \"diffnet\")) undirected <- graph$meta$undirected\n else undirected <- attr(graph, \"undirected\")\n\n if (warn)\n if (length(undirected) && undirected != FALSE)\n warning(\"The entered -graph- will now be directed.\")\n\n if (!length(undirected)) undirected <- default\n\n invisible(undirected)\n\n}\n", "meta": {"hexsha": "f8af83c72e3a516267cc2e7d05983be797a17529", "size": 10579, "ext": "r", "lang": "R", "max_stars_repo_path": "R/graph_data.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/graph_data.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/graph_data.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 34.4592833876, "max_line_length": 96, "alphanum_fraction": 0.6271859344, "num_tokens": 2887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.31095132679903065}} {"text": "## Main fitting function.\n## - Arguments:\n## - capthist: Capture history matrix.\n## - ids: A vector of IDs, where each element indicates which individual is associated with each capture history.\n## - traps: Matrix of detector locations.\n## - mask: Mask object with points for numerical integration over activity centre locations. Must include an attribute called \"area\", providing the area covered by a single point.\n## - detfn: The detection function to use; either \"hn\" (halfnormal) or \"hhn\" (hazard halfnormal). If signal strengths are provided, then this argument is ignored and a signal strength detection function is used.\n## - start: A named vector of start values for numerical maximisation. See the model parameters below for names.\n## - toa: Time of arrival matrix in the same structure as the capthist object (optional).\n## - ss: Signal strength matrix in the same structure as the capthist object (optional).\n## - speed_sound: The speed of sound in metres per second.\n## - ss_cutoff: A signal strength cutoff. See Stevenson et al (2015).\n##\n## For multisession models, capthist, ids, traps, mask, toa, and ss can be lists, where each component of the list corresponds to a single session.\n## \n## Model parameters:\n##\n## Mandatory:\n## - D: Animals per hectare.\n## - lambda: Expected number of calls per individual.\n##\n## When using the halfnormal detection function:\n## - g0: Detection function intercept.\n## - sigma: Detection function spatial scale.\n##\n## When using the hazard halfnormal detection function:\n## - lambda0: Detection function intercept on the hazard scale.\n## - sigma: Detection function spatial scale.\n##\n## When time-of-arrival data are provided:\n## - sigma_toa: Measurement error of times-of-arrival.\n##\n## When signal strength data are provided:\n## - b0_ss: Source signal strength.\n## - b1_ss: Signal strength loss per metre.\n## - sigma_ss: Measurement error of signal strengths.\n\ncuerate.scr.fit <- function(capthist, ids, traps, mask, detfn = NULL, start, toa = NULL, ss = NULL , speed_sound = 330, ss_cutoff = 0, trace = FALSE){\n ## Indicator for whether or not signal strengths are used.\n use_ss <- !is.null(ss)\n ## Indicator for whether or not times of arrival are used.\n use_toa <- !is.null(toa)\n if (is.list(capthist)){\n multi.sess <- TRUE\n } else {\n multi.sess <- FALSE\n capthist <- list(capthist)\n ids <- list(ids)\n traps <- list(traps)\n mask <- list(mask)\n if (use_toa){\n toa <- list(toa)\n }\n if (use_ss){\n ss <- list(ss)\n }\n }\n n.sessions <- length(capthist)\n aMask <- maskDists <- toa_ssq <- vector(\"list\", n.sessions)\n if (!use_toa){\n toa <- vector(\"list\", n.sessions)\n }\n if (!use_ss){\n ss <- vector(\"list\", n.sessions)\n }\n for (i in 1:n.sessions){\n ## ids must be 1:N animals.\n ids[[i]] = as.numeric(factor(ids[[i]]))\n ## Area of a single mask point.\n aMask[[i]] <- attr(mask[[i]], \"area\")\n \n ## Calculating distances between mask points and detectors.\n maskDists[[i]] <- eucdist(mask[[i]], traps[[i]])\n if (use_toa){\n ## Creating TOA sum of squares matrix.\n toa_ssq[[i]] <- make_toa_ssq(toa[[i]], eucdist(traps[[i]], mask[[i]]), speed_sound)\n } else {\n ## Dummy objects if not used.\n toa[[i]] <- toa_ssq[[i]] <- matrix(0, nrow = 1, ncol = 1)\n }\n if (!use_ss){\n ss[[i]] <- matrix(0, nrow = 1, ncol = 1)\n }\n }\n ## Indicator for detection function.\n if (is.null(detfn) & !use_ss){\n stop(\"A detection function must be selected.\")\n }\n if (use_ss){\n if (!is.null(detfn)){\n warning(\"The choice of detection function is being ignored because signal strengths have been provided.\")\n }\n detfn <- \"ss\"\n hn <- FALSE\n } else if (detfn == \"hn\"){\n hn <- TRUE\n } else if (detfn == \"hhn\"){\n hn <- FALSE\n } else {\n stop(\"The argument detfn must either be 'hn' or 'hhn'.\")\n }\n ## Converting parameters to link scale.\n start.link <- numeric(6)\n names(start.link) <- c(\"D\", \"df1\", \"df2\", \"lambda\", \"sigma_toa\", \"sigma_ss\")\n start.link[\"D\"] <- log(start[\"D\"])\n start.link[\"lambda\"] <- log(start[\"lambda\"])\n if (use_ss){\n names(start.link)[c(2, 3)] <- c(\"b0_ss\", \"b1_ss\")\n start.link[\"b0_ss\"] <- log(start[\"b0_ss\"])\n start.link[\"b1_ss\"] <- log(start[\"b1_ss\"])\n start.link[\"sigma_ss\"] <- log(start[\"sigma_ss\"])\n } else if (hn){\n names(start.link)[c(2, 3)] <- c(\"g0\", \"sigma\")\n start.link[\"g0\"] <- qlogis(start[\"g0\"])\n start.link[\"sigma\"] <- log(start[\"sigma\"])\n } else {\n names(start.link)[c(2, 3)] <- c(\"lambda0\", \"sigma\")\n start.link[\"lambda0\"] <- log(start[\"lambda0\"])\n start.link[\"sigma\"] <- log(start[\"sigma\"])\n }\n if (use_toa){\n start.link[\"sigma_toa\"] <- log(start[\"sigma_toa\"])\n }\n start <- c(start[1:4], start[\"sigma_toa\"][use_toa], start[\"sigma_ss\"][use_ss])\n start.link <- c(start.link[1:4], start.link[\"sigma_toa\"][use_toa], start.link[\"sigma_ss\"][use_ss])\n n.pars <- length(start)\n par.names <- names(start)\n ## Fitting model.\n fit <- nlminb(start.link, scr.nll.cuerate.multi,\n caps = capthist,\n aMask = aMask,\n maskDists = maskDists,\n ID = ids,\n toa = toa,\n toa_ssq = toa_ssq,\n use_toa = use_toa,\n ss = ss,\n use_ss = use_ss,\n ss_cutoff = ss_cutoff,\n hn = hn,\n trace = trace,\n par_names = par.names)\n ## Approximating Hessian.\n hess <- optimHess(fit$par, scr.nll.cuerate.multi,\n caps = capthist,\n aMask = aMask,\n maskDists = maskDists,\n ID = ids,\n toa = toa,\n toa_ssq = toa_ssq,\n use_toa = use_toa,\n ss = ss,\n ss_cutoff = ss_cutoff,\n use_ss = use_ss,\n hn = hn,\n trace = trace,\n par_names = par.names)\n \n ## Calculating confidence intervals\n ## - Using the (sqrt of) diagonals of (-ve) Hessian obtained from optimHess\n ## - i.e. Information matrix\n ## - Wald CIs calculated by sapply() loop\n ## - Loops through each of fitted parameters and calculates lower/upper bounds\n ## Note: fitted pars must be on LINK scale\n ## : if matrix is singular, none of the SEs or CIs are calculated (inherits/try statement)\n fittedPars = fit$par\n names(fittedPars) <- par.names\n if(inherits(try(solve(hess), silent = TRUE), \"try-error\")) {\n ## Hessian is singular\n warning(\"Warning: singular hessian\")\n ## SE and Wald CIs not calculated\n se = NA\n waldCI = matrix(NA, nrow = length(fittedPars), ncol = 2)\n ## But columns still need to be returned (if/when simulations are run)\n cnames = c(\"Estimate\", \"SE\", \"Lower\", \"Upper\")\n } else {\n ## Calculating basic Wald CIs\n se = sqrt(diag(solve(hess)))\n waldCI.link = t(sapply(1:length(fittedPars),\n function(i) fittedPars[i] + (c(-1, 1) * (qnorm(0.975) * se[i]))))\n G.mult <- numeric(n.pars)\n waldCI <- 0*waldCI.link\n ## Back-transforming the confidence limits.\n for (i in par.names){\n if (i %in% c(\"D\", \"b0_ss\", \"b1_ss\", \"sigma_ss\", \"lambda0\", \"sigma\", \"lambda\", \"sigma_toa\")){\n waldCI[par.names == i, ] <- exp(waldCI.link[par.names == i, ])\n G.mult[par.names == i] <- exp(fittedPars[i])\n fittedPars[i] <- exp(fittedPars[i])\n }\n if (i == \"g0\"){\n waldCI[par.names == i, ] <- plogis(waldCI.link[par.names == i, ])\n G.mult[par.names == i] <- dlogis(fittedPars[i])\n fittedPars[i] <- plogis(fittedPars[i])\n }\n }\n ## Using the delta method to get the standard errors\n ## - G = jacobian matrix of partial derivatives of back-transformed\n ## - i.e. log(D) -> exp(D) -- deriv. --> exp(D)\n ## - Note: 1st deriv of plogis (CDF) = dlogis (PDF)\n G = diag(length(fittedPars)) * G.mult\n se = sqrt(diag(G %*% solve(hess) %*% t(G)))\n }\n results = cbind(fittedPars, se, waldCI)\n dimnames(results) = list(par.names, c(\"Estimate\", \"SE\", \"Lower\", \"Upper\"))\n ## Returning a list with everything.\n list(results = results, capthist = capthist, \n mask = mask, aMask = aMask, maskDists = maskDists, \n speed_sound = speed_sound, ids = ids,\n traps = traps, detfn = detfn, toa = toa, toa_ssq = toa_ssq, hess = hess)\n \n}\n\nscr.nll.cuerate.multi <- function(pars, caps, aMask, maskDists, ID, toa, toa_ssq,\n use_toa, ss, use_ss, ss_cutoff, hn, trace, par_names){\n n.sessions <- length(caps)\n sess.nll <- numeric(n.sessions)\n for (i in 1:n.sessions){\n sess.nll[i] <- scr_nll_cuerate(pars, caps[[i]], aMask[[i]], maskDists[[i]],\n ID[[i]], toa[[i]], toa_ssq[[i]], use_toa, ss[[i]],\n use_ss, ss_cutoff, hn, trace, par_names)\n }\n sum(sess.nll)\n}\n", "meta": {"hexsha": "73b2fcaaa018de4a4b1de53be66901cd7ad92f13", "size": 9638, "ext": "r", "lang": "R", "max_stars_repo_path": "fit-cuerate-scr.r", "max_stars_repo_name": "b-steve/scr-cuerate", "max_stars_repo_head_hexsha": "f775ab3fd2e6d41b1c6ab32e0d13257464432441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fit-cuerate-scr.r", "max_issues_repo_name": "b-steve/scr-cuerate", "max_issues_repo_head_hexsha": "f775ab3fd2e6d41b1c6ab32e0d13257464432441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fit-cuerate-scr.r", "max_forks_repo_name": "b-steve/scr-cuerate", "max_forks_repo_head_hexsha": "f775ab3fd2e6d41b1c6ab32e0d13257464432441", "max_forks_repo_licenses": ["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.0267857143, "max_line_length": 220, "alphanum_fraction": 0.5505291554, "num_tokens": 2563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.3104559213997218}} {"text": "# Run init.r before other scripts\nrm(list=ls())\n # for use in R console.\n # set own relevant directory if working in R console, otherwise ignore if in terminal\nsetwd(\"/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/EGSL_species_distribution\")\n# -----------------------------------------------------------------------------\n# PROJECT:\n# Evaluating the structure of the communities of the estuary\n# and gulf of St.Lawrence\n# -----------------------------------------------------------------------------\n\n# Studying the HMSC package, contact is G. Blanchet for inquiries\n\n# Dependencies\n library(Rcpp)\n library(RcppArmadillo)\n library(coda)\n\n# Installing the package\n # library(devtools)\n # install_github(\"guiblanchet/HMSC\")\n library(HMSC)\n\n# Other libraries\n # install.packages('beanplot', dependencies = T)\n # install.packages('corrplot', dependencies = T)\n # install.packages('circlize', dependencies = T)\n library(beanplot)\n library(corrplot)\n library(circlize)\n\n# First part of the workflow:\n # 1. Setting up an HMSC object by de\fning the model structure (e.g. whether traits or random effects are to be included) and organizing the data (typically imported from \fles with standard R commands).\n # 2. De\fning the priors required for Bayesian inference.\n # 3. Initiating the model parameters\n # 4. Running the actual estimation scheme. This involves setting the Markov chain Monte Carlo (MCMC) sampler (e.g. by de\fning the number of iterations and how they will be thinned). As running the estimation scheme may take some time, we recommend the user to save the HMSC object to a \fle outside of R (e.g. called \\model.RData\"). This object includes the model structure, the data, and the full posterior distribution.\n\n# Second part of the workflow:\n # No set order, but the user might typically wish to do the following:\n # - Assess the convergence of the MCMC chains,\n # - Produce posterior summaries (e.g. posterior means and quantiles) such as tables or plots,\n # - Measure the explanatory power of the model,\n # - Perform a variance partitioning among the \ffixed and random eff\u000bects,\n # - Make predictions.\n\n# Structure of the HMSC model\n # For ecologically meaningful analyses, the minimal set of data needed are either of the following:\n # 1. The occurrence matrix for one species as well as the environmental covariate matrix, in which case the HMSC model corresponds to a traditional single-species model.\n # 2. The occurrence matrix for several species, in which case the HMSC model corresponds to a model-based ordination.\n\n# Formatting data\n # species: numeric values\n # environmental covariates: numeric values\n # random effects: factor if single random effect, data frame if multiple random effects\n # traits: numeric values\n # phylogeny: square symmetric correlation or covariance matrix\n # autocorrelated random eff\u000bect: either a data frame with the \ffirst column a factor while the other columns are spatial or temporal coordinates or a list of data frame following the structure presented previously if there are multiple autocorrelated random eff\u000bects.\n\n # Typically highly recommended to scale (center and divide by the standard deviation) the environmental covariates and the traits so that their mean is zero and their variance one.\n # this removes the potential e\u000bects units can have on the parameter estimation\n # the default priors are compatible with the scaled covariates\n\n# Example 1\n # 1. Reading the data\n # Community matrix\n spComm <- read.csv(\"./documentation/HMSC-data/simulated/Y.csv\")\n # Environmental covariates\n env <- read.csv(\"./documentation/HMSC-data/simulated/X.csv\")\n # Random effects\n sitePlot <- read.csv(\"./documentation/HMSC-data/simulated/Pi.csv\")\n\n # 2. Creating HMSC data\n # Convert all columns of Pi to a factor\n for(i in 1:ncol(sitePlot)) {\n sitePlot[,i] <- as.factor(sitePlot[,i])\n }\n\n simulEx1 <- as.HMSCdata(Y = spComm, X = env, Random = sitePlot, interceptX = FALSE, scaleX = FALSE)\n\n # Alternatively, load the data directly. Available for this example, but I will have to do it myself for my own data\n data(\"simulEx1\")\n\n # 3. Defining prior distribution\n # We are using uninformative priors for this part. However, the user can modify this if desired.\n simulEx1prior <- as.HMSCprior(simulEx1)\n\n # 4. Setting initial model parameters\n simulEx1param <- as.HMSCparam(simulEx1, simulEx1prior)\n\n # 5. Setting the values of the true parameters\"\n # This is only possible with simulated data for which we know the actual parameter values. Otherwise, it is impossible.\n data(\"simulParamEx1\")\n\n # 6. Performing the MCMC sampling\n model <- hmsc(simulEx1,\n param = simulEx1param,\n priors = simulEx1prior,\n family = \"probit\",\n niter = 10000,\n nburn = 1000,\n thin = 10)\n\n # Simpler version when uninformative priors are sufficient and a priori parameters do not need to be set\n model <- hmsc(simulEx1,\n family = \"probit\",\n niter = 10000,\n nburn = 1000,\n thin = 10)\n\n # 7. Producing MCMC trace and density plots\n # Mixing objects\n mixingParamX <- as.mcmc(model, parameters = \"paramX\")\n mixingMeansParamX <- as.mcmc(model, parameters = \"meansParamX\")\n mixingMeansVarX <- as.mcmc(model, parameters = \"varX\")\n mixingParamLatent <- as.mcmc(model, parameters = \"paramLatent\")\n\n plot(mixingMeansParamX, col = \"blue\")\n\n # 8. Producing posterior summaries\n # Violin plot\n par(mar=c(6,4,1,1))\n mixingParamXDF <- as.data.frame(mixingParamX)\n beanplot(mixingParamXDF, las = 2)\n points(1:30, as.vector(simulParamEx1$param$paramX), pch=19, col=\"blue\", cex=2)\n\n # Box plot\n par(mar=c(6,4,1,1))\n boxplot(mixingParamXDF, las = 2)\n points(1:30, as.vector(simulParamEx1$param$paramX), pch=19, col=\"blue\", cex=2)\n\n # Average\n average <- apply(model$results$estimation$paramX, 1:2, mean)\n # 95% confidence intervals\n CI.025 <- apply(model$results$estimation$paramX, 1:2, quantile, probs = 0.025)\n CI.975 <- apply(model$results$estimation$paramX, 1:2, quantile, probs = 0.975)\n\n # Summary table\n paramXCITable <- cbind(unlist(as.data.frame(average)),\n unlist(as.data.frame(CI.025)),\n unlist(as.data.frame(CI.975)))\n colnames(paramXCITable) <- c(\"average\", \"lowerCI\", \"upperCI\")\n rownames(paramXCITable) <- paste(rep(colnames(average), each = nrow(average)), \"_\", rep(rownames(average), ncol(average)), sep=\"\")\n\n # Print summary table\n paramXCITable\n\n # Credible intervals\n par(mar=c(7,4,1,1))\n plot(0, 0, xlim = c(1, nrow(paramXCITable)), ylim = range(paramXCITable), type = \"n\", xlab = \"\", ylab = \"\", main=\"paramX\", xaxt=\"n\")\n axis(1,1:30,rownames(paramXCITable),las=2)\n abline(h = 0,col = \"grey\")\n arrows(x0 = 1:nrow(paramXCITable), x1 = 1:nrow(paramXCITable), y0 = paramXCITable[, 2], y1 = paramXCITable[, 3], code = 3, angle = 90, length = 0.05)\n points(1:nrow(paramXCITable), paramXCITable[,1], pch = 15, cex = 2)\n points(1:nrow(paramXCITable), as.vector(simulParamEx1$param$paramX),col = \"blue\", pch = 19, cex = 2)\n\n # 9. Variance partitioning\n variationPart <- variPart(model, c(rep(\"climate\", 2), \"habitat\"))\n\n Colour <- c(\"orange\", \"blue\", \"darkgreen\", \"purple\")\n barplot(t(variationPart), col=Colour, las=1)\n legend(\"bottomleft\",\n legend = c(paste(\"Fixed climate (mean = \", round(mean(variationPart[, 1]), 4)*100, \"%)\", sep=\"\"),\n paste(\"Fixed habitat (mean = \", round(mean(variationPart[, 2]), 4)*100, \"%)\", sep=\"\"),\n paste(\"Random site (mean = \", round(mean(variationPart[, 3]), 4)*100, \"%)\", sep=\"\"),\n paste(\"Random plot (mean = \", round(mean(variationPart[, 4]), 4)*100, \"%)\", sep=\"\")),\n fill = Colour,\n bg=\"white\")\n\n # 10. Association networks\n # Extract all estimated associatin matrix\n assoMat <- corRandomEff(model)\n # Average\n siteMean <- apply(assoMat[, , , 1], 1:2, mean)\n plotMean <- apply(assoMat[, , , 2], 1:2, mean)\n\n #=======================\n ### Associations to draw\n #=======================\n #--------------------\n ### Site level effect\n #--------------------\n # Build matrix of colours for chordDiagram\n siteDrawCol <- matrix(NA, nrow = nrow(siteMean), ncol = ncol(siteMean))\n siteDrawCol[which(siteMean > 0.4, arr.ind=TRUE)]<-\"red\"\n siteDrawCol[which(siteMean < -0.4, arr.ind=TRUE)]<-\"blue\"\n # Build matrix of \"significance\" for corrplot\n siteDraw <- siteDrawCol\n siteDraw[which(!is.na(siteDraw), arr.ind = TRUE)] <- 0\n siteDraw[which(is.na(siteDraw), arr.ind = TRUE)] <- 1\n siteDraw <- matrix(as.numeric(siteDraw), nrow = nrow(siteMean), ncol = ncol(siteMean))\n #--------------------\n ### Plot level effect\n #--------------------\n # Build matrix of colours for chordDiagram\n plotDrawCol <- matrix(NA, nrow = nrow(plotMean), ncol = ncol(plotMean))\n plotDrawCol[which(plotMean > 0.4, arr.ind=TRUE)]<-\"red\"\n plotDrawCol[which(plotMean < -0.4, arr.ind=TRUE)]<-\"blue\"\n # Build matrix of \"significance\" for corrplot\n plotDraw <- plotDrawCol\n plotDraw[which(!is.na(plotDraw), arr.ind = TRUE)] <- 0\n plotDraw[which(is.na(plotDraw), arr.ind = TRUE)] <- 1\n plotDraw <- matrix(as.numeric(plotDraw), nrow = nrow(plotMean), ncol = ncol(plotMean))\n\n # plotDraw plots\n par(mfrow=c(1,2))\n # Matrix plot\n Colour <- colorRampPalette(c(\"blue\", \"white\", \"red\"))(200)\n corrplot::corrplot(siteMean, method = \"color\", col = Colour, type = \"lower\", diag = FALSE, p.mat = siteDraw, tl.srt = 45)\n # Chord diagram\n circlize::chordDiagram(siteMean, symmetric = TRUE, annotationTrack = c(\"name\", \"grid\"), grid.col = \"grey\", col = siteDrawCol)\n\n # siteDraw plots\n par(mfrow=c(1,2))\n # Matrix plot\n Colour <- colorRampPalette(c(\"blue\", \"white\", \"red\"))(200)\n corrplot::corrplot(plotMean, method = \"color\", col = Colour, type = \"lower\", diag = FALSE, p.mat = plotDraw, tl.srt = 45)\n # Chord diagram\n circlize::chordDiagram(plotMean, symmetric = TRUE, annotationTrack = c(\"name\", \"grid\"), grid.col = \"grey\", col = plotDrawCol)\n\n # 11. Computing the explanatory power of the model\n # Prevalence\n prevSp <- colSums(simulEx1$Y)\n # Coefficient of multiple determination\n R2 <- Rsquared(model, averageSp = FALSE)\n R2comm <- Rsquared(model, averageSp = TRUE)\n # Draw figure\n par(mar=c(5,6,0.5,0.5))\n plot(prevSp, R2, xlab = \"Prevalence\", ylab = expression(R^2), pch=19, las=1,cex.lab = 2)\n abline(h = R2comm, col = \"blue\", lwd = 2)\n\n # Extract all MCMC of paramX\n model$results$estimation$paramX\n\n ### Full joint probability distribution\n fullPost <- jposterior(model)\n\n # 12. Generating predictions for training data\n # predictions that are not conditional on the occurrences of other species\n predTrain <- predict(model)\n\n #13. Generating predictions for new data\n # New environmental covariates\n newPred <- 100\n nEnv <- ncol(simulEx1$X)\n Xnew <- matrix(nrow = newPred, ncol = nEnv)\n colnames(Xnew) <- colnames(simulEx1$X)\n Xnew[, 1] <- 1\n Xnew[, 2] <- mean(simulEx1$X[, 2])\n Xnew[, 3] <- seq(min(simulEx1$X[, 3]), max(simulEx1$X[, 3]), length = newPred)\n\n # New site- and plot-level random effect\n RandomSel <- sample(200, 100)\n RandomNew <- simulEx1$Random[RandomSel, ]\n for(i in 1:ncol(RandomNew)) {\n RandomNew[, i] <- as.factor(as.character(RandomNew[, i]))\n }\n colnames(RandomNew) <- colnames(simulEx1$Random)\n\n # Organize the data into an HMSCdata object\n dataVal <- as.HMSCdata(X = Xnew, Random = RandomNew, scaleX = FALSE, interceptX = FALSE)\n\n # Generate predictions\n predVal <- predict(model, newdata = dataVal)\n\n # Plot predictions\n plot(0, 0, type=\"n\", xlim = range(dataVal$X[, 3]), ylim = c(0, 1),\n xlab = \"Environmental covariate 3\",\n ylab = \"Probability of occurrence\")\n Colours <- rainbow(ncol(predVal))\n for(i in 1:ncol(predVal)) {\n lines(dataVal$X[, 3], predVal[, i], col = Colours[i], lwd=3)\n }\n", "meta": {"hexsha": "cb536710e5166b8ae01936d328762834dbda1c27", "size": 13404, "ext": "r", "lang": "R", "max_stars_repo_path": "Script/HMSC.r", "max_stars_repo_name": "david-beauchesne/EGSL_species_distribution", "max_stars_repo_head_hexsha": "490ff78c43e8597786c9ab55f9db1b8ddb458acd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-04-10T12:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-10T12:54:25.000Z", "max_issues_repo_path": "Script/HMSC.r", "max_issues_repo_name": "david-beauchesne/EGSL_species_distribution", "max_issues_repo_head_hexsha": "490ff78c43e8597786c9ab55f9db1b8ddb458acd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Script/HMSC.r", "max_forks_repo_name": "david-beauchesne/EGSL_species_distribution", "max_forks_repo_head_hexsha": "490ff78c43e8597786c9ab55f9db1b8ddb458acd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0989010989, "max_line_length": 424, "alphanum_fraction": 0.5957923008, "num_tokens": 3463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.310422474121176}} {"text": "#Evolutionary models of continuous trait evolution in R\n\n## Read data & tree\nlibrary(phytools)\nlibrary(geiger)\n\ntree<-read.tree(\"TutorialData/anole.gp.tre\",tree.names=T)\ngroup<-read.csv('TutorialData/anole.gp.csv', row.names=1, header=TRUE,colClasses=c('factor'))\ngp<-as.factor(t(group)); names(gp)<-row.names(group)\nsvl<-read.csv('TutorialData/anole.svl2.csv', row.names=1, header=TRUE)\nsvl<-as.matrix(treedata(phy = tree,data = svl, warnings=FALSE)$data)[,1] #match data to tree\n\n##BM plot data\ntree.col<-contMap(tree,svl,plot=FALSE) #runs Anc. St. Est. on branches of tree\nplot(tree.col,legend=0.7*max(nodeHeights(tree)),\n fsize=c(0.7,0.9))\n\n#PLOT data\ntree.col<-contMap(tree,svl,plot=FALSE) #runs Anc. St. Est. on branches of tree\nplot(tree.col,type=\"fan\",legend=0.7*max(nodeHeights(tree)),\n fsize=c(0.7,0.9))\ncols<-setNames(palette()[1:length(unique(gp))],sort(unique(gp)))\ntiplabels(pie=model.matrix(~gp-1),piecol=cols,cex=0.3)\nadd.simmap.legend(colors=cols,prompt=FALSE,x=0.8*par()$usr[1],\n y=-max(nodeHeights(tree)-.6),fsize=0.8)\n\n\n## 1: Some evolutionary models in GEIGER\n #NOTE: may need to adjust the bounds of the search: see help file\nfit.BM1<-fitContinuous(tree, svl, model=\"BM\") #Brownian motion model\nfit.BMtrend<-fitContinuous(tree, svl, model=\"trend\") #Brownian motion with a trend\nfit.EB<-fitContinuous(tree, svl, model=\"EB\") #Early-burst model\nfit.lambda<-fitContinuous(tree, svl, \n bounds = list(lambda = c(min = exp(-5), max = 2)), model=\"lambda\") #Lambda model\noptions(warn=-1)\nfit.K<-fitContinuous(tree, svl, model=\"kappa\") #Early-burst model\noptions(warn=-1)\nfit.OU1<-fitContinuous(tree, svl,model=\"OU\") #OU1 model\n\n#Examine AIC\nc(fit.BM1$opt$aic,fit.BMtrend$opt$aic,fit.EB$opt$aic,fit.lambda$opt$aic,fit.OU1$opt$aic)\n #NOTE: none of these generate dAIC > 4. So go with simplest model (BM1)\n\n# Compare LRT formally (NOT needed in this case, but done so anyway)\nLRT<-(2*(fit.BM1$opt$lnL-fit.OU1$opt$lnL))\nprob<-pchisq(LRT, 1, lower.tail=FALSE)\nLRT\nprob\n\n## 2: More complex models: Multiple Ornstein-Uhlenbeck Peaks\nlibrary(OUwie)\ndata<-data.frame(Genus_species=names(svl),Reg=gp,X=svl) #input data.frame for OUwie\n\nfitBM1<-OUwie(tree,data,model=\"BM1\",simmap.tree=TRUE)\nfitOU1<-OUwie(tree,data,model=\"OU1\",simmap.tree=TRUE) \n tree.simmap<-make.simmap(tree,gp) # perform & plot stochastic maps (we would normally do this x100)\nfitOUM<-OUwie(tree.simmap,data,model=\"OUM\",simmap.tree=TRUE)\n\nfitBM1 \nfitOU1\nfitOUM #OUM is strongly preferred (examine AIC)\n\n#How it SHOULD be run\n#trees.simmap<-make.simmap(tree = tree,x = gp,nsim = 100) # 100 simmaps\n#fitOUM.100<-lapply(1:100, function(j) OUwie(trees.simmap[[j]],data,model=\"OUM\",simmap.tree=TRUE))\n#OUM.AIC<-unlist(lapply(1:100, function(j) fitOUM.100[[j]]$AIC))\n#hist(OUM.AIC)\n#abline(v=fitBM1$AIC, lwd=2) #add value for BM1\n\n## 3: More complex models: Multiple Evolutionary Rates\n\n# 3A: BM1 vs BMM: Comparing evolutionary rates\ntree.simmap<-make.simmap(tree,gp) # perform & plot stochastic maps (we would normally do this x100)\nBMM.res<-brownie.lite(tree = tree.simmap,x = svl,test=\"simulation\")\nBMM.res\n\n# 3B: Identifying rate shifts on phylogeny\n #Bayesian MCMC: single rate shift (Revell et al. 2012: Evol.)\nBM.MCMC<-evol.rate.mcmc(tree=tree,x=svl, quiet=TRUE)\npost.splits<-minSplit(tree,BM.MCMC$mcmc) #summarize\nMCMC.post<-posterior.evolrate(tree=tree,mcmc=BM.MCMC$mcmc,tips = BM.MCMC$tips,ave.shift = post.splits)\n #Plot rescaled to rates\nave.rates(tree,post.splits,extract.clade(tree, node=post.splits$node)$tip.label,\n colMeans(MCMC.post)[\"sig1\"], colMeans(MCMC.post)[\"sig2\"],post.splits)\n\n #Reversible-jump MCMC: multiple rate shifts (Eastman et al. 2011: Evol.)\nBM.RJMC<-rjmcmc.bm(phy = tree,dat = svl)\n#Run again for plotting\nr <- paste(sample(letters,9,replace=TRUE),collapse=\"\")\nrjmcmc.bm(phy=tree, dat=svl, prop.width=1.5, ngen=20000, samp=500, filebase=r, simple.start=TRUE, type=\"rbm\")\noutdir <- paste(\"relaxedBM\", r, sep=\".\")\nps <- load.rjmcmc(outdir)\ndev.new()\nplot(x=ps, par=\"shifts\", burnin=0.25, legend=TRUE, show.tip=FALSE, edge.width=2)\n\n\n\n################### FOR LECTURE:\n#1: what does lambda do?\nTreeLambda0 <- rescale(tree, model = \"lambda\", 0)\nTreeLambda5 <- rescale(tree, model = \"lambda\", 0.5)\n\npar(mfcol = c(1, 3))\nplot(tree, show.tip.label = FALSE)\nplot(TreeLambda5,show.tip.label = FALSE)\nplot(TreeLambda0,show.tip.label = FALSE)\npar(mfcol=c(1,1))\n\n \n", "meta": {"hexsha": "5dfad6b765511f336187b951d5db8bd531a03518", "size": 4435, "ext": "r", "lang": "R", "max_stars_repo_path": "practicals/TutorialData/FitEvolModels.r", "max_stars_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_stars_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practicals/TutorialData/FitEvolModels.r", "max_issues_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_issues_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practicals/TutorialData/FitEvolModels.r", "max_forks_repo_name": "EEOB-Macroevolution/EEOB-565X-Spring2018", "max_forks_repo_head_hexsha": "da192d6744dfaaa68a7f02d6a00ed2642192d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3181818182, "max_line_length": 109, "alphanum_fraction": 0.7098083427, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3087982402547768}} {"text": "########################################################################################################################\n####\n#### R-Script to reproduce the results (Figures and Tables) of the paper\n#### \"Asymmetric latent semantic indexing for gene expression experiments visualization\"\n#### Submitted to Advances in data analysis and classifciation.\n####\n#### Authors: Javier Gonzalez, Alberto Munoz and Gabriel Martos\n####\n#### 15/02/2014\n####\n########################################################################################################################\n# requiered libraries \nlibrary(geneplotter)\nlibrary(RColorBrewer) \nlibrary(genefilter)\nlibrary(MASS)\nlibrary(mclust)\nlibrary(gplots)\nlibrary(mclust)\nlibrary(xtable)\n\n### Load the data\ndata <- read.table(\"nci.data\")\nlabels <- read.table(\"labels.txt\")[,1]\n\n# Expression estimates on the UN-LOGGED scale\ne.mat <- exp(data)\n\n# look at mean, sd, & cv for each gene across arrays\ngene.mean <- apply(e.mat,1,mean) \ngene.sd <- apply(e.mat,1,sd) \ngene.cv <- gene.sd/gene.mean\n\n# Plot of the gene.sd over the gene mean and histogram of those with cv. larger that 7.7\nblues.ramp <- colorRampPalette(brewer.pal(9,\"Blues\")[-1]) \ndCol <- densCols(log(gene.mean),log(gene.sd), colramp=blues.ramp) \n\n###########\n# Figure 3: cut-off for differential expression analysis \n###########\npar(mfrow=c(1,2)) \nplot(gene.mean,gene.sd,log='xy',col=dCol,pch=16,cex=0.1,xlim = c(1,2),ylim = c(0.2,5),xlab=\"Gene mean\", ylab=\"Gene sd.\",main=\"A\",cex.main=2) \nabline(v=100,lwd=3,col='red') \nhist(log(gene.cv),xlab = \"Gene CV (log. scale)\",col=\"grey\",main=\"B\",cex.main=2) \nabline(v=log(.5),lwd=3,col='red')\ntext(0.8,800,\"Theshold: CV>0.5\")\n\n# We select those genes with CV larger.5 (genes differentially expressed in the data)\nffun <- filterfun(cv(0.5,100))\nt.fil <- genefilter(e.mat,ffun)\n\n# Apply filter and transform back on log scale\nsmall.eset <- e.mat[t.fil,]\nsmall.noeset <- e.mat[!t.fil,]\n\n# Threshod to consider that a gene is expressed (the maximum value of the not expressed).\nthres = max(small.noeset)\n\n###########\n# Figure 2: diff-expressed vs. not diff-expressed gene.\n###########\npar(mfrow=c(1,2))\npar(mar=c(5,5,3,3))\nplot(1:64,small.eset[99,],ylim=c(0,15),pch =20,xlab=\"Experiment\",ylab=\"Expression\",main=\"Differentially expressed gene\",cex=2)\nabline(h = thres ,lwd=2, col = \"red\",lty=2)\nplot(1:64,small.noeset[2,],ylim=c(0,15),pch =20,xlab=\"Experiment\",ylab=\"Expression\",main=\"Non differentially expressed gene\",cex=2)\nabline(h = thres ,lwd=2, col = \"red\",lty=2)\n\n# Select those genes expressed at least one time\nffun2 <- filterfun(pOverA(0.025,thres))\nt.fil2 <- genefilter(small.eset,ffun2)\nsmall.eset2 <- small.eset[t.fil2,] \n\n# Create genes by experiments matrix of differentially expressed genes\ncolnames(small.eset2) <- labels\nX <- as.matrix((sign(small.eset2 - thres)+1)/2) # genes by experiments matrix\ncolnames(X) <- labels\nn.genes <- nrow(X)\n\n###########\n# Figure 2: Zipf's law, histogram of the norm of the genes\n###########\npar(mfrow=c(1,1))\nnorm.genes = apply(X,1,sum)\nhist(norm.genes,nclass=25,col = \"grey\",main = \" \",xlab=\"Genes Norm\",ylab=\"Frequency\")\ntext(16,600,paste(n.genes,\" differentially expressed genes\"),cex=1.7)\n\n###########\n# Figure 1 (A and B): Heatmaps pf raw data and differentially expressed genes\n###########\nheatmapA <- heatmap(log(t(small.eset2)), Rowv=NA, Colv=NA,scale=\"column\",margins = c(0.5, 15))\nheatmapB <- heatmap(t(X), Rowv=NA, Colv=NA, scale=\"none\",margins = c(0.5, 15))\n\n# Define the degree of membership of each gene to each type of experiment\nn.groups <- length(table(labels))\nmembership.genes.probs <- matrix(0,n.genes,n.groups )\nmembership.genes <- matrix(0,n.genes,n.groups )\ncolnames(membership.genes.probs) <- levels(labels)\ncolnames(membership.genes) <- levels(labels)\n\nfor (i in 1:n.genes)\n {\n membership.genes.probs[i,] = table(labels[X[i,]==1])/norm.genes[i]\n membership.genes[i,which(membership.genes.probs[i,] == max(membership.genes.probs[i,]))]=1 \n }\n\n### Calculate the (asymmetric) matrix of similarities between genes with respect to the experiments\nS0 \t\t <- X %*% t(X) \nMatrix.norms.inv\t<- diag(1/norm.genes) \nS \t\t <- Matrix.norms.inv %*% S0 \n \n## Calculate the polar decomposition\nsvdS <- svd(S)\nM1 <- svdS$u%*%diag(svdS$d)%*%t(svdS$u) \nM2 <- svdS$v%*%diag(svdS$d)%*%t(svdS$v) \n\n### Calculate the (asymmetric) matrix of similarities between genes with respect to the classes\nZ <- membership.genes%*%t(membership.genes)%*%diag(1/apply(membership.genes,1,sum)) \nsvdZ <- svd(Z)\nR1 <- svdZ$u%*%diag(svdZ$d)%*%t(svdZ$u) \nR2 <- svdZ$v%*%diag(svdZ$d)%*%t(svdZ$v) \n\n## Matrix combination of the two asymmetric similarities\nA <- (M1+M2)/2 + 0.2*(R1+R2) \n\n## Extract components\neigA <- eigen(A)\nXX <- Re(eigA$vectors[,Re(eigA$values)>0.0001])%*%diag(sqrt(Re(eigA$values)[Re(eigA$values)>0.0001]))\n\n# Extract components of the mixture\ncluster.lsa <- Mclust(XX, G =14)\n\n# Cross the clusters with the original classes\ncross = matrix(NA,14,14)\nfor (k in 1:14){cross[k,] = table(membership.genes[,k],cluster.lsa$classification)[2,]}\nrownames(cross) <- levels(labels)\ncolnames(cross) <- c(\"C1\",\"C2\",\"C3\",\"C4\",\"C5\",\"C6\",\"C7\",\"C8\",\"C9\",\"C10\",\"C11\",\"C12\",\"C13\",\"C14\") \n\n###########\n# Table 2: clusters vs. orignal classes\n###########\nxtable(cross)\n\n###########\n# Figure 6: MDS of the groups\n##########\nX.cross = sammon(dist(cross))\nplot(X.cross$points,xlab= \"Component 1\",ylab= \"Component 2\",type=\"n\",col=1:14,xlim=c(-270,270),ylim=c(-270,270),main = \"aLSI mapping of types of Cancer\")\ntext(X.cross$points,rownames(X.cross$points),col=\"blue\",cex=1.1)\n \n\n### Obtain genes with higest probability in each cluster\nmp <- matrix(NA,5,14)\nfor (i in 1:14){mp[,i] = order(cluster.lsa$z[,i],decreasing = TRUE)[1:5]} \ncolnames(mp) <- c(\"C1\",\"C2\",\"C3\",\"C4\",\"C5\",\"C6\",\"C7\",\"C8\",\"C9\",\"C10\",\"C11\",\"C12\",\"C13\",\"C14\") \nrownames(mp) <- c(\"gene 1\",\"gene 2\",\"gene 3\",\"gene 4\",\"gene 5\") \n\n###########\n# Table 1: most probable genes of each cluster\n###########\nxtable(t(mp))\n\n\n## Sammon mapping for the combination\nmds.S12 <- prcomp(XX)$x[,c(1,2)] ## save similarity matrix\nmds.S13 <- prcomp(XX)$x[,c(1,3)] ## save s \ncluster.lsa <- hclust(dist(XX),method=\"ward\")\n \n### MDS-Correlation \nC <- cor(log(t(small.eset2)))\nmds.C12 <- cmdscale(1-C,k=3)[,c(1,2)]\nmds.C13 <- cmdscale(1-C,k=3)[,c(1,3)]\n\n### MDS-Euclidean \nD <- dist(log(small.eset2)) \nmds.D12 <- cmdscale(D,k=3)[,c(1,2)]\nmds.D13 <- cmdscale(D,k=3)[,c(1,3)]\n\n###########\n# Figure 5: genes maps produced by the aLSI, Pearson's correlation and Euclidean distance. \n###########\npar(mfrow = c(3,2))\npar(mar= c(5,5,1.5,1))\nplot(mds.S12,pch=19,cex=0.8,col=\"grey\",type=\"n\",main = \"Asymmetric LSI\",xlab=\"1st component\",ylab=\"2nd component\",xlim=c(-1,1.4))\nfor(k in 1:14)\npoints(mds.S12[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9)\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n \nplot(mds.S13,pch=19,cex=0.8,col=\"grey\",type=\"n\",main = \"Asymmetric LSI\",xlab=\"1st component\",ylab=\"3th component\",xlim=c(-1,1.4))\nfor(k in 1:14)\npoints(mds.S13[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9,xlab=\"1st component\")\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n \nplot(mds.C12,pch=19,cex=0.8,col=\"grey\",main = \"Correlation\",xlab=\"1st component\",ylab=\"2nd component\",xlim=c(-1,1.2)) \nfor(k in 1:14)\npoints(mds.C12[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9)\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n\nplot(mds.C13,pch=19,cex=0.8,col=\"grey\",main = \"Correlation\",xlab=\"1st component\",ylab=\"3th component\",xlim=c(-1,1.2)) \nfor(k in 1:14)\npoints(mds.C13[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9)\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n\nplot(mds.D12,pch=19,cex=0.8,col=\"grey\",main = \"Euclidean distance\",xlab=\"1st component\",ylab=\"2nd component\",xlim=c(-20,20))\nfor(k in 1:14)\npoints(mds.D12[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9)\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n\nplot(mds.D13,pch=19,cex=0.8,col=\"grey\",main = \"Euclidean distance\",xlab=\"1st component\",ylab=\"3th component\",xlim=c(-20,20))\nfor(k in 1:14)\npoints(mds.D13[which(apply(membership.genes,1,sum)==1 & membership.genes[,k]==1), ],col=k,pch=k,cex=0.9)\nlegend(\"topleft\", c(\"G1\",\"G2\",\"G3\",\"G4\",\"G5\",\"G6\",\"G7\"), col=1:7,pch=1:7) \nlegend(\"topright\", c(\"G8\",\"G9\",\"G10\",\"G11\",\"G12\",\"G13\",\"G14\"), col=8:14,pch=8:14) \n \n \n", "meta": {"hexsha": "2fb33f0deb21d2c99361a2cccf29f5859ba5488f", "size": 9575, "ext": "r", "lang": "R", "max_stars_repo_path": "code/Script for aLSI for gene expression visualization.r", "max_stars_repo_name": "javiergonzalezh/aLSI", "max_stars_repo_head_hexsha": "591de7abee0cd7a8ec2d3cf44f4c3c765ddd6d01", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Script for aLSI for gene expression visualization.r", "max_issues_repo_name": "javiergonzalezh/aLSI", "max_issues_repo_head_hexsha": "591de7abee0cd7a8ec2d3cf44f4c3c765ddd6d01", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Script for aLSI for gene expression visualization.r", "max_forks_repo_name": "javiergonzalezh/aLSI", "max_forks_repo_head_hexsha": "591de7abee0cd7a8ec2d3cf44f4c3c765ddd6d01", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.3257918552, "max_line_length": 153, "alphanum_fraction": 0.597075718, "num_tokens": 3326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.30853350645981986}} {"text": "setwd(\"/Users/xxuadmin/BUSINESS/PUBLICATIONS/WorkingOn_Abramoff_Perspective/millennial_code_2017July_Century_WT\")\n\n# output\ndata <- read.table(\"outputcontrol.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutputcontrol <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\n#par(mai = c(1,1,1,1,1))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\n\npdf(file = \"outputcontrol.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"Control run:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output5cwarm.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput5cwarm <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output5cwarm.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"5 C warming:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output10clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput10clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output10clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"10% Clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output20clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput20clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output20clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"20% Clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output30clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput30clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output30clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"30% clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output40clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput40clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output40clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"40% clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output50clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput50clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output50clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"50% clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output60clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput60clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output60clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"60% clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n# output\ndata <- read.table(\"output70clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput70clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output70clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"70% Clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"output80clay.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutput80clay <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"output80clay.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"80% Clay content:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"outputdoubleCinput.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutputdoubleCinput <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"outputdoubleCinput.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"Double C input:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"outputhalfwater.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutputhalfwater <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"outputhalfwater.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"Half water moisture:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"outputTandCinput.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutputTandCinput <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"outputTandCinput.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"5C Warming and Double C input:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n# output\ndata <- read.table(\"outputTandW.txt\")\nLMC <- data$V2[729636:730000]\nPOM <- data$V3[729636:730000]\nMB <- data$V4[729636:730000]\nMINERAL <- data$V5[729636:730000]\nAGG <- data$V6[729636:730000]\noutputTandW <- data$V2 + data$V3 + data$V4 + data$V5 + data$V6\n\nsummary(LMC)\nsummary(POM)\nsummary(MB)\nsummary(MINERAL)\nsummary(AGG)\nlmcaverage = mean(LMC)\npomaverage = mean(POM)\nmbaverage = mean(MB)\nmineralaverage = mean(MINERAL)\naggaverage = mean(AGG)\n\ncarbon <- c(lmcaverage, pomaverage, mbaverage, mineralaverage, aggaverage)\n#lbls <- c(\"LMWC\", \"POM\", \"MB\", \"MINERAL\", \"AGGREGATE\")\n#pct <- round(carbon/sum(carbon)*100)\n#lbls <- paste(lbls,pct) # add percents to labels\n#lbls <- paste(lbls, \"%\", sep=\"\")\n#pie(carbon, labels=lbls, col=rainbow(length(lbls)),main=round(sum(carbon)))\ncolors <- c(\"black\",\"red\",\"green\",\"blue\",\"pink\")\nnumb_labels <- round(carbon/sum(carbon) * 100,1)\nnumb_labels <- paste(numb_labels, \"%\", sep=\"\")\nxx <- c(\"LMWC\",\"POM\",\"MB\",\"MINERAL\",\"AGGREGATE\")\nxx <- paste(round(carbon/sum(carbon) * 100,1),xx,sep=\" \")\n\npdf(file = \"outputTandW.pdf\")\npie(carbon, labels=\"\", col=colors,clockwise=TRUE,main=paste(\"5C Warming and Half Water:\", round(sum(carbon)),\"gC\",sep=\" \"))\nlegend(-1.25,-0.5, legend = xx, fill=colors,bty=\"n\")\ndev.off()\n\nrm(data)\nrm(LMC)\nrm(POM)\nrm(MB)\nrm(MINERAL)\nrm(AGG)\n# end\n\n\n#plot time series of total carbon for all scenarios\n#outputcontrol\n#output5cwarm\n#output10clay\n#output20clay\n#output30clay\n#output40clay\n#output50clay\n#output60clay\n#output70clay\n#output80clay\n#outputdoubleCinput\n#outputhalfwater\n#outputTandCinput\n#outputTandW\npdf(file = \"timeseries.pdf\")\nday=c(1:136500)\nplot(c(1,175000),c(-2000,2000),type=\"n\",xlab=\"Day\",ylab=\"changed in total C storage\")\nlines(day,output5cwarm[1:136500] - outputcontrol[1:136500],col=\"blue\")\nlines(day,output10clay[1:136500] - outputcontrol[1:136500],col=\"brown\")\nlines(day,output20clay[1:136500] - outputcontrol[1:136500],col=\"yellow\")\nlines(day,output30clay[1:136500] - outputcontrol[1:136500],col=\"cyan\")\nlines(day,output40clay[1:136500] - outputcontrol[1:136500],col=\"darkblue\")\nlines(day,output50clay[1:136500] - outputcontrol[1:136500],col=\"darkgreen\")\nlines(day,output60clay[1:136500] - outputcontrol[1:136500],col=\"darkgray\")\nlines(day,output70clay[1:136500] - outputcontrol[1:136500],col=\"darkorange\")\nlines(day,output80clay[1:136500] - outputcontrol[1:136500],col=\"darkred\")\nlines(day,outputdoubleCinput[1:136500] - outputcontrol[1:136500],col=\"deeppink\")\nlines(day,outputhalfwater[1:136500] - outputcontrol[1:136500],col=\"deepskyblue\")\nlines(day,outputTandCinput[1:136500] - outputcontrol[1:136500],col=\"darkgreen\")\nlines(day,outputTandW[1:136500] - outputcontrol[1:136500],col=\"lightgreen\")\nlegend(137500,1000,c(\"warming\",\"10% clay\",\"20% clay\",\"30% clay\",\"40% clay\",\"50% clay\",\"60% clay\",\"70% clay\",\"80% clay\",\"double C input\",\"half water\",\"warming and double C input\",\"warming and half water\"),lty=c(1,1),lwd=c(2.5,2.5),col=c(\"blue\",\"brown\",\"yellow\",\"cyan\",\"darkblue\",\"darkgreen\",\"darkgray\",\"darkorange\",\"darkred\",\"deeppink\",\"deepskyblue\",\"darkgreen\",\"lightgreen\"))\ndev.off()\n\n", "meta": {"hexsha": "9d7a1bfe764f814bd9303634e2cea6962ef89954", "size": 20266, "ext": "r", "lang": "R", "max_stars_repo_path": "Fortran/MillennialV1/simulation/plot.r", "max_stars_repo_name": "rabramoff/Millennial", "max_stars_repo_head_hexsha": "ea1f8fb4b5b2f513517bf287feb6803c8c7482e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:11:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T12:42:35.000Z", "max_issues_repo_path": "Fortran/MillennialV1/simulation/plot.r", "max_issues_repo_name": "rabramoff/Millennial", "max_issues_repo_head_hexsha": "ea1f8fb4b5b2f513517bf287feb6803c8c7482e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fortran/MillennialV1/simulation/plot.r", "max_forks_repo_name": "rabramoff/Millennial", "max_forks_repo_head_hexsha": "ea1f8fb4b5b2f513517bf287feb6803c8c7482e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-25T15:37:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T12:46:58.000Z", "avg_line_length": 30.2929745889, "max_line_length": 375, "alphanum_fraction": 0.6853843876, "num_tokens": 7294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3062538502961012}} {"text": "# Methods for in silico tryptic digestion, formula calculation, monoisotopic mass\r\n# calculation and b and y fragment ion simulation in R.\r\n#\r\n# Written by Tom Taverner for Pacific Northwest National Lab.\r\n# 10-26-2010\r\n\r\n# Methods for in silico digestion, \r\n\r\n# Required packages\r\ninstall.packages(\"seqinr\")\r\nlibrary(seqinr)\r\nlibrary(reshape)\r\n\r\n # lookup table for amino acid formulae\r\nmy.aa <- array(c(6, 6, 6, 5, 9, 4, 11, 5, 6, 6, 3, 4, 4, 3, 5, 5, 2, 5, 3, 9, 11, 11, 12, 9, 9, 7, 10, 9, 12, 7, 5, 6, 5, 5, 7, 8, 3, 7, 5, 9, 1, 1, 2, 1, 1, 1, 2, 1, 4, 3, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 3, 1, 3, 2, 1, 1, 2, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0), c(20L, 5L))\r\ndimnames(my.aa) <- list(c(\"I\", \"L\", \"K\", \"M\", \"F\", \"T\", \"W\", \"V\", \"R\", \"H\", \"A\", \"N\", \"D\", \"C\", \"E\", \"Q\", \"G\", \"P\", \"S\", \"Y\"), c(\"C\", \"H\", \"N\", \"O\", \"S\"))\r\n\r\n # lookup table for monoisotopic masses\r\nmy.fw = c(C = 12.0, H = 1.00782503207, N = 14.0030740048, O = 15.99491461956, S = 31.97207100)\r\n\r\n\r\n # get.formula: given a string of 1-letter amino acid codes, returns the formula of the peptide\r\n # arguments: x, peptide sequence, \r\n # plusFormula - default corresponds to H2O for peptides\r\n # b ions: plusFormula = c(C=0,H=0,N=0,O=0,S=0)\r\n # y ions: default is OK\r\n # charge, charge to place on sequence\r\nget.formula <- function(x, charge=1, plusFormula=c(C=0, H=2, N=0, O=1, S=0)){\r\n f1 <- factor(strsplit(x, \"\")[[1]], levels=rownames(my.aa))\r\n colSums(rbind(model.matrix(~f1-1) %*% my.aa, plusFormula, c(C=0, H=charge, N=0, O=0, S=0)))\r\n}\r\n\r\n # get.monoisotopic.mass: given a formula output from get.formula, get the monoisotopic mass\r\nget.monoisotopic.mass <- function(ff){\r\n stopifnot(identical(names(ff), names(my.fw)))\r\n drop(ff %*% my.fw)\r\n}\r\n\r\n\r\n # apply.protease: virtual protease digestion function\r\n # arguments:\r\n # prots: list containing protein sequences\r\n # missed: number of missed cleavages\r\n # include.re and exclude.re: regular expressions corresponding to protease cleavage rules\r\n # the cleavage sites are the include.re matches that aren't in exclude.re\r\n # note: only supports cleavage on C-terminal side\r\n # output: the same list of prots, with $peptide containing \r\n # (1) list of peptides \r\n # (2) position of cleavage \r\n # (3) number of missed cleavages\r\napply.protease <- function(prots, missed=1, include.re = \"[KR]\", exclude.re = \"([KR]$)|([KR][P])\"){\r\n for(jj in seq(length=length(prots))){\r\n prot <- prots[[jj]][[1]]\r\n pos <- setdiff(gregexpr(include.re, prot)[[1]], gregexpr(exclude.re, prot)[[1]])\r\n\r\n pos <- c(0, c(pos), nchar(prot))\r\n n <- length(pos)+1\r\n nmis <- missed+1\r\n pid <- cbind(rep(1:n, each=nmis), rep(1:nmis, n))\r\n zz <- cbind(pos[pid[,1]], pos[pid[,1]+pid[,2]])\r\n ok.idx <- !rowSums(is.na(zz))\r\n zz <- zz[ok.idx,,drop=F]\r\n # this is where we'd extend the method with PTM's, etc\r\n suppressWarnings(prots[[jj]]$peps <- substr(rep(prot[[1]], nrow(zz)), zz[,1]+1, zz[,2]))\r\n\r\n attr(prots[[jj]]$peps, \"start\") <- pos[pid[ok.idx,1]]\r\n attr(prots[[jj]]$peps, \"missed\") <- pid[ok.idx,2]-1\r\n } \r\n return(prots)\r\n}\r\n\r\n\r\n # For a given protein from the apply.protease() output\r\n # create a Protein Prospector style data frame \r\n # Input: a single list item from apply.protease() output\r\n # Output: a data frame containing sequence, start, missed cleavages, charge, monoisotopic m/z\r\ncreate.peptides.table <- function(digested.peps, minMZ=800, maxMZ=4000, maxCharge=1){\r\n thePeps <- digested.peps$peps\r\n theFormulas <- sapply(thePeps, get.formula)\r\n theCharge <- rep(1:maxCharge, each=length(thePeps))\r\n\r\n mono.mz <- c()\r\n for(z in 1:maxCharge)\r\n mono.mz <- c(mono.mz, c(t(theFormulas)%*%my.fw + (z-1)*my.fw[[\"H\"]])/z)\r\n\r\n peps.and.masses <- data.frame(MassToCharge = mono.mz, \r\n Start = attr(thePeps, \"start\"), MissedCleavages = attr(thePeps, \"missed\"), \r\n Charge = theCharge, Sequence=thePeps)\r\n\r\n # ensure we have reasonable numbers of charges - don't allow more charge than K + R + 1\r\n maxAllowedCharge <- sapply(gregexpr(\"[KR]\", thePeps), length)+1\r\n peps.and.masses <- peps.and.masses[peps.and.masses$Charge <= maxAllowedCharge,,drop=FALSE]\r\n\r\n peps.and.masses <- peps.and.masses[minMZ< peps.and.masses$MassToCharge \r\n & peps.and.masses$MassToCharge < maxMZ,,drop=FALSE]\r\n peps.and.masses <- peps.and.masses[order(peps.and.masses$MassToCharge),,drop=FALSE]\r\n\r\n\r\n return(peps.and.masses)\r\n}\r\n\r\n # create b and y ions for a given peptide sequence\r\n # input: peptide sequence\r\n # output: list containing b.ions and y.ions\r\n # both are named vectors containing monoisotopic singly charged masses of ions\r\ncreate.ions <- function(peptide){\r\n ncp <- nchar(peptide)\r\n b.sequences <- c(mapply(substr, rep(peptide, ncp), 1, 1:ncp))\r\n names(b.sequences) <- paste(\"b\", 1:length(b.sequences), sep=\"\")\r\n\r\n b.ions <- sapply(b.sequences, \r\n function(x) get.monoisotopic.mass(get.formula(x, plusFormula = c(C=0,H=0,N=0,O=0,S=0))))\r\n b.ions[1] <- NA # there's no such thing as a b1 ion ;-)\r\n b.ions[length(b.ions)] <- NA\r\n\r\n\r\n y.sequences <- c(mapply(substr, rep(peptide, ncp), ncp:1, ncp))\r\n names(y.sequences) <- paste(\"y\", 1:length(y.sequences), sep=\"\")\r\n\r\n y.ions <- sapply(y.sequences, \r\n function(x) get.monoisotopic.mass(get.formula(x, plusFormula = c(C=0,H=2,N=0,O=1,S=0))))\r\n y.ions[length(y.ions)] <- NA\r\n\r\n return(list(b.ions=b.ions, y.ions=y.ions))\r\n}\r\n\r\n\r\n\r\n#\r\n# Demonstration code\r\n#\r\n\r\nlibrary(seqinr)\r\n # read in the Shew fasta file here\r\nmy.fasta <- read.fasta(file.choose(), as.string=TRUE, forceDNAtolower=FALSE)\r\n\r\n # take the first 5\r\nprots <- my.fasta[1:5]\r\n\r\n # apply simulated tryptic digestion to get a list of all peptides given 1 missed\r\ndigested <- apply.protease(prots, missed=1)\r\n \r\n # create tables including monoisotopic masses, etc\r\npeptide.tables <- lapply(digested, create.peptides.table, minMZ=800, maxMZ=4000, maxCharge=3)\r\n\r\nlibrary(RGtk2Extras)\r\ndfedit(peptide.tables$SO_0001)\r\n# compare to prospector\r\nhttp://prospector.ucsf.edu/prospector/cgi-bin/msform.cgi?form=msdigest\r\n\r\n# enter in MTKIAILVGTTLGSSEYIADEMQAQLTPLGHEVHTFLHPTLDELKPYPLWILVSSTHGAGDLPDNLQPFCKELLL\r\nNTPDLTQVKFALCAIGDSSYDTFCQGPEKLIEALEYSGAKAVVDKIQIDVQQDPVPEDPALAWLAQWQDQI\r\n# notice we predict some peptides their algorithm doesn't...\r\n\r\n # bring peptides from first 5 proteins together\r\nlibrary(reshape)\r\nmm <- melt(peptide.tables, measure.vars=\"MassToCharge\")\r\nall.peptides <- cast(mm)\r\ncolnames(all.peptides)[colnames(all.peptides)==\"L1\"] <- \"Protein\"\r\nall.peptides <- all.peptides[order(all.peptides$MassToCharge),,drop=FALSE]\r\n\r\n # take a look\r\ndfedit(all.peptides)\r\n\r\n# generate some b and y ions\r\nmy.fragments <- create.ions(\"LIEALEYSGAKAVVDK\")\r\ndata.frame(b.type=names(my.fragments$b.ions), b.mass=my.fragments$b.ions, y.type=rev(names(my.fragments$y.ions)), y.mass=rev(my.fragments$y.ions))\r\n\r\n# compare to prospector\r\nhttp://prospector.ucsf.edu/prospector/cgi-bin/mssearch.cgi?search_name=msproduct&output_type=HTML&report_title=MS-Product&version=5.6.2&instrument_name=ESI-Q-TOF&use_instrument_ion_types=1&parent_mass_convert=monoisotopic&user_aa_composition=C2%20H3%20N1%20O1&max_charge=2&s=1&sequence=LIEALEYSGAKAVVDK&\r\n\r\n", "meta": {"hexsha": "aefab091ec03f6c3c44cafcdb271f169dde2047f", "size": 7186, "ext": "r", "lang": "R", "max_stars_repo_path": "Documentation/PeptideManipulation.r", "max_stars_repo_name": "PNNL-Comp-Mass-Spec/Protein-Digestion-Simulator", "max_stars_repo_head_hexsha": "4ec8053a4521a1ad0acccbfbd31a5a2cd9231c2a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-05-11T02:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-30T10:29:59.000Z", "max_issues_repo_path": "Documentation/PeptideManipulation.r", "max_issues_repo_name": "PNNL-Comp-Mass-Spec/Protein-Digestion-Simulator", "max_issues_repo_head_hexsha": "4ec8053a4521a1ad0acccbfbd31a5a2cd9231c2a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-12-16T14:25:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T15:46:00.000Z", "max_forks_repo_path": "Documentation/PeptideManipulation.r", "max_forks_repo_name": "PNNL-Comp-Mass-Spec/Protein-Digestion-Simulator", "max_forks_repo_head_hexsha": "4ec8053a4521a1ad0acccbfbd31a5a2cd9231c2a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2017-10-12T15:12:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-30T10:30:00.000Z", "avg_line_length": 41.7790697674, "max_line_length": 336, "alphanum_fraction": 0.6661564153, "num_tokens": 2520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752916, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.30572603232082296}} {"text": "#This contains all of the functions used in the model\n\n#Hardcode the corps names by class as generally accessible variables\nWorldClass = c(\"The Academy\",\"Blue Devils\",\"Blue Knights\",\"Blue Stars\",\"Bluecoats\",\"Boston Crusaders\",\"The Cadets\",\"Carolina Crown\",\n\t\"The Cavaliers\",\"Colts\",\"Crossmen\",\"Genesis\",\"Jersey Surf\",\"Madison Scouts\",\"Mandarins\",\"Music City\",\"Oregon Crusaders\",\n\t\"Pacific Crest\",\"Phantom Regiment\",\"Pioneer\",\"Santa Clara Vanguard\",\"Seattle Cascades\",\"Spirit of Atlanta\",\"Troopers\"\n)\nOpenClass = c(\"7th Regiment\",\"The Battalion\",\"Blue Devils B\",\"Blue Devils C\",\"Colt Cadets\",\"Columbians\",\"Encorps\",\"Gold\",\"Golden Empire\",\n\t\"Guardians\",\"Heat Wave\",\"Impulse\",\"Incognito\",\"Legends\",\"Louisiana Stars\",\"Raiders\",\"River City Rhythm\",\"Shadow\",\n\t\"Southwind\",\"Spartans\",\"Vanguard Cadets\",\"Vessel\",\"Watchmen\"\n)\nOC_NotAttending = c(\"The Battalion\",\"Blue Devils B\",\"Blue Devils C\",\"Columbians\",\"Encorps\",\"Impulse\",\"Incognito\",\n\t\"Vanguard Cadets\",\"Vessel\",\"Watchmen\"\n)\n\n\nScoreParse <- function(filename, WorldNames=WorldClass, OpenNames=OpenClass) {\n\t#Start by loading the file\n\tBigTable = read.csv(filename, stringsAsFactors=F)\n\t\t\n\t#This function creates a data frame for a given corps\n\tFrameCreate <- function(CorpsName, Table) {\n\t\t#Start by finding all the rows which have data\n\t\tCorpsRows = which(Table$Corps == CorpsName)\n\t\tif (length(CorpsRows) == 0) {\n\t\t\treturn(NULL)\n\t\t}\n\t\t\n\t\t#Get vectors for the scores and Day\n\t\tGEvec = Table[CorpsRows,\"GE\"]\n\t\tVisVec = Table[CorpsRows,\"Visual\"]\n\t\tMusVec = Table[CorpsRows,\"Music\"]\n\t\tDayVec = Table[CorpsRows,\"Day\"]\n\t\t\n\t\t#Now make the data frame\n\t\tOutFrame = data.frame(Day=DayVec, GE=GEvec, Vis=VisVec, Mus=MusVec)\n\t\treturn(OutFrame)\n\t}\n\t\n\t#Now run the function on all the world class and open class corps\n\tWorldFrames = lapply(WorldNames, FrameCreate, Table=BigTable)\n\tOpenFrames = lapply(OpenNames, FrameCreate, Table=BigTable)\n\t#Combine them into a single frame\n\tAllFrames = c(WorldFrames, OpenFrames)\n\t\n\t#Add the corps names to the frames\n\tnames(AllFrames) = c(WorldNames, OpenNames)\n\treturn(AllFrames)\n}\n\n#Create a function that fits the exponential curve to a data frame\nExpFitter <- function(CorpsFrame, BaseDay, PrelimsDay=50) {\n\t#50 is the prelims day for 2019, which is why it's defaulted here\n\t\n\t#Start by checking the number of shows\n\tif (is.null(CorpsFrame)) { return(NULL) }\n\tif (nrow(CorpsFrame) < 6) { return(NULL) }\n\t\n\t#Order the frame by day\n\tCorpsFrame = CorpsFrame[order(CorpsFrame$Day),]\n\t\n\t#The weight vector reduces weights of recent scores, based on their correlation with finals week scores\n\t#The weight vector reduces weights of recent scores, based on their correlation with finals week scores\n\tDayVec = seq(from=0, to=PrelimsDay+2, by=1)\n\tWeightVec = 1 - (PrelimsDay-DayVec)*0.00224\n\tDiscountOrig = 0.25 + (0.75-0.25)/PrelimsDay * BaseDay\n\tDiscountVec = seq(from=1, to=DiscountOrig, length.out=6)\n\t\n\t#Create a vector for the corps-specific day weights\n\tShowWeights = WeightVec[CorpsFrame$Day]\n\t#Now discount the most recent 5\n\tNshow = length(ShowWeights)\n\tShowWeights[(Nshow-5):Nshow] = ShowWeights[(Nshow-5):Nshow] * DiscountVec\n\t\n\t#Pull out the individual vectors to match nls input better\n\tN = sum(CorpsFrame$Day <= BaseDay)\n\tGE = CorpsFrame$GE[CorpsFrame$Day <= BaseDay]\n\tVis = CorpsFrame$Vis[CorpsFrame$Day <= BaseDay]\n\tMus = CorpsFrame$Mus[CorpsFrame$Day <= BaseDay]\n\tDay = CorpsFrame$Day[CorpsFrame$Day <= BaseDay]\n\t\n\t#Now fit the curve for each caption, wrapped in a try to avoid catastrophic errors\n\t#This tryCatch won't make the objects if we're not successful\n\ttryCatch({ \n\t\tGEModel = nls(GE ~ a + Day^b, data=data.frame(GE, Day), start=list(a=GE[1], b=0.5), \n\t\t\tcontrol=nls.control(warnOnly=TRUE), weights=ShowWeights)\n\t\tVisModel = nls(Vis ~ a + Day^b, data=data.frame(Vis, Day), start=list(a=Vis[1], b=0.5), \n\t\t\tcontrol=nls.control(warnOnly=TRUE), weights=ShowWeights)\n\t\tMusModel = nls(Mus ~ a + Day^b, data=data.frame(Mus, Day), start=list(a=Mus[1], b=0.5), \n\t\t\tcontrol=nls.control(warnOnly=TRUE), weights=ShowWeights)\n\t}, warning = function(w) { #This makes it so scenarios of non-convergence don't return bad coefficients\n\t\t#print(\"Can't run corps due to non-convergence\")\n\t}, error = function(e) {\n\t\t#print(\"Can't run corps due to an error in curve fitting\")\n\t}) \n\t\n\t#Check to see how many of the 3 models exist\n\tExistVec = c(exists('GEModel'), exists('VisModel'), exists('MusModel'))\n\t\n\t#Create a copy of CorpsFrame we can modify\n\tCorpsFrame2 = CorpsFrame\n\tTrimmedResult = NA #This tracks if we're successful in the if loop\n\t\n\tif (sum(ExistVec) < 3) { #This means we didn't get a good fit in at least 1 caption\n\t\t#print(\"Nonconvergence!\")\n\t\t#Try removing the most recent scores until we get convergence or too small a sample\n\t\tCorpsFrame2 = CorpsFrame2[1:(nrow(CorpsFrame2)-1) ,]\n\t\t\n\t\tif (nrow(CorpsFrame) < 6) { #Check for sample size\n\t\t\tbreak\n\t\t} else {\n\t\t\t#Recursion!\n\t\t\tTrimmedResult = ExpFitter(CorpsFrame2, BaseDay)\n\t\t\t#No matter what, we can return TrimmedResult because this is the top level of the recursion\n\t\t\treturn(TrimmedResult)\n\t\t}\n\t}\n\t\n\t#Pull out the summary of the models\n\tGEcoef = summary(GEModel)$coefficients\n\tVcoef = summary(VisModel)$coefficients\n\tMcoef = summary(MusModel)$coefficients\n\t\n\t#Now pull out the coefficients\n\taVec = c(GEcoef[1,1], Vcoef[1,1], Mcoef[1,1])\n\tbVec = c(GEcoef[2,1], Vcoef[2,1], Mcoef[2,1])\n\t\n\t#And now pull out the standard errors\n\taseVec = c(GEcoef[1,2], Vcoef[1,2], Mcoef[1,2])\n\tbseVec = c(GEcoef[2,2], Vcoef[2,2], Mcoef[2,2])\n\t\n\t#Put the coefficients and standard errors into a data frame\n\tOutFrame = data.frame(a=aVec, b=bVec, aSE=aseVec, bSE=bseVec, N=rep(N,3))\n\trow.names(OutFrame) = c('GE','Vis','Mus')\n\t#return the data frame\n\treturn(OutFrame)\n}\n\n#Now make a function that predicts a day for all corps\nPredictor <- function(CorpsList, PredictDay, Nmonte, RankDay) {\n\t#Start by making a function that predicts N scores based on the exponential uncertainty\n\tExpPredict <- function(CorpsCoefList, PredictDay, Nmonte) {\n\t\t#Start by gathering basic information\n\t\tNcorps = length(CorpsCoefList)\n\t\t\n\t\t#This function returns a list of N predictions\n\t\tScoreList = vector(mode='list', length=Ncorps)\n\t\t\n\t\t#Loop through each corps and make the random vectors\n\t\tfor (C in 1:Ncorps) {\n\t\t\tCorpsCoefs = CorpsCoefList[[C]]\n\t\t\t#Recall the exponential is of the form Score = a + Day^b\n\t\t\t\n\t\t\t#Make a vector of random a's for each caption\n\t\t\tGEa = rnorm(Nmonte, mean=CorpsCoefs[\"GE\",\"a\"], sd=CorpsCoefs[\"GE\",\"aSE\"])\n\t\t\tVa = rnorm(Nmonte, mean=CorpsCoefs[\"Vis\",\"a\"], sd=CorpsCoefs[\"Vis\",\"aSE\"]) \n\t\t\tMa = rnorm(Nmonte, mean=CorpsCoefs[\"Mus\",\"a\"], sd=CorpsCoefs[\"Mus\",\"aSE\"]) \n\t\t\t#Make a vector of b's for each caption\n\t\t\tGEb = rnorm(Nmonte, mean=CorpsCoefs[\"GE\",\"b\"], sd=CorpsCoefs[\"GE\",\"bSE\"]) \n\t\t\tVb = rnorm(Nmonte, mean=CorpsCoefs[\"Vis\",\"b\"], sd=CorpsCoefs[\"Vis\",\"bSE\"])\n\t\t\tMb = rnorm(Nmonte, mean=CorpsCoefs[\"Mus\",\"b\"], sd=CorpsCoefs[\"Mus\",\"bSE\"])\n\t\t\t\n\t\t\t#Now create the score for each caption\n\t\t\tGEscore = GEa + PredictDay ^ GEb\n\t\t\tVscore = Va + PredictDay ^ Vb\n\t\t\tMscore = Ma + PredictDay ^ Mb\n\t\t\t\n\t\t\t#Now correct each score to make sure they're actually possible\n\t\t\tGEscore[GEscore > 40] = 40\n\t\t\tVscore[Vscore > 30] = 30\n\t\t\tMscore[Mscore > 30] = 30\n\t\t\t\n\t\t\t#Now get the total score list\n\t\t\tScoreList[[C]] = GEscore + Vscore + Mscore\n\t\t}\n\t\t\n\t\t#Convert each simulation score to gaps\n\t\tBaseScores = vector(mode='double', length=Nmonte)\n\t\tfor (i in 1:Nmonte) {\n\t\t\tBaseScores[i] = max(sapply(ScoreList, '[[', i))\n\t\t}\n\t\t#Now loop through each corps and subtract the base score\n\t\tfor (C in 1:length(ScoreList)) {\n\t\t\tScoreList[[C]] = ScoreList[[C]] - BaseScores\n\t\t}\t\t\n\t\treturn(ScoreList)\n\t}\n\t\n\t#Now create a function that predicts N scores based on the random error\n\tRandPredict <- function(CorpsCoefList, PredictDay, Nmonte, RankDay) {\n\t\tlibrary(MASS)\n\t\t\n\t\t#Get the basic information\n\t\tNcorps = length(CorpsCoefList)\n\t\t#The output will be the score list\n\t\tScoreList = vector(mode='list', length=Ncorps)\n\t\t\n\t\t#Make a correlation matrix for the errors\n\t\tCorrMat = matrix(nrow=Ncorps, ncol=Ncorps)\n\t\tfor (Row in 1:Ncorps) {\n\t\t\tfor (Col in 1:Ncorps) {\n\t\t\t\tIndexDiff = abs(Row - Col)\n\t\t\t\t#Use IndexDiff to determine the correlation\n\t\t\t\tif (IndexDiff == 0) { \n\t\t\t\t\t#This is a diag\n\t\t\t\t\tCorrMat[Row,Col] = 1\n\t\t\t\t} else if (IndexDiff > 14) { \n\t\t\t\t\t#This is a background correlation\n\t\t\t\t\tCorrMat[Row,Col] = 0.263\n\t\t\t\t} else { \n\t\t\t\t\t#This is an off-diag\n\t\t\t\t\tCorrMat[Row,Col] = 0.513 - (IndexDiff-1)*(0.25/14)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t#To account for the effect of doing caption specific correlations, we increase the correlation\n\t\tCorrMat = CorrMat * 1.25\n\t\tdiag(CorrMat) = 1\n\t\t\n\t\t#Now multiply the correlation matrix by the variances for each captions \n\t\t#the historical noise magnitude is 4, so the captions are adjusted to add to that:\n\t\t\t# 40^2 * GEvar + 30^2 * Mvar + 30^2 Vvar = 4\n\t\t\t# 1600GEvar + 900Mvar + 900Vvar = 4\n\t\t\t# Mvar = Vvar = Cvar - assuming the music and visual errors are the same\n\t\t\t# 1600GEvar + 1800Cvar = 4\n\t\t\t# GEvar = 4/3 * Cvar - assuming error is scaled by total caption score\n\t\t\t# (4/3)1600Cvar + 1800Cvar = 4\n\t\t\t# with some rounding...\n\t\t\t# 3900Cvar = 4\n\t\t\t# Cvar = 4 / 3900\n\t\t# We now need to apply the variance to each individual caption \n\t\t# At some point the error needs to be scaled by total points, so we'll do it here\n\t\tGEcov = CorrMat * 40 * sqrt(4/3900)\n\t\tCapCov = CorrMat * 30 * sqrt(4/3900)\n\t\t\n\t\t#Draw the random numbers using the covariance matrices, \n\t\tGErand = mvrnorm(Nmonte, mu=rep(0,Ncorps), Sigma=GEcov, empirical=F)\n\t\tMrand = mvrnorm(Nmonte, mu=rep(0,Ncorps), Sigma=CapCov, empirical=F)\n\t\tVrand = mvrnorm(Nmonte, mu=rep(0,Ncorps), Sigma=CapCov, empirical=F)\n\t\t\n\t\t#We choose the column of random numbers for each corps based on their rank\n\t\t# In 2018, we ranked by caption but now we use total score as it better indicates performance order\n\t\tRankScores = vector(mode='double', length=Ncorps)\n\t\t\n\t\t#We still need the caption scores to do the predictions\n\t\tGEscores = vector(mode='double', length=Ncorps)\n\t\tVscores = vector(mode='double', length=Ncorps)\n\t\tMscores = vector(mode='double', length=Ncorps)\n\t\t\n\t\t#Fill in the vectors\n\t\tfor (C in 1:Ncorps) {\n\t\t\tGEscores[C] = CorpsCoefList[[C]][\"GE\",\"a\"] + RankDay ^ CorpsCoefList[[C]][\"GE\",\"b\"]\n\t\t\tVscores[C] = CorpsCoefList[[C]][\"Vis\",\"a\"] + RankDay ^ CorpsCoefList[[C]][\"Vis\",\"b\"]\n\t\t\tMscores[C] = CorpsCoefList[[C]][\"Mus\",\"a\"] + RankDay ^ CorpsCoefList[[C]][\"Mus\",\"b\"]\n\t\t\tRankScores = GEscores + Vscores + Mscores\n\t\t}\n\t\t\n\t\t#Convert these to gaps\n\t\tGEscores = GEscores - max(GEscores) \n\t\tVscores = Vscores - max(Vscores)\n\t\tMscores = Mscores - max(Mscores)\n\t\tRankScores = RankScores - max(RankScores)\n\t\t\n\t\t#Adjust the scores down of OC if we're late in the season\n\t\t# OC coprs need to be discounted because the scores get inflated late in the season\n\t\tif (RankDay >= 40 & PredictDay > 48) {\n\t\t\tneedOCadjust = names(CorpsCoefList) %in% OpenClass\n\t\t\tGEscores[needOCadjust] = GEscores[needOCadjust] - (2 * 0.4)\n\t\t\tVscores[needOCadjust] = Vscores[needOCadjust] - (2 * 0.3)\n\t\t\tMscores[needOCadjust] = Mscores[needOCadjust] - (2 * 0.3)\n\t\t\tRankScores[needOCadjust] = RankScores[needOCadjust] - 2\n\t\t}\n\t\t\n\t\t#Get the rank vector\n\t\tCorpsRanks = match(RankScores, sort(RankScores, decreasing=T)) #Ranks from highest to lowest\n\t\t\n\t\t#Now loop through each corps and fill in ScoreList\n\t\tfor (C in 1:Ncorps) {\n\t\t\t# In 2018 we had a damping effect to account for slotting, but that effect is now captured\n\t\t\t# \tby other parts in the model.\n\t\t\tGEvec = GEscores[C] + GErand[,CorpsRanks[C]]\n\t\t\tMvec = Mscores[C] + Mrand[,CorpsRanks[C]]\n\t\t\tVvec = Vscores[C] + Vrand[,CorpsRanks[C]]\n\t\t\t\n\t\t\t#Put the summed scores into the list\n\t\t\tScoreList[[C]] = GEvec + Mvec + Vvec\n\t\t}\n\t\t\n\t\treturn(ScoreList)\n\t}\n\t\n\t#Get the number of corps\n\tNcorps = length(CorpsList)\n\t\n\t#Run both score predictors\n\tExpScoreList = ExpPredict(CorpsList, PredictDay, Nmonte)\n\tRandScoreList = RandPredict(CorpsList, PredictDay, Nmonte, RankDay)\n\t#print(RandScoreList)\n\t\n\t#Now create the overall score and rank lists to return\n\tScoreList = vector(mode='list', length=Ncorps)\n\tRankList = vector(mode='list', length=Ncorps)\n\t\n\t#Fill in the final ScoreList\n\tfor (C in 1:Ncorps) {\n\t\tScoreList[[C]] = 0.317*ExpScoreList[[C]] + 0.683*RandScoreList[[C]]\n\t}\n\t# vars = sapply(ScoreList, var); print(mean(vars)); print(vars) #debugging\n\t\n\t#Fill in RankList by sorting the scores\n\tfor (n in 1:Nmonte) {\n\t\t#Get the scores and rank them\n\t\tscores = sapply(ScoreList, '[[', n)\n\t\tranks = match(scores, sort(scores, decreasing=T))\n\t\t#Now put the ranks into the list\n\t\tfor (C in 1:Ncorps) {\n\t\t\tRankList[[C]][n] = ranks[C]\n\t\t}\n\t}\n\t\n\t#Retain the names in the lists\n\tnames(ScoreList) = names(CorpsList)\n\tnames(RankList) = names(CorpsList)\n\t\n\t#return the lists\n\treturn(list(ScoreList, RankList))\n}\n\n#this function returns a vector of information for each corps \n\t#mean score,percent odds of being in 1st, second, thrid, top12, and top25\nPredictionReduce_WorldClass <- function(PredictionList) {\n\tScoreList = PredictionList[[1]]\n\tRankList = PredictionList[[2]]\n\t\n\t#Get the simple information\n\tNcorps = length(PredictionList[[1]])\n\tNmonte = length(PredictionList[[1]][[1]])\n\tCorpsNames = names(PredictionList[[1]])\n\t\n\t#create a vector for each returned value\n\tMeanScores = vector(mode='double', length=Ncorps)\n\tPercGold = vector(mode='double', length=Ncorps)\n\tPercSilver = vector(mode='double', length=Ncorps)\n\tPercBronze = vector(mode='double', length=Ncorps)\n\tPercFinals = vector(mode='double', length=Ncorps)\n\tPercSemis = vector(mode='double', length=Ncorps)\n\t\n\t#Loop through each corps and fill the vectors in\n\tfor (C in 1:Ncorps) {\n\t\tMeanScores[C] = mean(ScoreList[[C]])\n\t\tPercGold[C] = sum(RankList[[C]] == 1) / Nmonte\n\t\tPercSilver[C] = sum(RankList[[C]] == 2) / Nmonte\n\t\tPercBronze[C] = sum(RankList[[C]] == 3) / Nmonte\n\t\tPercFinals[C] = sum(RankList[[C]] <= 12) / Nmonte\n\t\tPercSemis[C] = sum(RankList[[C]] <= 25) / Nmonte\n\t}\n\t\n\t#Adjust the gaps to make sure 1st place is a 0\n\tMeanScores = MeanScores - max(MeanScores)\n\t\n\t#Now format these into a data frame\n\tOutFrame = data.frame(Mean=MeanScores, Gold=PercGold, Silver=PercSilver, Bronze=PercBronze, Finals=PercFinals, Semis=PercSemis)\n\trow.names(OutFrame) = CorpsNames\n\t\n\t#Sort the data frame by percent chance of gold\n\tOutFrame = OutFrame[order(OutFrame$Mean, decreasing=T),]\n\t\n\t#Now return the data frame\n\treturn(OutFrame)\n}\n\n#This function returns a vector of information for each corps, based on open class\n\t#that's mean score, percent odds of being in 1st, 2nd, 3rd, and making OC Finals\nPredictionReduce_OpenClass <- function(PredictionList) {\n\tScoreList = PredictionList[[1]]\n\tRankList = PredictionList[[2]]\n\t\n\t#Get the simple information\n\tNcorps = length(PredictionList[[1]])\n\tNmonte = length(PredictionList[[1]][[1]])\n\tCorpsNames = names(PredictionList[[1]])\n\t\n\t#create a vector for each returned value\n\tMeanScores = vector(mode='double', length=Ncorps)\n\tPercGold = vector(mode='double', length=Ncorps)\n\tPercSilver = vector(mode='double', length=Ncorps)\n\tPercBronze = vector(mode='double', length=Ncorps)\n\tPercFinals = vector(mode='double', length=Ncorps)\n\t\n\t#Loop through each corps and fill the vectors in\n\tfor (C in 1:Ncorps) {\n\t\tMeanScores[C] = mean(ScoreList[[C]])\n\t\tPercGold[C] = sum(RankList[[C]] == 1) / Nmonte\n\t\tPercSilver[C] = sum(RankList[[C]] == 2) / Nmonte\n\t\tPercBronze[C] = sum(RankList[[C]] == 3) / Nmonte\n\t\tPercFinals[C] = sum(RankList[[C]] <= 12) / Nmonte\n\t}\n\t\n\t#Make sure 1st place's gap is 0\n\tMeanScores = MeanScores - max(MeanScores)\n\t\n\t#Now format these into a data frame\n\tOutFrame = data.frame(Mean=MeanScores, Gold=PercGold, Silver=PercSilver, Bronze=PercBronze, Finals=PercFinals)\n\trow.names(OutFrame) = CorpsNames\n\t\n\t#Sort the data frame by percent chance of gold\n\tOutFrame = OutFrame[order(OutFrame$Mean, decreasing=T),]\n\t\n\t#Now return the data frame\n\treturn(OutFrame)\n}\n\n", "meta": {"hexsha": "b1c4cbd4444ff2f2ccb208812dc339284c27e50f", "size": 15786, "ext": "r", "lang": "R", "max_stars_repo_path": "DCI_Library_CaptionScore.r", "max_stars_repo_name": "kant/forecastDCI", "max_stars_repo_head_hexsha": "9c3eda78bcc33d77f6f145bcb382bb8bccfdb32d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-07-04T00:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-16T16:27:19.000Z", "max_issues_repo_path": "DCI_Library_CaptionScore.r", "max_issues_repo_name": "kant/forecastDCI", "max_issues_repo_head_hexsha": "9c3eda78bcc33d77f6f145bcb382bb8bccfdb32d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2019-07-16T16:30:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T15:41:47.000Z", "max_forks_repo_path": "DCI_Library_CaptionScore.r", "max_forks_repo_name": "kant/forecastDCI", "max_forks_repo_head_hexsha": "9c3eda78bcc33d77f6f145bcb382bb8bccfdb32d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-08-13T22:42:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-13T22:42:50.000Z", "avg_line_length": 38.2227602906, "max_line_length": 137, "alphanum_fraction": 0.7020777904, "num_tokens": 5153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.30515755852673}} {"text": "# plotrocfischer.r - plot ROCs for different method on Fischer and Nh3D data\n#\n# Alex Stivala, October 2008\n#\n# Plot ROC curves for different methods on the Fischer data set\n# (Fischer et al 1996) and Nh3D data set (Thiruv et al 2005)\n# as used in Pelta et al 2008.\n#\n# Requires the ROCR package from CRAN (developed with version 1.0-2)\n# (ROCR in turn requires gplots, gtools, gdata)\n#\n# Run this on the output of e.g. tsevalfn.py with the -l option,\n# it is a table with one column of scores from classifier, and second\n# column of true class label (0 or 1)\n#\n# The citation for the ROCR package is\n# Sing et al 2005 \"ROCR: visualizing classifier performance in R\"\n# Bioinformatics 21(20):3940-3941\n# \n# \n# $Id: plotrocs_fischer_nh3d.r 2376 2009-05-14 01:40:32Z astivala $\n \n\nlibrary(ROCR)\n\n#\n# globals\n#\n\ncolorvec=c('deepskyblue4','brown','red','turquoise','blue','purple','green','cyan','gray20','magenta','darkolivegreen2','midnightblue','magenta3','darkseagreen','violetred3','darkslategray3')\nltyvec=c(1,2,4,5,6,1,2,1,5,6,1,2,4,5,6,1,2)\nnamevec=c('MSVNS3 norm1','MSVNS3 norm2', 'MSVNS3 norm3', 'QP tableau search norm1', 'QP tableau search norm2', 'QP tableau search norm3')\n\nfischer_fold_files=c('../maxcmo_results/fischer/norm1/fold.slrtab', '../maxcmo_results/fischer/norm2/fold.slrtab','../maxcmo_results/fischer/norm3/fold.slrtab','fischer/norm1/fold.slrtab','fischer/norm2/fold.slrtab','fischer/norm3/fold.slrtab')\nfischer_class_files=c('../maxcmo_results/fischer/norm1/class.slrtab','../maxcmo_results/fischer/norm2/class.slrtab','../maxcmo_results/fischer/norm3/class.slrtab','fischer/norm1/class.slrtab','fischer/norm2/class.slrtab','fischer/norm3/class.slrtab')\nnh3d_arch_files=c('../maxcmo_results/nh3d/norm1/arch.slrtab','../maxcmo_results/nh3d/norm2/arch.slrtab','../maxcmo_results/nh3d/norm3/arch.slrtab','nh3d/norm1/arch.slrtab','nh3d/norm2/arch.slrtab','nh3d/norm3/arch.slrtab')\nnh3d_class_files=c('../maxcmo_results/nh3d/norm1/class.slrtab','../maxcmo_results/nh3d/norm2/class.slrtab','../maxcmo_results/nh3d/norm3/class.slrtab','nh3d/norm1/class.slrtab','nh3d/norm2/class.slrtab','nh3d/norm3/class.slrtab')\n\n#\n# functions\n#\n\n#\n# Return the ROCR performance object for plotting ROC curve\n#\n# Parameters:\n# tab : data frame with score and label columns\n# \n# Return value:\n# ROCR performance object with FPR and TPR for plotting ROC curve\n#\ncompute_perf <- function(tab)\n{\n # tab is a data frame with score and label columns\n pred <- prediction(tab$score, tab$label)\n perfroc <- performance(pred, measure=\"tpr\",x.measure=\"fpr\")\n return(perfroc)\n}\n\n#\n# main\n#\n\n\n\n# EPS suitable for inserting into LaTeX\n\npostscript('rocs_fischer_fold.eps',\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\nfor (i in 1:length(fischer_fold_files)) {\n tab <- read.table(fischer_fold_files[i], header=TRUE)\n perfroc <- compute_perf(tab)\n plot(perfroc, lty=ltyvec[i], col=colorvec[i], add=(i>1),\n #main='Fischer data set at fold level' # remove title for paper\n )\n}\nlegend('bottomright', col=colorvec, lty=ltyvec, legend=namevec)\n#lines(c(0,1),c(0,1),type='l',lty=3)\ndev.off()\n\n\npostscript('rocs_fischer_class.eps',\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\nfor (i in 1:length(fischer_class_files)) {\n tab <- read.table(fischer_class_files[i], header=TRUE)\n perfroc <- compute_perf(tab)\n plot(perfroc, lty=ltyvec[i], col=colorvec[i], add=(i>1),\n# main='Fischer data set at class level' # remove title for paper\n )\n}\nlegend('bottomright', col=colorvec, lty=ltyvec, legend=namevec)\n#lines(c(0,1),c(0,1),type='l',lty=3)\ndev.off()\n\npostscript('rocs_nh3d_arch.eps',\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\nfor (i in 1:length(nh3d_arch_files)) {\n tab <- read.table(nh3d_arch_files[i], header=TRUE)\n perfroc <- compute_perf(tab)\n plot(perfroc, lty=ltyvec[i], col=colorvec[i], add=(i>1),\n # main='Nh3D data set at architecture level' # remove title for paper\n )\n}\nlegend('bottomright', col=colorvec, lty=ltyvec, legend=namevec)\n#lines(c(0,1),c(0,1),type='l',lty=3)\ndev.off()\n\n\npostscript('rocs_nh3d_class.eps',\n onefile=FALSE,paper=\"special\",horizontal=FALSE, \n width = 9, height = 6)\nfor (i in 1:length(nh3d_class_files)) {\n tab <- read.table(nh3d_class_files[i], header=TRUE)\n perfroc <- compute_perf(tab)\n plot(perfroc, lty=ltyvec[i], col=colorvec[i], add=(i>1),\n # main='Nh3D data set at class level' # removed title for paper\n )\n \n}\n#lines(c(0,1),c(0,1),type='l',lty=3)\nlegend('bottomright', col=colorvec, lty=ltyvec, legend=namevec) \ndev.off()\n\n", "meta": {"hexsha": "7f3bcc59bd40fe108a6e9077d9ff4638f77d70e6", "size": 4744, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/plotrocs_fischer_nh3d.r", "max_stars_repo_name": "stivalaa/cuda_satabsearch", "max_stars_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_stars_repo_licenses": ["MIT"], "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/plotrocs_fischer_nh3d.r", "max_issues_repo_name": "stivalaa/cuda_satabsearch", "max_issues_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_issues_repo_licenses": ["MIT"], "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/plotrocs_fischer_nh3d.r", "max_forks_repo_name": "stivalaa/cuda_satabsearch", "max_forks_repo_head_hexsha": "b947fb711f8b138e5a50c81e7331727c372eb87d", "max_forks_repo_licenses": ["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.3543307087, "max_line_length": 250, "alphanum_fraction": 0.6945615514, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.30507449306892004}} {"text": "#------ 2015. 7. 08\r\n#----------------------- RVPA program -----------------------------\r\n# written by Hiroshi Okamura (VPA & reference point) \r\n# and Momoko Ichinokawa (future projection & reference point)\r\n#\r\n# (*) macで読む場合は、\r\n# source(\"rvpa1.6.r\",encoding=\"shift-jis\")\r\n# として、文字コードを指定して読んでください\r\n# (*) vpaを使う場合、初期値の指定によっては収束しない場合があります。p.initの値をいろいろ変えて試して下さい\r\n#\r\n#\r\n#\r\n# 変更履歴\r\n# rvpa0.9 - 2013.7.3. 将来予測関数;将来予測のdeterminisitc runでのrpsの参照範囲と、\r\n# stochastic runでのrpsの参照範囲が異なる場合のオプション(sample.yearで指定)を追加\r\n# リサンプリングされるRPS = RPS[sample.yearの範囲]/mean(RPS[sample.yearの範囲])*median(RPS[rps.yearの範囲])\r\n# (bias.adjustedしていない場合は関係ない。sample.yearを設定しない場合、自動的にsample.year=rps.yearとなる)\r\n# rvpa0.92 - vpaのsel.update部分の修正とprofile likelihood信頼区間関数の修正・追加\r\n# rvpa0.95 - 管理基準値計算のところに、nlmでの計算回数の上限を設定する引数を追加(デフォルトでは1000)\r\n# rvpa0.96 - likelihood profile用に、CPUEごとに目的関数の値を出力するオプションを追加。その他\r\n# rvpa1.0 - パッケージとして公開したバージョン\r\n# rvpa1.3 - 重み付け計算を追加\r\n# rvpa1.6 -warningsメッセージを追加.vpaでindexの一部だけ利用するオプション(use.index)を追加.MSY.EST2関数を追加\r\n# rvpa1.7 - selupdate+F推定オプション.制約付最適化.\r\n# rvpa.1.8 - Retrospective analysisを行うための関数 (retro.est, retro.est2) と、リッジ回帰を行うための引数 (lambda) を追加(2017/05/29)\r\n# rvpa1.9 - maa.tune(tuning時だけ使用のmaa), waa.catch(資源と漁獲でwaaが違う場合に対応)を使用可能に.index=NULLでtune=FALSEのときエラーが出ないように修正.\r\n# rvpa1.9.2 - 各indexに対する分散に制約をかけられるように修正。例えばindexが5本ある場合、sigma.constraint=c(1,2,2,3,3)とすると2,3本めと4,5本目のindexに対する分散は等しいとして推定する。180522中山\r\n##\r\n\r\ndata.handler <- function(\r\n caa,\r\n waa,\r\n maa,\r\n index=NULL,\r\n M = 0.4,\r\n maa.tune=NULL,\r\n waa.catch=NULL,\r\n catch.prop=NULL\r\n)\r\n{\r\n years <- as.numeric(sapply(strsplit(names(caa[1,]),\"X\"), function(x) x[2]))\r\n\r\n if (is.null(dim(waa)) | dim(waa)[2]==1) waa <- as.data.frame(matrix(unlist(waa), nrow=nrow(caa), ncol=ncol(caa)))\r\n\r\n if (is.null(dim(maa)) | dim(maa)[2]==1) maa <- as.data.frame(matrix(unlist(maa), nrow=nrow(caa), ncol=ncol(caa)))\r\n\r\n colnames(caa) <- colnames(waa) <- colnames(maa) <- years\r\n\r\n if (!is.null(waa.catch)) {\r\n if (is.null(dim(waa.catch)) | dim(waa.catch)[2]==1) waa.catch <- as.data.frame(matrix(unlist(waa.catch), nrow=nrow(caa), ncol=ncol(caa)))\r\n colnames(waa.catch) <- years\r\n }\r\n\r\n if (!is.null(maa.tune)) {\r\n if (is.null(dim(maa.tune)) | dim(maa.tune)[2]==1) maa.tune <- as.data.frame(matrix(unlist(maa.tune), nrow=nrow(caa), ncol=ncol(caa)))\r\n colnames(maa.tune) <- years\r\n }\r\n\r\n if (!is.null(catch.prop)) colnames(catch.prop) <- years\r\n \r\n if (!is.null(index)) colnames(index) <- years\r\n\r\n if (is.null(dim(M))) M <- as.data.frame(matrix(M, nrow=nrow(caa), ncol=ncol(caa)))\r\n\r\n colnames(M) <- years\r\n rownames(M) <- rownames(caa)\r\n\r\n res <- list(caa=caa, maa=maa, waa=waa, index=index, M=M, maa.tune=maa.tune, waa.catch=waa.catch, catch.prop=catch.prop)\r\n\r\n invisible(res)\r\n}\r\n\r\n# miscellaneous functions\r\n\r\n#max.age <- function(x) max(which(!is.na(x)))\r\nmax.age.func <- function(x) max(which(!is.na(x)))\r\n\r\nvpa.core <- function(caa,faa,M,k){\r\n out <- caa[,k]/(1-exp(-faa[,k]-M[,k]))*(faa[,k]+M[,k])/faa[,k]\r\n return(out)\r\n}\r\n\r\nvpa.core.Pope <- function(caa,faa,M,k){\r\n out <- caa[, k]*exp(M[, k]/2)/(1-exp(-faa[, k]))\r\n return(out)\r\n}\r\n\r\nik.est <- function(caa,naa,M,i,k,min.caa=0.01,maxit=5,d=0.0001){\r\n K <- 1\r\n it <- 0\r\n \r\n f0 <- 1\r\n f1 <- NA\r\n\r\n if (!is.na(naa[i+1,k+1])){\r\n while(it < maxit & K > d){\r\n it <- it + 1\r\n f1 <- log(1+max(caa[i,k],min.caa)/naa[i+1,k+1]*exp(-M[i,k])*(f0+M[i,k])*(1-exp(-f0))/(f0*(1-exp(-f0-M[i,k]))))\r\n K <- sqrt((f1-f0)^2)\r\n f0 <- f1\r\n }\r\n }\r\n \r\n return(f1)\r\n}\r\n\r\nhira.est <- function(caa,naa,M,i,k,alpha=1,min.caa=0.01,maxit=5,d=0.0001){\r\n K <- 1\r\n it <- 0\r\n \r\n f0 <- 1\r\n f1 <- NA\r\n\r\n if (!is.na(naa[i+1,k+1])){\r\n while(it < maxit & K > d){\r\n it <- it + 1\r\n f1 <- log(1+(1-exp(-f0))*exp(-M[i,k])/(naa[i+1,k+1]*f0)*(max(caa[i+1,k],min.caa)*(alpha*f0+M[i+1,k])/(alpha*(1-exp(-alpha*f0-M[i+1,k])))*exp((1-alpha)*f0)+max(caa[i,k],min.caa)*(f0+M[i,k])/(1-exp(-f0-M[i,k]))))\r\n K <- sqrt((f1-f0)^2)\r\n f0 <- f1\r\n }\r\n }\r\n \r\n return(f1)\r\n}\r\n\r\nf.forward.est <- function(caa,naa,M,i,k,maxit=5,d=0.0001){\r\n K <- 1\r\n it <- 0\r\n \r\n f0 <- f1 <- 1\r\n \r\n while(it < maxit & K > d){\r\n it <- it + 1\r\n f1 <- caa[i,k]/naa[i,k]*(f0+M[i,k])/f0*1/(1-exp(-f0-M[i,k]))\r\n K <- sqrt((f1-f0)^2)\r\n f0 <- f1\r\n }\r\n \r\n return(f1)\r\n}\r\n\r\nfp.forward.est <- function(caa,naa,M,i,k,alpha=1,maxit=5,d=0.0001){\r\n K <- 1\r\n it <- 0\r\n \r\n f0 <- f1 <- 1\r\n \r\n while(it < maxit & K > d){\r\n it <- it + 1\r\n f1 <- 1/(1+alpha)*(caa[i,k]/naa[i,k]*(f0+M[i,k])*1/(1-exp(-f0-M[i,k]))+caa[i+1,k]/naa[i+1,k]*(alpha*f0+M[i+1,k])*1/(1-exp(-alpha0*f0-M[i+1,k])))\r\n K <- sqrt((f1-f0)^2)\r\n f0 <- f1\r\n }\r\n \r\n return(f1)\r\n}\r\n\r\nbackward.calc <- function(caa,naa,M,na,k,min.caa=0.001,plus.group=TRUE){\r\n out <- rep(NA, na[k])\r\n if(na[k+1] > na[k]){\r\n for (i in 1:na[k]){\r\n out[i] <- naa[i+1,k+1]*exp(M[i,k])+caa[i,k]*exp(M[i,k]/2)\r\n }\r\n }\r\n else{\r\n for (i in 1:(na[k+1]-2)){\r\n out[i] <- naa[i+1,k+1]*exp(M[i,k])+caa[i,k]*exp(M[i,k]/2)\r\n }\r\n if (isTRUE(plus.group)){\r\n out[(na[k+1]-1):na[k]] <- pmax(caa[(na[k+1]-1):na[k],k],min.caa)/sum(pmax(caa[(na[k+1]-1):na[k],k],min.caa))*naa[na[k+1],k+1]*exp(M[(na[k+1]-1):na[k],k])+caa[(na[k+1]-1):na[k],k]*exp(M[(na[k+1]-1):na[k],k]/2)\r\n }\r\n else{\r\n out[na[k+1]-1] <- naa[na[k+1],k+1]*exp(M[na[k+1]-1,k])+caa[na[k+1]-1,k]*exp(M[na[k+1]-1,k]/2)\r\n out[na[k]] <- out[na[k+1]-1]*caa[na[k+1],k]/caa[na[k+1]-1,k]*exp((M[na[k+1],k]-M[na[k+1]-1,k])/2)\r\n }\r\n }\r\n return(out)\r\n}\r\n\r\nforward.calc <- function(faa,naa,M,na,k){\r\n out <- rep(NA, na[k])\r\n for (i in 2:(na[k]-1)){\r\n out[i] <- naa[i-1,k-1]*exp(-faa[i-1,k-1]-M[i-1,k-1])\r\n }\r\n out[na[k]] <- sum(sapply(seq(na[k]-1,max(na[k], na[k-1])), plus.group.eq, naa=naa, faa=faa, M=M, k=k))\r\n return(out)\r\n}\r\n\r\nplus.group.eq <- function(x, naa, faa, M, k) naa[x,k-1]*exp(-faa[x,k-1]-M[x,k-1])\r\n\r\nf.at.age <- function(caa,naa,M,na,k,alpha=1) {\r\n out <- -log(1-caa[1:(na[k]-1),k]*exp(M[1:(na[k]-1),k]/2)/naa[1:(na[k]-1),k])\r\n c(out, alpha*out[length(out)])\r\n}\r\n\r\nsel.func <- function(faa, def=\"maxage\") {\r\n if(def==\"maxage\") saa <- apply(faa, 2, function(x) x/x[length(x[!is.na(x)])])\r\n if(def==\"max\") saa <- apply(faa, 2, function(x) x/max(x,na.rm=TRUE))\r\n if(def==\"mean\") saa <- apply(faa, 2, function(x) x/sum(x,na.rm=TRUE))\r\n\r\n return(saa)\r\n}\r\n\r\nff <- function(x, z) get(x)(z)\r\n\r\nabund.extractor <- function(\r\n abund=\"SSB\",\r\n naa,\r\n faa,\r\n dat,\r\n min.age=0,\r\n max.age=0,\r\n link=\"id\",\r\n base=exp(1),\r\n af=1,\r\n catch.prop=NULL,\r\n sel.def=\"maxage\",\r\n scale=1000\r\n){\r\n# abund = \"N\": abundance\r\n# abund = \"Nm\": abundance at the middle of the year\r\n# abund = \"B\": biomass\r\n# abund = \"Bm\": abundance at the middle of the year\r\n# abund = \"SSB\": SSB\r\n# # abund = \"SSB\": SSB at the middle of the year\r\n\r\n naa <- as.data.frame(naa)\r\n faa <- as.data.frame(faa)\r\n\r\n waa <- dat$waa/scale\r\n maa <- dat$maa\r\n\r\n min.age <- min.age + 1\r\n max.age <- max.age + 1\r\n\r\n maa.tune <- dat$maa.tune\r\n \r\n if (abund==\"N\") res <- colSums(naa[min.age:max.age,], na.rm=TRUE)\r\n if (abund==\"Nm\") res <- colSums(naa[min.age:max.age,]*exp(-dat$M[min.age:max.age,]/2-af*faa[min.age:max.age,]/2), na.rm=TRUE)\r\n if (abund==\"B\") res <- colSums((naa*waa)[min.age:max.age,], na.rm=TRUE)\r\n if (abund==\"Bm\") res <- colSums((naa*waa)[min.age:max.age,]*exp(-dat$M[min.age:max.age,]/2-af*faa[min.age:max.age,]/2), na.rm=TRUE)\r\n if (abund==\"SSB\"){\r\n if (is.null(maa.tune)) ssb <- naa*waa*maa else ssb <- naa*waa*maa.tune\r\n res <- colSums(ssb,na.rm=TRUE)\r\n }\r\n if (abund==\"Bs\"){\r\n saa <- sel.func(faa, def=sel.def)\r\n res <- colSums((naa*waa*saa)[min.age:max.age,], na.rm=TRUE)\r\n }\r\n if (abund==\"Ns\"){\r\n saa <- sel.func(faa, def=sel.def)\r\n res <- colSums((naa*saa)[min.age:max.age,], na.rm=TRUE)\r\n } \r\n if (abund==\"SSBm\"){\r\n if (is.null(maa.tune)) ssb <- naa*waa*maa*exp(-dat$M/2-af*faa/2) else ssb <- naa*waa*maa.tune*exp(-dat$M/2-af*faa/2)\r\n res <- colSums(ssb,na.rm=TRUE)\r\n }\r\n\r\n if (abund==\"N1sj\") res <- colSums(cbind(naa[1,-1]*exp(dat$M[1,-1]),NA), na.rm=TRUE)\r\n if (abund==\"N0sj\") res <- colSums(cbind(naa[1,-1]*exp(dat$M[1,-1]*2),NA), na.rm=TRUE)\r\n if (abund==\"F\") if (is.null(catch.prop)) res <- colMeans(faa[min.age:max.age,], na.rm=TRUE) else res <- colMeans(catch.prop[min.age:max.age, ]*faa[min.age:max.age,], na.rm=TRUE)\r\n \r\n if (link==\"log\") res <- log(res, base=base)\r\n\r\n return(invisible(res))\r\n}\r\n\r\n#\r\n\r\ntmpfunc2 <- function(x=1,y=2,z=3){\r\n argname <- ls() # 関数が呼び出されたばかりのときのls()は引数のみが入っている\r\n arglist <- lapply(argname,function(xx) eval(parse(text=xx)))\r\n names(arglist) <- argname\r\n value <- x+y+z\r\n return(list(value=value,args=arglist))\r\n}\r\n\r\n#\r\n##\r\n\r\nqbs.f <- function(q.const, b.const, sigma.const, index, Abund, nindex, index.w, max.dd=0.0001, max.iter=100){\r\n \r\n np.q <- length(unique(q.const[q.const > 0])) \r\n np.b <- length(unique(b.const[b.const > 0])) \r\n np.s <- length(unique(sigma.const[sigma.const > 0]))\r\n \r\n q <- b <- sigma <- numeric(nindex)\r\n \r\n q[1:nindex] <- b[1:nindex] <- sigma[1:nindex] <- 1\r\n \r\n delta <- 1\r\n \r\n obj <- NULL\r\n \r\n NN <- 0\r\n \r\n while(delta > max.dd & NN < max.iter){\r\n NN <- NN+1\r\n q0 <- q\r\n b0 <- b\r\n sigma0 <- sigma\r\n \r\n if (np.q > 0){\r\n for(i in 1:np.q){\r\n id <- which(q.const==i)\r\n num <- den <- 0\r\n for (j in id){\r\n avail <- which(!is.na(as.numeric(index[j,])))\r\n num <- num+index.w[j]*mean(log(as.numeric(index[j,avail]))-b[j]*log(as.numeric(Abund[j,avail])))/sigma[j]^2\r\n den <- den+index.w[j]/sigma[j]^2 \r\n }\r\n q[i] <- num/den\r\n }\r\n }\r\n if (np.b > 0){\r\n for(i in 1:np.b){\r\n id <- which(b.const==i)\r\n num <- den <- 0\r\n for (j in id){\r\n avail <- which(!is.na(as.numeric(index[j,])))\r\n num <- num+index.w[j]*cov(log(as.numeric(index[j,avail])),log(as.numeric(Abund[j,avail])))/var(log(as.numeric(Abund[j,avail])))/sigma[j]^2\r\n den <- den+index.w[j]/sigma[j]^2 \r\n }\r\n b[i] <- num/den\r\n } \r\n }\r\n if (np.s > 0){\r\n for(i in 1:np.s){\r\n id <- which(sigma.const==i)\r\n num <- den <- 0\r\n for (j in id){\r\n avail <- which(!is.na(as.numeric(index[j,])))\r\n nn <- length(avail)\r\n num <- num+index.w[j]*sum((log(as.numeric(index[j,avail]))-q[j]-b[j]*log(as.numeric(Abund[j,avail])))^2)\r\n den <- den+index.w[j]*nn \r\n }\r\n sigma[i] <- sqrt(num/den)\r\n } \r\n }\r\n \r\n q[which(q.const>0)] <- q[q.const[which(q.const>0)]]\r\n b[which(b.const>0)] <- b[b.const[which(b.const>0)]]\r\n sigma[which(sigma.const>0)] <- sigma[sigma.const[which(sigma.const>0)]]\r\n \r\n delta <- max(c(sqrt((q-q0)^2),sqrt((b-b0)^2),sqrt((sigma-sigma0)^2)))\r\n }\r\n\r\n for (i in 1:nindex){\r\n avail <- which(!is.na(as.numeric(index[i,]))) \r\n obj <- c(obj, index.w[i]*(-as.numeric(na.omit(dnorm(log(as.numeric(index[i,avail])),log(q[i])+b[i]*log(as.numeric(Abund[i,avail])),sigma[i],log=TRUE)))))\r\n }\r\n \r\n convergence <- ifelse(delta <= max.dd, 1, 0) \r\n \r\n return(list(q=q, b=b, sigma=sigma, obj=sum(obj), convergence=convergence))\r\n}\r\n\r\nqbs.f2 <- function(p0,index, Abund, nindex, index.w, fixed.index.var=NULL){\r\n \r\n if (is.null(fixed.index.var)) fixed.index.var <- matrix(0, nrow=nrow(index), ncol=ncol(index))\r\n if (class(fixed.index.var)==\"numeric\") fixed.index.var <- matrix(fixed.index.var, nrow=1)\r\n if (class(fixed.index.var)==\"matrix\" | class(fixed.index.var)==\"data.frame\") fixed.index.var <- array(fixed.index.var, dim=c(dim(fixed.index.var),1))\r\n \r\n np <- min(nindex,sum(index.w>0))\r\n \r\n p <- vector(length=2*np)\r\n q <- sigma <- vector(length=np)\r\n\r\n obj.f <- function(p){\r\n obj <- j <- 0\r\n \r\n for (i in 1:nindex){\r\n if (index.w[i] > 0 ){\r\n j <- j + 1\r\n q[j] <- exp(p[2*j-1])\r\n sigma[j] <- exp(p[2*j])\r\n \r\n avail <- which(!is.na(as.numeric(index[i,])))\r\n obj <- obj+index.w[i]*(-as.numeric(na.omit(dmvnorm(log(as.numeric(index[i,avail])),log(q[j])+log(as.numeric(Abund[i,avail])),as.matrix(fixed.index.var[avail,avail,j])+sigma[j]^2*diag(length(avail)),log=TRUE))))\r\n }\r\n }\r\n \r\n sum(obj)\r\n }\r\n \r\n res <- nlm(obj.f,p0)\r\n \r\n q <- res$estimate[1:np]\r\n sigma <- exp(res$estimate[1:np+np])\r\n obj <- res$minimum\r\n convergence <- res$code\r\n \r\n return(list(q=q, b=rep(1,np), sigma=sigma, obj=obj, convergence=convergence))\r\n}\r\n \r\n#\r\n\r\n# vpa \r\n#\r\n\r\nvpa <- function(\r\n dat, # data for vpa\r\n sel.f = NULL, # 最終年の選択率\r\n tf.year = 2008:2010, # terminal Fをどの年の平均にするか\r\n rec.new = NULL, # 翌年の加入を外から与える\r\n rec=NULL, # rec.yearの加入\r\n rec.year=2010, # 加入を代入する際の年\r\n rps.year = 2001:2010, # 翌年のRPSをどの範囲の平均にするか\r\n fc.year = 2009:2011, # Fcurrentでどの範囲を参照するか\r\n last.year = NULL, # vpaを計算する最終年を指定(retrospective analysis)\r\n last.catch.zero = FALSE, # TRUEなら強制的に最終年の漁獲量を0にする\r\n faa0 = NULL, # sel.update=TRUEのとき,初期値となるfaa\r\n naa0 = NULL, # sel.update=TRUEのとき,初期値となるnaa\r\n f.new = NULL,\r\n Pope = TRUE, # Popeの近似式を使うかどうか\r\n tune = FALSE, # tuningをするかどうか\r\n abund = \"B\", # tuningの際,何の指標に対応するか\r\n min.age = 0, # tuning指標の年齢参照範囲の下限\r\n max.age = 0, # tuning指標の年齢参照範囲の上限\r\n link = \"id\", # tuningのlink関数\r\n base = NA, # link関数が\"log\"のとき,底を何にするか\r\n af = NA, # 資源量指数が年の中央のとき,af=0なら漁期前,af=1なら漁期真ん中,af=2なら漁期後となる\r\n index.w = NULL, # tuning indexの重み\r\n use.index = \"all\",\r\n scale = 1000, # 重量のscaling\r\n hessian = TRUE,\r\n alpha = 1, # 最高齢と最高齢-1のFの比 F_a = alpha*F_{a-1}\r\n maxit = 5, # 石岡・岸田/平松の方法の最大繰り返し数\r\n d = 0.0001, # 石岡・岸田/平松の方法の収束判定基準\r\n min.caa = 0.001, # caaに0があるとき,0をmin.caaで置き換える\r\n plot = FALSE, # tuningに使った資源量指数に対するフィットのプロット\r\n plot.year = 1998:2015, # 上のプロットの参照年\r\n term.F = \"max\", # terminal Fの何を推定するか: \"max\" or \"all\"\r\n plus.group = TRUE, \r\n stat.tf = \"mean\", # 最終年のFを推定する統計量(年齢別に与えること可)\r\n add.p.est = NULL, # 追加で最高齢以外のfaaを推定する際.年齢を指定する.\r\n add.p.ini = NULL, \r\n sel.update=FALSE, # チューニングVPAにおいて,選択率を更新しながら推定\r\n sel.def = \"max\", # sel.update=TRUEで選択率を更新していく際に,選択率をどのように計算するか.最大値を1とするか,平均値を1にするか...\r\n max.dd = 0.000001, # sel.updateの際の収束判定基準\r\n ti.scale = NULL, # 資源量の係数と切片のscaling\r\n tf.mat = NULL, # terminal Fの平均をとる年の設定.0-1行列.\r\n eq.tf.mean = FALSE, # terminal Fの平均値を過去のFの平均値と等しくする\r\n no.est = FALSE, # パラメータ推定しない.\r\n est.method = \"ls\", # 推定方法 (ls = 最小二乗法,ml = 最尤法)\r\n b.est = FALSE, # bを推定するかどうか\r\n est.constraint = FALSE, # 制約付き推定をするかどうか\r\n q.const = 1:length(abund), # qパラメータの制約(0は推定しないで1にfix)\r\n b.const = 1:length(abund), # bパラメータの制約(0は推定しないで1にfix)\r\n q.fix = NULL,\r\n b.fix = NULL,\r\n sigma.const = 1:length(abund), # sigmaパラメータの制約\r\n fixed.index.var = NULL,\r\n max.iter = 100, # q,b,sigma計算の際の最大繰り返し数\r\n optimizer = \"nlm\",\r\n Lower = -Inf,\r\n Upper = Inf,\r\n p.fix = NULL,\r\n lambda = 0, # ridge回帰係数\r\n beta = 2, # penaltyのexponent (beta = 1: lasso, 2: ridge)\r\n penalty = \"p\",\r\n ssb.def = \"i\", # i: 年はじめ,m: 年中央, l: 年最後\r\n ssb.lag = 0, # 0: no lag, 1: lag 1\r\n TMB=FALSE,\r\n TMB.compile=FALSE,\r\n sel.rank=NULL,\r\n p.init = 0.2, # 推定パラメータの初期値\r\n sigma.constraint = 1:length(abund)\r\n)\r\n{\r\n #\r\n \r\n if (TMB.compile) {\r\n library(TMB)\r\n compile(\"rvpa_tmb.cpp\")\r\n dyn.load(dynlib(\"rvpa_tmb\"))\r\n }\r\n \r\n # inputデータをリスト化\r\n\r\n argname <- ls() # 関数が呼び出されたばかりのときのls()は引数のみが入っている\r\n arglist <- lapply(argname,function(xx) eval(parse(text=xx)))\r\n names(arglist) <- argname\r\n \r\n # data handling\r\n\r\n caa <- dat$caa # catch-at-age\r\n waa <- dat$waa # weight-at-age\r\n maa <- dat$maa # maturity-at-age\r\n if (!is.null(dat$maa.tune)) maa.tune <- dat$maa.tune\r\n if (!is.null(dat$catch.prop)) catch.prop <- dat$catch.prop\r\n index <- dat$index # abundance indices\r\n M <- dat$M # natural mortality-at-age\r\n waa.catch <- ifelse(is.null(dat$waa.catch),waa,dat$waa.catch)\r\n\r\n if (isTRUE(tune) & is.null(index)) {print(\"Check!: There is no abundance index.\"); stop()}\r\n \r\n years <- dimnames(caa)[[2]] # 年\r\n ages <- dimnames(caa)[[1]] # 年齢\r\n\r\n if (class(index)==\"numeric\") index <- t(as.matrix(index))\r\n\r\n if (use.index[1]!=\"all\") {\r\n index <- index[use.index,,drop=FALSE]\r\n if (length(use.index)!=length(abund)){\r\n if (length(abund)>1) abund <- abund[use.index]\r\n if (length(min.age)>1) min.age <- min.age[use.index]\r\n if (length(max.age)>1) max.age <- max.age[use.index]\r\n if (length(link)>1) link <- link[use.index]\r\n if (length(base)>1) base <- base[use.index]\r\n if (length(af)>1) af <- af[use.index] \r\n if (length(index.w)>1) index.w <- index.w[use.index] \r\n }\r\n }\r\n\r\n #\r\n \r\n if(!is.null(fixed.index.var)) require(mvtnorm)\r\n\r\n # 最終年 last.yearに値が入っている場合は,それ以降のデータを削除する(retrospective analysis)\r\n if (!is.null(last.year)) {\r\n caa <- caa[,years <= last.year]\r\n waa <- waa[,years <= last.year]\r\n maa <- maa[,years <= last.year]\r\n if (!is.null(dat$maa.tune)) maa.tune <- maa.tune[,years <= last.year] \r\n if (!is.null(dat$cathc.prop)) maa.tune <- catch.prop[,years <= last.year] \r\n M <- M[,years <= last.year]\r\n if(!is.null(index)) index <- index[,years <= last.year,drop=FALSE]\r\n years <- dimnames(caa)[[2]]\r\n dat <- list(caa=caa, waa=waa, maa=maa, M=M, index=index)\r\n }\r\n\r\n na <- apply(caa, 2, max.age.func) # 年ごとの最大年齢(年によって最大年齢が違う場合に対応するため)\r\n ny <- ncol(caa) # 年の数\r\n \r\n if (isTRUE(last.catch.zero)) {caa[,ny] <- 0; ny <- ny - 1; n.add <- 1; saa.new <- NULL} else n.add <- 0 # 最終年の漁獲量を0とし,年を1個減らす\r\n\r\n if (term.F==\"max\") { # 最高齢のFだけを推定する場合\r\n p.init <- ifelse(is.na(p.init[1]), M[na[ny],ny], p.init[1]) # 初期値がNAなら,最終年最高齢の自然死亡係数を初期値とする\r\n if (!is.null(add.p.est) & is.null(add.p.ini)) {add.p.est <- add.p.est + 1; p.init <- rep(p.init, length(add.p.est)+1)} # add.p.estに数字があれば,その年齢を追加のパラメータとして推定する\r\n if (!is.null(add.p.est) & !is.null(add.p.ini)) {add.p.est <- add.p.est + 1; p.init <- c(add.p.ini,p.init)} # add.p.estに数字があれば,その年齢を追加のパラメータとして推定する\r\n }\r\n if (term.F==\"all\"){ # 最終年のすべての年齢のFを推定\r\n if(length(p.init)==0) p.init <- rep(M[na[ny],ny], na[ny]-1) # 初期値がNAなら,最終年最高齢の自然死亡係数を0~na-1の初期値とする\r\n if(length(p.init) < na[ny]-1) p.init <- rep(p.init[1], na[ny]-1) # 初期値の成分数が年齢数-1より小さい場合は,初期値の最初の値を要素に持つ年齢数-1の大きさのベクトルを初期値とする\r\n if(length(p.init) >= na[ny]-1) p.init <- p.init[1:na[ny]-1] # 初期値の成分数が年齢数-1以上であれば,年齢数以上の値は使用しない\r\n }\r\n\r\n if (length(stat.tf)==1) stat.tf <- rep(stat.tf, na[ny]-1) # stat.tfが1個だけ指定されているときは,全年齢その統計量を使う\r\n\r\n # tuningの際のパラメータが1個だけ指定されている場合は,nindexの数だけ増やす\r\n if (isTRUE(tune)){\r\n \r\n nindex <- nrow(index)\r\n\r\n if (nindex > length(abund) & length(abund)==1) abund <- rep(abund, nindex)\r\n if (nindex > length(min.age) & length(min.age)==1) min.age <- rep(min.age, nindex)\r\n if (nindex > length(max.age) & length(max.age)==1) max.age <- rep(max.age, nindex)\r\n if (nindex > length(link) & length(link)==1) link <- rep(link, nindex)\r\n if (nindex > length(base) & length(base)==1) base <- rep(base, nindex)\r\n \r\n if (is.null(index.w)) index.w <- rep(1, nindex)\r\n if (!is.na(af[1])) if(nindex > length(af) & length(af)==1) af <- rep(af, nindex)\r\n\r\n q <- rep(NA, nindex)\r\n }\r\n\r\n\r\n # selectivityを更新する場合にfaa0,naa0が与えられていれば,それを使う\r\n if (!isTRUE(sel.update)){\r\n faa <- naa <- matrix(NA, nrow=max(na), ncol=ny+n.add, dimnames=list(ages, years))\r\n }else {\r\n if(is.null(faa0) | is.null(naa0)) faa <- naa <- matrix(1, nrow=max(na), ncol=ny+n.add, dimnames=list(ages, years))\r\n else {faa <- as.matrix(faa0); naa <- as.matrix(naa0)}\r\n }\r\n\r\n if (is.null(p.fix)) p.fix <- 1:length(p.init)\r\n\r\n # warnings\r\n \r\n if (!tune & sel.update) print(\"sel.update = TRUE but tune=FALSE. So, the results are unreliable.\")\r\n if (tune & is.null(sel.f) & (!sel.update & term.F==\"max\")) print(\"sel.f=NULL although tune=TRUE & sel.update=FALSE & term.F=max. The results are unreliable.\")\r\n if (tune) if(length(abund)!=nrow(index)) print(\"Check!: The number of abundance definition is different from the number of indices.\")\r\n\r\n# ssb.def\r\n\r\n if (ssb.def==\"i\") ssb.coef <- 0\r\n if (ssb.def==\"m\") ssb.coef <- 0.5\r\n if (ssb.def==\"l\") ssb.coef <- 1 \r\n \r\n\r\n\r\n# core function for optimization\r\n\r\n p.est <- function(log.p, out=FALSE){\r\n \r\n p <- exp(log.p)\r\n\r\n\r\n # sel.f==NULLで,パラメータpが1個なら,最終年最高齢のfaaとnaaを推定\r\n if (is.null(sel.f) & length(p) == 1){\r\n faa[na[ny], ny] <- p\r\n if (isTRUE(Pope)) naa[na[ny], ny] <- caa[na[ny], ny]*exp(M[na[ny], ny]/2)/(1-exp(-faa[na[ny], ny]))\r\n else naa[na[ny], ny] <- caa[na[ny], ny]/(1-exp(-faa[na[ny], ny]-M[na[ny], ny]))*(faa[na[ny],ny]+M[na[ny],ny])/faa[na[ny],ny]\r\n }\r\n\r\n # sel.f!=NULLで,パラメータが年齢-1より少ない場合,sel.fを使って,最終年/全年齢のfaaとnaaを計算\r\n if (!is.null(sel.f) & length(p) < na[ny]-1){\r\n if(length(p)==1) faa[, ny] <- sel.f*p\r\n if(length(p) > 1) { # パラメータ数が1より大きい場合,add.p.estの分,推定パラメータ数を増やす\r\n faa[,ny] <- sel.f*p[length(p)]\r\n for (i in 1:(length(p)-1)){\r\n faa[add.p.est[i],ny] <- p[i]*p[length(p)]\r\n }\r\n }\r\n if (isTRUE(Pope)) naa[, ny] <- vpa.core.Pope(caa,faa,M,ny)\r\n else naa[, ny] <- vpa.core(caa,faa,M,ny)\r\n }\r\n\r\n #\r\n if (is.null(sel.f) & isTRUE(sel.update)){\r\n if(length(p)==1) faa[, ny] <- p\r\n if(length(p) > 1) { # パラメータ数が1より大きい場合,add.p.estの分,推定パラメータ数を増やす\r\n faa[,ny] <- p[length(p)]\r\n }\r\n }\r\n \r\n # パラメータが年齢-1であれば,それらをパラメータとして最終年/全年齢のfaaとnaaを計算\r\n if (length(p) == na[ny]-1){\r\n faa[1:(na[ny]-1), ny] <- p[p.fix]\r\n faa[na[ny], ny] <- alpha*p[na[ny]-1]\r\n if (isTRUE(Pope)) naa[, ny] <- vpa.core.Pope(caa,faa,M,ny)\r\n else naa[, ny] <- vpa.core(caa,faa,M,ny)\r\n }\r\n \r\n # selctivityを更新しながら推定する場合\r\n if (isTRUE(sel.update)){\r\n dd <- itt <- 1\r\n while(dd > max.dd & itt < max.iter){\r\n saa <- sel.func(faa, def=sel.def) # sel.defに従って選択率を計算\r\n for (i in (na[ny]-1):1){\r\n saa[i, ny] <- get(stat.tf[i])(saa[i, years %in% tf.year]) \r\n }\r\n \r\n saa[na[ny], ny] <- get(stat.tf[na[ny]-1])(saa[na[ny], years %in% tf.year])\r\n if(length(p)==1) faa[1:na[ny], ny] <- p*sel.func(saa, def=sel.def)[1:na[ny],ny] else faa[1:na[ny], ny] <- p[length(p)]*sel.func(saa, def=sel.def)[1:na[ny],ny] \r\n \r\n if (isTRUE(Pope)) naa[ , ny] <- vpa.core.Pope(caa,faa,M,ny)\r\n else naa[, ny] <- vpa.core(caa,faa,M,ny)\r\n \r\n if (isTRUE(Pope)){\r\n for (i in (ny-1):1){\r\n naa[1:na[i], i] <- backward.calc(caa,naa,M,na,i,min.caa=min.caa,plus.group=plus.group)\r\n faa[1:na[i], i] <- f.at.age(caa,naa,M,na,i,alpha=alpha)\r\n }\r\n }\r\n else{\r\n for (i in (ny-1):1){\r\n for (j in 1:(na[i]-2)){\r\n faa[j, i] <- ik.est(caa,naa,M,j,i,min.caa=min.caa,maxit=maxit,d=d)\r\n }\r\n if (isTRUE(plus.group)){\r\n faa[na[i]-1, i] <- hira.est(caa,naa,M,na[i]-1,i,alpha=alpha,min.caa=min.caa,maxit=maxit,d=d)\r\n }\r\n else faa[na[i]-1, i] <- ik.est(caa,naa,M,na[i]-1,i,min.caa=min.caa,maxit=maxit,d=d)\r\n \r\n faa[na[i], i] <- alpha*faa[na[i]-1, i]\r\n naa[1:na[i], i] <- vpa.core(caa,faa,M,i)\r\n }\r\n }\r\n\r\n faa1 <- faa\r\n saa1 <- sel.func(faa1, def=sel.def)\r\n\r\n for (i in (na[ny]-1):1){\r\n saa1[i, ny] <- get(stat.tf[i])(saa1[i, years %in% tf.year]) \r\n }\r\n saa1[na[ny], ny] <- get(stat.tf[na[ny]-1])(saa1[na[ny], years %in% tf.year]) \r\n if(length(p)==1) faa1[1:na[ny], ny] <- p*sel.func(saa1, def=sel.def)[1:na[ny],ny] else faa1[1:na[ny], ny] <- p[length(p)]*sel.func(saa1, def=sel.def)[1:na[ny],ny]\r\n faa1[na[ny], ny] <- alpha*faa1[na[ny]-1, ny]\r\n \r\n dd <- max(sqrt((saa1[,ny] - saa[,ny])^2))\r\n itt <- itt + 1\r\n \r\n faa <- faa1\r\n }\r\n\r\n saa <- sel.func(faa, def=sel.def)\r\n \r\n if(length(p) > 1) { # パラメータ数が1より大きい場合,add.p.estの分,推定パラメータ数を増やす\r\n for (i in 1:(length(p)-1)){\r\n faa[add.p.est[i],ny] <- p[i]\r\n }\r\n naa[, ny] <- vpa.core.Pope(caa,faa,M,ny)\r\n for (i in (ny-1):(ny-na[ny]+1)){\r\n naa[1:na[i], i] <- backward.calc(caa,naa,M,na,i,min.caa=min.caa,plus.group=plus.group)\r\n faa[1:na[i], i] <- f.at.age(caa,naa,M,na,i,alpha=alpha)\r\n }\r\n } \r\n }\r\n\r\n if (!isTRUE(sel.update)){\r\n if (isTRUE(Pope)){\r\n for (i in (ny-1):1){\r\n naa[1:na[i], i] <- backward.calc(caa,naa,M,na,i,min.caa=min.caa,plus.group=plus.group)\r\n faa[1:na[i], i] <- f.at.age(caa,naa,M,na,i,alpha=alpha)\r\n }\r\n }\r\n else{\r\n for (i in (ny-1):1){\r\n for (j in 1:(na[i]-2)){\r\n faa[j, i] <- ik.est(caa,naa,M,j,i,min.caa=min.caa,maxit=maxit,d=d)\r\n }\r\n if (isTRUE(plus.group)) faa[na[i]-1, i] <- hira.est(caa,naa,M,na[i]-1,i,alpha=alpha,min.caa=min.caa,maxit=maxit,d=d)\r\n else faa[na[i]-1, i] <- ik.est(caa,naa,M,na[i]-1,i,min.caa=min.caa,maxit=maxit,d=d)\r\n faa[na[i], i] <- alpha*faa[na[i]-1, i]\r\n naa[1:na[i], i] <- vpa.core(caa,faa,M,i)\r\n }\r\n }\r\n\r\n if (is.na(naa[na[ny]-1,ny])){\r\n if(isTRUE(Pope)){\r\n for (i in (na[ny]-1):1){\r\n if (is.null(tf.mat)) faa[i, ny] <- get(stat.tf[i])(faa[i, years %in% tf.year]) \r\n else faa[i, ny] <- get(stat.tf[i])(faa[i, !is.na(tf.mat[i,])]) \r\n naa[i, ny] <- caa[i, ny]*exp(M[i, ny]/2)/(1-exp(-faa[i, ny]))\r\n k <- 0\r\n for (j in (i-1):1){\r\n k <- k + 1\r\n if (i-k > 0){\r\n naa[j,ny-k] <- naa[j+1,ny-k+1]*exp(M[j,ny-k])+caa[j,ny-k]*exp(M[j,ny-k]/2)\r\n faa[j,ny-k] <- -log(1-caa[j,ny-k]*exp(M[j,ny-k]/2)/naa[j,ny-k])\r\n } \r\n }\r\n }\r\n }\r\n else{\r\n for (i in (na[ny]-1):1){\r\n faa[i, ny] <- get(stat.tf[i])(faa[i, years %in% tf.year]) \r\n naa[i, ny] <- caa[i, ny]/(1-exp(-faa[i, ny]-M[i, ny]))*(faa[i, ny]+M[i, ny])/faa[i, ny]\r\n k <- 0\r\n for (j in (i-1):1){\r\n k <- k + 1\r\n if (i-k > 0){\r\n faa[j,ny-k] <- ik.est(caa,naa,M,j,ny-k,min.caa=min.caa,maxit=maxit,d=d)\r\n naa[j,ny-k] <- caa[j, ny-k]/(1-exp(-faa[j, ny-k]-M[j, ny-k]))*(faa[j, ny-k]+M[j, ny-k])/faa[j, ny-k]\r\n } \r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!is.null(rec)){\r\n naa[1, years %in% rec.year] <- rec\r\n if(isTRUE(Pope)) faa[1, years %in% rec.year] <- -as.numeric(log(1-caa[1, years %in% rec.year]/naa[1, years %in% rec.year]*exp(M[1, years %in% rec.year]/2)))\r\n else{ \r\n for (j in which(years %in% rec.year)){\r\n faa[1,j] <- f.forward.est(caa,naa,M,1,j,maxit=maxit,d=d)\r\n }\r\n }\r\n\r\n terminal.year <- as.numeric(years[ny])\r\n for (kk in 1:length(rec.year)){\r\n for (i in rec.year[kk]:terminal.year){\r\n if(terminal.year-i > 0 & i-rec.year[kk]+1 <= max(ages)){\r\n naa[i-rec.year[kk]+2, years %in% (i+1)] <- naa[i-rec.year[kk]+1, years %in% i]*exp(-faa[i-rec.year[kk]+1, years %in% i]-M[i-rec.year[kk]+1, years %in% i])\r\n if (isTRUE(Pope)) faa[i-rec.year[kk]+2, years %in% (i+1)] <- -log(1-caa[i-rec.year[kk]+2, years %in% (i+1)]/naa[i-rec.year[kk]+2, years %in% (i+1)]*exp(M[i-rec.year[kk]+2, years %in% (i+1)]/2))\r\n else {\r\n for (j in which(years %in% (i+1))){\r\n if(i-rec.year[kk]+2 < na[j]-1) faa[i-rec.year[kk]+2, j] <- f.forward.est(caa,naa,M,i-rec.year[kk]+2,j,maxit=maxit,d=d)\r\n if (isTRUE(plus.group)){\r\n if(i-rec.year[kk]+2 == na[j]-1) faa[i-rec.year[kk]+2, j] <- fp.forward.est(caa,naa,M,i-rec.year[kk]+2,j,alpha,maxit=maxit,d=d) \r\n if(i-rec.year[kk]+2 == na[j]) faa[i-rec.year[kk]+2, j] <- alpha*fp.forward.est(caa,naa,M,i-rec.year[kk]+1,j,alpha,maxit=maxit,d=d)\r\n } \r\n else{\r\n if(i-rec.year[kk]+2 == na[j]-1) faa[i-rec.year[kk]+2, j] <- f.forward.est(caa,naa,M,i-rec.year[kk]+2,j,maxit=maxit,d=d) \r\n if(i-rec.year[kk]+2 == na[j]) faa[i-rec.year[kk]+2, j] <- alpha*f.forward.est(caa,naa,M,i-rec.year[kk]+1,j,maxit=maxit,d=d) \r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n # next year\r\n\r\n if (isTRUE(tune)){\r\n if (n.add==1 & !is.na(mean(index[,ny+n.add],na.rm=TRUE))){\r\n \r\n new.naa <- forward.calc(faa,naa,M,na,ny+n.add)\r\n\r\n naa[,ny+n.add] <- new.naa\r\n baa <- naa*waa\r\n ssb <- baa*maa*exp(-ssb.coef*(faa+M))\r\n \r\n if (is.null(rec.new)) {\r\n new.naa[1] <- median((naa[1,]/colSums(ssb))[years %in% rps.year])*sum(ssb[,ny+n.add],na.rm=TRUE)\r\n }\r\n else new.naa[1] <- rec.new\r\n\r\n naa[1,ny+n.add] <- new.naa[1]\r\n baa[1,ny+n.add] <- naa[1,ny+n.add]*waa[1,ny+n.add]\r\n\r\n if (!is.null(f.new) & !is.null(saa.new)) faa[,ny+n.add] <- f.new*saa.new else faa[,ny+n.add] <- 0\r\n if (isTRUE(Pope)) caa[,ny+n.add] <- naa[,ny+n.add]*(1-exp(-faa[,ny+n.add]))*exp(-M[,ny+n.add]/2) else caa[,ny+n.add] <- naa[,ny+n.add]*(1-exp(-faa[,ny+n.add]-M[,ny+n.add]))*faa[,ny+n.add]/(faa[,ny+n.add]+M[,ny+n.add])\r\n \r\n ssb[1,ny+n.add] <- baa[1,ny+n.add]*maa[1,ny+n.add]*exp(-ssb.coef*(faa[1,ny+n.add]+M[1,ny+n.add]))\r\n\r\n if (ssb.lag==1) ssb <- cbind(NA, ssb[,-ncol(ssb)])\r\n }\r\n\r\n\r\n\r\n\r\n # tuning\r\n \r\n obj <- NULL\r\n\r\n if (tune){\r\n if (est.constraint | !is.null(fixed.index.var)){\r\n \r\n Abund <- NULL\r\n \r\n for (i in 1:nindex){\r\n abundance <- abund.extractor(abund=abund[i], naa, faa, dat, min.age=min.age[i], max.age=max.age[i], link=link[i], base=base[i], af=af[i], catch.prop=catch.prop, sel.def=sel.def, scale=scale)\r\n Abund <- rbind(Abund, abundance)\r\n }\r\n \r\n if (is.null(fixed.index.var)) est.qbs <- qbs.f(q.const, b.const, sigma.const, index, Abund, nindex, index.w, max.dd, max.iter) else {\r\n p00 <- c(log(q.const[which(index.w >0)]), log(sigma.const[which(index.w >0)]))\r\n est.qbs <- qbs.f2(p00, index, Abund, nindex, index.w, fixed.index.var)\r\n }\r\n \r\n q <- exp(est.qbs$q)\r\n b <- est.qbs$b \r\n sigma <- est.qbs$sigma\r\n obj <- est.qbs$obj\r\n convergence <- est.qbs$convergence\r\n obj0 <- obj\r\n \r\n rownames(Abund) <- 1:nindex\r\n }\r\n else{\r\n \r\n if (est.method==\"ls\")\r\n {\r\n Abund <- nn <- sigma <- b <- NULL\r\n for (i in 1:nindex)\r\n {\r\n abundance <- abund.extractor(abund=abund[i], naa, faa, dat, min.age=min.age[i], max.age=max.age[i], link=link[i], base=base[i], af=af[i], catch.prop=catch.prop, sel.def=sel.def, scale=scale)\r\n Abund <- rbind(Abund, abundance)\r\n avail <- which(!is.na(as.numeric(index[i,])))\r\n if (b.est)\r\n {\r\n if (is.null(b.fix))\r\n {\r\n b[i] <- cov(log(as.numeric(index[i,avail])),log(as.numeric(abundance[avail])))/var(log(as.numeric(abundance[avail])))\r\n }else\r\n {\r\n if (is.na(b.fix[i])) b[i] <- cov(log(as.numeric(index[i,avail])),log(as.numeric(abundance[avail])))/var(log(as.numeric(abundance[avail]))) else b[i] <- b.fix[i]\r\n }\r\n }else\r\n {\r\n if (is.null(b.fix)) b[i] <- 1 else b[i] <- b.fix[i]\r\n }\r\n if (is.null(q.fix))\r\n {\r\n q[i] <- exp(mean(log(as.numeric(index[i,avail]))-b[i]*log(as.numeric(abundance[avail]))))\r\n }else\r\n {\r\n q[i] <- q.fix[i]\r\n }\r\n obj <- c(obj,index.w[i]*sum((log(as.numeric(index[i,avail]))-log(q[i])-b[i]*log(as.numeric(abundance[avail])))^2))\r\n }\r\n }\r\n if (est.method==\"ml\")\r\n {\r\n if(!(length(sigma.constraint)==nindex))\r\n {\r\n stop(\"length of sigma constraint does not match the number of indices!!!!\")#sigma.constraintの長さがindexの本数と異なる場合にはエラーを出して停止。\r\n }\r\n Abund <- nn <- sigma <- b <- NULL\r\n for (i in 1:nindex)\r\n {\r\n abundance <- abund.extractor(abund=abund[i], naa, faa, dat, min.age=min.age[i], max.age=max.age[i], link=link[i], base=base[i], af=af[i], catch.prop=catch.prop, sel.def=sel.def, scale=scale)\r\n Abund <- rbind(Abund, abundance)\r\n avail <- which(!is.na(as.numeric(index[i,])))\r\n nn[i] <- length(avail)\r\n if (b.est)\r\n {\r\n if (is.null(b.fix))\r\n {\r\n b[i] <- cov(log(as.numeric(index[i,avail])),log(as.numeric(abundance[avail])))/var(log(as.numeric(abundance[avail])))\r\n }else\r\n {\r\n if (is.na(b.fix[i]))\r\n {\r\n b[i] <- cov(log(as.numeric(index[i,avail])),log(as.numeric(abundance[avail])))/var(log(as.numeric(abundance[avail])))\r\n }else\r\n {\r\n b[i] <- b.fix[i]\r\n }\r\n }\r\n }else\r\n {\r\n if (is.null(b.fix))\r\n {\r\n b[i] <- 1\r\n }else\r\n {\r\n b[i] <- b.fix[i]\r\n }\r\n }\r\n if (is.null(q.fix))\r\n {\r\n q[i] <- exp(mean(log(as.numeric(index[i,avail]))-b[i]*log(as.numeric(abundance[avail]))))\r\n }else\r\n {\r\n q[i] <- q.fix[i]\r\n }\r\n #sigma[i] <- sqrt(sum((log(as.numeric(index[i,avail]))-log(q[i])-b[i]*log(as.numeric(abundance[avail])))^2)/nn[i])\r\n #obj <- c(obj,index.w[i]*(-as.numeric(na.omit(dnorm(log(as.numeric(index[i,avail])),log(q[i])+b[i]*log(as.numeric(abundance[avail])),sigma[i],log=TRUE)))))\r\n }\r\n unique.sigma.constraint <- unique(sigma.constraint)\r\n for(i in 1:length(unique.sigma.constraint))\r\n {\r\n index.num <- which(sigma.constraint==unique.sigma.constraint[i])\r\n sq.error <- 0\r\n for(j in index.num)\r\n {\r\n abundance <- abund.extractor(abund=abund[j], naa, faa, dat, min.age=min.age[j], max.age=max.age[j], link=link[j], base=base[j], af=af[j], catch.prop=catch.prop, sel.def=sel.def, scale=scale)\r\n avail <- which(!is.na(as.numeric(index[j,])))\r\n sq.error <- sq.error + sum((log(as.numeric(index[j,avail]))-log(q[j])-b[j]*log(as.numeric(abundance[avail])))^2)\r\n }\r\n sigma[index.num] <- sqrt(sq.error/sum(nn[index.num]))\r\n }\r\n for (i in 1:nindex)\r\n {\r\n abundance <- abund.extractor(abund=abund[i], naa, faa, dat, min.age=min.age[i], max.age=max.age[i], link=link[i], base=base[i], af=af[i], catch.prop=catch.prop, sel.def=sel.def, scale=scale)\r\n obj <- c(obj,index.w[i]*(-as.numeric(na.omit(dnorm(log(as.numeric(index[i,avail])),log(q[i])+b[i]*log(as.numeric(abundance[avail])),sigma[i],log=TRUE)))))\r\n }\r\n }\r\n\r\n obj0 <- obj\r\n obj <- sum(obj)\r\n convergence <- 1\r\n saa <- sel.func(faa, def=sel.def)\r\n\r\n if (penalty==\"p\") obj <- (1-lambda)*obj + lambda*sum(p^beta) \r\n \r\n if (penalty==\"s\") obj <- (1-lambda)*obj + lambda*sum((abs(saa[,ny]-apply(saa[, years %in% tf.year],1,get(stat.tf))))^beta)\r\n \r\n if (!is.null(sel.rank)) obj <- obj+1000000*sum((rank(saa[,ny])-sel.rank)^2)\r\n \r\n rownames(Abund) <- 1:nindex\r\n } \r\n }\r\n }\r\n else {obj <- (p - alpha*faa[na[ny]-1, ny])^2; obj0 <- NA}\r\n \r\n #\r\n\r\n if (isTRUE(out)) {\r\n # next year\r\n\r\n if (n.add==1 & is.na(naa[1,ny+n.add])){\r\n new.naa <- forward.calc(faa,naa,M,na,ny+n.add)\r\n\r\n naa[,ny+n.add] <- new.naa\r\n baa <- naa*waa\r\n ssb <- baa*maa*exp(-ssb.coef*(faa+M))\r\n\r\n if (is.null(rec.new)) {\r\n new.naa[1] <- median((naa[1,]/colSums(ssb))[years %in% rps.year])*sum(ssb[,ny+n.add],na.rm=TRUE)\r\n } else new.naa[1] <- rec.new\r\n\r\n naa[1,ny+n.add] <- new.naa[1]\r\n baa[1,ny+n.add] <- naa[1,ny+n.add]*waa[1,ny+n.add]\r\n \r\n if (!is.null(f.new) & !is.null(saa.new)) faa[,ny+n.add] <- f.new*saa.new else faa[,ny+n.add] <- 0\r\n if (isTRUE(Pope)) caa[,ny+n.add] <- naa[,ny+n.add]*(1-exp(-faa[,ny+n.add]))*exp(-M[,ny+n.add]/2) else caa[,ny+n.add] <- naa[,ny+n.add]*(1-exp(-faa[,ny+n.add]-M[,ny+n.add]))*faa[,ny+n.add]/(faa[,ny+n.add]+M[,ny+n.add])\r\n \r\n ssb[1,ny+n.add] <- baa[1,ny+n.add]*maa[1,ny+n.add]*exp(-ssb.coef*(faa[1,ny+n.add]+M[1,ny+n.add]))\r\n\r\n if (ssb.lag==1) ssb <- cbind(NA, ssb[,-ncol(ssb)])\r\n } \r\n else {\r\n baa <- naa*waa\r\n ssb <- baa*maa*exp(-ssb.coef*(faa+M))\r\n if (ssb.lag==1) ssb <- cbind(NA, ssb[,-ncol(ssb)])\r\n }\r\n\r\n \r\n obj <- list(minimum=obj, minimum.c=obj0, caa=caa, naa=naa, faa=faa, baa=baa, ssb=ssb)\r\n if (isTRUE(eq.tf.mean)) obj$p <- max(faa[,ny],na.rm=TRUE)\r\n\r\n if (isTRUE(tune)) {\r\n if (est.method==\"ls\"){\r\n if (use.index[1]==\"all\") Nindex <- sum(!is.na(index[index.w > 0,])) else Nindex <- sum(!is.na(index[index.w[use.index > 0] > 0,])) \r\n Sigma2 <- obj$minimum/Nindex\r\n neg.logLik <- Nindex/2*log(2*pi*Sigma2)+Nindex/2\r\n obj$q <- q\r\n obj$b <- b\r\n obj$sigma <- sqrt(Sigma2)\r\n obj$convergence <- convergence \r\n obj$Abund <- Abund\r\n obj$logLik <- -neg.logLik\r\n }\r\n if (est.method==\"ml\"|est.constraint| !is.null(fixed.index.var)){\r\n if (est.constraint){\r\n names(q) <- q.const\r\n names(b) <- b.const \r\n names(sigma) <- sigma.const \r\n }\r\n obj$convergence <- convergence \r\n obj$q <- q\r\n obj$b <- b\r\n obj$sigma <- sigma\r\n obj$Abund <- Abund\r\n obj$logLik <- -obj$minimum\r\n } \r\n \r\n }\r\n }\r\n \r\n return(obj) # 目的関数を返す\r\n }\r\n\r\n\r\n########################################################################################\r\n\r\n # execution of optimization\r\n# if (isTRUE(ADMB)){\r\n# require(R2admb)\r\n# \r\n# index2 <- as.matrix(t(apply(index,1,function(x) ifelse(is.na(x),0,x))))\r\n# \r\n# Type <- ifelse(abund==\"SSB\", 1, ifelse(abund==\"B\",4,ifelse(abund==\"N\",3,2)))\r\n# \r\n# if(is.null(dat$maa.tune)) MAA <- as.matrix(dat$maa) else MAA <- as.matrix(dat$maa.tune)\r\n# if (is.na(af[1])) af <- rep(0,nindex)\r\n# \r\n# data2 <- list(A=nrow(dat$caa),Y=ncol(dat$caa),K=length(use.index),Est=ifelse(est.method==\"ls\",0,1),b_est=as.numeric(b.est),alpha=alpha,lambda=lambda,beta=beta,Type=Type,w=index.w,af=af,CATCH=as.matrix(dat$caa),WEI=as.matrix(dat$waa/scale),MAT=MAA,M=as.matrix(dat$M),CPUE=index2,MISS=ifelse(index2==0,1,0))\r\n# \r\n# init <- log(p.init)\r\n# \r\n# write_dat(\"vpa\",data2)\r\n# write_pin(\"vpa\",init)\r\n\r\n# system(\"vpa -nohess\")\r\n \r\n# summary.p.est <- read_pars(\"vpa\")\r\n# summary.p.est$estimate <- exp(summary.p.est$coeflist$log_F)\r\n# summary.p.est$minimum <- -summary.p.est$loglik \r\n# summary.p.est$gradient <- summary.p.est$maxgrad\r\n# summary.p.est$code <- 0\r\n# log.p.hat <- log(summary.p.est$estimate)\r\n# } else {\r\n if (isTRUE(TMB)){\r\n index2 <- as.matrix(t(apply(index,1,function(x) ifelse(is.na(x),0,x))))\r\n \r\n Ab_type <- ifelse(abund==\"SSB\", 1, ifelse(abund==\"N\", 2, 3))\r\n Ab_type_age <- ifelse(is.na(min.age),0,min.age)\r\n \r\n if(is.null(dat$maa.tune)) MAA <- as.matrix(dat$maa) else MAA <- as.matrix(dat$maa.tune)\r\n if (is.na(af[1])) af <- rep(0,nindex)\r\n \r\n if (isTRUE(b.est)) b_fix <- rep(0,nindex) else b_fix <- rep(1,nindex)\r\n b_fix <- ifelse(is.na(b.fix),b_fix,b.fix)\r\n \r\n data2 <- list(Est=ifelse(est.method==\"ls\",0,1),b_fix=as.numeric(b_fix),alpha=alpha,lambda=lambda,beta=beta,Ab_type=Ab_type,Ab_type_age=Ab_type_age,w=index.w,af=af,CATCH=t(as.matrix(dat$caa)),WEI=t(as.matrix(dat$waa)),MAT=t(MAA),M=t(as.matrix(dat$M)),CPUE=t(index2),MISS=t(ifelse(index2==0,1,0)),Last_Catch_Zero=ifelse(isTRUE(last.catch.zero),1,0))\r\n \r\n parameters <- list(\r\n log_F=log(p.init)\r\n )\r\n \r\n obj <- MakeADFun(data2, parameters, DLL=\"rvpa_tmb\")\r\n opt <- nlm(obj$fn, obj$par, gradient=obj$gr, hessian=hessian)\r\n \r\n summary.p.est <- list()\r\n summary.p.est$estimate <- exp(opt$estimate)\r\n summary.p.est$minimum <- -opt$minimum\r\n summary.p.est$gradient <- opt$gradient\r\n summary.p.est$code <- opt$code\r\n log.p.hat <- opt$estimate\r\n } else {\r\n if (isTRUE(no.est)){\r\n if (isTRUE(eq.tf.mean)) {\r\n summary.p.est <- p.est(log(p.init), out=TRUE)\r\n summary.p.est <- list(estimate=summary.p.est$p, minimum=p.est(log(summary.p.est$p)), gradient=NA, code=NA)\r\n log.p.hat <- log(summary.p.est$estimate)\r\n }else{\r\n summary.p.est <- list(estimate=log(p.init), minimum=p.est(log(p.init)), gradient=NA, code=NA)\r\n log.p.hat <- summary.p.est$estimate\r\n }\r\n }else{\r\n if (optimizer==\"nlm\") summary.p.est <- nlm(p.est, log(p.init), hessian=hessian)\r\n if (optimizer==\"nlminb\") {\r\n summary.p.est <- nlminb(log(p.init), p.est, hessian=hessian, lower=Lower, upper=Upper)\r\n summary.p.est$estimate <- summary.p.est$par\r\n summary.p.est$minimum <- summary.p.est$objective \r\n summary.p.est$gradient <- NA \r\n summary.p.est$code <- summary.p.est$convergence\r\n }\r\n log.p.hat <- summary.p.est$estimate\r\n }\r\n }\r\n\r\n gradient <- summary.p.est$gradient\r\n code <- summary.p.est$code\r\n message.nlminb <- summary.p.est$message\r\n \r\n np <- length(summary.p.est$estimate)\r\n\r\n out <- p.est(log.p.hat, out=TRUE)\r\n\r\n term.f <- exp(log.p.hat)\r\n \r\n # \r\n\r\n if(isTRUE(hessian)) hessian <- summary.p.est$hessian\r\n\r\n naa <- as.data.frame(out$naa)\r\n faa <- as.data.frame(out$faa)\r\n baa <- as.data.frame(out$baa)\r\n ssb <- as.data.frame(out$ssb)\r\n saa <- as.data.frame(sel.func(faa, def=sel.def))\r\n\r\n if(isTRUE(tune)){\r\n logLik <- out$logLik\r\n sigma <- out$sigma\r\n q <- out$q\r\n b <- out$b\r\n convergence <- out$convergence\r\n message <- message.nlminb\r\n pred.index <- q*out$Abund^b\r\n }\r\n else logLik <- sigma <- q <- b <- convergence <- message <- pred.index <- NULL\r\n\r\nFt <- mean(faa[,ny],na.rm=TRUE)\r\n Fc.at.age <- apply(faa[,years %in% fc.year,drop=FALSE],1,mean) # drop=FALSEで,行列のベクトル化を防ぐ\r\n Fc.mean <- mean(Fc.at.age,na.rm=TRUE)\r\n Fc.max <- max(Fc.at.age,na.rm=TRUE)\r\n\r\n res <- list(input=arglist, term.f=term.f, np=np, minimum=out$minimum, minimum.c=out$minimum.c, logLik=logLik, gradient=gradient, code=code, q=q, b=b, sigma=sigma, convergence=convergence, message=message, hessian=hessian, Ft=Ft, Fc.at.age=Fc.at.age, Fc.mean=Fc.mean, Fc.max=Fc.max, last.year=last.year, Pope=Pope, ssb.coef=ssb.coef, pred.index=pred.index, wcaa=caa*waa.catch,naa=naa, faa=faa, baa=baa, ssb=ssb, saa=saa)\r\n\r\n if (isTRUE(plot) & isTRUE(tune)){\r\n for (i in 1:nindex){\r\n Y <- years %in% plot.year\r\n Pred <- (index[i,Y]/q[i])^(1/b[i])\r\n plot(years[Y], Pred, ylim=range(Pred, out$Abund[i,Y], na.rm=TRUE),col=3,pch=16,xlab=\"Year\",ylab=paste(\"index\", i), main=abund[i])\r\n lines(years[Y],out$Abund[i,Y],col=2,lwd=2)\r\n }\r\n }\r\n return(invisible(res))\r\n\r\n \r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# profile likelihood (one parameter)\r\n\r\nprofile.likelihood.vpa <- function(res,Alpha=0.95,min.p=1.0E-6,max.p=1,L=20,method=\"ci\"){\r\n \r\n res.c <- res\r\n res.c$input$no.est <- TRUE\r\n res.c$input$plot <- FALSE\r\n\r\n like <- function(p,method=\"ci\") {\r\n res.c$input$p.init <- p\r\n\r\n res1 <- do.call(vpa,res.c$input)\r\n\r\n if (method==\"ci\") obj <- (-2*(res1$logLik - res$logLik)-qchisq(Alpha,1))^2\r\n# if (method==\"dist\") obj <- res1$logLik\r\n if (method==\"dist\"){ # 市野川変更\r\n obj <- list(logLik=res1$logLik,LLs=res1$minimum.c)\r\n }\r\n return(obj)\r\n }\r\n\r\n if (method==\"ci\"){\r\n res.lo <- nlminb(start=res$term.f*0.5, like, lower=0.001, upper=0.999*res$term.f, method=\"ci\")\r\n res.up <- nlminb(start=res$term.f*1.5, like, lower=1.001*res$term.f, upper=Inf, method=\"ci\")\r\n out <- list(lower=res.lo,upper=res.up,ci=c(res.lo$par, res.up$par))\r\n }\r\n if (method==\"dist\"){\r\n p0 <- seq(min.p,max.p,len=L)\r\n tmp <- lapply(p0, like, method=\"dist\")\r\n out <- list(logLik=sapply(tmp,function(x) x$logLik),\r\n \t\t\tLLs = sapply(tmp,function(x) x$LLs))\r\n out$TLL <- -out$logLik - min(-out$logLik)\r\n out$RLLs <- sweep(out$LLs,1,apply(out$LLs,1,min),FUN=\"-\")\r\n out$p0 <- p0\r\n# out <- p0 # 市野川変更\r\n }\r\n\r\n return(out)\r\n}\r\n\r\ndp.est <- function(p,res,Ref,target=\"F\",beta=1){\r\n res.c <- res\r\n res.c$input$no.est <- TRUE\r\n res.c$input$plot <- FALSE\r\n\r\n res.c$input$p.init <- p\r\n\r\n ny <- length(res.c$faa[1,])\r\n na <- length(res.c$faa[,ny])\r\n\r\n res1 <- do.call(vpa,res.c$input)\r\n\r\n if (target==\"B\") out <- -res1$logLik+beta*(sum(res1$baa[,ny])-Ref)^2\r\n if (target==\"F\") out <- -res1$logLik+beta*(res1$faa[na,ny]-Ref)^2\r\n\r\n return(out)\r\n}\r\n\r\npl.ci.dp <- function(res,target=\"F\",beta=10^5,Alpha=0.8,lo.p=0.1,up.p=2.0,lo.Ref=0.5,up.Ref=3,method=\"ci\"){\r\n res.c <- res\r\n res.c$input$no.est <- TRUE\r\n res.c$input$plot <- FALSE\r\n\r\n p.est <- function(Ref) optimize(dp.est,c(lo.p,up.p),res=res,Ref=Ref,target=target,beta=beta)$minimum\r\n\r\n ny <- length(res$faa[1,])\r\n na <- length(res$faa[,ny])\r\n\r\n if (target==\"F\") Ref0 <- res$faa[na,ny]\r\n if (target==\"B\") Ref0 <- sum(res$baa[,ny])\r\n\r\n like <- function(Ref,method=\"ci\") {\r\n\r\n p <- p.est(Ref)\r\n\r\n res.c$input$p.init <- p\r\n\r\n res1 <- do.call(vpa,res.c$input)\r\n \r\n if (method==\"ci\") obj <- -2*(res1$logLik - res$logLik)-qchisq(Alpha,1)\r\n if (method==\"dist\") obj <- res1$logLik\r\n return(obj)\r\n }\r\n\r\n if (method==\"ci\"){\r\n res.lo <- uniroot(like, lower=Ref0*lo.Ref, upper=Ref0, method=\"ci\")\r\n res.up <- uniroot(like, lower=Ref0, upper=Ref0*up.Ref, method=\"ci\")\r\n out <- list(lower=res.lo,upper=res.up,ci=c(res.lo$root, res.up$root))\r\n }\r\n if (method==\"dist\"){\r\n p0 <- seq(Ref0*lo.Ref,Ref0*up.Ref,len=L)\r\n out <- sapply(p0, like, method=\"dist\")\r\n }\r\n\r\n return(out)\r\n}\r\n\r\nprofile.likelihood.vpa.B <- function(res,Alpha=0.95,min.p=1.0E-6,max.p=1,L=20,method=\"ci\"){\r\n \r\n res.c <- res\r\n res.c$input$no.est <- TRUE\r\n\r\n like <- function(p,method=\"ci\") {\r\n\r\n Bm <- exp(p)\r\n\r\n p0 <- res.c$term.f\r\n\r\n f1 <- function(p0){\r\n res.c$input$p.init <- p0\r\n res1 <- do.call(vpa,res.c$input)\r\n (sum(res1$baa[,37])-Bm)^2\r\n }\r\n\r\n res1 <- nlm(f1,p0)\r\n\r\n res.c$input$p.init <- res1$estimate\r\n res1 <- do.call(vpa,res.c$input)\r\n \r\n if (method==\"ci\") obj <- (-2*(res1$logLik - res$logLik)-qchisq(Alpha,1))^2\r\n if (method==\"dist\") obj <- res1$logLik\r\n return(obj)\r\n }\r\n\r\n if (method==\"ci\"){\r\n res.lo <- nlminb(start=log(sum(res$baa[,37])*0.5), like, lower=-Inf, upper=log(sum(res$baa[,37])), method=\"ci\")\r\n res.up <- nlminb(start=log(sum(res$baa[,37])*1.5), like, lower=log(sum(res$baa[,37])), upper=Inf, method=\"ci\")\r\n out <- list(lower=res.lo,upper=res.up,ci=c(res.lo$par, res.up$par))\r\n }\r\n if (method==\"dist\"){\r\n p0 <- seq(min.p,max.p,len=L)\r\n out <- sapply(p0, like, method=\"dist\")\r\n }\r\n\r\n return(out)\r\n}\r\n\r\n# bootstrap\r\n\r\nboo.vpa <- function(res,B=5,method=\"p\",mean.correction=FALSE){\r\n ## method == \"p\": parametric bootstrap\r\n ## method == \"n\": non-parametric bootstrap\r\n ## method == \"r\": smoothed residual bootstrap-t\r\n\r\n index <- res$input$dat$index\r\n p.index <- res$pred.index\r\n resid <- log(as.matrix(index))-log(as.matrix(p.index))\r\n \r\n R <- nrow(resid)\r\n\r\n n <- apply(resid,1,function(x) sum(!is.na(x)))\r\n\r\n np <- res$np\r\n\r\n rs2 <- rowSums(resid^2, na.rm=TRUE)/(n-np)\r\n\r\n res.c <- res\r\n \r\n res.c$input$p.init <- res$term.f[1]\r\n \r\n b.index <- res$input$dat$index\r\n \r\n Res1 <- list()\r\n\r\n for (b in 1:B){\r\n print(b)\r\n\r\n for (i in 1:R){\r\n if (method==\"p\") b.index[i,!is.na(index[i,])] <- exp(log(p.index[i,!is.na(index[i,])]) + rnorm(sum(!is.na(index[i,])),0,sd=sqrt(rs2[i])))\r\n if (method==\"n\") b.index[i,!is.na(index[i,])] <- exp(log(p.index[i,!is.na(index[i,])]) + sample(resid[i,!is.na(index[i,])],length(index[i,!is.na(index[i,])]),replace=TRUE))\r\n if (isTRUE(mean.correction)) b.index[i,!is.na(index[i,])] <- b.index[i,!is.na(index[i,])]*exp(-rs2[i]/2)\r\n if (method==\"r\") {\r\n rs.d <- density(resid[i,!is.na(index[i,])])\r\n rs.db <- sample(rs.d$x,length(index[i,!is.na(index[i,])]),prob=rs.d$y,replace=TRUE)\r\n sd.j <- sd(rs.db)\r\n s.rs.b <- rs.db/sd.j\r\n b.index[i,!is.na(index[i,])] <- exp(log(p.index[i,!is.na(index[i,])]) + s.rs.b*sqrt(rs2[i]))\r\n }\r\n if (isTRUE(mean.correction)) b.index[i,!is.na(index[i,])] <- b.index[i,!is.na(index[i,])]*exp(-rs2[i]/2)\r\n }\r\n \r\n res.c$input$dat$index <- b.index\r\n\r\n res1 <- try(do.call(vpa,res.c$input))\r\n if(class(res1)==\"try-error\"){\r\n Res1[[b]] <- \"try-error\"\r\n }\r\n else{\r\n Res1[[b]] <- list(index=b.index,naa=res1$naa,baa=res1$baa,ssb=res1$ssb,faa=res1$faa,saa=res1$saa,\r\n Fc.at.age=res1$Fc.at.age,q=res1$q,b=res1$b,sigma=res1$sigma) # 2013.8.20追記(市野川)\r\n }\r\n }\r\n\r\n return(Res1)\r\n}\r\n\r\n# SR estimation\r\n\r\nSR.est.old <- function(res, model=\"BH\", method=\"log\", scale=1){\r\n SSB <- colSums(res$ssb,na.rm=TRUE)/scale\r\n R <- unlist(res$naa[1,])\r\n \r\n if (model==\"BH\"){\r\n res0 <- lm(SSB/R ~ SSB)\r\n\r\n a0 <- 1/res0$coef[1]\r\n b0 <- res0$coef[2]*a0\r\n }\r\n if (model==\"RI\"){\r\n res0 <- lm(log(R/SSB) ~ SSB)\r\n\r\n a0 <- exp(res0$coef[1])\r\n b0 <- -res0$coef[2]\r\n }\r\n\r\n p0 <- log(c(a0,b0)) \r\n\r\n data <- data.frame(SSB=SSB,R=R)\r\n\r\n if (model==\"BH\"){\r\n if (method==\"id\") res <- nls(R~exp(log.a)*SSB/(1+exp(log.b)*SSB), data, start=list(log.a=p0[1],log.b=p0[2]))\r\n if (method==\"log\") res <- nls(log(R)~log.a+log(SSB)-log(1+exp(log.b)*SSB), data, start=list(log.a=p0[1],log.b=p0[2]))\r\n }\r\n\r\n if (model==\"RI\"){\r\n if (method==\"id\") res <- nls(R~exp(log.a)*SSB*exp(-exp(log.b)*SSB), data, start=list(log.a=p0[1],log.b=p0[2]))\r\n if (method==\"log\") res <- nls(log(R)~log.a+log(SSB)-exp(log.b)*SSB, data, start=list(log.a=p0[1],log.b=p0[2]))\r\n }\r\n\r\n par <- exp(coef(res))\r\n names(par) <- c(\"a\",\"b\")\r\n\r\n out <- list(res=res, model=model, method=method, par=par)\r\n\r\n return(out)\r\n}\r\n\r\n# MSY estimation\r\n\r\nMSY.est <- function(res,model=\"schaefer\",r.fix=NULL,K.fix=NULL,p.init=NULL,scale=1,main=\"\"){\r\n B <- colSums(res$baa,na.rm=TRUE)/scale\r\n C <- colSums(res$input$dat$caa*res$input$dat$waa,na.rm=TRUE)/scale\r\n\r\n n <- length(B)\r\n\r\n if (C[n]==0) {n <- n-1; B <- B[1:n]; C <- C[1:n]}\r\n\r\n B2 <- B[2:n]\r\n B1 <- B[1:(n-1)]\r\n C1 <- C[1:(n-1)]\r\n \r\n S1 <- B2 - B1 + C1\r\n\r\n if (is.null(p.init)){\r\n if (model==\"schaefer\") {\r\n res0 <- lm(S1/B1 ~ B1)\r\n r0 <- res0$coef[1]\r\n K0 <- -r0/res0$coef[2]\r\n }\r\n if (model==\"fox\") {\r\n res0 <- lm(S1/B1 ~ log(B1))\r\n r0 <- res0$coef[1]\r\n K0 <- exp(-r0/res0$coef[2])\r\n }\r\n\r\n p0 <- log(c(max(r0, 0.001), max(K0, 100)))\r\n }\r\n else p0 <- p.init\r\n\r\n data <- data.frame(S1=S1,B1=B1)\r\n\r\n if (is.null(r.fix) & is.null(K.fix)){\r\n if (model==\"schaefer\") res <- nls(S1~exp(log.r)*B1*(1-B1/exp(log.K)), data, start=list(log.r=p0[1],log.K=p0[2]))\r\n if (model==\"fox\") res <- nls(S1~exp(log.r)*B1*(1-log(B1)/log.K), data, start=list(log.r=p0[1],log.K=p0[2]))\r\n\r\n p <- exp(coef(res))\r\n names(p) <- c(\"r\",\"K\")\r\n }\r\n else {\r\n if (!is.null(r.fix) & is.null(K.fix)){\r\n if (model==\"schaefer\") res <- nls(S1~r.fix*B1*(1-B1/exp(log.K)), data, start=list(log.K=p0[2]))\r\n if (model==\"fox\") res <- nls(S1~r.fix*B1*(1-log(B1)/log.K), data, start=list(log.K=p0[2]))\r\n\r\n p <- c(r.fix, exp(coef(res)))\r\n names(p) <- c(\"r\",\"K\")\r\n }\r\n if (is.null(r.fix) & !is.null(K.fix)){\r\n log.K <- log(K.fix)\r\n if (model==\"schaefer\") res <- nls(S1~exp(log.r)*B1*(1-B1/exp(log.K)), data, start=list(log.r=log(0.2)))\r\n if (model==\"fox\") res <- nls(S1~exp(log.r)*B1*(1-log(B1)/log.K), data, start=list(log.r=log(0.2)))\r\n\r\n p <- c(exp(coef(res)),exp(log.K))\r\n names(p) <- c(\"r\",\"K\")\r\n }\r\n if (!is.null(r.fix) & !is.null(K.fix)){\r\n res <- list()\r\n\r\n p <- c(r.fix, B[1])\r\n names(p) <- c(\"r\",\"K\")\r\n }\r\n }\r\n\r\n r <- p[1]\r\n K <- p[2]\r\n\r\n p.S1 <- predict(res)\r\n\r\n if (model==\"schaefer\") MSY <- c(r*K/4, K/2, r/2)\r\n if (model==\"fox\") MSY <- c(r*K/(log(K)*exp(1)), K/exp(1), r/log(K))\r\n names(MSY) <- c(\"MSY\",\"Bmsy\",\"Fmsy\")\r\n\r\n Assess <- c(B[n]/MSY[2], (C[n]/B[n])/MSY[3])\r\n names(Assess) <- c(\"Bcur/Bmsy\",\"Fcur/Fmsy\")\r\n\r\n # SP plot\r\n std.S <- (S1-mean(S1,na.rm=TRUE))/sd(S1,na.rm=TRUE)\r\n std.pS <- (p.S1-mean(S1,na.rm=TRUE))/sd(S1,na.rm=TRUE)\r\n std.MSY <- (MSY[1]-mean(S1,na.rm=TRUE))/sd(S1,na.rm=TRUE)\r\n std.C <- (C1-mean(S1,na.rm=TRUE))/sd(S1,na.rm=TRUE)\r\n\r\n plot(names(B1), std.S, pch=16, col=\"blue\", xlab=\"Year\", ylab=\"Standardized Surplus Production\", main=main, cex=1.5)\r\n lines(names(B1), std.pS , col=\"red\", lwd=2)\r\n abline(h=std.MSY, col=\"green\", lty=2, lwd=2)\r\n points(names(B1), std.C , pch=17, col=\"orange\", cex=1.5)\r\n\r\n Res <- list(B=B, C=C, S=S1, std.S=std.S, std.pS=std.pS, std.MSY=std.MSY, std.C=std.C, res=res, log.p = coef(res), p = p, vcov = vcov(res), MSY=MSY, Assess=Assess)\r\n\r\n return(Res)\r\n}\r\n\r\nSR.est.old <- function(res,model=\"BH\",k=1,p.init=NULL,lower.limit=-25,scale=1,main=NULL,log=FALSE){\r\n SSB <- colSums(res$ssb,na.rm=TRUE)/scale\r\n R <- res$naa[1,]/scale\r\n\r\n n <- length(R)\r\n\r\n R1 <- R[(1+k):n]\r\n SSB1 <- SSB[1:(n-k)]\r\n\r\n if (is.null(p.init)){\r\n if (model==\"BH\") {\r\n Y <- as.numeric(SSB1/R1)\r\n res0 <- lm(Y ~ SSB1)\r\n alpha <- 1/res0$coef[1]\r\n beta <- res0$coef[2]*alpha\r\n }\r\n if (model==\"RI\") {\r\n Y <- as.numeric(log(R1/SSB1))\r\n res0 <- lm(Y ~ SSB1)\r\n alpha <- exp(res0$coef[1])\r\n beta <- -res0$coef[2]\r\n }\r\n\r\n p0 <- log(c(max(alpha, 0.00000000001), max(beta, 0.00000000001)))\r\n }\r\n else p0 <- p.init\r\n\r\n data <- data.frame(R1=as.numeric(R1),SSB1=as.numeric(SSB1))\r\n\r\n if (isTRUE(log)){\r\n if (model==\"BH\") res <- nls(log(R1)~log.a+log(SSB1)-log(1+exp(log.b)*SSB1), data, start=list(log.a=p0[1],log.b=p0[2]), control=list(warnOnly=TRUE), lower=rep(lower.limit,2), algorithm=\"port\")\r\n if (model==\"RI\") res <- nls(log(R1)~log.a+log(SSB1)-exp(log.b)*SSB1, data, start=list(log.a=p0[1],log.b=p0[2]), control=list(warnOnly=TRUE), lower=rep(lower.limit,2), algorithm=\"port\")\r\n }\r\n else{\r\n if (model==\"BH\") res <- nls(R1~exp(log.a)*SSB1/(1+exp(log.b)*SSB1), data, start=list(log.a=p0[1],log.b=p0[2]), control=list(warnOnly=TRUE), lower=rep(lower.limit,2), algorithm=\"port\")\r\n if (model==\"RI\") res <- nls(R1~exp(log.a)*SSB1*exp(-exp(log.b)*SSB1), data, start=list(log.a=p0[1],log.b=p0[2]), control=list(warnOnly=TRUE), lower=rep(lower.limit,2), algorithm=\"port\")\r\n }\r\n\r\n p <- exp(coef(res))\r\n names(p) <- c(\"alpha\",\"beta\")\r\n\r\n if(is.null(main)) main <- model \r\n plot(SSB1,R1,xlab=\"SSB\",ylab=\"R\",xlim=c(0,max(SSB1)*1.05),ylim=c(0,max(R1)*1.05),main=main)\r\n \r\n x <- seq(0,max(SSB1),len=100)\r\n\r\n if(model==\"BH\") pred <- p[1]*x/(1+p[2]*x)\r\n if(model==\"RI\") pred <- p[1]*x*exp(-p[2]*x)\r\n\r\n lines(x,pred,col=\"red\",lwd=2)\r\n\r\n Res <- list(SSB=SSB1,R=R1, k=k, p=p)\r\n\r\n return(Res)\r\n}\r\n\r\n\r\nlogit <- function(x) log(x/(1-x))\r\n\r\n##\r\n\r\ncv.est <- function(res,n=5){\r\n\r\n nr <- ifelse(res$input$use.index==\"all\", 1:nrow(res$input$dat$index), res$input$use.index)\r\n nc <- ncol(res$input$dat$index)\r\n \r\n obj <- NULL\r\n \r\n for (i in 0:(n-1)){\r\n res.c <- res\r\n\r\n res.c$input$dat$index[,nc-i] <- NA\r\n res.c$input$plot <- FALSE\r\n# res.c$input$p.init <- res$term.f\r\n\r\n res1 <- do.call(vpa,res.c$input)\r\n\r\n if (abs(res1$gradient) < 10^(-3)){\r\n obj <- c(obj,mean(dnorm(log(res$input$dat$index[nr,nc-i]),log(res1$pred[,nc-i]),res1$sigma,log=TRUE),na.rm=TRUE))\r\n }\r\n }\r\n \r\n return(mean(obj,na.rm=TRUE))\r\n}\r\n\r\nretro.est <- function(res,n=5,stat=\"mean\",init.est=FALSE, b.fix=TRUE){\r\n res.c <- res\r\n res.c$input$plot <- FALSE\r\n Res <- list()\r\n obj.n <- obj.b <- obj.s <- obj.r <- obj.f <- NULL\r\n \r\n if (isTRUE(b.fix)){\r\n res.c$input$b.fix <- res$b\r\n res.c$input$b.est <- FALSE\r\n }\r\n \r\n if (res$input$last.catch.zero) res.c$input$last.catch.zero <- FALSE\r\n \r\n for (i in 1:n){\r\n nc <- ncol(res.c$input$dat$caa)\r\n \r\n res.c$input$dat$caa <- res.c$input$dat$caa[,-nc]\r\n res.c$input$dat$maa <- res.c$input$dat$maa[,-nc]\r\n res.c$input$dat$maa.tune <- res.c$input$dat$maa.tune[,-nc]\r\n res.c$input$dat$waa <- res.c$input$dat$waa[,-nc]\r\n res.c$input$dat$M <- res.c$input$dat$M[,-nc]\r\n res.c$input$dat$index <- res.c$input$dat$index[,-nc,drop=FALSE]\r\n res.c$input$dat$catch.prop <- res.c$input$dat$catch.prop[,-nc]\r\n \r\n res.c$input$tf.year <- res.c$input$tf.year-1\r\n res.c$input$fc.year <- res.c$input$fc.year-1\r\n \r\n if (isTRUE(init.est)) res.c$input$p.init <- res.c$term.f\r\n \r\n res1 <- do.call(vpa,res.c$input)\r\n\r\n Res[[i]] <- res1\r\n \r\n if ((max(abs(res1$gradient)) < 10^(-3) & !isTRUE(res1$input$TMB)) | (max(abs(res1$gradient)) > 0 & max(abs(res1$gradient)) < 10^(-3) & isTRUE(res1$input$TMB)) | (is.na(max(abs(res1$gradient))) & res1$input$optimizer==\"nlminb\")){\r\n obj.n <- c(obj.n, (sum(res1$naa[,nc-1])-sum(res$naa[,nc-1]))/sum(res$naa[,nc-1]))\r\n obj.b <- c(obj.b, (sum(res1$baa[,nc-1])-sum(res$baa[,nc-1]))/sum(res$baa[,nc-1]))\r\n obj.s <- c(obj.s, (sum(res1$ssb[,nc-1])-sum(res$ssb[,nc-1]))/sum(res$ssb[,nc-1]))\r\n obj.r <- c(obj.r, (res1$naa[1,nc-1]-res$naa[1,nc-1])/res$naa[1,nc-1])\r\n obj.f <- c(obj.f, (sum(res1$faa[,nc-1])-sum(res$faa[,nc-1]))/sum(res$faa[,nc-1]))\r\n } else {\r\n obj.n <- c(obj.n, NA)\r\n obj.b <- c(obj.b, NA)\r\n obj.s <- c(obj.s, NA)\r\n obj.r <- c(obj.r, NA)\r\n obj.f <- c(obj.f, NA)\r\n }\r\n }\r\n \r\n mohn <- c(get(stat)(obj.n,na.rm=TRUE),get(stat)(obj.b,na.rm=TRUE),get(stat)(obj.s,na.rm=TRUE),get(stat)(obj.r,na.rm=TRUE),get(stat)(obj.f,na.rm=TRUE))\r\n \r\n names(mohn) <- c(\"N\",\"B\",\"SSB\",\"R\",\"F\")\r\n \r\n return(list(Res=Res,retro.n=obj.n, retro.b=obj.b, retro.s=obj.s, retro.r=obj.r, retro.f=obj.f, mohn=mohn))\r\n}\r\n\r\n#最新年の漁獲量が0の場合 (last.zero.catch=0)、最新年のFが0となり、加入量も推定できないため、もう1年前の推定値でMohn's rhoを計算するための関数\r\nretro.est2 <- function(res,n=5,stat=\"mean\",init.est=FALSE, b.fix=TRUE){\r\n res.c <- res\r\n res.c$input$plot <- FALSE\r\n Res <- list()\r\n obj.n <- obj.b <- obj.s <- obj.r <- obj.f <- NULL\r\n \r\n if (isTRUE(b.fix)){\r\n res.c$input$b.fix <- res$b\r\n res.c$input$b.est <- FALSE\r\n }\r\n \r\n for (i in 1:n){\r\n nc <- ncol(res.c$input$dat$caa)\r\n \r\n res.c$input$dat$caa <- res.c$input$dat$caa[,-nc]\r\n res.c$input$dat$maa <- res.c$input$dat$maa[,-nc]\r\n res.c$input$dat$maa.tune <- res.c$input$dat$maa.tune[,-nc]\r\n res.c$input$dat$waa <- res.c$input$dat$waa[,-nc]\r\n res.c$input$dat$M <- res.c$input$dat$M[,-nc]\r\n res.c$input$dat$index <- res.c$input$dat$index[,-nc,drop=FALSE]\r\n res.c$input$dat$catch.prop <- res.c$input$dat$catch.prop[,-nc]\r\n \r\n res.c$input$tf.year <- res.c$input$tf.year-1\r\n res.c$input$fc.year <- res.c$input$fc.year-1\r\n \r\n if (isTRUE(init.est)) res.c$input$p.init <- res.c$term.f\r\n \r\n if (res.c$input$last.catch.zero) {res.c$input$dat$caa[,nc-1] <- 0; Y <- nc-2} else Y <- nc-1\r\n \r\n res1 <- do.call(vpa,res.c$input)\r\n\r\n Res[[i]] <- res1\r\n\r\n if ((max(abs(res1$gradient)) < 10^(-3) & !isTRUE(res1$input$ADMB)) | (max(abs(res1$gradient)) > 0 & max(abs(res1$gradient)) < 10^(-3) & isTRUE(res1$input$ADMB)) | (is.na(max(abs(res1$gradient))) & res1$input$optimizer==\"nlminb\")){\r\n obj.n <- c(obj.n, (sum(res1$naa[,Y])-sum(res$naa[,Y]))/sum(res$naa[,Y]))\r\n obj.b <- c(obj.b, (sum(res1$baa[,Y])-sum(res$baa[,Y]))/sum(res$baa[,Y]))\r\n obj.s <- c(obj.s, (sum(res1$ssb[,Y])-sum(res$ssb[,Y]))/sum(res$ssb[,Y]))\r\n obj.r <- c(obj.r, (res1$naa[1,Y]-res$naa[1,Y])/res$naa[1,Y])\r\n obj.f <- c(obj.f, (sum(res1$faa[,Y])-sum(res$faa[,Y]))/sum(res$faa[,Y]))\r\n } else {\r\n obj.n <- c(obj.n, NA)\r\n obj.b <- c(obj.b, NA)\r\n obj.s <- c(obj.s, NA)\r\n obj.r <- c(obj.r, NA)\r\n obj.f <- c(obj.f, NA)\r\n }\r\n }\r\n \r\n mohn <- c(get(stat)(obj.n,na.rm=TRUE),get(stat)(obj.b,na.rm=TRUE),get(stat)(obj.s,na.rm=TRUE),get(stat)(obj.r,na.rm=TRUE),get(stat)(obj.f,na.rm=TRUE))\r\n \r\n names(mohn) <- c(\"N\",\"B\",\"SSB\",\"R\",\"F\")\r\n \r\n return(list(Res=Res,retro.n=obj.n, retro.b=obj.b, retro.s=obj.s, retro.r=obj.r, retro.f=obj.f, mohn=mohn))\r\n}\r\n\r\n", "meta": {"hexsha": "3d7dc095985c981dda994b767b8e7e9cef1f7915", "size": 60410, "ext": "r", "lang": "R", "max_stars_repo_path": "4-akita/rvpa1.9.2.r", "max_stars_repo_name": "ichimomo/Shigen-kensyu-2018", "max_stars_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2018-12-17T07:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T04:22:43.000Z", "max_issues_repo_path": "4-akita/rvpa1.9.2.r", "max_issues_repo_name": "ichimomo/Shigen-kensyu-2018", "max_issues_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "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": "4-akita/rvpa1.9.2.r", "max_forks_repo_name": "ichimomo/Shigen-kensyu-2018", "max_forks_repo_head_hexsha": "7469078a0d19f00837b5cba7d1c2b5ec5d3c3e21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-01-20T02:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-24T09:09:31.000Z", "avg_line_length": 35.5352941176, "max_line_length": 422, "alphanum_fraction": 0.5356729018, "num_tokens": 22801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3041835981678674}} {"text": "model_updateleafflag <- function (cumulTT = 741.510096671757,\n leafNumber = 8.919453833361189,\n calendarMoments = c('Sowing'),\n calendarDates = c('2007/3/21'),\n calendarCumuls = c(0.0),\n currentdate = '2007/4/29',\n finalLeafNumber = 8.797582013199484,\n hasFlagLeafLiguleAppeared_t1 = 1,\n phase = 1.0){\n #'- Name: UpdateLeafFlag -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: UpdateLeafFlag 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: tells if flag leaf has appeared and update the calendar if so\n #' \t\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 #' ** uri : some url\n #' ** inputtype : variable\n #' * name: leafNumber\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 8.919453833361189\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: currentdate\n #' ** description : current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DATE\n #' ** default : 2007/4/29\n #' ** unit : \n #' ** uri : some url\n #' ** inputtype : variable\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: hasFlagLeafLiguleAppeared_t1\n #' ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber)\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 1\n #' ** unit : \n #' ** uri : some url\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 #' ** uri : some url\n #' ** inputtype : variable\n #'- outputs:\n #' * name: hasFlagLeafLiguleAppeared\n #' ** description : true if flag leaf has appeared (leafnumber reached finalLeafNumber)\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\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 hasFlagLeafLiguleAppeared <- 0\n if (phase >= 1.0 && phase < 4.0)\n {\n if (leafNumber > 0.0)\n {\n if (hasFlagLeafLiguleAppeared == 0 && (finalLeafNumber > 0.0 && leafNumber >= finalLeafNumber))\n {\n hasFlagLeafLiguleAppeared <- 1\n if (!('FlagLeafLiguleJustVisible' %in% calendarMoments))\n {\n calendarMoments <- c(calendarMoments, 'FlagLeafLiguleJustVisible')\n calendarCumuls <- c(calendarCumuls, cumulTT)\n calendarDates <- c(calendarDates, currentdate)\n }\n }\n }\n }\n return (list (\"hasFlagLeafLiguleAppeared\" = hasFlagLeafLiguleAppeared,\"calendarMoments\" = calendarMoments,\"calendarDates\" = calendarDates,\"calendarCumuls\" = calendarCumuls))\n}", "meta": {"hexsha": "5b3a16d1f37f6f2d9783feb1d75ff8678eefd528", "size": 7492, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Updateleafflag.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/Updateleafflag.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/Updateleafflag.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": 52.7605633803, "max_line_length": 177, "alphanum_fraction": 0.3796049119, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3036429565362066}} {"text": "#' Graph rewiring algorithms\n#'\n#' Changes the structure of a graph by altering ties.\n#'\n#' @inheritParams rgraph_ws\n#' @templateVar undirected TRUE\n#' @template graph_template\n#' @param p Either a [0,1] vector with rewiring probabilities (\\code{algorithm=\"endpoints\"}),\n#' or an integer vector with number of iterations (\\code{algorithm=\"swap\"}).\n#' @param copy.first Logical scalar. When \\code{TRUE} and \\code{graph} is dynamic uses\n#' the first slice as a baseline for the rest of slices (see details).\n#' @param pr.change Numeric scalar. Probability ([0,1]) of doing a rewire (see details).\n#' @param algorithm Character scalar. Either \\code{\"swap\"}, \\code{\"endpoints\"}, or \\code{\"qap\"}\n#' (see \\code{\\link{rewire_qap}}).\n#' @param althexagons Logical scalar. When \\code{TRUE} uses the compact alternating\n#' hexagons algorithm (currently ignored [on development]).\n#' @details\n#' The algorithm \\code{\"qap\"} is described in \\code{\\link{rewire_qap}}, and only\n#' uses \\code{graph} from the arguments (since it is simply relabelling the graph).\n#'\n#'\n#' In the case of \"swap\" and \"endpoints\", both algorithms are implemented\n#' sequentially, this is, edge-wise checking self edges and multiple edges over\n#' the changing graph; in other words, at step\n#' \\eqn{m} (in which either a new endpoint or edge is chosen, depending on the algorithm),\n#' the algorithms verify whether the proposed change creates either multiple edges\n#' or self edges using the resulting graph at step \\eqn{m-1}.\n#'\n#' The main difference between the two algorithms is that the \\code{\"swap\"} algorithm\n#' preserves the degree sequence of the graph and \\code{\"endpoints\"} does not.\n#' The \\code{\"swap\"} algorithm is specially useful to asses the non-randomness of\n#' a graph's structural properties, furthermore it is this algorithm the one used\n#' in the \\code{\\link{struct_test}} routine implemented in \\pkg{netdiffuseR}.\n#'\n#' Rewiring assumes a weighted network, hence \\eqn{G(i,j) = k = G(i',j')},\n#' where \\eqn{i',j'} are the new end points of the edge and \\eqn{k} may not be equal\n#' to one.\n#'\n#' In the case of dynamic graphs, when \\code{copy.first=TRUE}, after rewiring the\n#' first slice--\\eqn{t=1}--the rest of slices are generated by rewiring the rewired\n#' version of the first slice. Formally:\n#'\n#' \\deqn{%\n#' G(t)' = \\left\\{\\begin{array}{ll}\n#' R(G(t)) & \\mbox{if }t=1 \\\\\n#' R(G(1)') & \\mbox{otherwise}\n#' \\end{array}\n#' \\right.\n#' }{%\n#' G(t)' = R(G(t)) if t=1,\n#' R(G(1)') otherwise\n#' }\n#'\n#' Where \\eqn{G(t)} is the t-th slice, \\eqn{G(t)'} is the t-th rewired slice, and\n#' \\eqn{R} is the rewiring function. Otherwise, \\code{copy.first=FALSE} (default),\n#' The rewiring function is simply \\eqn{G(t)' = R(G(t))}.\n#'\n#' The following sections describe the way both algorithms were implemented.\n#'\n#' @section \\emph{Swap} algorithm:\n#' The \\code{\"swap\"} algorithm chooses randomly two edges \\eqn{(a,b)} and\n#' \\eqn{(c,d)} and swaps the 'right' endpoint of boths such that we get\n#' \\eqn{(a,d)} and \\eqn{(c,b)} (considering self and multiple edges).\n#'\n#' Following Milo et al. (2004) testing procedure, the algorithm shows to be\n#' well behaved in terms of been unbiased, so after each iteration each possible\n#' structure of the graph has the same probability of been generated. The algorithm\n#' has been implemented as follows:\n#'\n#' Let \\eqn{E} be the set of edges of the graph \\eqn{G}. For \\eqn{i=1} to \\eqn{p}, do:\n#' \\enumerate{\n#' \\item With probability \\code{1-pr.change} got to the last step.\n#' \\item Choose \\eqn{e0=(a, b)} from \\eqn{E}. If \\code{!self & a == b} then go to the last step.\n#' \\item Choose \\eqn{e1=(c, d)} from \\eqn{E}. If \\code{!self & c == d } then go to the last step.\n#' \\item Define \\eqn{e0'=(a, d)} and \\eqn{e1' = (c, b)}. If \\code{!multiple & [G[e0']!= 0 | G[e1'] != 0]} then go to the last step.(*)\n#' \\item Define \\eqn{v0 = G[e0]} and \\eqn{v1 = G[e1]}, set \\eqn{G[e0]=0} and \\eqn{G[e1]=0}\n#' (and the same to the diagonally opposed coordinates in the case of undirected graphs)\n#' \\item Set \\eqn{G[e0'] = v0} and \\eqn{G[e1'] = v1} (and so with the diagonally opposed coordinates\n#' in the case of undirected graphs).\n#' \\item Next i.\n#' }\n#'\n#' (*) When \\code{althexagons=TRUE}, the algorithm changes and applies what Rao et al.\n#' (1996) describe as Compact Alternating Hexagons. This modification assures the\n#' algorithm to be able to achieve any structure. The algorithm consists on doing\n#' the following swapping: \\eqn{(i1i2,i1i3,i2i3,i2i1,i3i1,i3i2)} with values\n#' \\eqn{(1,0,1,0,1,0)} respectively with \\eqn{i1!=i2!=i3}. See the examples and\n#' references.\n#'\n#' In Milo et al. (2004) is suggested that in order for the rewired graph to be independent\n#' from the original one researchers usually iterate around \\code{nlinks(graph)*100}\n#' times, so \\code{p=nlinks(graph)*100}. On the other hand in Ray et al (2012)\n#' it is shown that in order to achive such it is needed to perform\n#' \\code{nlinks(graph)*log(1/eps)}, where \\code{eps}\\eqn{\\sim}1e-7, in other words,\n#' around \\code{nlinks(graph)*16}. We set the default to be 20.\n#'\n#' In the case of Markov chains, the variable \\code{pr.change} allows making the\n#' algorithm aperiodic. This is relevant only if the\n#' probability self-loop to a particular state is null, for example, if\n#' we set \\code{self=TRUE} and \\code{muliple=TRUE}, then in every step the\n#' algorithm will be able to change the state. For more details see\n#' Stanton and Pinar (2012) [p. 3.5:9].\n#'\n#'\n#' @section \\emph{Endpoints} algorithm:\n#'\n#' This reconnect either one or both of the endpoints of the edge randomly. As a big\n#' difference with the swap algorithm is that this does not preserves the degree\n#' sequence of the graph (at most the outgoing degree sequence). The algorithm is\n#' implemented as follows:\n#'\n#' Let \\eqn{G} be the baseline graph and \\eqn{G'} be a copy of it. Then, For \\eqn{l=1} to \\eqn{|E|} do:\n#'\n#' \\enumerate{\n#' \\item Pick the \\eqn{l}-th edge from \\eqn{E}, define it as \\eqn{e = (i,j)}.\n#' \\item Draw \\eqn{r} from \\eqn{U(0,1)}, if \\eqn{r > p} go to the last step.\n#' \\item If \\code{!undirected & i < j} go to the last step.\n#' \\item Randomly select a vertex \\eqn{j'} (and \\eqn{i'} if \\code{both_ends==TRUE}).\n#' And define \\eqn{e'=(i, j')} (or \\eqn{e'=(i', j')} if \\code{both_ends==TRUE}).\n#' \\item If \\code{!self &} \\code{i==j}' (or if \\code{both_ends==TRUE & i'==j'}) go to the last step.\n#' \\item If \\code{!multiple & G'[e']!= 0} then go to the last step.\n#' \\item Define \\eqn{v = G[e]}, set \\eqn{G'[e] = 0} and \\eqn{G'[e'] = v} (and the\n#' same to the diagonally opposed coordinates in the case of undirected graphs).\n#' \\item Next \\eqn{l}.\n#' }\n#'\n#' The endpoints algorithm is used by default in \\code{\\link{rdiffnet}} and used\n#' to be the default in \\code{\\link{struct_test}} (now \\code{swap} is the default).\n#'\n#' @references\n#' Watts, D. J., & Strogatz, S. H. (1998). Collectivedynamics of \"small-world\" networks.\n#' Nature, 393(6684), 440–442. \\doi{10.1038/30918}\n#'\n#' Milo, R., Kashtan, N., Itzkovitz, S., Newman, M. E. J., & Alon, U.\n#' (2004). On the uniform generation of random graphs with prescribed degree sequences.\n#' Arxiv Preprint condmat0312028, cond-mat/0, 1–4. Retrieved from\n#' \\url{https://arxiv.org/abs/cond-mat/0312028}\n#'\n#' Ray, J., Pinar, A., and Seshadhri, C. (2012).\n#' Are we there yet? When to stop a Markov chain while generating random graphs.\n#' pages 1–21.\n#'\n#' Ray, J., Pinar, A., & Seshadhri, C. (2012). Are We There Yet? When to Stop a\n#' Markov Chain while Generating Random Graphs. In A. Bonato & J. Janssen (Eds.),\n#' Algorithms and Models for the Web Graph (Vol. 7323, pp. 153–164).\n#' Berlin, Heidelberg: Springer Berlin Heidelberg.\n#' \\doi{10.1007/978-3-642-30541-2}\n#'\n#' A . Ramachandra Rao, R. J. and S. B. (1996). A Markov Chain Monte Carlo Method\n#' for Generating Random ( 0 , 1 ) -Matrices with Given Marginals. The Indian\n#' Journal of Statistics, 58, 225–242.\n#'\n#' Stanton, I., & Pinar, A. (2012). Constructing and sampling graphs with a\n#' prescribed joint degree distribution. Journal of Experimental Algorithmics,\n#' 17(1), 3.1. \\doi{10.1145/2133803.2330086}\n#'\n#' @family simulation functions\n#' @export\n#' @author George G. Vega Yon\n#' @examples\n#' # Checking the consistency of the \"swap\" ------------------------------------\n#'\n#' # A graph with known structure (see Milo 2004)\n#' n <- 5\n#' x <- matrix(0, ncol=n, nrow=n)\n#' x <- as(x, \"dgCMatrix\")\n#' x[1,c(-1,-n)] <- 1\n#' x[c(-1,-n),n] <- 1\n#'\n#' x\n#'\n#' # Simulations (increase the number for more precision)\n#' set.seed(8612)\n#' nsim <- 1e4\n#' w <- sapply(seq_len(nsim), function(y) {\n#' # Creating the new graph\n#' g <- rewire_graph(x,p=nlinks(x)*100, algorithm = \"swap\")\n#'\n#' # Categorizing (tag of the generated structure)\n#' paste0(as.vector(g), collapse=\"\")\n#' })\n#'\n#' # Counting\n#' coded <- as.integer(as.factor(w))\n#'\n#' plot(table(coded)/nsim*100, type=\"p\", ylab=\"Frequency %\", xlab=\"Class of graph\", pch=3,\n#' main=\"Distribution of classes generated by rewiring\")\n#'\n#' # Marking the original structure\n#' baseline <- paste0(as.vector(x), collapse=\"\")\n#' points(x=7,y=table(as.factor(w))[baseline]/nsim*100, pch=3, col=\"red\")\n#'\n# ' # Compact Alternating Hexagons ----------------------------------------------\n# ' x <- matrix(c(0,0,1,1,0,0,0,1,0), ncol=3, nrow=3)\n# '\n# ' set.seed(123)\n# ' nsim <- 1e4\n# ' w <- sapply(seq_len(nsim), function(y) {\n# ' g <- rewire_graph(x,p=nlinks(x)*20, algorithm = \"swap\", althexagons=TRUE)\n# ' paste0(as.vector(g), collapse=\"\")\n# ' })\n# '\n# ' # Counting\n# ' coded <- as.integer(as.factor(w))\n# '\n# ' plot(table(coded)/nsim*100, type=\"p\", ylab=\"Frequency %\", xlab=\"Class of graph\", pch=3,\n# ' main=\"Distribution of classes generated by rewiring\")\n# '\n# ' # Marking the original structure\n# ' baseline <- paste0(as.vector(x), collapse=\"\")\n# ' points(x=7,y=table(as.factor(w))[baseline]/nsim*100, pch=3, col=\"red\")\nrewire_graph <- function(graph, p,\n algorithm=\"endpoints\",\n both.ends=FALSE, self=FALSE, multiple=FALSE,\n undirected=getOption(\"diffnet.undirected\"),\n pr.change= ifelse(self, 0.5, 1),\n copy.first=TRUE, althexagons=FALSE) {\n\n # Checking undirected (if exists)\n checkingUndirected(graph)\n\n # althexagons is still on development\n if (althexagons) {\n althexagons <- FALSE\n warning(\"The option -althexagons- is still on development. So it has been set to FALSE.\")\n }\n\n # Checking copy.first\n # if (missing(copy.first)) copy.first <- FALSE\n\n cls <- class(graph)\n out <- if (\"dgCMatrix\" %in% cls) {\n rewire_graph.dgCMatrix(graph, p, algorithm, both.ends, self, multiple, undirected, pr.change, althexagons)\n } else if (\"list\" %in% cls) {\n rewire_graph.list(graph, p, algorithm, both.ends, self, multiple, undirected, pr.change, copy.first, althexagons)\n } else if (\"matrix\" %in% cls) {\n rewire_graph.dgCMatrix(\n methods::as(graph, \"dgCMatrix\"), p, algorithm, both.ends, self, multiple, undirected, pr.change, althexagons)\n } else if (\"diffnet\" %in% cls) {\n rewire_graph.list(graph$graph, p, algorithm, both.ends, self, multiple,\n graph$meta$undirected, pr.change, copy.first, althexagons)\n } else if (\"array\" %in% cls) {\n rewire_graph.array(graph, p, algorithm, both.ends, self, multiple, undirected, pr.change, copy.first, althexagons)\n } else stopifnot_graph(graph)\n\n # If diffnet, then it must return the same object but rewired, and change\n # the attribute of directed or not\n if (inherits(graph, \"diffnet\")) {\n graph$meta$undirected <- undirected\n graph$graph <- out\n return(graph)\n }\n\n attr(out, \"undirected\") <- FALSE\n\n return(out)\n}\n\n# @rdname rewire_graph\nrewire_graph.list <- function(graph, p, algorithm, both.ends, self, multiple, undirected,\n pr.change, copy.first, althexagons) {\n t <- length(graph)\n out <- graph\n\n # Names\n tn <- names(graph)\n if (!length(tn)) tn <- 1:t\n names(out) <- tn\n\n # Checking p\n if (length(p)==1)\n p <- rep(p, t)\n\n for (i in 1:t) {\n\n # Copy replaces the first from 2 to T with 1\n j <- ifelse(copy.first, 1, i)\n\n out[[i]] <- if (algorithm == \"endpoints\")\n rewire_endpoints(out[[j]], p[i], both.ends, self, multiple, undirected)\n else if (algorithm == \"swap\")\n rewire_swap(out[[j]], p[i], self, multiple, undirected, pr.change) #, althexagons)\n else if (algorithm == \"qap\")\n rewire_qap(out[[j]])\n else stop(\"No such rewiring algorithm: \", algorithm)\n\n # Names\n rn <- rownames(graph[[i]])\n if (!length(rn)) rn <- 1:nrow(graph[[i]])\n dimnames(out[[i]]) <- list(rn, rn)\n }\n\n out\n}\n\n# @rdname rewire_graph\nrewire_graph.dgCMatrix <- function(graph, p, algorithm, both.ends, self, multiple, undirected, pr.change, althexagons) {\n out <- if (algorithm == \"endpoints\")\n rewire_endpoints(graph, p, both.ends, self, multiple, undirected)\n else if (algorithm == \"swap\")\n rewire_swap(graph, p, self, multiple, undirected, pr.change) #, althexagons)\n else if (algorithm == \"qap\")\n rewire_qap(graph)\n else stop(\"No such rewiring algorithm: \", algorithm)\n\n rn <- rownames(out)\n if (!length(rn)) rn <- 1:nrow(out)\n dimnames(out) <- list(rn, rn)\n out\n}\n\n# @rdname rewire_graph\nrewire_graph.array <-function(graph, p, algorithm, both.ends, self, multiple, undirected,\n pr.change, copy.first, althexagons) {\n n <- dim(graph)[1]\n t <- dim(graph)[3]\n out <- apply(graph, 3, methods::as, Class=\"dgCMatrix\")\n\n # Checking time names\n tn <- dimnames(graph)[[3]]\n if (!length(tn)) tn <- 1:t\n names(out) <- tn\n\n return(rewire_graph.list(out, p, algorithm, both.ends, self, multiple, undirected,\n pr.change, copy.first, althexagons))\n}\n\n#' Permute the values of a matrix\n#'\n#' \\code{permute_graph} Shuffles the values of a matrix either considering\n#' \\emph{loops} and \\emph{multiple} links (which are processed as cell values\n#' different than 1/0). \\code{rewire_qap} generates a new graph \\code{graph}\\eqn{'}\n#' that is isomorphic to \\code{graph}.\n#' @templateVar self TRUE\n#' @templateVar multiple TRUE\n#' @template graph_template\n#' @author George G. Vega Yon\n#' @return A permuted version of \\code{graph}.\n#' @examples\n#' # Simple example ------------------------------------------------------------\n#' set.seed(1231)\n#' g <- rgraph_ba(t=9)\n#' g\n#'\n#' # These preserve the density\n#' permute_graph(g)\n#' permute_graph(g)\n#'\n#' # These are isomorphic to g\n#' rewire_qap(g)\n#' rewire_qap(g)\n#'\n#' @references\n#'\n#' Anderson, B. S., Butts, C., & Carley, K. (1999). The interaction of size and\n#' density with graph-level indices. Social Networks, 21(3), 239–267.\n#' \\doi{10.1016/S0378-8733(99)00011-8}\n#'\n#' Mantel, N. (1967). The detection of disease clustering and a generalized\n#' regression approach. Cancer Research, 27(2), 209–20.\n#' \\url{https://cancerres.aacrjournals.org/content/27/2_Part_1/209}\n#'\n#' @seealso This function can be used as null distribution in \\code{struct_test}\n#' @family simulation functions\n#' @export\n#' @aliases CUG QAP\npermute_graph <- function(graph, self=FALSE, multiple=FALSE) {\n\n # Changing class\n cls <- class(graph)\n x <- if (\"matrix\" %in% cls) methods::as(graph, \"dgCMatrix\")\n else if (\"list\" %in% cls) lapply(graph, methods::as, Class=\"dgCMatrix\")\n else if (\"diffnet\" %in% cls) graph$graph\n else if (\"array\" %in% cls) apply(graph, 3, methods::as, Class=\"dgCMatrix\")\n else if (\"dgCMatrix\" %in% cls) graph\n else stopifnot_graph(graph)\n\n if (any(c(\"list\", \"array\") %in% cls) & !(\"matrix\" %in% cls)) {\n\n ans <- lapply(x, permute_graph_cpp, self=self, multiple=multiple)\n\n } else if (\"diffnet\" %in% cls) {\n ans <- graph\n ans$graph <- lapply(x, permute_graph_cpp, self=self, multiple=multiple)\n } else {\n ans <- permute_graph_cpp(x, self, multiple)\n }\n\n return(ans)\n\n}\n\n#' @export\n#' @rdname permute_graph\nrewire_permute <- permute_graph\n\n#' @export\n#' @rdname permute_graph\nrewire_qap <- function(graph) {\n\n neword <- order(runif(nnodes(graph)))\n rewirefun <- function(graph) {\n graph[neword, neword]\n }\n\n # Changing class\n cls <- class(graph)\n x <- if (\"matrix\" %in% cls) methods::as(graph, \"dgCMatrix\")\n else if (\"list\" %in% cls) lapply(graph, methods::as, Class=\"dgCMatrix\")\n else if (\"diffnet\" %in% cls) graph$graph\n else if (\"array\" %in% cls) apply(graph, 3, methods::as, Class=\"dgCMatrix\")\n else if (\"dgCMatrix\" %in% cls) graph\n else\n stopifnot_graph(graph)\n\n if (any(c(\"diffnet\", \"list\") %in% cls) | ((\"array\" %in% cls) & length(dim(graph)) == 3L )) {\n\n ans <- lapply(x, rewirefun)\n\n if (inherits(graph, \"diffnet\")) {\n # Naming\n neword <- match(neword, nodes(graph))\n\n graph$graph <- ans\n graph$graph <- lapply(graph$graph, Matrix::unname)\n graph$meta$ids <- graph$meta$ids[neword]\n\n # Attributes\n if (nrow(graph$vertex.static.attrs)) {\n graph$vertex.static.attrs <- graph$vertex.static.attrs[neword,,drop=FALSE]\n }\n if (nrow(graph$vertex.dyn.attrs[[1]])) {\n graph$vertex.dyn.attrs <- lapply(graph$vertex.dyn.attrs, function(y) {\n y[neword,,drop=FALSE]\n })\n }\n\n # Adoptions\n graph$cumadopt <- graph$cumadopt[neword,,drop=FALSE]\n graph$adopt <- graph$adopt[neword,,drop=FALSE]\n graph$toa <- graph$toa[neword]\n\n return(graph)\n }\n\n\n } else {\n ans <- rewirefun(x)\n }\n\n return(ans)\n}\n\n", "meta": {"hexsha": "9217983c040505eda4848087904dc137a615a31b", "size": 17491, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rewire.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/rewire.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/rewire.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 38.5264317181, "max_line_length": 135, "alphanum_fraction": 0.6477045338, "num_tokens": 5391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.303282088492264}} {"text": "#####################################################\r\n# Phylogenetic diversity in R\r\n\r\n#Set working directory\r\nsetwd(\"D:/Dropbox/iDiv/MLU Biodiversity_2021/phylogenetic_diversity/Practice\")\r\n\r\n#install and load package \"V.PhyloMaker\" to generate phylogenoes based on mega-tree\r\nif(!require(\"devtools\")) install.packages(\"devtools\")\r\nlibrary(devtools)\r\nif(!require(\"V.PhyloMaker\")) devtools::install_github(\"jinyizju/V.PhyloMaker\")\r\nlibrary(V.PhyloMaker)\r\n\r\n#install and load other packages\r\npackages <- c(\"vegan\",\"ape\",\"picante\",\"fields\")\r\npackage.check <- lapply(packages,FUN=function(x)\r\n {\r\n if(!require(x,character.only=TRUE)){\r\n install.packages(x,dependencies=TRUE)\r\n library(x,character.only=TRUE)\r\n }\r\n }\r\n)\r\n\r\n\r\n###############\r\n#1.we will load the BCI data in the packag \"vegan\", and assemble the taxonomic names for the species in BCI, \r\n#and finally build a phylogeny for these species\r\n\r\n#a. BCI dataset\r\ndata(BCI, BCI.env)\r\n\r\n##b.Regute taxonomic informaiton for species in BCI. Both geuns and family are needed to build a phylogeny here.\r\n#The genus are extracted from species names. The species list is then submitted to the TNRS website http://tnrs.iplantcollaborative.org/.\r\n#The TNRS will check taxonomic information and the return result includs the family. Check the website youself. You can also use the \r\n#result \"bci.spp.final.csv\" for next steps\r\n\r\nbci.spp <- data.frame(\"ID\"=1:ncol(BCI),\"species.raw\"=colnames(BCI),\"species\"=NA,\"genus\"=NA,\"family\"=NA,stringsAsFactors=FALSE)\r\nfor(i in 1:nrow(bci.spp)){\r\n names <- unlist(strsplit(bci.spp[i,2],split=\".\",fixed=TRUE))\r\n bci.spp[i,3]<- paste(names,collapse=\" \")\r\n bci.spp[i,4] <- names[1]\r\n}\r\n\r\n#Output the taxonomic informaiton to check use TNRS: http://tnrs.iplantcollaborative.org/\r\nwrite.csv(bci.spp,file=\"bci.spp.raw.csv\", row.names=FALSE)\r\n\r\n#Input the resultant taxonomic information for next steps\r\nbci.spp <- read.csv(\"bci.spp.final.csv\")\r\n\r\n#c. Generate a phylogeny for species in BCI\r\n?phylo.maker()\r\nbci.tree.output <- phylo.maker(bci.spp[,3:5],tree=GBOTB.extended,nodes=nodes.info.1,scenarios=\"S3\")\r\n\r\n#write the tree generated to a txt.\r\nwrite.tree(bci.tree.output$scenario.3,file=\"bci.tree.txt\")\r\n\r\n\r\n############\r\n#2. To check the attributes of the generated phylogeny, and do simple manipulations\r\n\r\n#Read the bci phylogenetic tree\r\nbci.tree <- read.tree(\"bci.tree.txt\")\r\n\r\n#a. check the attributes\r\nclass(bci.tree)\r\nstr(bci.tree)\r\nsummary(bci.tree)\r\nhead(bci.tree$edge) #the first six edge (branch), with the first column as parental node and the second as child node\r\nlength(bci.tree$edge.length) #the number of edge\r\nlength(bci.tree$tip.label) #the nunber of tips\r\n\r\n\r\n#b. Do some simple plotting. To find out what options are available for plotting phylogenies, use ?plot.phylo. \r\n#Then, make a set of plots of the phylogeny using different types.\r\n?plot.phylo\r\nplot(bci.tree,type=\"fan\",cex=0.4)\r\n\r\npar(mfrow=c(1,5),mar=c(0,1,0,1))\r\nplot(bci.tree,cex=0.4)\r\nplot(bci.tree,type=\"cladogram\",cex=0.4)\r\nplot(bci.tree,type=\"fan\",cex=0.4)\r\nplot(bci.tree,type=\"unrooted\",cex=0.4)\r\nplot(bci.tree,type=\"radial\",cex=0.4)\r\n\r\n\r\n#c. plot a zoomed part of the phylogeny \r\n#(in this case, try the first 14 tips) using the zoom() function.\r\nzoom(bci.tree,focus=bci.tree$tip[5:19])\r\n\r\n\r\n#d. Use drop.tip() to remove 180 random tips from the tree, and plot the new tree\r\nbci.tree.drop <- drop.tip(bci.tree,sample(bci.tree$tip,180,replace=F))\r\npar(mfrow=c(1,1),mar=c(4,4,4,4))\r\nplot(bci.tree.drop,type=\"fan\",cex=0.8)\r\n\r\n\r\n##e. Creating a random tree\r\nrandom.tree <- rtree(50)\r\nplot(random.tree)\r\n\r\n\r\n##f. Calculate phylogentic distance among species\r\nbci.tree.drop.dist <- cophenetic(bci.tree.drop)\r\ndim(bci.tree.drop.dist )\r\nbci.tree.drop.dist [1:5,1:5] #the distance among the first five species\r\n\r\n\r\n\r\n####################\r\n#3.\tNow we will calculate some phylogenetic community measures \r\n#(PD, MPD, MNTD, and their related indices,PDI, NRI and NTI) using BCI community data, \r\n\r\n#a. Make the species names in the community data and phylogy are consistent in format \r\nBCI2 <- BCI\r\nbci.tree2 <- bci.tree\r\ncolnames(BCI2) <- bci.spp[,3]\r\nbci.tree2$tip.label <- gsub(\"_\",\" \",fixed=TRUE,bci.tree2$tip.label)\r\n\r\n\r\n#b.Now use the mpd(), pd() and mntd() functions to calculate phylogenetic diversity.\r\n#Calculate PD\r\nbci.pd <- pd(BCI2,bci.tree2)\r\nbci.pd.mat <- matrix(bci.pd$PD,ncol=10,nrow=5);\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.pd.mat),xlab=\"\",ylab=\"\")\r\n\r\n#Calculate MPD\r\nbci.mpd <- mpd(BCI2,cophenetic(bci.tree2))\r\nbci.mpd.mat <- matrix(bci.mpd,ncol=10,nrow=5);\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.mpd.mat),xlab=\"\",ylab=\"\")\r\n\r\n#Calculate MNTD\r\nbci.mntd <- mntd(BCI2,cophenetic(bci.tree2))\r\nbci.mntd.mat <- matrix(bci.mntd,ncol=10,nrow=5);\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.mntd.mat),xlab=\"\",ylab=\"\")\r\n\r\n\r\n\r\n#c.\tUse ses.mpd(), ses.pd() and ses.mntd() to calculate the standardized effect size statistics (PDI, NRI, and NTI).\r\n#Calculate PDI\r\nbci.pdi <- ses.pd(BCI2,bci.tree2,runs=99)\r\nbci.pdi.mat <- matrix(bci.pdi$pd.obs.z,ncol=10,nrow=5);\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.pdi.mat),xlab=\"\",ylab=\"\")\r\n\r\n#Calculate NRI\r\nbci.nri <- ses.mpd(BCI2,cophenetic(bci.tree2),runs=99)\r\nbci.nri.mat <- matrix(-bci.nri$mpd.obs.z,ncol=10,nrow=5)\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.nri.mat),xlab=\"\",ylab=\"\")\r\n\r\n#Calculate NTI\r\nbci.nti <- ses.mntd(BCI2,cophenetic(bci.tree2),runs=99)\r\nbci.nti.mat <- matrix(-bci.nti$mntd.obs.z,ncol=10,nrow=5)\r\nimage.plot(x=seq(0,1000,by=100),y=seq(0,500,by=100),t(bci.nti.mat),xlab=\"\",ylab=\"\")\r\n\r\n\r\n#d.\tCompare the results for NRI using the \"taxa.labels\" algorithm to two other null model algorithms.\r\nNRI1 = ses.mpd(BCI2,cophenetic(bci.tree2),null.model=\"taxa.labels\",runs=99)\r\nNRI2 = ses.mpd(BCI2,cophenetic(bci.tree2),null.model=\"frequency\",runs=99)\r\nNRI3 = ses.mpd(BCI2,cophenetic(bci.tree2),null.model=\"trialswap\",runs=99)\r\n\r\nplot(NRI1$mpd.obs.z,NRI2$mpd.obs.z)\r\nplot(NRI1$mpd.obs.z,NRI3$mpd.obs.z)\r\nplot(NRI2$mpd.obs.z,NRI3$mpd.obs.z)\r\n#Pretty different, but still highly correlated.\r\n\r\n", "meta": {"hexsha": "239011ee90784fcb40f514cb5f2f725b82648265", "size": 6136, "ext": "r", "lang": "R", "max_stars_repo_path": "week 1/5 - Friday/phylogenetic_diversity/Practice/Phylogeny_diversity.r", "max_stars_repo_name": "chase-lab/biodiv-patterns-course-2021", "max_stars_repo_head_hexsha": "5973a33a6c243a9d0ef8a9e053d188e999557167", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week 1/5 - Friday/phylogenetic_diversity/Practice/Phylogeny_diversity.r", "max_issues_repo_name": "chase-lab/biodiv-patterns-course-2021", "max_issues_repo_head_hexsha": "5973a33a6c243a9d0ef8a9e053d188e999557167", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week 1/5 - Friday/phylogenetic_diversity/Practice/Phylogeny_diversity.r", "max_forks_repo_name": "chase-lab/biodiv-patterns-course-2021", "max_forks_repo_head_hexsha": "5973a33a6c243a9d0ef8a9e053d188e999557167", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:09:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-25T10:09:33.000Z", "avg_line_length": 37.1878787879, "max_line_length": 138, "alphanum_fraction": 0.6931225554, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.30315014929217027}} {"text": "###############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n###############################################################################\n# Examples for the Minimum Correlation Algorithm paper\n# Copyright (C) 2012 Michael Kapler\n#\n# Forecast-Free Algorithms: A New Benchmark For Tactical Strategies\n# http://cssanalytics.wordpress.com/2011/08/09/forecast-free-algorithms-a-new-benchmark-for-tactical-strategies/\n#\n# For more information please visit my blog at www.SystematicInvestor.wordpress.com\n# or drop me a line at TheSystematicInvestor at gmail\n###############################################################################\n\n\n\n\n\n\n###############################################################################\n# Main program to run all examples\n#\n# Please Load Systematic Investor Toolbox prior to running this routine\n###############################################################################\n# Load Systematic Investor Toolbox (SIT)\n# http://systematicinvestor.wordpress.com/systematic-investor-toolbox/\n###############################################################################\n#setInternet2(TRUE)\n#con = gzcon(url('http://www.systematicportfolio.com/sit.gz', 'rb'))\n# source(con)\n#close(con)\n###############################################################################\nmin.corr.paper.examples <- function() \n{\n#*****************************************************************\n# Load historical data sets\n#****************************************************************** \n\tload.packages('quantmod')\t\n\t\n\t#*****************************************************************\n\t# Load historical data for Futures and Forex\n\t#****************************************************************** \n\tdata <- new.env()\n\tgetSymbols.TB(env = data, auto.assign = T, download = T)\n\t\t\n\tbt.prep(data, align='remove.na', dates='1990::')\n\tsave(data,file='FuturesForex.Rdata')\n\t#load(file='FuturesForex.Rdata')\n\n\n\t#*****************************************************************\n\t# Load historical data for ETFs\n\t#****************************************************************** \n\ttickers = spl('SPY,QQQ,EEM,IWM,EFA,TLT,IYR,GLD')\n\n\tdata <- new.env()\n\tgetSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)\n\t\tfor(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)\t\t\t\t\t\t\t\n\t# TLT first date is 7/31/2002\n\tbt.prep(data, align='keep.all', dates='2002:08::')\n\tsave(data,file='ETF.Rdata')\n\t#load(file='ETF.Rdata')\n\n\t\n\t#*****************************************************************\n\t# Load historical data for dow stock (engle)\n\t#****************************************************************** \n\tload.packages('quantmod,quadprog')\n\ttickers = spl('AA,AXP,BA,CAT,DD,DIS,GE,IBM,IP,JNJ,JPM,KO,MCD,MMM,MO,MRK,MSFT')\n\t\t\n\tdata <- new.env()\n\tgetSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)\n\t\tfor(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)\t\t\t\t\t\t\t\n\t\t\n\tbt.prep(data, align='keep.all', dates='1980::')\n\t\n\t# backfill prices\n\tprices = coredata(data$prices)\n\t\tprices[is.na(prices)] = mlag(prices)[is.na(prices)]\n\t\tprices[is.na(prices)] = mlag(prices)[is.na(prices)]\n\tdata$prices[] = prices\n\t\t\n\tsave(data,file='Dow.Engle.Rdata')\n\t#load(file='Dow.Engle.Rdata')\n\n\n\t#*****************************************************************\n\t# Load historical data for ETFs\n\t#****************************************************************** \n\tload.packages('quantmod,quadprog')\n\ttickers = spl('VTI,IEV,EEM,EWJ,AGG,GSG,GLD,ICF')\n\t\t\n\tdata <- new.env()\n\tgetSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T)\n\t\tfor(i in ls(data)) data[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)\t\t\t\t\t\t\t\n\t\t\n\tbt.prep(data, align='keep.all', dates='2003:10::')\t\n\tsave(data,file='ETF2.Rdata')\n\t#load(file='ETF2.Rdata')\n\n\t\n\t#*****************************************************************\n\t# Load historical data for nasdaq 100 stocks\n\t#****************************************************************** \n\tload.packages('quantmod,quadprog')\n\t#tickers = nasdaq.100.components()\n\ttickers = spl('ATVI,ADBE,ALTR,AMZN,AMGN,APOL,AAPL,AMAT,ADSK,ADP,BBBY,BIIB,BMC,BRCM,CHRW,CA,CELG,CERN,CHKP,CTAS,CSCO,CTXS,CTSH,CMCSA,COST,DELL,XRAY,DISH,EBAY,EA,EXPD,ESRX,FAST,FISV,FLEX,FLIR,FWLT,GILD,HSIC,HOLX,INFY,INTC,INTU,JBHT,KLAC,LRCX,LIFE,LLTC,LOGI,MAT,MXIM,MCHP,MSFT,MYL,NTAP,NWSA,NVDA,ORLY,ORCL,PCAR,PDCO,PAYX,PCLN,QGEN,QCOM,BBRY,ROST,SNDK,SIAL,SPLS,SBUX,SRCL,SYMC,TEVA,URBN,VRSN,VRTX,VOD,XLNX,YHOO')\n\t\t\n\tdata <- new.env()\n\tfor(i in tickers) {\n\t\ttry(getSymbols(i, src = 'yahoo', from = '1980-01-01', env = data, auto.assign = T), TRUE)\n\t\tdata[[i]] = adjustOHLC(data[[i]], use.Adjusted=T)\t\t\t\t\t\t\t\n\t}\n\tbt.prep(data, align='keep.all', dates='1995::')\n\t\n\t# backfill prices\n\tprices = coredata(data$prices)\n\t\tprices[is.na(prices)] = mlag(prices)[is.na(prices)]\n\t\tprices[is.na(prices)] = mlag(prices)[is.na(prices)]\n\tdata$prices[] = prices\n\t\t\n\t# plot\n\t#plota(make.xts(count(t(data$prices)),index(data$prices)),type='l')\n\t\t\n\tsave(data,file='nasdaq.100.Rdata')\n\t#load(file='nasdaq.100.Rdata')\n\n\n\t\n\t\n#*****************************************************************\n# Run all strategies\n#****************************************************************** \n\tnames = spl('ETF,FuturesForex,Dow.Engle,ETF2,nasdaq.100')\t\n\tlookback.len = 60\n\tperiodicitys = spl('weeks,months')\n\tperiodicity = periodicitys[1]\n\tprefix = paste(substr(periodicity,1,1), '.', sep='')\n\t\n\t\n\t\n\tfor(name in names) {\n\t\tload(file = paste(name, '.Rdata', sep=''))\n\t\t\n\t\tobj = portfolio.allocation.helper(data$prices, periodicity, lookback.len = lookback.len, prefix = prefix,\n\t\t\tmin.risk.fns = 'min.corr.portfolio,min.corr2.portfolio,max.div.portfolio,min.var.portfolio,risk.parity.portfolio(),equal.weight.portfolio',\n\t\t\tcustom.stats.fn = 'portfolio.allocation.custom.stats')\t\t\n\t\t\t\n\t\tsave(obj, file=paste(name, lookback.len, periodicity, '.bt', '.Rdata', sep=''))\n\t}\n\t\t\n\t\n\t#*****************************************************************\n\t# Create Reports\n\t#****************************************************************** \n\tfor(name in names) {\n\t\tload(file=paste(name, '.Rdata', sep=''))\n\t\t\n\t\t# create summary of inputs report\n\t\tcustom.input.report.helper(paste('report.', name, sep=''), data)\n\t\t\n\t\t# create summary of strategies report\n\t\tload(file=paste(name, lookback.len, periodicity, '.bt', '.Rdata', sep=''))\n\t\tcustom.report.helper(paste('report.', name, lookback.len, periodicity, sep=''), \n\t\t\tcreate.strategies(obj, data))\t\n\t}\n\n\t\n\t#*****************************************************************\n\t# Futures and Forex: rescale strategies to match Equal Weight strategy risk profile\n\t#****************************************************************** \n\tnames = spl('FuturesForex')\t\n\tfor(name in names) {\n\t\tload(file=paste(name, '.Rdata', sep=''))\n\n\t\t# create summary of strategies report\n\t\tload(file=paste(name, lookback.len, periodicity, '.bt', '.Rdata', sep=''))\n\t\t\tleverage = c(5, 4, 15, 20, 3, 1)\n\t\tcustom.report.helper(paste('report.leverage.', name, lookback.len, periodicity, sep=''), \n\t\t\tcreate.strategies(obj, data, leverage))\t\n\t}\n\n}\n\n\n\n###############################################################################\n# Custom Report routines\n###############################################################################\n\n#*****************************************************************\n# Create summary of inputs report\n#*****************************************************************\ncustom.input.report.helper <- function(filename, data) {\n\tfilename.pdf = paste(filename, '.pdf', sep='')\n\tfilename.csv = paste(filename, '.csv', sep='')\n\n\t#*****************************************************************\n\t# Create Report\n\t#****************************************************************** \n\t# put all reports into one pdf file\n\tpdf(file = filename.pdf, width=8.5, height=11)\n\t\n\n\t# Input Details\n\tlayout(1:2)\n\tasset.models = list()\n\tfor(i in data$symbolnames) {\n\t\tdata$weight[] = NA\n\t\t\tdata$weight[,i] = 1\t\n\t\tasset.models[[i]] = bt.run(data, silent=T)\n\t}\t\t\n\tasset.summary = plotbt.strategy.sidebyside(asset.models, return.table=T)\n\n\t\t\n\t# plot correlations\n\tret.log = bt.apply.matrix(data$prices, ROC, type='continuous')\n\ttemp = cor(ret.log, use='complete.obs', method='pearson')\n\t\t\ttemp[] = plota.format(100 * temp, 0, '', '%')\n\tplot.table(temp, smain='Correlation', highlight = TRUE, colorbar = TRUE)\t\n\n\n\t# line plot for each input series\n\tlayout(matrix(1:4,2,2))\t\n\tif( is.null(data$symbol.groups) ) {\n\t\tindex = order(data$symbolnames)\n\t\tfor(i in data$symbolnames[index]) \n\t\t\tplota(data[[i]], type='l', cex.main=0.7,main= i)\n\t} else {\n\t\tindex = order(data$symbol.groups)\n\t\tfor(i in data$symbolnames[index]) \n\t\t\tplota(data[[i]], type='l', cex.main=0.7, main= paste(i, data$symbol.groups[i], data$symbol.descriptions.print[i], sep=' / ') )\n\t\t\n\t\tasset.summary = rbind(data$symbol.groups, data$symbol.descriptions.print, asset.summary)\n\t}\n\t\n\t\n\t# close pdf\n\tdev.off()\t\n\n\t#*****************************************************************\n\t# save summary & equity curves into csv file\n\t#****************************************************************** \n\tload.packages('abind')\n\twrite.csv(asset.summary, filename.csv)\n\tcat('\\n\\n', file=filename.csv, append=TRUE)\n\t\n write.table(temp, sep=',', row.names = , col.names = NA,\n\t\tfile=filename.csv, append=TRUE)\n\t\t\n}\n\n\n#*****************************************************************\n# Create summary of strategies report\n#*****************************************************************\ncustom.report.helper <- function(filename, obj) {\n\tfilename.pdf = paste(filename, '.pdf', sep='')\n\tfilename.csv = paste(filename, '.csv', sep='')\n\n\tmodels = obj$models\n\t\t\n\t#*****************************************************************\n\t# Create Report\n\t#****************************************************************** \n\t# put all reports into one pdf file\n\tpdf(file = filename.pdf, width=8.5, height=11)\n\n\t\n\t# Plot perfromance\n\tplotbt(models, plotX = T, log = 'y', LeftMargin = 3)\t \t\n\t\tmtext('Cumulative Performance', side = 2, line = 1)\n\n\t\t\n\t# Plot Strategy Statistics Side by Side\n\tout = plotbt.strategy.sidebyside(models, perfromance.fn = 'custom.returns.kpi', return.table=T)\n\n\t\n\t\n\t# Plot time series of components of Composite Diversification Indicator\n\tcdi = custom.composite.diversification.indicator(obj)\t\n\t\tout = rbind(colMeans(cdi, na.rm=T), out)\n\t\trownames(out)[1] = 'Composite Diversification Indicator(CDI)'\n\t\t\t\n\t# Portfolio Turnover for each strategy\n\ty = 100 * sapply(models, compute.turnover, data)\n\t\tout = rbind(y, out)\n\t\trownames(out)[1] = 'Portfolio Turnover'\t\t\n\t\n\t# Bar chart in descending order of the best algo by Sharpe Ratio, CAGR, Gini, Herfindahl\t\n\tperformance.barchart.helper(out, 'Sharpe,Cagr,RC Gini,RC Herfindahl,Volatility,Portfolio Turnover,Composite Diversification Indicator(CDI)', c(T,T,F,F,F,F,T))\n\n\t\t\n\t# summary allocation statistics for each model\t\n\tcustom.summary.positions(obj$weights)\n\t\n\t\n\t# monhtly returns for each model\t\n\tcustom.period.chart(models)\n\n\t\t\n\t# Plot transition maps\n\tlayout(1:len(models))\n\tfor(m in names(models)) {\n\t\tplotbt.transition.map(models[[m]]$weight, name=m)\n\t\t\tlegend('topright', legend = m, bty = 'n')\n\t}\n\t\n\t\n\t# Plot transition maps for Risk Contributions\n\tdates = index(models[[1]]$weight)[obj$period.ends]\n\tlayout(1:len(models))\n\tfor(m in names(models)) {\n\t\tplotbt.transition.map(make.xts(obj$risk.contributions[[m]], dates), \n\t\tname=paste('Risk Contributions',m))\n\t\t\tlegend('topright', legend = m, bty = 'n')\n\t}\n\n\t# close pdf\n\tdev.off()\t\n\n\t\n\t#*****************************************************************\n\t# save summary & equity curves into csv file\n\t#****************************************************************** \n\tload.packages('abind')\n\twrite.csv(out, filename.csv)\n\tcat('\\n\\n', file=filename.csv, append=TRUE)\n\t\n\tout = abind(lapply(models, function(m) m$equity))\n\t\tcolnames(out) = names(models)\n\twrite.xts(make.xts(out, index(models[[1]]$equity)), filename.csv, append=TRUE)\t\t\n}\n\n\n\n#*****************************************************************\n# Composite Diversification Indicator (CDI) is 50/50 of\n# * 1 - Gini(portfolio risk contribution weights) and \n# * Minimum Average Correlation (from max.div) / Average Portfolio Correlation (w * Correlation Matrix * w) \t\t\t\n#' @export \n#*****************************************************************\ncustom.composite.diversification.indicator <- function\n(\n\tobj,\t# portfolio.backtest object\n\tavg.flag = T,\n\tavg.len = 10,\n\tplot.main = T,\n\tplot.table = T\n) \n{\n\tcdi = 0.5 * obj$risk.gini + 0.5 * obj$degree.diversification\n\t\tif(avg.flag) cdi = bt.apply.matrix(cdi, EMA, avg.len)\n\n\tif(plot.main) {\t\n\t\tavg.name = iif(avg.flag, paste(avg.len,'period EMA') , '')\n\n\t\tlayout(1:3)\n\t\tout = obj$degree.diversification\n\t\t\tif(avg.flag) out = bt.apply.matrix(out, EMA, avg.len)\n\t\tplota.matplot(out, cex.main = 1, \n\t\t\tmain=paste('D = 1 - Portfolio Risk/Weighted Average of asset vols in the portfolio', avg.name))\n\t\t\t\t\t\n\t\tout = obj$risk.gini\n\t\t\tif(avg.flag) out = bt.apply.matrix(out, EMA, avg.len)\n\t\tplota.matplot(out, cex.main = 1, \n\t\t\tmain=paste('1 - Gini(Risk Contributions)', avg.name))\n\t\t\t\n\t\tplota.matplot(cdi, cex.main = 1, \n\t\t\tmain=paste('Composite Diversification Indicator (CDI) = 50/50 Gini/D', avg.name))\n\t}\n\n\n\t# create sensitivity plot\t\t\n\tif(plot.table) {\t\n\t\tweights = seq(0,1,0.1)\n\t\t# create temp matrix with data you want to plot\n\t\ttemp = matrix(NA, nc=len(weights), nr=ncol(cdi))\n\t\t\tcolnames(temp) = paste(weights)\n\t\t\trownames(temp) = colnames(cdi)\n\t\t\t\n\t\tfor(j in 1:len(weights)) {\n\t\t\ti = weights[j]\n\t\t\ttemp[,j] = rank(-colMeans((1-i) * obj$risk.gini + i * obj$degree.diversification, na.rm=T))\n\t\t}\n\t\ttemp = cbind(temp, round(rowMeans(temp),1))\n\t\t\tcolnames(temp)[ncol(temp)] = 'AVG'\n\t\t\n\t\t# highlight each column separately\n\t\thighlight = apply(temp,2, function(x) plot.table.helper.color(t(x)) )\n\t\t\n\t\t# plot temp with colorbar\n\t\tlayout(1)\n\t\tplot.table(temp, smain = 'CDI Rank\\nAlgo vs %D',highlight = highlight, colorbar = TRUE)\n\t}\t\n\n\treturn(cdi)\n} \n\t\t\t\n\n\n#*****************************************************************\n# Summary Positions for each model\n#*****************************************************************\ncustom.summary.positions <- function(weights) {\n\tlayout(1:len(weights))\n\t\n\tfor(w in names(weights)) {\n\t\ttickers = colnames(weights[[w]])\n\t\tn = len(tickers)\n\t\t\n\t\ttemp = matrix(NA, nr=4, nc=n)\n\t\t\tcolnames(temp) = tickers\n\t\t\trownames(temp) = spl('Avg Pos,Max Pos,Min Pos,# Periods')\n\t\t\t\n\t\ttemp['Avg Pos',] = 100 * apply(weights[[w]],2,mean,na.rm=T)\n\t\ttemp['Max Pos',] = 100 * apply(weights[[w]],2,max,na.rm=T)\n\t\ttemp['Min Pos',] = 100 * apply(weights[[w]],2,min,na.rm=T)\n\t\ttemp['# Periods',] = apply(weights[[w]] > 1/1000,2,sum,na.rm=T)\n\t\t\n\t\ttemp[] = plota.format(temp, 0, '', '')\n\t\tplot.table(temp, smain=w)\n\t}\n}\t\n\n\n#*****************************************************************\n# Helper function to create barplot\n#*****************************************************************\ncustom.profit.chart <- function(data, main, cols) {\n\tpar(mar=c(4, 3, 2, 2),cex.main=2,cex.sub=1, cex.axis=1.5,cex.lab=1.5)\t\n\t\n\tbarplot(data, names.arg = names(data),\n\t\tcol=iif(data > 0, cols[1], cols[2]), \n\t\tmain=main, \n\t\tcex.names = 1.5, border = 'darkgray',las=2) \n\tgrid(NA,NULL) \n\tabline(h=0,col='black')\n\tabline(h=mean(data),col='gray',lty='dashed',lwd=3)\n}\n\n\n#*****************************************************************\n# Monhtly returns for each model\t\n#*****************************************************************\ncustom.period.chart <- function(models) {\n\tfor(imodel in 1:len(models)) {\n\t\tequity = models[[imodel]]$equity\n\t\n\t\t#*****************************************************************\n\t\t# Compute monthly returns\n\t\t#****************************************************************** \n\t\tperiod.ends = endpoints(equity, 'months')\n\t\t\tperiod.ends = unique(c(1, period.ends[period.ends > 0]))\n\t\n\t\tret = equity[period.ends,] / mlag(equity[period.ends,]) - 1\n\t\t\tret = ret[-1]\n\t\n\t\tret.by.month = create.monthly.table(ret)\t\n\t\tret.by.month = 100 * apply(ret.by.month, 2, mean, na.rm=T)\n\t\t\n\t\t#*****************************************************************\n\t\t# Compute annual returns\n\t\t#****************************************************************** \n\t\tperiod.ends = endpoints(equity, 'years')\n\t\t\tperiod.ends = unique(c(1, period.ends[period.ends > 0]))\n\t\n\t\tret = equity[period.ends,] / mlag(equity[period.ends,]) - 1\n\t\tret.by.year = ret[-1]\n\t\t\t\n\t\t#*****************************************************************\n\t\t# Create plots\n\t\t#****************************************************************** \n\t\t# create layout\t\n\t\tilayout = \n\t\t\t'1,1\n\t\t\t2,2\n\t\t\t2,2\n\t\t\t2,2\n\t\t\t2,2\n\t\t\t2,2\n\t\t\t3,4\n\t\t\t3,4\n\t\t\t3,4\n\t\t\t3,4\n\t\t\t3,4\n\t\t\t3,4'\n\t\tplota.layout(ilayout)\n\t\t\n\t\t# make dummy table with name of strategy\t\t\n\t\tmake.table(1,1)\n\t\ta = matrix(names(models)[imodel],1,1)\n\t\tcex = plot.table.helper.auto.adjust.cex(a)\n\t\tdraw.cell(a[1],1,1, text.cex=cex,frame.cell=F)\t\t\n\t\t\n\t\t# plots\n\t\ttemp = plotbt.monthly.table(equity)\t\n\t\n\t\t# plot months\n\t\tcols = spl('green,red')\n\t\tcustom.profit.chart(ret.by.month, 'Average Monthly Returns', cols)\n\t\t\n\t\t# plot years\n\t\tret = 100*as.vector(ret.by.year)\n\t\t\tnames(ret) = date.year(index(ret.by.year))\n\t\tcustom.profit.chart(ret, 'Annual Returns', cols)\n\t}\n}\t\n\t\n\n#*****************************************************************\n# Custom Summary function to add consentration statistics (Gini and Herfindahl)\n#\n# On the properties of equally-weighted risk contributions portfolios by\n# S. Maillardy, T. Roncalliz, J. Teiletchex (2009)\n# A.4 Concentration and turnover statistics, page 22\n#*****************************************************************\ncustom.returns.kpi <- function\n(\n\tbt,\t\t# backtest object\n\ttrade.summary = NULL\n) \n{\t\n\tout = list()\n\tw = bt$period.weight\n\trc = bt$risk.contribution\n\t\n\t# Average Number of Holdings\n\tout[[ 'Avg #' ]] = mean(rowSums(w > 1/1000)) / 100\n\t\n\t# Consentration stats\n\tout[[ 'W Gini' ]] = mean(portfolio.concentration.gini.coefficient(w), na.rm=T)\n\tout[[ 'W Herfindahl' ]] = mean(portfolio.concentration.herfindahl.index(w), na.rm=T) \n\t\n\t# Consentration stats on marginal risk contributions\n\tout[[ 'RC Gini' ]] = mean(portfolio.concentration.gini.coefficient(rc), na.rm=T)\n\tout[[ 'RC Herfindahl' ]] = mean(portfolio.concentration.herfindahl.index(rc), na.rm=T) \n\n\tout = lapply(out, function(x) if(is.double(x)) round(100*x,1) else x)\n\tout = c(bt.detail.summary(bt)$System, out)\n\t\n\treturn( list(System=out))\n}\n\n\t\t\t\n###############################################################################\n# \"Let us skip now to the general case. If we sum up the situations from the point\n# of view of mathematical de nitions of these portfolios, they are as follows (where\n# we use the fact that MV portfolios are equalizing marginal contributions to risk; see\n# Scherer, 2007b)\" (this is from the Roncalli Paper)\n#\n# \"All stocks belonging to the MDP have the same correlation to it\" (Choeifaty: Properties of the Most Diversified Portfolio)\n#\n# The marginals for the minimum variance and maximum diversification portfolios \n# and the property of equal marginals ONLY holds is we do not impose long-only constraints. \n#\n# If we only have a budget constraint (i.e. sum of portfolio weights = 100%)\n# min.var weights = | 2.05, -0.57, -0.48 |\n# marginal risk contributions = | 0.01468981, 0.01468981, 0.01468981 |\n#\n# max.div weights = | -0.26, 0.65, 0.61 |\n# marginal correlation contributions = | 0.8434783, 0.8434783, 0.8434783 |\n# marginal contributions are the same\n#\n# Now if we add long only constraint (i.e. all weights >= 0 and sum of portfolio weights = 100%)\n# min.var weights = | 1, 0, 0 |\n# marginal risk contributions = | 0.0196, 0.02268, 0.02618 |\n# \n# max.div weights = | 0, 0.5, 0.5 |\n# marginal correlation contributions = | 0.875, 0.85, 0.85 |\n# marginal contributions are the different\n###############################################################################\n#\n# Numerical examples used in the Minimum Correlation Algorithm papaer\n#\n###############################################################################\nmin.corr.paper.numerical.examples <- function() \n{\n\t#*****************************************************************\n\t# create input assumptions\n\t#*****************************************************************\n\t\tn = 3\n\t\tia = list()\n\t\t\tia$n = 3\n\t\t\tia$risk = c(14, 18, 22) / 100;\n\t\t\tia$correlation = matrix(\n\t\t\t\tc(1, 0.90, 0.85,\n\t\t\t\t0.90, 1, 0.70,\n\t\t\t\t0.85, 0.70, 1), nr=3, byrow=T)\n\t\t\tia$cov = ia$correlation * (ia$risk %*% t(ia$risk))\n\n\t#*****************************************************************\n\t# create constraints\n\t#*****************************************************************\n\t\tconstraints = new.constraints(n)\n\t\t# 0 <= x.i <= 1\n\t\tconstraints = new.constraints(n, lb = 0, ub = 1)\n\t\t\tconstraints = add.constraints(diag(n), type='>=', b=0, constraints)\n\t\t\tconstraints = add.constraints(diag(n), type='<=', b=1, constraints)\n\n\t\t# SUM x.i = 1\n\t\tconstraints = add.constraints(rep(1, n), 1, type = '=', constraints)\t\t\n\t\t\t\t\n\t#*****************************************************************\n\t# Minimum Variance Portfolio \n\t#*****************************************************************\n\t\tx = min.var.portfolio(ia, constraints)\n\t\t\n\t\tsol = solve.QP(Dmat=ia$cov, dvec=rep(0, ia$n), \n\t\t\tAmat=constraints$A, bvec=constraints$b, meq=constraints$meq)\n\t\tx = sol$solution\n\t\t\n\t\t\tround(x,4)\n\t\t\tsqrt(x %*% ia$cov %*% x)\n\t\t\t\n\t\t# marginal contributions\t\n\t\tx %*% ia$cov\n\t\t\n\t#*****************************************************************\n\t# Maximum Diversification Portfolio \n\t#*****************************************************************\t\t\t\n\t\tsol = solve.QP(Dmat=ia$correlation, dvec=rep(0, ia$n), \n\t\t\tAmat=constraints$A, bvec=constraints$b, meq=constraints$meq)\n\t\tx = sol$solution\n\t\t\tround(x,4)\n\t\t\t\n\t\t# marginal contributions\n\t\tx %*% ia$correlation\n\t\t\n\t\t\n\t\t# re-scale and normalize weights to sum up to 1\n\t\tx = x / sqrt( diag(ia$cov) )\n\t\tx = x / sum(x)\n\t\t\tround(x,4)\n\t\t\tsqrt(x %*% ia$cov %*% x)\n\t\t\t\n\t#*****************************************************************\n\t# Minimum Correlation Portfolio \n\t#*****************************************************************\t\t\t\t\t\t\n\t\tupper.index = upper.tri(ia$correlation)\n\t\tcor.m = ia$correlation[upper.index]\n\t\t\tcor.mu = mean(cor.m)\n\t\t\tcor.sd = sd(cor.m)\n\t\t\t\n\t\tnorm.dist.m = 0 * ia$correlation\t\n\t\t\tdiag(norm.dist.m) = NA\n\t\t\tnorm.dist.m[upper.index] = sapply(cor.m, function(x) 1-pnorm(x, cor.mu, cor.sd))\n\t\tnorm.dist.m = (norm.dist.m + t(norm.dist.m))\n\t\t\n\t\tnorm.dist.avg = apply(norm.dist.m, 1, mean, na.rm=T)\n\t\t\n\t\tnorm.dist.rank = rank(-norm.dist.avg)\n\t\t\n\t\t\tadjust.factor = 1\n\t\tadjusted.norm.dist.rank = norm.dist.rank ^ adjust.factor\n\t\t\n\t\tnorm.dist.weight = adjusted.norm.dist.rank / sum(adjusted.norm.dist.rank)\n\t\t\n\t\tweighted.norm.dist.average = norm.dist.weight %*% ifna(norm.dist.m,0)\n\t\t\n\t\tfinal.weight = weighted.norm.dist.average / sum(weighted.norm.dist.average)\n\t\t\n\t\tx = final.weight\n\t\t\n\t\t# re-scale and normalize weights to sum up to 1\n\t\tx = x / sqrt( diag(ia$cov) )\n\t\tx = x / sum(x)\n\t\t\tround(x,4)\n\t\t\tx = as.vector(x)\n\t\t\tsqrt(x %*% ia$cov %*% x)\n\t\t\t\n\t#*****************************************************************\n\t# Minimum Correlation 2 Portfolio \n\t#*****************************************************************\t\t\t\t\t\t\n\t\tcor.m = ia$correlation\n\t\t\tdiag(cor.m) = 0\n\t\t\t\n\t\tavg = rowMeans(cor.m)\n\t\t\tcor.mu = mean(avg)\n\t\t\tcor.sd = sd(avg)\n\t\tnorm.dist.avg = 1-pnorm(avg, cor.mu, cor.sd)\n\t\t\n\t\tnorm.dist.rank = rank(-norm.dist.avg)\n\t\t\n\t\t\tadjust.factor = 1\n\t\tadjusted.norm.dist.rank = norm.dist.rank ^ adjust.factor\n\t\t\n\t\tnorm.dist.weight = adjusted.norm.dist.rank / sum(adjusted.norm.dist.rank)\n\t\t\t\t\n\t\tweighted.norm.dist.average = norm.dist.weight %*% (1-cor.m)\n\t\tfinal.weight = weighted.norm.dist.average / sum(weighted.norm.dist.average)\n\t\t\n\t\tx = final.weight\n\t\t\n\t\t# re-scale and normalize weights to sum up to 1\n\t\tx = x / sqrt( diag(ia$cov) )\n\t\tx = x / sum(x)\n\t\t\tround(x,4)\n\t\t\tx = as.vector(x)\n\t\t\tsqrt(x %*% ia$cov %*% x)\n\t\t\t\t\t\n\t\t\t\n\t\t#min.corr.portfolio(ia, constraints)\n\t\t#min.corr2.portfolio(ia, constraints)\t\t\t\t\t\n}\n\t\n\n\n", "meta": {"hexsha": "ff0f1eff1a9b2906f11587bf000459f50e6436fd", "size": 24730, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/min.corr.paper.r", "max_stars_repo_name": "wisonhang/Shiny_report", "max_stars_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patterns.matching/SIT/min.corr.paper.r", "max_issues_repo_name": "wisonhang/Shiny_report", "max_issues_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patterns.matching/SIT/min.corr.paper.r", "max_forks_repo_name": "wisonhang/Shiny_report", "max_forks_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3949930459, "max_line_length": 409, "alphanum_fraction": 0.5374039628, "num_tokens": 6552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30271106987308793}}